xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision a94497a34290bea077398c83d3031179c08ec2e7)
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 VPRecipeBase::moveBefore(VPBasicBlock &BB,
437                               iplist<VPRecipeBase>::iterator I) {
438   assert(I == BB.end() || I->getParent() == &BB);
439   removeFromParent();
440   Parent = &BB;
441   BB.getRecipeList().insert(I, this);
442 }
443 
444 void VPInstruction::generateInstruction(VPTransformState &State,
445                                         unsigned Part) {
446   IRBuilder<> &Builder = State.Builder;
447 
448   if (Instruction::isBinaryOp(getOpcode())) {
449     Value *A = State.get(getOperand(0), Part);
450     Value *B = State.get(getOperand(1), Part);
451     Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B);
452     State.set(this, V, Part);
453     return;
454   }
455 
456   switch (getOpcode()) {
457   case VPInstruction::Not: {
458     Value *A = State.get(getOperand(0), Part);
459     Value *V = Builder.CreateNot(A);
460     State.set(this, V, Part);
461     break;
462   }
463   case VPInstruction::ICmpULE: {
464     Value *IV = State.get(getOperand(0), Part);
465     Value *TC = State.get(getOperand(1), Part);
466     Value *V = Builder.CreateICmpULE(IV, TC);
467     State.set(this, V, Part);
468     break;
469   }
470   case Instruction::Select: {
471     Value *Cond = State.get(getOperand(0), Part);
472     Value *Op1 = State.get(getOperand(1), Part);
473     Value *Op2 = State.get(getOperand(2), Part);
474     Value *V = Builder.CreateSelect(Cond, Op1, Op2);
475     State.set(this, V, Part);
476     break;
477   }
478   case VPInstruction::ActiveLaneMask: {
479     // Get first lane of vector induction variable.
480     Value *VIVElem0 = State.get(getOperand(0), {Part, 0});
481     // Get the original loop tripcount.
482     Value *ScalarTC = State.TripCount;
483 
484     auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
485     auto *PredTy = FixedVectorType::get(Int1Ty, State.VF.getKnownMinValue());
486     Instruction *Call = Builder.CreateIntrinsic(
487         Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()},
488         {VIVElem0, ScalarTC}, nullptr, "active.lane.mask");
489     State.set(this, Call, Part);
490     break;
491   }
492   default:
493     llvm_unreachable("Unsupported opcode for instruction");
494   }
495 }
496 
497 void VPInstruction::execute(VPTransformState &State) {
498   assert(!State.Instance && "VPInstruction executing an Instance");
499   for (unsigned Part = 0; Part < State.UF; ++Part)
500     generateInstruction(State, Part);
501 }
502 
503 void VPInstruction::print(raw_ostream &O, const Twine &Indent,
504                           VPSlotTracker &SlotTracker) const {
505   O << "EMIT ";
506   print(O, SlotTracker);
507 }
508 
509 void VPInstruction::print(raw_ostream &O) const {
510   VPSlotTracker SlotTracker(getParent()->getPlan());
511   print(O, SlotTracker);
512 }
513 
514 void VPInstruction::print(raw_ostream &O, VPSlotTracker &SlotTracker) const {
515   if (hasResult()) {
516     printAsOperand(O, SlotTracker);
517     O << " = ";
518   }
519 
520   switch (getOpcode()) {
521   case VPInstruction::Not:
522     O << "not";
523     break;
524   case VPInstruction::ICmpULE:
525     O << "icmp ule";
526     break;
527   case VPInstruction::SLPLoad:
528     O << "combined load";
529     break;
530   case VPInstruction::SLPStore:
531     O << "combined store";
532     break;
533   case VPInstruction::ActiveLaneMask:
534     O << "active lane mask";
535     break;
536 
537   default:
538     O << Instruction::getOpcodeName(getOpcode());
539   }
540 
541   for (const VPValue *Operand : operands()) {
542     O << " ";
543     Operand->printAsOperand(O, SlotTracker);
544   }
545 }
546 
547 /// Generate the code inside the body of the vectorized loop. Assumes a single
548 /// LoopVectorBody basic-block was created for this. Introduce additional
549 /// basic-blocks as needed, and fill them all.
550 void VPlan::execute(VPTransformState *State) {
551   // -1. Check if the backedge taken count is needed, and if so build it.
552   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
553     Value *TC = State->TripCount;
554     IRBuilder<> Builder(State->CFG.PrevBB->getTerminator());
555     auto *TCMO = Builder.CreateSub(TC, ConstantInt::get(TC->getType(), 1),
556                                    "trip.count.minus.1");
557     auto VF = State->VF;
558     Value *VTCMO =
559         VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
560     for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part)
561       State->set(BackedgeTakenCount, VTCMO, Part);
562   }
563 
564   // 0. Set the reverse mapping from VPValues to Values for code generation.
565   for (auto &Entry : Value2VPValue)
566     State->VPValue2Value[Entry.second] = Entry.first;
567 
568   BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB;
569   BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor();
570   assert(VectorHeaderBB && "Loop preheader does not have a single successor.");
571 
572   // 1. Make room to generate basic-blocks inside loop body if needed.
573   BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock(
574       VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch");
575   Loop *L = State->LI->getLoopFor(VectorHeaderBB);
576   L->addBasicBlockToLoop(VectorLatchBB, *State->LI);
577   // Remove the edge between Header and Latch to allow other connections.
578   // Temporarily terminate with unreachable until CFG is rewired.
579   // Note: this asserts the generated code's assumption that
580   // getFirstInsertionPt() can be dereferenced into an Instruction.
581   VectorHeaderBB->getTerminator()->eraseFromParent();
582   State->Builder.SetInsertPoint(VectorHeaderBB);
583   UnreachableInst *Terminator = State->Builder.CreateUnreachable();
584   State->Builder.SetInsertPoint(Terminator);
585 
586   // 2. Generate code in loop body.
587   State->CFG.PrevVPBB = nullptr;
588   State->CFG.PrevBB = VectorHeaderBB;
589   State->CFG.LastBB = VectorLatchBB;
590 
591   for (VPBlockBase *Block : depth_first(Entry))
592     Block->execute(State);
593 
594   // Setup branch terminator successors for VPBBs in VPBBsToFix based on
595   // VPBB's successors.
596   for (auto VPBB : State->CFG.VPBBsToFix) {
597     assert(EnableVPlanNativePath &&
598            "Unexpected VPBBsToFix in non VPlan-native path");
599     BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
600     assert(BB && "Unexpected null basic block for VPBB");
601 
602     unsigned Idx = 0;
603     auto *BBTerminator = BB->getTerminator();
604 
605     for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
606       VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
607       BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
608       ++Idx;
609     }
610   }
611 
612   // 3. Merge the temporary latch created with the last basic-block filled.
613   BasicBlock *LastBB = State->CFG.PrevBB;
614   // Connect LastBB to VectorLatchBB to facilitate their merge.
615   assert((EnableVPlanNativePath ||
616           isa<UnreachableInst>(LastBB->getTerminator())) &&
617          "Expected InnerLoop VPlan CFG to terminate with unreachable");
618   assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) &&
619          "Expected VPlan CFG to terminate with branch in NativePath");
620   LastBB->getTerminator()->eraseFromParent();
621   BranchInst::Create(VectorLatchBB, LastBB);
622 
623   // Merge LastBB with Latch.
624   bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI);
625   (void)Merged;
626   assert(Merged && "Could not merge last basic block with latch.");
627   VectorLatchBB = LastBB;
628 
629   // We do not attempt to preserve DT for outer loop vectorization currently.
630   if (!EnableVPlanNativePath)
631     updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB,
632                         L->getExitBlock());
633 }
634 
635 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
636 LLVM_DUMP_METHOD
637 void VPlan::dump() const { dbgs() << *this << '\n'; }
638 #endif
639 
640 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB,
641                                 BasicBlock *LoopLatchBB,
642                                 BasicBlock *LoopExitBB) {
643   BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor();
644   assert(LoopHeaderBB && "Loop preheader does not have a single successor.");
645   // The vector body may be more than a single basic-block by this point.
646   // Update the dominator tree information inside the vector body by propagating
647   // it from header to latch, expecting only triangular control-flow, if any.
648   BasicBlock *PostDomSucc = nullptr;
649   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
650     // Get the list of successors of this block.
651     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
652     assert(Succs.size() <= 2 &&
653            "Basic block in vector loop has more than 2 successors.");
654     PostDomSucc = Succs[0];
655     if (Succs.size() == 1) {
656       assert(PostDomSucc->getSinglePredecessor() &&
657              "PostDom successor has more than one predecessor.");
658       DT->addNewBlock(PostDomSucc, BB);
659       continue;
660     }
661     BasicBlock *InterimSucc = Succs[1];
662     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
663       PostDomSucc = Succs[1];
664       InterimSucc = Succs[0];
665     }
666     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
667            "One successor of a basic block does not lead to the other.");
668     assert(InterimSucc->getSinglePredecessor() &&
669            "Interim successor has more than one predecessor.");
670     assert(PostDomSucc->hasNPredecessors(2) &&
671            "PostDom successor has more than two predecessors.");
672     DT->addNewBlock(InterimSucc, BB);
673     DT->addNewBlock(PostDomSucc, BB);
674   }
675   // Latch block is a new dominator for the loop exit.
676   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
677   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
678 }
679 
680 const Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
681   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
682          Twine(getOrCreateBID(Block));
683 }
684 
685 const Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
686   const std::string &Name = Block->getName();
687   if (!Name.empty())
688     return Name;
689   return "VPB" + Twine(getOrCreateBID(Block));
690 }
691 
692 void VPlanPrinter::dump() {
693   Depth = 1;
694   bumpIndent(0);
695   OS << "digraph VPlan {\n";
696   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
697   if (!Plan.getName().empty())
698     OS << "\\n" << DOT::EscapeString(Plan.getName());
699   if (Plan.BackedgeTakenCount) {
700     OS << ", where:\\n";
701     Plan.BackedgeTakenCount->print(OS, SlotTracker);
702     OS << " := BackedgeTakenCount";
703   }
704   OS << "\"]\n";
705   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
706   OS << "edge [fontname=Courier, fontsize=30]\n";
707   OS << "compound=true\n";
708 
709   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
710     dumpBlock(Block);
711 
712   OS << "}\n";
713 }
714 
715 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
716   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
717     dumpBasicBlock(BasicBlock);
718   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
719     dumpRegion(Region);
720   else
721     llvm_unreachable("Unsupported kind of VPBlock.");
722 }
723 
724 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
725                             bool Hidden, const Twine &Label) {
726   // Due to "dot" we print an edge between two regions as an edge between the
727   // exit basic block and the entry basic of the respective regions.
728   const VPBlockBase *Tail = From->getExitBasicBlock();
729   const VPBlockBase *Head = To->getEntryBasicBlock();
730   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
731   OS << " [ label=\"" << Label << '\"';
732   if (Tail != From)
733     OS << " ltail=" << getUID(From);
734   if (Head != To)
735     OS << " lhead=" << getUID(To);
736   if (Hidden)
737     OS << "; splines=none";
738   OS << "]\n";
739 }
740 
741 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
742   auto &Successors = Block->getSuccessors();
743   if (Successors.size() == 1)
744     drawEdge(Block, Successors.front(), false, "");
745   else if (Successors.size() == 2) {
746     drawEdge(Block, Successors.front(), false, "T");
747     drawEdge(Block, Successors.back(), false, "F");
748   } else {
749     unsigned SuccessorNumber = 0;
750     for (auto *Successor : Successors)
751       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
752   }
753 }
754 
755 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
756   OS << Indent << getUID(BasicBlock) << " [label =\n";
757   bumpIndent(1);
758   OS << Indent << "\"" << DOT::EscapeString(BasicBlock->getName()) << ":\\n\"";
759   bumpIndent(1);
760 
761   // Dump the block predicate.
762   const VPValue *Pred = BasicBlock->getPredicate();
763   if (Pred) {
764     OS << " +\n" << Indent << " \"BlockPredicate: \"";
765     if (const VPInstruction *PredI = dyn_cast<VPInstruction>(Pred)) {
766       PredI->printAsOperand(OS, SlotTracker);
767       OS << " (" << DOT::EscapeString(PredI->getParent()->getName())
768          << ")\\l\"";
769     } else
770       Pred->printAsOperand(OS, SlotTracker);
771   }
772 
773   for (const VPRecipeBase &Recipe : *BasicBlock) {
774     OS << " +\n" << Indent << "\"";
775     Recipe.print(OS, Indent, SlotTracker);
776     OS << "\\l\"";
777   }
778 
779   // Dump the condition bit.
780   const VPValue *CBV = BasicBlock->getCondBit();
781   if (CBV) {
782     OS << " +\n" << Indent << " \"CondBit: ";
783     if (const VPInstruction *CBI = dyn_cast<VPInstruction>(CBV)) {
784       CBI->printAsOperand(OS, SlotTracker);
785       OS << " (" << DOT::EscapeString(CBI->getParent()->getName()) << ")\\l\"";
786     } else {
787       CBV->printAsOperand(OS, SlotTracker);
788       OS << "\"";
789     }
790   }
791 
792   bumpIndent(-2);
793   OS << "\n" << Indent << "]\n";
794   dumpEdges(BasicBlock);
795 }
796 
797 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
798   OS << Indent << "subgraph " << getUID(Region) << " {\n";
799   bumpIndent(1);
800   OS << Indent << "fontname=Courier\n"
801      << Indent << "label=\""
802      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
803      << DOT::EscapeString(Region->getName()) << "\"\n";
804   // Dump the blocks of the region.
805   assert(Region->getEntry() && "Region contains no inner blocks.");
806   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
807     dumpBlock(Block);
808   bumpIndent(-1);
809   OS << Indent << "}\n";
810   dumpEdges(Region);
811 }
812 
813 void VPlanPrinter::printAsIngredient(raw_ostream &O, const Value *V) {
814   std::string IngredientString;
815   raw_string_ostream RSO(IngredientString);
816   if (auto *Inst = dyn_cast<Instruction>(V)) {
817     if (!Inst->getType()->isVoidTy()) {
818       Inst->printAsOperand(RSO, false);
819       RSO << " = ";
820     }
821     RSO << Inst->getOpcodeName() << " ";
822     unsigned E = Inst->getNumOperands();
823     if (E > 0) {
824       Inst->getOperand(0)->printAsOperand(RSO, false);
825       for (unsigned I = 1; I < E; ++I)
826         Inst->getOperand(I)->printAsOperand(RSO << ", ", false);
827     }
828   } else // !Inst
829     V->printAsOperand(RSO, false);
830   RSO.flush();
831   O << DOT::EscapeString(IngredientString);
832 }
833 
834 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent,
835                               VPSlotTracker &SlotTracker) const {
836   O << "WIDEN-CALL ";
837 
838   auto *CI = cast<CallInst>(getUnderlyingInstr());
839   if (CI->getType()->isVoidTy())
840     O << "void ";
841   else {
842     printAsOperand(O, SlotTracker);
843     O << " = ";
844   }
845 
846   O << "call @" << CI->getCalledFunction()->getName() << "(";
847   printOperands(O, SlotTracker);
848   O << ")";
849 }
850 
851 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent,
852                                 VPSlotTracker &SlotTracker) const {
853   O << "WIDEN-SELECT ";
854   printAsOperand(O, SlotTracker);
855   O << " = select ";
856   getOperand(0)->printAsOperand(O, SlotTracker);
857   O << ", ";
858   getOperand(1)->printAsOperand(O, SlotTracker);
859   O << ", ";
860   getOperand(2)->printAsOperand(O, SlotTracker);
861   O << (InvariantCond ? " (condition is loop invariant)" : "");
862 }
863 
864 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent,
865                           VPSlotTracker &SlotTracker) const {
866   O << "WIDEN ";
867   printAsOperand(O, SlotTracker);
868   O << " = " << getUnderlyingInstr()->getOpcodeName() << " ";
869   printOperands(O, SlotTracker);
870 }
871 
872 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent,
873                                           VPSlotTracker &SlotTracker) const {
874   O << "WIDEN-INDUCTION";
875   if (Trunc) {
876     O << "\\l\"";
877     O << " +\n" << Indent << "\"  " << VPlanIngredient(IV) << "\\l\"";
878     O << " +\n" << Indent << "\"  " << VPlanIngredient(Trunc);
879   } else
880     O << " " << VPlanIngredient(IV);
881 }
882 
883 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent,
884                              VPSlotTracker &SlotTracker) const {
885   O << "WIDEN-GEP ";
886   O << (IsPtrLoopInvariant ? "Inv" : "Var");
887   size_t IndicesNumber = IsIndexLoopInvariant.size();
888   for (size_t I = 0; I < IndicesNumber; ++I)
889     O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]";
890 
891   O << " ";
892   printAsOperand(O, SlotTracker);
893   O << " = getelementptr ";
894   printOperands(O, SlotTracker);
895 }
896 
897 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent,
898                              VPSlotTracker &SlotTracker) const {
899   O << "WIDEN-PHI " << VPlanIngredient(Phi);
900 }
901 
902 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent,
903                           VPSlotTracker &SlotTracker) const {
904   O << "BLEND ";
905   Phi->printAsOperand(O, false);
906   O << " =";
907   if (getNumIncomingValues() == 1) {
908     // Not a User of any mask: not really blending, this is a
909     // single-predecessor phi.
910     O << " ";
911     getIncomingValue(0)->printAsOperand(O, SlotTracker);
912   } else {
913     for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
914       O << " ";
915       getIncomingValue(I)->printAsOperand(O, SlotTracker);
916       O << "/";
917       getMask(I)->printAsOperand(O, SlotTracker);
918     }
919   }
920 }
921 
922 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent,
923                               VPSlotTracker &SlotTracker) const {
924   O << "REDUCE ";
925   printAsOperand(O, SlotTracker);
926   O << " = ";
927   getChainOp()->printAsOperand(O, SlotTracker);
928   O << " + reduce." << Instruction::getOpcodeName(RdxDesc->getOpcode())
929     << " (";
930   getVecOp()->printAsOperand(O, SlotTracker);
931   if (getCondOp()) {
932     O << ", ";
933     getCondOp()->printAsOperand(O, SlotTracker);
934   }
935   O << ")";
936 }
937 
938 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent,
939                               VPSlotTracker &SlotTracker) const {
940   O << (IsUniform ? "CLONE " : "REPLICATE ");
941 
942   if (!getUnderlyingInstr()->getType()->isVoidTy()) {
943     printAsOperand(O, SlotTracker);
944     O << " = ";
945   }
946   O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " ";
947   printOperands(O, SlotTracker);
948 
949   if (AlsoPack)
950     O << " (S->V)";
951 }
952 
953 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent,
954                                 VPSlotTracker &SlotTracker) const {
955   O << "PHI-PREDICATED-INSTRUCTION ";
956   printOperands(O, SlotTracker);
957 }
958 
959 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent,
960                                            VPSlotTracker &SlotTracker) const {
961   O << "WIDEN ";
962 
963   if (!isStore()) {
964     getVPValue()->printAsOperand(O, SlotTracker);
965     O << " = ";
966   }
967   O << Instruction::getOpcodeName(Ingredient.getOpcode()) << " ";
968 
969   printOperands(O, SlotTracker);
970 }
971 
972 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) {
973   Value *CanonicalIV = State.CanonicalIV;
974   Type *STy = CanonicalIV->getType();
975   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
976   ElementCount VF = State.VF;
977   assert(!VF.isScalable() && "the code following assumes non scalables ECs");
978   Value *VStart = VF.isScalar()
979                       ? CanonicalIV
980                       : Builder.CreateVectorSplat(VF.getKnownMinValue(),
981                                                   CanonicalIV, "broadcast");
982   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) {
983     SmallVector<Constant *, 8> Indices;
984     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
985       Indices.push_back(
986           ConstantInt::get(STy, Part * VF.getKnownMinValue() + Lane));
987     // If VF == 1, there is only one iteration in the loop above, thus the
988     // element pushed back into Indices is ConstantInt::get(STy, Part)
989     Constant *VStep =
990         VF.isScalar() ? Indices.back() : ConstantVector::get(Indices);
991     // Add the consecutive indices to the vector value.
992     Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
993     State.set(getVPValue(), CanonicalVectorIV, Part);
994   }
995 }
996 
997 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent,
998                                      VPSlotTracker &SlotTracker) const {
999   O << "EMIT ";
1000   getVPValue()->printAsOperand(O, SlotTracker);
1001   O << " = WIDEN-CANONICAL-INDUCTION";
1002 }
1003 
1004 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
1005 
1006 void VPValue::replaceAllUsesWith(VPValue *New) {
1007   for (unsigned J = 0; J < getNumUsers();) {
1008     VPUser *User = Users[J];
1009     unsigned NumUsers = getNumUsers();
1010     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
1011       if (User->getOperand(I) == this)
1012         User->setOperand(I, New);
1013     // If a user got removed after updating the current user, the next user to
1014     // update will be moved to the current position, so we only need to
1015     // increment the index if the number of users did not change.
1016     if (NumUsers == getNumUsers())
1017       J++;
1018   }
1019 }
1020 
1021 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1022   if (const Value *UV = getUnderlyingValue()) {
1023     OS << "ir<";
1024     UV->printAsOperand(OS, false);
1025     OS << ">";
1026     return;
1027   }
1028 
1029   unsigned Slot = Tracker.getSlot(this);
1030   if (Slot == unsigned(-1))
1031     OS << "<badref>";
1032   else
1033     OS << "vp<%" << Tracker.getSlot(this) << ">";
1034 }
1035 
1036 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1037   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1038     Op->printAsOperand(O, SlotTracker);
1039   });
1040 }
1041 
1042 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1043                                           Old2NewTy &Old2New,
1044                                           InterleavedAccessInfo &IAI) {
1045   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
1046   for (VPBlockBase *Base : RPOT) {
1047     visitBlock(Base, Old2New, IAI);
1048   }
1049 }
1050 
1051 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1052                                          InterleavedAccessInfo &IAI) {
1053   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1054     for (VPRecipeBase &VPI : *VPBB) {
1055       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1056       auto *VPInst = cast<VPInstruction>(&VPI);
1057       auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue());
1058       auto *IG = IAI.getInterleaveGroup(Inst);
1059       if (!IG)
1060         continue;
1061 
1062       auto NewIGIter = Old2New.find(IG);
1063       if (NewIGIter == Old2New.end())
1064         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1065             IG->getFactor(), IG->isReverse(), IG->getAlign());
1066 
1067       if (Inst == IG->getInsertPos())
1068         Old2New[IG]->setInsertPos(VPInst);
1069 
1070       InterleaveGroupMap[VPInst] = Old2New[IG];
1071       InterleaveGroupMap[VPInst]->insertMember(
1072           VPInst, IG->getIndex(Inst),
1073           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1074                                 : IG->getFactor()));
1075     }
1076   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1077     visitRegion(Region, Old2New, IAI);
1078   else
1079     llvm_unreachable("Unsupported kind of VPBlock.");
1080 }
1081 
1082 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1083                                                  InterleavedAccessInfo &IAI) {
1084   Old2NewTy Old2New;
1085   visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI);
1086 }
1087 
1088 void VPSlotTracker::assignSlot(const VPValue *V) {
1089   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
1090   const Value *UV = V->getUnderlyingValue();
1091   if (UV)
1092     return;
1093   const auto *VPI = dyn_cast<VPInstruction>(V);
1094   if (VPI && !VPI->hasResult())
1095     return;
1096 
1097   Slots[V] = NextSlot++;
1098 }
1099 
1100 void VPSlotTracker::assignSlots(const VPBlockBase *VPBB) {
1101   if (auto *Region = dyn_cast<VPRegionBlock>(VPBB))
1102     assignSlots(Region);
1103   else
1104     assignSlots(cast<VPBasicBlock>(VPBB));
1105 }
1106 
1107 void VPSlotTracker::assignSlots(const VPRegionBlock *Region) {
1108   ReversePostOrderTraversal<const VPBlockBase *> RPOT(Region->getEntry());
1109   for (const VPBlockBase *Block : RPOT)
1110     assignSlots(Block);
1111 }
1112 
1113 void VPSlotTracker::assignSlots(const VPBasicBlock *VPBB) {
1114   for (const VPRecipeBase &Recipe : *VPBB) {
1115     if (const auto *VPI = dyn_cast<VPInstruction>(&Recipe))
1116       assignSlot(VPI);
1117     else if (const auto *VPIV = dyn_cast<VPWidenCanonicalIVRecipe>(&Recipe))
1118       assignSlot(VPIV->getVPValue());
1119   }
1120 }
1121 
1122 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1123 
1124   for (const VPValue *V : Plan.VPExternalDefs)
1125     assignSlot(V);
1126 
1127   for (auto &E : Plan.Value2VPValue)
1128     if (!isa<VPInstruction>(E.second))
1129       assignSlot(E.second);
1130 
1131   for (const VPValue *V : Plan.VPCBVs)
1132     assignSlot(V);
1133 
1134   if (Plan.BackedgeTakenCount)
1135     assignSlot(Plan.BackedgeTakenCount);
1136 
1137   ReversePostOrderTraversal<const VPBlockBase *> RPOT(Plan.getEntry());
1138   for (const VPBlockBase *Block : RPOT)
1139     assignSlots(Block);
1140 }
1141