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