xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision f4257c5832aa51e960e7351929ca3d37031985b7)
1 //===- VPlan.cpp - Vectorizer Plan ----------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This is the LLVM vectorization plan. It represents a candidate for
11 /// vectorization, allowing to plan and optimize how to vectorize a given loop
12 /// before generating LLVM-IR.
13 /// The vectorizer uses vectorization plans to estimate the costs of potential
14 /// candidates and if profitable to execute the desired plan, generating vector
15 /// LLVM-IR code.
16 ///
17 //===----------------------------------------------------------------------===//
18 
19 #include "VPlan.h"
20 #include "VPlanDominatorTree.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/PostOrderIterator.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/CFG.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/GenericDomTreeConstruction.h"
38 #include "llvm/Support/GraphWriter.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include <cassert>
42 #include <iterator>
43 #include <string>
44 #include <vector>
45 
46 using namespace llvm;
47 extern cl::opt<bool> EnableVPlanNativePath;
48 
49 #define DEBUG_TYPE "vplan"
50 
51 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
52   const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
53   VPSlotTracker SlotTracker(
54       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
55   V.print(OS, SlotTracker);
56   return OS;
57 }
58 
59 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
60   if (const VPInstruction *Instr = dyn_cast<VPInstruction>(this))
61     Instr->print(OS, SlotTracker);
62   else
63     printAsOperand(OS, SlotTracker);
64 }
65 
66 // Get the top-most entry block of \p Start. This is the entry block of the
67 // containing VPlan. This function is templated to support both const and non-const blocks
68 template <typename T> static T *getPlanEntry(T *Start) {
69   T *Next = Start;
70   T *Current = Start;
71   while ((Next = Next->getParent()))
72     Current = Next;
73 
74   SmallSetVector<T *, 8> WorkList;
75   WorkList.insert(Current);
76 
77   for (unsigned i = 0; i < WorkList.size(); i++) {
78     T *Current = WorkList[i];
79     if (Current->getNumPredecessors() == 0)
80       return Current;
81     auto &Predecessors = Current->getPredecessors();
82     WorkList.insert(Predecessors.begin(), Predecessors.end());
83   }
84 
85   llvm_unreachable("VPlan without any entry node without predecessors");
86 }
87 
88 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
89 
90 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
91 
92 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
93 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
94   const VPBlockBase *Block = this;
95   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
96     Block = Region->getEntry();
97   return cast<VPBasicBlock>(Block);
98 }
99 
100 VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
101   VPBlockBase *Block = this;
102   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
103     Block = Region->getEntry();
104   return cast<VPBasicBlock>(Block);
105 }
106 
107 void VPBlockBase::setPlan(VPlan *ParentPlan) {
108   assert(ParentPlan->getEntry() == this &&
109          "Can only set plan on its entry block.");
110   Plan = ParentPlan;
111 }
112 
113 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
114 const VPBasicBlock *VPBlockBase::getExitBasicBlock() const {
115   const VPBlockBase *Block = this;
116   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
117     Block = Region->getExit();
118   return cast<VPBasicBlock>(Block);
119 }
120 
121 VPBasicBlock *VPBlockBase::getExitBasicBlock() {
122   VPBlockBase *Block = this;
123   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
124     Block = Region->getExit();
125   return cast<VPBasicBlock>(Block);
126 }
127 
128 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
129   if (!Successors.empty() || !Parent)
130     return this;
131   assert(Parent->getExit() == this &&
132          "Block w/o successors not the exit of its parent.");
133   return Parent->getEnclosingBlockWithSuccessors();
134 }
135 
136 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
137   if (!Predecessors.empty() || !Parent)
138     return this;
139   assert(Parent->getEntry() == this &&
140          "Block w/o predecessors not the entry of its parent.");
141   return Parent->getEnclosingBlockWithPredecessors();
142 }
143 
144 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
145   SmallVector<VPBlockBase *, 8> Blocks;
146   for (VPBlockBase *Block : depth_first(Entry))
147     Blocks.push_back(Block);
148 
149   for (VPBlockBase *Block : Blocks)
150     delete Block;
151 }
152 
153 BasicBlock *
154 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
155   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
156   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
157   BasicBlock *PrevBB = CFG.PrevBB;
158   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
159                                          PrevBB->getParent(), CFG.LastBB);
160   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
161 
162   // Hook up the new basic block to its predecessors.
163   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
164     VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock();
165     auto &PredVPSuccessors = PredVPBB->getSuccessors();
166     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
167 
168     // In outer loop vectorization scenario, the predecessor BBlock may not yet
169     // be visited(backedge). Mark the VPBasicBlock for fixup at the end of
170     // vectorization. We do not encounter this case in inner loop vectorization
171     // as we start out by building a loop skeleton with the vector loop header
172     // and latch blocks. As a result, we never enter this function for the
173     // header block in the non VPlan-native path.
174     if (!PredBB) {
175       assert(EnableVPlanNativePath &&
176              "Unexpected null predecessor in non VPlan-native path");
177       CFG.VPBBsToFix.push_back(PredVPBB);
178       continue;
179     }
180 
181     assert(PredBB && "Predecessor basic-block not found building successor.");
182     auto *PredBBTerminator = PredBB->getTerminator();
183     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
184     if (isa<UnreachableInst>(PredBBTerminator)) {
185       assert(PredVPSuccessors.size() == 1 &&
186              "Predecessor ending w/o branch must have single successor.");
187       PredBBTerminator->eraseFromParent();
188       BranchInst::Create(NewBB, PredBB);
189     } else {
190       assert(PredVPSuccessors.size() == 2 &&
191              "Predecessor ending with branch must have two successors.");
192       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
193       assert(!PredBBTerminator->getSuccessor(idx) &&
194              "Trying to reset an existing successor block.");
195       PredBBTerminator->setSuccessor(idx, NewBB);
196     }
197   }
198   return NewBB;
199 }
200 
201 void VPBasicBlock::execute(VPTransformState *State) {
202   bool Replica = State->Instance &&
203                  !(State->Instance->Part == 0 && State->Instance->Lane == 0);
204   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
205   VPBlockBase *SingleHPred = nullptr;
206   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
207 
208   // 1. Create an IR basic block, or reuse the last one if possible.
209   // The last IR basic block is reused, as an optimization, in three cases:
210   // A. the first VPBB reuses the loop header BB - when PrevVPBB is null;
211   // B. when the current VPBB has a single (hierarchical) predecessor which
212   //    is PrevVPBB and the latter has a single (hierarchical) successor; and
213   // C. when the current VPBB is an entry of a region replica - where PrevVPBB
214   //    is the exit of this region from a previous instance, or the predecessor
215   //    of this region.
216   if (PrevVPBB && /* A */
217       !((SingleHPred = getSingleHierarchicalPredecessor()) &&
218         SingleHPred->getExitBasicBlock() == PrevVPBB &&
219         PrevVPBB->getSingleHierarchicalSuccessor()) && /* B */
220       !(Replica && getPredecessors().empty())) {       /* C */
221     NewBB = createEmptyBasicBlock(State->CFG);
222     State->Builder.SetInsertPoint(NewBB);
223     // Temporarily terminate with unreachable until CFG is rewired.
224     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
225     State->Builder.SetInsertPoint(Terminator);
226     // Register NewBB in its loop. In innermost loops its the same for all BB's.
227     Loop *L = State->LI->getLoopFor(State->CFG.LastBB);
228     L->addBasicBlockToLoop(NewBB, *State->LI);
229     State->CFG.PrevBB = NewBB;
230   }
231 
232   // 2. Fill the IR basic block with IR instructions.
233   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
234                     << " in BB:" << NewBB->getName() << '\n');
235 
236   State->CFG.VPBB2IRBB[this] = NewBB;
237   State->CFG.PrevVPBB = this;
238 
239   for (VPRecipeBase &Recipe : Recipes)
240     Recipe.execute(*State);
241 
242   VPValue *CBV;
243   if (EnableVPlanNativePath && (CBV = getCondBit())) {
244     Value *IRCBV = CBV->getUnderlyingValue();
245     assert(IRCBV && "Unexpected null underlying value for condition bit");
246 
247     // Condition bit value in a VPBasicBlock is used as the branch selector. In
248     // the VPlan-native path case, since all branches are uniform we generate a
249     // branch instruction using the condition value from vector lane 0 and dummy
250     // successors. The successors are fixed later when the successor blocks are
251     // visited.
252     Value *NewCond = State->Callback.getOrCreateVectorValues(IRCBV, 0);
253     NewCond = State->Builder.CreateExtractElement(NewCond,
254                                                   State->Builder.getInt32(0));
255 
256     // Replace the temporary unreachable terminator with the new conditional
257     // branch.
258     auto *CurrentTerminator = NewBB->getTerminator();
259     assert(isa<UnreachableInst>(CurrentTerminator) &&
260            "Expected to replace unreachable terminator with conditional "
261            "branch.");
262     auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond);
263     CondBr->setSuccessor(0, nullptr);
264     ReplaceInstWithInst(CurrentTerminator, CondBr);
265   }
266 
267   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
268 }
269 
270 void VPRegionBlock::execute(VPTransformState *State) {
271   ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry);
272 
273   if (!isReplicator()) {
274     // Visit the VPBlocks connected to "this", starting from it.
275     for (VPBlockBase *Block : RPOT) {
276       if (EnableVPlanNativePath) {
277         // The inner loop vectorization path does not represent loop preheader
278         // and exit blocks as part of the VPlan. In the VPlan-native path, skip
279         // vectorizing loop preheader block. In future, we may replace this
280         // check with the check for loop preheader.
281         if (Block->getNumPredecessors() == 0)
282           continue;
283 
284         // Skip vectorizing loop exit block. In future, we may replace this
285         // check with the check for loop exit.
286         if (Block->getNumSuccessors() == 0)
287           continue;
288       }
289 
290       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
291       Block->execute(State);
292     }
293     return;
294   }
295 
296   assert(!State->Instance && "Replicating a Region with non-null instance.");
297 
298   // Enter replicating mode.
299   State->Instance = {0, 0};
300 
301   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
302     State->Instance->Part = Part;
303     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
304     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
305          ++Lane) {
306       State->Instance->Lane = Lane;
307       // Visit the VPBlocks connected to \p this, starting from it.
308       for (VPBlockBase *Block : RPOT) {
309         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
310         Block->execute(State);
311       }
312     }
313   }
314 
315   // Exit replicating mode.
316   State->Instance.reset();
317 }
318 
319 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) {
320   assert(!Parent && "Recipe already in some VPBasicBlock");
321   assert(InsertPos->getParent() &&
322          "Insertion position not in any VPBasicBlock");
323   Parent = InsertPos->getParent();
324   Parent->getRecipeList().insert(InsertPos->getIterator(), this);
325 }
326 
327 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) {
328   assert(!Parent && "Recipe already in some VPBasicBlock");
329   assert(InsertPos->getParent() &&
330          "Insertion position not in any VPBasicBlock");
331   Parent = InsertPos->getParent();
332   Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this);
333 }
334 
335 void VPRecipeBase::removeFromParent() {
336   assert(getParent() && "Recipe not in any VPBasicBlock");
337   getParent()->getRecipeList().remove(getIterator());
338   Parent = nullptr;
339 }
340 
341 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() {
342   assert(getParent() && "Recipe not in any VPBasicBlock");
343   return getParent()->getRecipeList().erase(getIterator());
344 }
345 
346 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) {
347   removeFromParent();
348   insertAfter(InsertPos);
349 }
350 
351 void VPInstruction::generateInstruction(VPTransformState &State,
352                                         unsigned Part) {
353   IRBuilder<> &Builder = State.Builder;
354 
355   if (Instruction::isBinaryOp(getOpcode())) {
356     Value *A = State.get(getOperand(0), Part);
357     Value *B = State.get(getOperand(1), Part);
358     Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B);
359     State.set(this, V, Part);
360     return;
361   }
362 
363   switch (getOpcode()) {
364   case VPInstruction::Not: {
365     Value *A = State.get(getOperand(0), Part);
366     Value *V = Builder.CreateNot(A);
367     State.set(this, V, Part);
368     break;
369   }
370   case VPInstruction::ICmpULE: {
371     Value *IV = State.get(getOperand(0), Part);
372     Value *TC = State.get(getOperand(1), Part);
373     Value *V = Builder.CreateICmpULE(IV, TC);
374     State.set(this, V, Part);
375     break;
376   }
377   case Instruction::Select: {
378     Value *Cond = State.get(getOperand(0), Part);
379     Value *Op1 = State.get(getOperand(1), Part);
380     Value *Op2 = State.get(getOperand(2), Part);
381     Value *V = Builder.CreateSelect(Cond, Op1, Op2);
382     State.set(this, V, Part);
383     break;
384   }
385   case VPInstruction::ActiveLaneMask: {
386     // Get first lane of vector induction variable.
387     Value *VIVElem0 = State.get(getOperand(0), {Part, 0});
388     // Get the original loop tripcount.
389     Value *ScalarTC = State.TripCount;
390 
391     auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
392     auto *PredTy = FixedVectorType::get(Int1Ty, State.VF.getKnownMinValue());
393     Instruction *Call = Builder.CreateIntrinsic(
394         Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()},
395         {VIVElem0, ScalarTC}, nullptr, "active.lane.mask");
396     State.set(this, Call, Part);
397     break;
398   }
399   default:
400     llvm_unreachable("Unsupported opcode for instruction");
401   }
402 }
403 
404 void VPInstruction::execute(VPTransformState &State) {
405   assert(!State.Instance && "VPInstruction executing an Instance");
406   for (unsigned Part = 0; Part < State.UF; ++Part)
407     generateInstruction(State, Part);
408 }
409 
410 void VPInstruction::print(raw_ostream &O, const Twine &Indent,
411                           VPSlotTracker &SlotTracker) const {
412   O << "\"EMIT ";
413   print(O, SlotTracker);
414 }
415 
416 void VPInstruction::print(raw_ostream &O) const {
417   VPSlotTracker SlotTracker(getParent()->getPlan());
418   print(O, SlotTracker);
419 }
420 
421 void VPInstruction::print(raw_ostream &O, VPSlotTracker &SlotTracker) const {
422   if (hasResult()) {
423     printAsOperand(O, SlotTracker);
424     O << " = ";
425   }
426 
427   switch (getOpcode()) {
428   case VPInstruction::Not:
429     O << "not";
430     break;
431   case VPInstruction::ICmpULE:
432     O << "icmp ule";
433     break;
434   case VPInstruction::SLPLoad:
435     O << "combined load";
436     break;
437   case VPInstruction::SLPStore:
438     O << "combined store";
439     break;
440   case VPInstruction::ActiveLaneMask:
441     O << "active lane mask";
442     break;
443 
444   default:
445     O << Instruction::getOpcodeName(getOpcode());
446   }
447 
448   for (const VPValue *Operand : operands()) {
449     O << " ";
450     Operand->printAsOperand(O, SlotTracker);
451   }
452 }
453 
454 /// Generate the code inside the body of the vectorized loop. Assumes a single
455 /// LoopVectorBody basic-block was created for this. Introduce additional
456 /// basic-blocks as needed, and fill them all.
457 void VPlan::execute(VPTransformState *State) {
458   // -1. Check if the backedge taken count is needed, and if so build it.
459   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
460     Value *TC = State->TripCount;
461     IRBuilder<> Builder(State->CFG.PrevBB->getTerminator());
462     auto *TCMO = Builder.CreateSub(TC, ConstantInt::get(TC->getType(), 1),
463                                    "trip.count.minus.1");
464     auto VF = State->VF;
465     Value *VTCMO =
466         VF == 1 ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
467     for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part)
468       State->set(BackedgeTakenCount, VTCMO, Part);
469   }
470 
471   // 0. Set the reverse mapping from VPValues to Values for code generation.
472   for (auto &Entry : Value2VPValue)
473     State->VPValue2Value[Entry.second] = Entry.first;
474 
475   BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB;
476   BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor();
477   assert(VectorHeaderBB && "Loop preheader does not have a single successor.");
478 
479   // 1. Make room to generate basic-blocks inside loop body if needed.
480   BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock(
481       VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch");
482   Loop *L = State->LI->getLoopFor(VectorHeaderBB);
483   L->addBasicBlockToLoop(VectorLatchBB, *State->LI);
484   // Remove the edge between Header and Latch to allow other connections.
485   // Temporarily terminate with unreachable until CFG is rewired.
486   // Note: this asserts the generated code's assumption that
487   // getFirstInsertionPt() can be dereferenced into an Instruction.
488   VectorHeaderBB->getTerminator()->eraseFromParent();
489   State->Builder.SetInsertPoint(VectorHeaderBB);
490   UnreachableInst *Terminator = State->Builder.CreateUnreachable();
491   State->Builder.SetInsertPoint(Terminator);
492 
493   // 2. Generate code in loop body.
494   State->CFG.PrevVPBB = nullptr;
495   State->CFG.PrevBB = VectorHeaderBB;
496   State->CFG.LastBB = VectorLatchBB;
497 
498   for (VPBlockBase *Block : depth_first(Entry))
499     Block->execute(State);
500 
501   // Setup branch terminator successors for VPBBs in VPBBsToFix based on
502   // VPBB's successors.
503   for (auto VPBB : State->CFG.VPBBsToFix) {
504     assert(EnableVPlanNativePath &&
505            "Unexpected VPBBsToFix in non VPlan-native path");
506     BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
507     assert(BB && "Unexpected null basic block for VPBB");
508 
509     unsigned Idx = 0;
510     auto *BBTerminator = BB->getTerminator();
511 
512     for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
513       VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
514       BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
515       ++Idx;
516     }
517   }
518 
519   // 3. Merge the temporary latch created with the last basic-block filled.
520   BasicBlock *LastBB = State->CFG.PrevBB;
521   // Connect LastBB to VectorLatchBB to facilitate their merge.
522   assert((EnableVPlanNativePath ||
523           isa<UnreachableInst>(LastBB->getTerminator())) &&
524          "Expected InnerLoop VPlan CFG to terminate with unreachable");
525   assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) &&
526          "Expected VPlan CFG to terminate with branch in NativePath");
527   LastBB->getTerminator()->eraseFromParent();
528   BranchInst::Create(VectorLatchBB, LastBB);
529 
530   // Merge LastBB with Latch.
531   bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI);
532   (void)Merged;
533   assert(Merged && "Could not merge last basic block with latch.");
534   VectorLatchBB = LastBB;
535 
536   // We do not attempt to preserve DT for outer loop vectorization currently.
537   if (!EnableVPlanNativePath)
538     updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB,
539                         L->getExitBlock());
540 }
541 
542 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
543 LLVM_DUMP_METHOD
544 void VPlan::dump() const { dbgs() << *this << '\n'; }
545 #endif
546 
547 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB,
548                                 BasicBlock *LoopLatchBB,
549                                 BasicBlock *LoopExitBB) {
550   BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor();
551   assert(LoopHeaderBB && "Loop preheader does not have a single successor.");
552   // The vector body may be more than a single basic-block by this point.
553   // Update the dominator tree information inside the vector body by propagating
554   // it from header to latch, expecting only triangular control-flow, if any.
555   BasicBlock *PostDomSucc = nullptr;
556   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
557     // Get the list of successors of this block.
558     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
559     assert(Succs.size() <= 2 &&
560            "Basic block in vector loop has more than 2 successors.");
561     PostDomSucc = Succs[0];
562     if (Succs.size() == 1) {
563       assert(PostDomSucc->getSinglePredecessor() &&
564              "PostDom successor has more than one predecessor.");
565       DT->addNewBlock(PostDomSucc, BB);
566       continue;
567     }
568     BasicBlock *InterimSucc = Succs[1];
569     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
570       PostDomSucc = Succs[1];
571       InterimSucc = Succs[0];
572     }
573     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
574            "One successor of a basic block does not lead to the other.");
575     assert(InterimSucc->getSinglePredecessor() &&
576            "Interim successor has more than one predecessor.");
577     assert(PostDomSucc->hasNPredecessors(2) &&
578            "PostDom successor has more than two predecessors.");
579     DT->addNewBlock(InterimSucc, BB);
580     DT->addNewBlock(PostDomSucc, BB);
581   }
582   // Latch block is a new dominator for the loop exit.
583   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
584   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
585 }
586 
587 const Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
588   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
589          Twine(getOrCreateBID(Block));
590 }
591 
592 const Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
593   const std::string &Name = Block->getName();
594   if (!Name.empty())
595     return Name;
596   return "VPB" + Twine(getOrCreateBID(Block));
597 }
598 
599 void VPlanPrinter::dump() {
600   Depth = 1;
601   bumpIndent(0);
602   OS << "digraph VPlan {\n";
603   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
604   if (!Plan.getName().empty())
605     OS << "\\n" << DOT::EscapeString(Plan.getName());
606   if (Plan.BackedgeTakenCount) {
607     OS << ", where:\\n";
608     Plan.BackedgeTakenCount->print(OS, SlotTracker);
609     OS << " := BackedgeTakenCount";
610   }
611   OS << "\"]\n";
612   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
613   OS << "edge [fontname=Courier, fontsize=30]\n";
614   OS << "compound=true\n";
615 
616   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
617     dumpBlock(Block);
618 
619   OS << "}\n";
620 }
621 
622 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
623   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
624     dumpBasicBlock(BasicBlock);
625   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
626     dumpRegion(Region);
627   else
628     llvm_unreachable("Unsupported kind of VPBlock.");
629 }
630 
631 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
632                             bool Hidden, const Twine &Label) {
633   // Due to "dot" we print an edge between two regions as an edge between the
634   // exit basic block and the entry basic of the respective regions.
635   const VPBlockBase *Tail = From->getExitBasicBlock();
636   const VPBlockBase *Head = To->getEntryBasicBlock();
637   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
638   OS << " [ label=\"" << Label << '\"';
639   if (Tail != From)
640     OS << " ltail=" << getUID(From);
641   if (Head != To)
642     OS << " lhead=" << getUID(To);
643   if (Hidden)
644     OS << "; splines=none";
645   OS << "]\n";
646 }
647 
648 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
649   auto &Successors = Block->getSuccessors();
650   if (Successors.size() == 1)
651     drawEdge(Block, Successors.front(), false, "");
652   else if (Successors.size() == 2) {
653     drawEdge(Block, Successors.front(), false, "T");
654     drawEdge(Block, Successors.back(), false, "F");
655   } else {
656     unsigned SuccessorNumber = 0;
657     for (auto *Successor : Successors)
658       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
659   }
660 }
661 
662 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
663   OS << Indent << getUID(BasicBlock) << " [label =\n";
664   bumpIndent(1);
665   OS << Indent << "\"" << DOT::EscapeString(BasicBlock->getName()) << ":\\n\"";
666   bumpIndent(1);
667 
668   // Dump the block predicate.
669   const VPValue *Pred = BasicBlock->getPredicate();
670   if (Pred) {
671     OS << " +\n" << Indent << " \"BlockPredicate: ";
672     if (const VPInstruction *PredI = dyn_cast<VPInstruction>(Pred)) {
673       PredI->printAsOperand(OS, SlotTracker);
674       OS << " (" << DOT::EscapeString(PredI->getParent()->getName())
675          << ")\\l\"";
676     } else
677       Pred->printAsOperand(OS, SlotTracker);
678   }
679 
680   for (const VPRecipeBase &Recipe : *BasicBlock) {
681     OS << " +\n" << Indent;
682     Recipe.print(OS, Indent, SlotTracker);
683     OS << "\\l\"";
684   }
685 
686   // Dump the condition bit.
687   const VPValue *CBV = BasicBlock->getCondBit();
688   if (CBV) {
689     OS << " +\n" << Indent << " \"CondBit: ";
690     if (const VPInstruction *CBI = dyn_cast<VPInstruction>(CBV)) {
691       CBI->printAsOperand(OS, SlotTracker);
692       OS << " (" << DOT::EscapeString(CBI->getParent()->getName()) << ")\\l\"";
693     } else {
694       CBV->printAsOperand(OS, SlotTracker);
695       OS << "\"";
696     }
697   }
698 
699   bumpIndent(-2);
700   OS << "\n" << Indent << "]\n";
701   dumpEdges(BasicBlock);
702 }
703 
704 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
705   OS << Indent << "subgraph " << getUID(Region) << " {\n";
706   bumpIndent(1);
707   OS << Indent << "fontname=Courier\n"
708      << Indent << "label=\""
709      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
710      << DOT::EscapeString(Region->getName()) << "\"\n";
711   // Dump the blocks of the region.
712   assert(Region->getEntry() && "Region contains no inner blocks.");
713   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
714     dumpBlock(Block);
715   bumpIndent(-1);
716   OS << Indent << "}\n";
717   dumpEdges(Region);
718 }
719 
720 void VPlanPrinter::printAsIngredient(raw_ostream &O, Value *V) {
721   std::string IngredientString;
722   raw_string_ostream RSO(IngredientString);
723   if (auto *Inst = dyn_cast<Instruction>(V)) {
724     if (!Inst->getType()->isVoidTy()) {
725       Inst->printAsOperand(RSO, false);
726       RSO << " = ";
727     }
728     RSO << Inst->getOpcodeName() << " ";
729     unsigned E = Inst->getNumOperands();
730     if (E > 0) {
731       Inst->getOperand(0)->printAsOperand(RSO, false);
732       for (unsigned I = 1; I < E; ++I)
733         Inst->getOperand(I)->printAsOperand(RSO << ", ", false);
734     }
735   } else // !Inst
736     V->printAsOperand(RSO, false);
737   RSO.flush();
738   O << DOT::EscapeString(IngredientString);
739 }
740 
741 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent,
742                               VPSlotTracker &SlotTracker) const {
743   O << "\"WIDEN-CALL " << VPlanIngredient(&Ingredient);
744 }
745 
746 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent,
747                                 VPSlotTracker &SlotTracker) const {
748   O << "\"WIDEN-SELECT" << VPlanIngredient(&Ingredient)
749     << (InvariantCond ? " (condition is loop invariant)" : "");
750 }
751 
752 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent,
753                           VPSlotTracker &SlotTracker) const {
754   O << "\"WIDEN\\l\"";
755   O << "\"  " << VPlanIngredient(&Ingredient);
756 }
757 
758 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent,
759                                           VPSlotTracker &SlotTracker) const {
760   O << "\"WIDEN-INDUCTION";
761   if (Trunc) {
762     O << "\\l\"";
763     O << " +\n" << Indent << "\"  " << VPlanIngredient(IV) << "\\l\"";
764     O << " +\n" << Indent << "\"  " << VPlanIngredient(Trunc);
765   } else
766     O << " " << VPlanIngredient(IV);
767 }
768 
769 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent,
770                              VPSlotTracker &SlotTracker) const {
771   O << "\"WIDEN-GEP ";
772   O << (IsPtrLoopInvariant ? "Inv" : "Var");
773   size_t IndicesNumber = IsIndexLoopInvariant.size();
774   for (size_t I = 0; I < IndicesNumber; ++I)
775     O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]";
776   O << "\\l\"";
777   O << " +\n" << Indent << "\"  " << VPlanIngredient(GEP);
778 }
779 
780 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent,
781                              VPSlotTracker &SlotTracker) const {
782   O << "\"WIDEN-PHI " << VPlanIngredient(Phi);
783 }
784 
785 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent,
786                           VPSlotTracker &SlotTracker) const {
787   O << "\"BLEND ";
788   Phi->printAsOperand(O, false);
789   O << " =";
790   if (getNumIncomingValues() == 1) {
791     // Not a User of any mask: not really blending, this is a
792     // single-predecessor phi.
793     O << " ";
794     getIncomingValue(0)->printAsOperand(O, SlotTracker);
795   } else {
796     for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
797       O << " ";
798       getIncomingValue(I)->printAsOperand(O, SlotTracker);
799       O << "/";
800       getMask(I)->printAsOperand(O, SlotTracker);
801     }
802   }
803 }
804 
805 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent,
806                               VPSlotTracker &SlotTracker) const {
807   O << "\"REDUCE of" << *I << " as ";
808   ChainOp->printAsOperand(O, SlotTracker);
809   O << " + reduce(";
810   VecOp->printAsOperand(O, SlotTracker);
811   O << ")";
812 }
813 
814 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent,
815                               VPSlotTracker &SlotTracker) const {
816   O << "\"" << (IsUniform ? "CLONE " : "REPLICATE ")
817     << VPlanIngredient(Ingredient);
818   if (AlsoPack)
819     O << " (S->V)";
820 }
821 
822 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent,
823                                 VPSlotTracker &SlotTracker) const {
824   O << "\"PHI-PREDICATED-INSTRUCTION " << VPlanIngredient(PredInst);
825 }
826 
827 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent,
828                                            VPSlotTracker &SlotTracker) const {
829   O << "\"WIDEN " << VPlanIngredient(&Instr);
830   O << ", ";
831   getAddr()->printAsOperand(O, SlotTracker);
832   VPValue *Mask = getMask();
833   if (Mask) {
834     O << ", ";
835     Mask->printAsOperand(O, SlotTracker);
836   }
837 }
838 
839 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) {
840   Value *CanonicalIV = State.CanonicalIV;
841   Type *STy = CanonicalIV->getType();
842   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
843   ElementCount VF = State.VF;
844   assert(!VF.isScalable() && "the code following assumes non scalables ECs");
845   Value *VStart = VF.isScalar()
846                       ? CanonicalIV
847                       : Builder.CreateVectorSplat(VF.getKnownMinValue(),
848                                                   CanonicalIV, "broadcast");
849   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) {
850     SmallVector<Constant *, 8> Indices;
851     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
852       Indices.push_back(
853           ConstantInt::get(STy, Part * VF.getKnownMinValue() + Lane));
854     // If VF == 1, there is only one iteration in the loop above, thus the
855     // element pushed back into Indices is ConstantInt::get(STy, Part)
856     Constant *VStep = VF == 1 ? Indices.back() : ConstantVector::get(Indices);
857     // Add the consecutive indices to the vector value.
858     Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
859     State.set(getVPValue(), CanonicalVectorIV, Part);
860   }
861 }
862 
863 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent,
864                                      VPSlotTracker &SlotTracker) const {
865   O << "\"EMIT ";
866   getVPValue()->printAsOperand(O, SlotTracker);
867   O << " = WIDEN-CANONICAL-INDUCTION";
868 }
869 
870 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
871 
872 void VPValue::replaceAllUsesWith(VPValue *New) {
873   for (VPUser *User : users())
874     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
875       if (User->getOperand(I) == this)
876         User->setOperand(I, New);
877 }
878 
879 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
880   if (const Value *UV = getUnderlyingValue()) {
881     OS << "ir<";
882     UV->printAsOperand(OS, false);
883     OS << ">";
884     return;
885   }
886 
887   unsigned Slot = Tracker.getSlot(this);
888   if (Slot == unsigned(-1))
889     OS << "<badref>";
890   else
891     OS << "vp<%" << Tracker.getSlot(this) << ">";
892 }
893 
894 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
895                                           Old2NewTy &Old2New,
896                                           InterleavedAccessInfo &IAI) {
897   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
898   for (VPBlockBase *Base : RPOT) {
899     visitBlock(Base, Old2New, IAI);
900   }
901 }
902 
903 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
904                                          InterleavedAccessInfo &IAI) {
905   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
906     for (VPRecipeBase &VPI : *VPBB) {
907       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
908       auto *VPInst = cast<VPInstruction>(&VPI);
909       auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue());
910       auto *IG = IAI.getInterleaveGroup(Inst);
911       if (!IG)
912         continue;
913 
914       auto NewIGIter = Old2New.find(IG);
915       if (NewIGIter == Old2New.end())
916         Old2New[IG] = new InterleaveGroup<VPInstruction>(
917             IG->getFactor(), IG->isReverse(), IG->getAlign());
918 
919       if (Inst == IG->getInsertPos())
920         Old2New[IG]->setInsertPos(VPInst);
921 
922       InterleaveGroupMap[VPInst] = Old2New[IG];
923       InterleaveGroupMap[VPInst]->insertMember(
924           VPInst, IG->getIndex(Inst),
925           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
926                                 : IG->getFactor()));
927     }
928   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
929     visitRegion(Region, Old2New, IAI);
930   else
931     llvm_unreachable("Unsupported kind of VPBlock.");
932 }
933 
934 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
935                                                  InterleavedAccessInfo &IAI) {
936   Old2NewTy Old2New;
937   visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI);
938 }
939 
940 void VPSlotTracker::assignSlot(const VPValue *V) {
941   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
942   const Value *UV = V->getUnderlyingValue();
943   if (UV)
944     return;
945   const auto *VPI = dyn_cast<VPInstruction>(V);
946   if (VPI && !VPI->hasResult())
947     return;
948 
949   Slots[V] = NextSlot++;
950 }
951 
952 void VPSlotTracker::assignSlots(const VPBlockBase *VPBB) {
953   if (auto *Region = dyn_cast<VPRegionBlock>(VPBB))
954     assignSlots(Region);
955   else
956     assignSlots(cast<VPBasicBlock>(VPBB));
957 }
958 
959 void VPSlotTracker::assignSlots(const VPRegionBlock *Region) {
960   ReversePostOrderTraversal<const VPBlockBase *> RPOT(Region->getEntry());
961   for (const VPBlockBase *Block : RPOT)
962     assignSlots(Block);
963 }
964 
965 void VPSlotTracker::assignSlots(const VPBasicBlock *VPBB) {
966   for (const VPRecipeBase &Recipe : *VPBB) {
967     if (const auto *VPI = dyn_cast<VPInstruction>(&Recipe))
968       assignSlot(VPI);
969     else if (const auto *VPIV = dyn_cast<VPWidenCanonicalIVRecipe>(&Recipe))
970       assignSlot(VPIV->getVPValue());
971   }
972 }
973 
974 void VPSlotTracker::assignSlots(const VPlan &Plan) {
975 
976   for (const VPValue *V : Plan.VPExternalDefs)
977     assignSlot(V);
978 
979   for (auto &E : Plan.Value2VPValue)
980     if (!isa<VPInstruction>(E.second))
981       assignSlot(E.second);
982 
983   for (const VPValue *V : Plan.VPCBVs)
984     assignSlot(V);
985 
986   if (Plan.BackedgeTakenCount)
987     assignSlot(Plan.BackedgeTakenCount);
988 
989   ReversePostOrderTraversal<const VPBlockBase *> RPOT(Plan.getEntry());
990   for (const VPBlockBase *Block : RPOT)
991     assignSlots(Block);
992 }
993