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