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