xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision 5df34e971dd581d32955474b5b4b29d92fb87b30)
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/LoopInfo.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/CFG.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/Instruction.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/IR/Value.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/GenericDomTreeConstruction.h"
38 #include "llvm/Support/GraphWriter.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/LoopVersioning.h"
42 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
43 #include <cassert>
44 #include <string>
45 #include <vector>
46 
47 using namespace llvm;
48 extern cl::opt<bool> EnableVPlanNativePath;
49 
50 #define DEBUG_TYPE "vplan"
51 
52 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
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 #endif
61 
62 Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder,
63                                 const ElementCount &VF) const {
64   switch (LaneKind) {
65   case VPLane::Kind::ScalableLast:
66     // Lane = RuntimeVF - VF.getKnownMinValue() + Lane
67     return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF),
68                              Builder.getInt32(VF.getKnownMinValue() - Lane));
69   case VPLane::Kind::First:
70     return Builder.getInt32(Lane);
71   }
72   llvm_unreachable("Unknown lane kind");
73 }
74 
75 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)
76     : SubclassID(SC), UnderlyingVal(UV), Def(Def) {
77   if (Def)
78     Def->addDefinedValue(this);
79 }
80 
81 VPValue::~VPValue() {
82   assert(Users.empty() && "trying to delete a VPValue with remaining users");
83   if (Def)
84     Def->removeDefinedValue(this);
85 }
86 
87 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
88 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
89   if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def))
90     R->print(OS, "", SlotTracker);
91   else
92     printAsOperand(OS, SlotTracker);
93 }
94 
95 void VPValue::dump() const {
96   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def);
97   VPSlotTracker SlotTracker(
98       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
99   print(dbgs(), SlotTracker);
100   dbgs() << "\n";
101 }
102 
103 void VPDef::dump() const {
104   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this);
105   VPSlotTracker SlotTracker(
106       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
107   print(dbgs(), "", SlotTracker);
108   dbgs() << "\n";
109 }
110 #endif
111 
112 VPRecipeBase *VPValue::getDefiningRecipe() {
113   return cast_or_null<VPRecipeBase>(Def);
114 }
115 
116 const VPRecipeBase *VPValue::getDefiningRecipe() const {
117   return cast_or_null<VPRecipeBase>(Def);
118 }
119 
120 // Get the top-most entry block of \p Start. This is the entry block of the
121 // containing VPlan. This function is templated to support both const and non-const blocks
122 template <typename T> static T *getPlanEntry(T *Start) {
123   T *Next = Start;
124   T *Current = Start;
125   while ((Next = Next->getParent()))
126     Current = Next;
127 
128   SmallSetVector<T *, 8> WorkList;
129   WorkList.insert(Current);
130 
131   for (unsigned i = 0; i < WorkList.size(); i++) {
132     T *Current = WorkList[i];
133     if (Current->getNumPredecessors() == 0)
134       return Current;
135     auto &Predecessors = Current->getPredecessors();
136     WorkList.insert(Predecessors.begin(), Predecessors.end());
137   }
138 
139   llvm_unreachable("VPlan without any entry node without predecessors");
140 }
141 
142 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
143 
144 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
145 
146 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
147 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
148   const VPBlockBase *Block = this;
149   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
150     Block = Region->getEntry();
151   return cast<VPBasicBlock>(Block);
152 }
153 
154 VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
155   VPBlockBase *Block = this;
156   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
157     Block = Region->getEntry();
158   return cast<VPBasicBlock>(Block);
159 }
160 
161 void VPBlockBase::setPlan(VPlan *ParentPlan) {
162   assert(ParentPlan->getEntry() == this &&
163          "Can only set plan on its entry block.");
164   Plan = ParentPlan;
165 }
166 
167 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
168 const VPBasicBlock *VPBlockBase::getExitingBasicBlock() const {
169   const VPBlockBase *Block = this;
170   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
171     Block = Region->getExiting();
172   return cast<VPBasicBlock>(Block);
173 }
174 
175 VPBasicBlock *VPBlockBase::getExitingBasicBlock() {
176   VPBlockBase *Block = this;
177   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
178     Block = Region->getExiting();
179   return cast<VPBasicBlock>(Block);
180 }
181 
182 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
183   if (!Successors.empty() || !Parent)
184     return this;
185   assert(Parent->getExiting() == this &&
186          "Block w/o successors not the exiting block of its parent.");
187   return Parent->getEnclosingBlockWithSuccessors();
188 }
189 
190 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
191   if (!Predecessors.empty() || !Parent)
192     return this;
193   assert(Parent->getEntry() == this &&
194          "Block w/o predecessors not the entry of its parent.");
195   return Parent->getEnclosingBlockWithPredecessors();
196 }
197 
198 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
199   SmallVector<VPBlockBase *, 8> Blocks(depth_first(Entry));
200 
201   for (VPBlockBase *Block : Blocks)
202     delete Block;
203 }
204 
205 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
206   iterator It = begin();
207   while (It != end() && It->isPhi())
208     It++;
209   return It;
210 }
211 
212 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) {
213   if (!Def->hasDefiningRecipe())
214     return Def->getLiveInIRValue();
215 
216   if (hasScalarValue(Def, Instance)) {
217     return Data
218         .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)];
219   }
220 
221   assert(hasVectorValue(Def, Instance.Part));
222   auto *VecPart = Data.PerPartOutput[Def][Instance.Part];
223   if (!VecPart->getType()->isVectorTy()) {
224     assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar");
225     return VecPart;
226   }
227   // TODO: Cache created scalar values.
228   Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF);
229   auto *Extract = Builder.CreateExtractElement(VecPart, Lane);
230   // set(Def, Extract, Instance);
231   return Extract;
232 }
233 BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) {
234   VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion();
235   return VPBB2IRBB[LoopRegion->getPreheaderVPBB()];
236 }
237 
238 void VPTransformState::addNewMetadata(Instruction *To,
239                                       const Instruction *Orig) {
240   // If the loop was versioned with memchecks, add the corresponding no-alias
241   // metadata.
242   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
243     LVer->annotateInstWithNoAlias(To, Orig);
244 }
245 
246 void VPTransformState::addMetadata(Instruction *To, Instruction *From) {
247   propagateMetadata(To, From);
248   addNewMetadata(To, From);
249 }
250 
251 void VPTransformState::addMetadata(ArrayRef<Value *> To, Instruction *From) {
252   for (Value *V : To) {
253     if (Instruction *I = dyn_cast<Instruction>(V))
254       addMetadata(I, From);
255   }
256 }
257 
258 void VPTransformState::setDebugLocFromInst(const Value *V) {
259   const Instruction *Inst = dyn_cast<Instruction>(V);
260   if (!Inst) {
261     Builder.SetCurrentDebugLocation(DebugLoc());
262     return;
263   }
264 
265   const DILocation *DIL = Inst->getDebugLoc();
266   // When a FSDiscriminator is enabled, we don't need to add the multiply
267   // factors to the discriminators.
268   if (DIL && Inst->getFunction()->shouldEmitDebugInfoForProfiling() &&
269       !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
270     // FIXME: For scalable vectors, assume vscale=1.
271     auto NewDIL =
272         DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
273     if (NewDIL)
274       Builder.SetCurrentDebugLocation(*NewDIL);
275     else
276       LLVM_DEBUG(dbgs() << "Failed to create new discriminator: "
277                         << DIL->getFilename() << " Line: " << DIL->getLine());
278   } else
279     Builder.SetCurrentDebugLocation(DIL);
280 }
281 
282 BasicBlock *
283 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
284   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
285   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
286   BasicBlock *PrevBB = CFG.PrevBB;
287   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
288                                          PrevBB->getParent(), CFG.ExitBB);
289   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
290 
291   // Hook up the new basic block to its predecessors.
292   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
293     VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();
294     auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();
295     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
296 
297     assert(PredBB && "Predecessor basic-block not found building successor.");
298     auto *PredBBTerminator = PredBB->getTerminator();
299     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
300 
301     auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator);
302     if (isa<UnreachableInst>(PredBBTerminator)) {
303       assert(PredVPSuccessors.size() == 1 &&
304              "Predecessor ending w/o branch must have single successor.");
305       DebugLoc DL = PredBBTerminator->getDebugLoc();
306       PredBBTerminator->eraseFromParent();
307       auto *Br = BranchInst::Create(NewBB, PredBB);
308       Br->setDebugLoc(DL);
309     } else if (TermBr && !TermBr->isConditional()) {
310       TermBr->setSuccessor(0, NewBB);
311     } else {
312       // Set each forward successor here when it is created, excluding
313       // backedges. A backward successor is set when the branch is created.
314       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
315       assert(!TermBr->getSuccessor(idx) &&
316              "Trying to reset an existing successor block.");
317       TermBr->setSuccessor(idx, NewBB);
318     }
319   }
320   return NewBB;
321 }
322 
323 void VPBasicBlock::execute(VPTransformState *State) {
324   bool Replica = State->Instance && !State->Instance->isFirstIteration();
325   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
326   VPBlockBase *SingleHPred = nullptr;
327   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
328 
329   auto IsLoopRegion = [](VPBlockBase *BB) {
330     auto *R = dyn_cast<VPRegionBlock>(BB);
331     return R && !R->isReplicator();
332   };
333 
334   // 1. Create an IR basic block, or reuse the last one or ExitBB if possible.
335   if (getPlan()->getVectorLoopRegion()->getSingleSuccessor() == this) {
336     // ExitBB can be re-used for the exit block of the Plan.
337     NewBB = State->CFG.ExitBB;
338     State->CFG.PrevBB = NewBB;
339 
340     // Update the branch instruction in the predecessor to branch to ExitBB.
341     VPBlockBase *PredVPB = getSingleHierarchicalPredecessor();
342     VPBasicBlock *ExitingVPBB = PredVPB->getExitingBasicBlock();
343     assert(PredVPB->getSingleSuccessor() == this &&
344            "predecessor must have the current block as only successor");
345     BasicBlock *ExitingBB = State->CFG.VPBB2IRBB[ExitingVPBB];
346     // The Exit block of a loop is always set to be successor 0 of the Exiting
347     // block.
348     cast<BranchInst>(ExitingBB->getTerminator())->setSuccessor(0, NewBB);
349   } else if (PrevVPBB && /* A */
350              !((SingleHPred = getSingleHierarchicalPredecessor()) &&
351                SingleHPred->getExitingBasicBlock() == PrevVPBB &&
352                PrevVPBB->getSingleHierarchicalSuccessor() &&
353                (SingleHPred->getParent() == getEnclosingLoopRegion() &&
354                 !IsLoopRegion(SingleHPred))) &&         /* B */
355              !(Replica && getPredecessors().empty())) { /* C */
356     // The last IR basic block is reused, as an optimization, in three cases:
357     // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null;
358     // B. when the current VPBB has a single (hierarchical) predecessor which
359     //    is PrevVPBB and the latter has a single (hierarchical) successor which
360     //    both are in the same non-replicator region; and
361     // C. when the current VPBB is an entry of a region replica - where PrevVPBB
362     //    is the exiting VPBB of this region from a previous instance, or the
363     //    predecessor of this region.
364 
365     NewBB = createEmptyBasicBlock(State->CFG);
366     State->Builder.SetInsertPoint(NewBB);
367     // Temporarily terminate with unreachable until CFG is rewired.
368     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
369     // Register NewBB in its loop. In innermost loops its the same for all
370     // BB's.
371     if (State->CurrentVectorLoop)
372       State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI);
373     State->Builder.SetInsertPoint(Terminator);
374     State->CFG.PrevBB = NewBB;
375   }
376 
377   // 2. Fill the IR basic block with IR instructions.
378   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
379                     << " in BB:" << NewBB->getName() << '\n');
380 
381   State->CFG.VPBB2IRBB[this] = NewBB;
382   State->CFG.PrevVPBB = this;
383 
384   for (VPRecipeBase &Recipe : Recipes)
385     Recipe.execute(*State);
386 
387   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
388 }
389 
390 void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
391   for (VPRecipeBase &R : Recipes) {
392     for (auto *Def : R.definedValues())
393       Def->replaceAllUsesWith(NewValue);
394 
395     for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
396       R.setOperand(I, NewValue);
397   }
398 }
399 
400 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) {
401   assert((SplitAt == end() || SplitAt->getParent() == this) &&
402          "can only split at a position in the same block");
403 
404   SmallVector<VPBlockBase *, 2> Succs(successors());
405   // First, disconnect the current block from its successors.
406   for (VPBlockBase *Succ : Succs)
407     VPBlockUtils::disconnectBlocks(this, Succ);
408 
409   // Create new empty block after the block to split.
410   auto *SplitBlock = new VPBasicBlock(getName() + ".split");
411   VPBlockUtils::insertBlockAfter(SplitBlock, this);
412 
413   // Add successors for block to split to new block.
414   for (VPBlockBase *Succ : Succs)
415     VPBlockUtils::connectBlocks(SplitBlock, Succ);
416 
417   // Finally, move the recipes starting at SplitAt to new block.
418   for (VPRecipeBase &ToMove :
419        make_early_inc_range(make_range(SplitAt, this->end())))
420     ToMove.moveBefore(*SplitBlock, SplitBlock->end());
421 
422   return SplitBlock;
423 }
424 
425 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() {
426   VPRegionBlock *P = getParent();
427   if (P && P->isReplicator()) {
428     P = P->getParent();
429     assert(!cast<VPRegionBlock>(P)->isReplicator() &&
430            "unexpected nested replicate regions");
431   }
432   return P;
433 }
434 
435 static bool hasConditionalTerminator(const VPBasicBlock *VPBB) {
436   if (VPBB->empty()) {
437     assert(
438         VPBB->getNumSuccessors() < 2 &&
439         "block with multiple successors doesn't have a recipe as terminator");
440     return false;
441   }
442 
443   const VPRecipeBase *R = &VPBB->back();
444   auto *VPI = dyn_cast<VPInstruction>(R);
445   bool IsCondBranch =
446       isa<VPBranchOnMaskRecipe>(R) ||
447       (VPI && (VPI->getOpcode() == VPInstruction::BranchOnCond ||
448                VPI->getOpcode() == VPInstruction::BranchOnCount));
449   (void)IsCondBranch;
450 
451   if (VPBB->getNumSuccessors() >= 2 || VPBB->isExiting()) {
452     assert(IsCondBranch && "block with multiple successors not terminated by "
453                            "conditional branch recipe");
454 
455     return true;
456   }
457 
458   assert(
459       !IsCondBranch &&
460       "block with 0 or 1 successors terminated by conditional branch recipe");
461   return false;
462 }
463 
464 VPRecipeBase *VPBasicBlock::getTerminator() {
465   if (hasConditionalTerminator(this))
466     return &back();
467   return nullptr;
468 }
469 
470 const VPRecipeBase *VPBasicBlock::getTerminator() const {
471   if (hasConditionalTerminator(this))
472     return &back();
473   return nullptr;
474 }
475 
476 bool VPBasicBlock::isExiting() const {
477   return getParent()->getExitingBasicBlock() == this;
478 }
479 
480 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
481 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {
482   if (getSuccessors().empty()) {
483     O << Indent << "No successors\n";
484   } else {
485     O << Indent << "Successor(s): ";
486     ListSeparator LS;
487     for (auto *Succ : getSuccessors())
488       O << LS << Succ->getName();
489     O << '\n';
490   }
491 }
492 
493 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
494                          VPSlotTracker &SlotTracker) const {
495   O << Indent << getName() << ":\n";
496 
497   auto RecipeIndent = Indent + "  ";
498   for (const VPRecipeBase &Recipe : *this) {
499     Recipe.print(O, RecipeIndent, SlotTracker);
500     O << '\n';
501   }
502 
503   printSuccessors(O, Indent);
504 }
505 #endif
506 
507 void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
508   for (VPBlockBase *Block : depth_first(Entry))
509     // Drop all references in VPBasicBlocks and replace all uses with
510     // DummyValue.
511     Block->dropAllReferences(NewValue);
512 }
513 
514 void VPRegionBlock::execute(VPTransformState *State) {
515   ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry);
516 
517   if (!isReplicator()) {
518     // Create and register the new vector loop.
519     Loop *PrevLoop = State->CurrentVectorLoop;
520     State->CurrentVectorLoop = State->LI->AllocateLoop();
521     BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()];
522     Loop *ParentLoop = State->LI->getLoopFor(VectorPH);
523 
524     // Insert the new loop into the loop nest and register the new basic blocks
525     // before calling any utilities such as SCEV that require valid LoopInfo.
526     if (ParentLoop)
527       ParentLoop->addChildLoop(State->CurrentVectorLoop);
528     else
529       State->LI->addTopLevelLoop(State->CurrentVectorLoop);
530 
531     // Visit the VPBlocks connected to "this", starting from it.
532     for (VPBlockBase *Block : RPOT) {
533       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
534       Block->execute(State);
535     }
536 
537     State->CurrentVectorLoop = PrevLoop;
538     return;
539   }
540 
541   assert(!State->Instance && "Replicating a Region with non-null instance.");
542 
543   // Enter replicating mode.
544   State->Instance = VPIteration(0, 0);
545 
546   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
547     State->Instance->Part = Part;
548     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
549     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
550          ++Lane) {
551       State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);
552       // Visit the VPBlocks connected to \p this, starting from it.
553       for (VPBlockBase *Block : RPOT) {
554         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
555         Block->execute(State);
556       }
557     }
558   }
559 
560   // Exit replicating mode.
561   State->Instance.reset();
562 }
563 
564 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
565 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent,
566                           VPSlotTracker &SlotTracker) const {
567   O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
568   auto NewIndent = Indent + "  ";
569   for (auto *BlockBase : depth_first(Entry)) {
570     O << '\n';
571     BlockBase->print(O, NewIndent, SlotTracker);
572   }
573   O << Indent << "}\n";
574 
575   printSuccessors(O, Indent);
576 }
577 #endif
578 
579 VPActiveLaneMaskPHIRecipe *VPlan::getActiveLaneMaskPhi() {
580   VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
581   for (VPRecipeBase &R : Header->phis()) {
582     if (isa<VPActiveLaneMaskPHIRecipe>(&R))
583       return cast<VPActiveLaneMaskPHIRecipe>(&R);
584   }
585   return nullptr;
586 }
587 
588 static bool canSimplifyBranchOnCond(VPInstruction *Term) {
589   VPInstruction *Not = dyn_cast<VPInstruction>(Term->getOperand(0));
590   if (!Not || Not->getOpcode() != VPInstruction::Not)
591     return false;
592 
593   VPInstruction *ALM = dyn_cast<VPInstruction>(Not->getOperand(0));
594   return ALM && ALM->getOpcode() == VPInstruction::ActiveLaneMask;
595 }
596 
597 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,
598                              Value *CanonicalIVStartValue,
599                              VPTransformState &State,
600                              bool IsEpilogueVectorization) {
601 
602   VPBasicBlock *ExitingVPBB = getVectorLoopRegion()->getExitingBasicBlock();
603   auto *Term = dyn_cast<VPInstruction>(&ExitingVPBB->back());
604   // Try to simplify the branch condition if TC <= VF * UF when preparing to
605   // execute the plan for the main vector loop. We only do this if the
606   // terminator is:
607   //  1. BranchOnCount, or
608   //  2. BranchOnCond where the input is Not(ActiveLaneMask).
609   if (!IsEpilogueVectorization && Term && isa<ConstantInt>(TripCountV) &&
610       (Term->getOpcode() == VPInstruction::BranchOnCount ||
611        (Term->getOpcode() == VPInstruction::BranchOnCond &&
612         canSimplifyBranchOnCond(Term)))) {
613     ConstantInt *C = cast<ConstantInt>(TripCountV);
614     uint64_t TCVal = C->getZExtValue();
615     if (TCVal && TCVal <= State.VF.getKnownMinValue() * State.UF) {
616       auto *BOC =
617           new VPInstruction(VPInstruction::BranchOnCond,
618                             {getOrAddExternalDef(State.Builder.getTrue())});
619       Term->eraseFromParent();
620       ExitingVPBB->appendRecipe(BOC);
621       // TODO: Further simplifications are possible
622       //      1. Replace inductions with constants.
623       //      2. Replace vector loop region with VPBasicBlock.
624     }
625   }
626 
627   // Check if the trip count is needed, and if so build it.
628   if (TripCount && TripCount->getNumUsers()) {
629     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
630       State.set(TripCount, TripCountV, Part);
631   }
632 
633   // Check if the backedge taken count is needed, and if so build it.
634   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
635     IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
636     auto *TCMO = Builder.CreateSub(TripCountV,
637                                    ConstantInt::get(TripCountV->getType(), 1),
638                                    "trip.count.minus.1");
639     auto VF = State.VF;
640     Value *VTCMO =
641         VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
642     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
643       State.set(BackedgeTakenCount, VTCMO, Part);
644   }
645 
646   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
647     State.set(&VectorTripCount, VectorTripCountV, Part);
648 
649   // When vectorizing the epilogue loop, the canonical induction start value
650   // needs to be changed from zero to the value after the main vector loop.
651   // FIXME: Improve modeling for canonical IV start values in the epilogue loop.
652   if (CanonicalIVStartValue) {
653     VPValue *VPV = getOrAddExternalDef(CanonicalIVStartValue);
654     auto *IV = getCanonicalIV();
655     assert(all_of(IV->users(),
656                   [](const VPUser *U) {
657                     if (isa<VPScalarIVStepsRecipe>(U) ||
658                         isa<VPDerivedIVRecipe>(U))
659                       return true;
660                     auto *VPI = cast<VPInstruction>(U);
661                     return VPI->getOpcode() ==
662                                VPInstruction::CanonicalIVIncrement ||
663                            VPI->getOpcode() ==
664                                VPInstruction::CanonicalIVIncrementNUW;
665                   }) &&
666            "the canonical IV should only be used by its increments or "
667            "ScalarIVSteps when "
668            "resetting the start value");
669     IV->setOperand(0, VPV);
670   }
671 }
672 
673 /// Generate the code inside the preheader and body of the vectorized loop.
674 /// Assumes a single pre-header basic-block was created for this. Introduce
675 /// additional basic-blocks as needed, and fill them all.
676 void VPlan::execute(VPTransformState *State) {
677   // Set the reverse mapping from VPValues to Values for code generation.
678   for (auto &Entry : Value2VPValue)
679     State->VPValue2Value[Entry.second] = Entry.first;
680 
681   // Initialize CFG state.
682   State->CFG.PrevVPBB = nullptr;
683   State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();
684   BasicBlock *VectorPreHeader = State->CFG.PrevBB;
685   State->Builder.SetInsertPoint(VectorPreHeader->getTerminator());
686 
687   // Generate code in the loop pre-header and body.
688   for (VPBlockBase *Block : depth_first(Entry))
689     Block->execute(State);
690 
691   VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock();
692   BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB];
693 
694   // Fix the latch value of canonical, reduction and first-order recurrences
695   // phis in the vector loop.
696   VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
697   for (VPRecipeBase &R : Header->phis()) {
698     // Skip phi-like recipes that generate their backedege values themselves.
699     if (isa<VPWidenPHIRecipe>(&R))
700       continue;
701 
702     if (isa<VPWidenPointerInductionRecipe>(&R) ||
703         isa<VPWidenIntOrFpInductionRecipe>(&R)) {
704       PHINode *Phi = nullptr;
705       if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {
706         Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));
707       } else {
708         auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);
709         // TODO: Split off the case that all users of a pointer phi are scalar
710         // from the VPWidenPointerInductionRecipe.
711         if (WidenPhi->onlyScalarsGenerated(State->VF))
712           continue;
713 
714         auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));
715         Phi = cast<PHINode>(GEP->getPointerOperand());
716       }
717 
718       Phi->setIncomingBlock(1, VectorLatchBB);
719 
720       // Move the last step to the end of the latch block. This ensures
721       // consistent placement of all induction updates.
722       Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));
723       Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());
724       continue;
725     }
726 
727     auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
728     // For  canonical IV, first-order recurrences and in-order reduction phis,
729     // only a single part is generated, which provides the last part from the
730     // previous iteration. For non-ordered reductions all UF parts are
731     // generated.
732     bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) ||
733                             isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) ||
734                             (isa<VPReductionPHIRecipe>(PhiR) &&
735                              cast<VPReductionPHIRecipe>(PhiR)->isOrdered());
736     unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
737 
738     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
739       Value *Phi = State->get(PhiR, Part);
740       Value *Val = State->get(PhiR->getBackedgeValue(),
741                               SinglePartNeeded ? State->UF - 1 : Part);
742       cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
743     }
744   }
745 
746   // We do not attempt to preserve DT for outer loop vectorization currently.
747   if (!EnableVPlanNativePath) {
748     BasicBlock *VectorHeaderBB = State->CFG.VPBB2IRBB[Header];
749     State->DT->addNewBlock(VectorHeaderBB, VectorPreHeader);
750     updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB,
751                         State->CFG.ExitBB);
752   }
753 }
754 
755 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
756 LLVM_DUMP_METHOD
757 void VPlan::print(raw_ostream &O) const {
758   VPSlotTracker SlotTracker(this);
759 
760   O << "VPlan '" << getName() << "' {";
761 
762   if (VectorTripCount.getNumUsers() > 0) {
763     O << "\nLive-in ";
764     VectorTripCount.printAsOperand(O, SlotTracker);
765     O << " = vector-trip-count\n";
766   }
767 
768   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
769     O << "\nLive-in ";
770     BackedgeTakenCount->printAsOperand(O, SlotTracker);
771     O << " = backedge-taken count\n";
772   }
773 
774   for (const VPBlockBase *Block : depth_first(getEntry())) {
775     O << '\n';
776     Block->print(O, "", SlotTracker);
777   }
778 
779   if (!LiveOuts.empty())
780     O << "\n";
781   for (const auto &KV : LiveOuts) {
782     O << "Live-out ";
783     KV.second->getPhi()->printAsOperand(O);
784     O << " = ";
785     KV.second->getOperand(0)->printAsOperand(O, SlotTracker);
786     O << "\n";
787   }
788 
789   O << "}\n";
790 }
791 
792 std::string VPlan::getName() const {
793   std::string Out;
794   raw_string_ostream RSO(Out);
795   RSO << Name << " for ";
796   if (!VFs.empty()) {
797     RSO << "VF={" << VFs[0];
798     for (ElementCount VF : drop_begin(VFs))
799       RSO << "," << VF;
800     RSO << "},";
801   }
802 
803   if (UFs.empty()) {
804     RSO << "UF>=1";
805   } else {
806     RSO << "UF={" << UFs[0];
807     for (unsigned UF : drop_begin(UFs))
808       RSO << "," << UF;
809     RSO << "}";
810   }
811 
812   return Out;
813 }
814 
815 LLVM_DUMP_METHOD
816 void VPlan::printDOT(raw_ostream &O) const {
817   VPlanPrinter Printer(O, *this);
818   Printer.dump();
819 }
820 
821 LLVM_DUMP_METHOD
822 void VPlan::dump() const { print(dbgs()); }
823 #endif
824 
825 void VPlan::addLiveOut(PHINode *PN, VPValue *V) {
826   assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists");
827   LiveOuts.insert({PN, new VPLiveOut(PN, V)});
828 }
829 
830 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB,
831                                 BasicBlock *LoopLatchBB,
832                                 BasicBlock *LoopExitBB) {
833   // The vector body may be more than a single basic-block by this point.
834   // Update the dominator tree information inside the vector body by propagating
835   // it from header to latch, expecting only triangular control-flow, if any.
836   BasicBlock *PostDomSucc = nullptr;
837   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
838     // Get the list of successors of this block.
839     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
840     assert(Succs.size() <= 2 &&
841            "Basic block in vector loop has more than 2 successors.");
842     PostDomSucc = Succs[0];
843     if (Succs.size() == 1) {
844       assert(PostDomSucc->getSinglePredecessor() &&
845              "PostDom successor has more than one predecessor.");
846       DT->addNewBlock(PostDomSucc, BB);
847       continue;
848     }
849     BasicBlock *InterimSucc = Succs[1];
850     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
851       PostDomSucc = Succs[1];
852       InterimSucc = Succs[0];
853     }
854     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
855            "One successor of a basic block does not lead to the other.");
856     assert(InterimSucc->getSinglePredecessor() &&
857            "Interim successor has more than one predecessor.");
858     assert(PostDomSucc->hasNPredecessors(2) &&
859            "PostDom successor has more than two predecessors.");
860     DT->addNewBlock(InterimSucc, BB);
861     DT->addNewBlock(PostDomSucc, BB);
862   }
863   // Latch block is a new dominator for the loop exit.
864   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
865   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
866 }
867 
868 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
869 
870 Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
871   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
872          Twine(getOrCreateBID(Block));
873 }
874 
875 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
876   const std::string &Name = Block->getName();
877   if (!Name.empty())
878     return Name;
879   return "VPB" + Twine(getOrCreateBID(Block));
880 }
881 
882 void VPlanPrinter::dump() {
883   Depth = 1;
884   bumpIndent(0);
885   OS << "digraph VPlan {\n";
886   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
887   if (!Plan.getName().empty())
888     OS << "\\n" << DOT::EscapeString(Plan.getName());
889   if (Plan.BackedgeTakenCount) {
890     OS << ", where:\\n";
891     Plan.BackedgeTakenCount->print(OS, SlotTracker);
892     OS << " := BackedgeTakenCount";
893   }
894   OS << "\"]\n";
895   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
896   OS << "edge [fontname=Courier, fontsize=30]\n";
897   OS << "compound=true\n";
898 
899   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
900     dumpBlock(Block);
901 
902   OS << "}\n";
903 }
904 
905 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
906   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
907     dumpBasicBlock(BasicBlock);
908   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
909     dumpRegion(Region);
910   else
911     llvm_unreachable("Unsupported kind of VPBlock.");
912 }
913 
914 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
915                             bool Hidden, const Twine &Label) {
916   // Due to "dot" we print an edge between two regions as an edge between the
917   // exiting basic block and the entry basic of the respective regions.
918   const VPBlockBase *Tail = From->getExitingBasicBlock();
919   const VPBlockBase *Head = To->getEntryBasicBlock();
920   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
921   OS << " [ label=\"" << Label << '\"';
922   if (Tail != From)
923     OS << " ltail=" << getUID(From);
924   if (Head != To)
925     OS << " lhead=" << getUID(To);
926   if (Hidden)
927     OS << "; splines=none";
928   OS << "]\n";
929 }
930 
931 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
932   auto &Successors = Block->getSuccessors();
933   if (Successors.size() == 1)
934     drawEdge(Block, Successors.front(), false, "");
935   else if (Successors.size() == 2) {
936     drawEdge(Block, Successors.front(), false, "T");
937     drawEdge(Block, Successors.back(), false, "F");
938   } else {
939     unsigned SuccessorNumber = 0;
940     for (auto *Successor : Successors)
941       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
942   }
943 }
944 
945 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
946   // Implement dot-formatted dump by performing plain-text dump into the
947   // temporary storage followed by some post-processing.
948   OS << Indent << getUID(BasicBlock) << " [label =\n";
949   bumpIndent(1);
950   std::string Str;
951   raw_string_ostream SS(Str);
952   // Use no indentation as we need to wrap the lines into quotes ourselves.
953   BasicBlock->print(SS, "", SlotTracker);
954 
955   // We need to process each line of the output separately, so split
956   // single-string plain-text dump.
957   SmallVector<StringRef, 0> Lines;
958   StringRef(Str).rtrim('\n').split(Lines, "\n");
959 
960   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
961     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
962   };
963 
964   // Don't need the "+" after the last line.
965   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
966     EmitLine(Line, " +\n");
967   EmitLine(Lines.back(), "\n");
968 
969   bumpIndent(-1);
970   OS << Indent << "]\n";
971 
972   dumpEdges(BasicBlock);
973 }
974 
975 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
976   OS << Indent << "subgraph " << getUID(Region) << " {\n";
977   bumpIndent(1);
978   OS << Indent << "fontname=Courier\n"
979      << Indent << "label=\""
980      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
981      << DOT::EscapeString(Region->getName()) << "\"\n";
982   // Dump the blocks of the region.
983   assert(Region->getEntry() && "Region contains no inner blocks.");
984   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
985     dumpBlock(Block);
986   bumpIndent(-1);
987   OS << Indent << "}\n";
988   dumpEdges(Region);
989 }
990 
991 void VPlanIngredient::print(raw_ostream &O) const {
992   if (auto *Inst = dyn_cast<Instruction>(V)) {
993     if (!Inst->getType()->isVoidTy()) {
994       Inst->printAsOperand(O, false);
995       O << " = ";
996     }
997     O << Inst->getOpcodeName() << " ";
998     unsigned E = Inst->getNumOperands();
999     if (E > 0) {
1000       Inst->getOperand(0)->printAsOperand(O, false);
1001       for (unsigned I = 1; I < E; ++I)
1002         Inst->getOperand(I)->printAsOperand(O << ", ", false);
1003     }
1004   } else // !Inst
1005     V->printAsOperand(O, false);
1006 }
1007 
1008 #endif
1009 
1010 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
1011 
1012 void VPValue::replaceAllUsesWith(VPValue *New) {
1013   for (unsigned J = 0; J < getNumUsers();) {
1014     VPUser *User = Users[J];
1015     unsigned NumUsers = getNumUsers();
1016     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
1017       if (User->getOperand(I) == this)
1018         User->setOperand(I, New);
1019     // If a user got removed after updating the current user, the next user to
1020     // update will be moved to the current position, so we only need to
1021     // increment the index if the number of users did not change.
1022     if (NumUsers == getNumUsers())
1023       J++;
1024   }
1025 }
1026 
1027 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1028 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1029   if (const Value *UV = getUnderlyingValue()) {
1030     OS << "ir<";
1031     UV->printAsOperand(OS, false);
1032     OS << ">";
1033     return;
1034   }
1035 
1036   unsigned Slot = Tracker.getSlot(this);
1037   if (Slot == unsigned(-1))
1038     OS << "<badref>";
1039   else
1040     OS << "vp<%" << Tracker.getSlot(this) << ">";
1041 }
1042 
1043 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1044   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1045     Op->printAsOperand(O, SlotTracker);
1046   });
1047 }
1048 #endif
1049 
1050 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1051                                           Old2NewTy &Old2New,
1052                                           InterleavedAccessInfo &IAI) {
1053   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
1054   for (VPBlockBase *Base : RPOT) {
1055     visitBlock(Base, Old2New, IAI);
1056   }
1057 }
1058 
1059 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1060                                          InterleavedAccessInfo &IAI) {
1061   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1062     for (VPRecipeBase &VPI : *VPBB) {
1063       if (isa<VPHeaderPHIRecipe>(&VPI))
1064         continue;
1065       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1066       auto *VPInst = cast<VPInstruction>(&VPI);
1067 
1068       auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue());
1069       if (!Inst)
1070         continue;
1071       auto *IG = IAI.getInterleaveGroup(Inst);
1072       if (!IG)
1073         continue;
1074 
1075       auto NewIGIter = Old2New.find(IG);
1076       if (NewIGIter == Old2New.end())
1077         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1078             IG->getFactor(), IG->isReverse(), IG->getAlign());
1079 
1080       if (Inst == IG->getInsertPos())
1081         Old2New[IG]->setInsertPos(VPInst);
1082 
1083       InterleaveGroupMap[VPInst] = Old2New[IG];
1084       InterleaveGroupMap[VPInst]->insertMember(
1085           VPInst, IG->getIndex(Inst),
1086           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1087                                 : IG->getFactor()));
1088     }
1089   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1090     visitRegion(Region, Old2New, IAI);
1091   else
1092     llvm_unreachable("Unsupported kind of VPBlock.");
1093 }
1094 
1095 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1096                                                  InterleavedAccessInfo &IAI) {
1097   Old2NewTy Old2New;
1098   visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI);
1099 }
1100 
1101 void VPSlotTracker::assignSlot(const VPValue *V) {
1102   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
1103   Slots[V] = NextSlot++;
1104 }
1105 
1106 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1107 
1108   for (const auto &P : Plan.VPExternalDefs)
1109     assignSlot(P.second);
1110 
1111   assignSlot(&Plan.VectorTripCount);
1112   if (Plan.BackedgeTakenCount)
1113     assignSlot(Plan.BackedgeTakenCount);
1114 
1115   ReversePostOrderTraversal<
1116       VPBlockRecursiveTraversalWrapper<const VPBlockBase *>>
1117       RPOT(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>(
1118           Plan.getEntry()));
1119   for (const VPBasicBlock *VPBB :
1120        VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1121     for (const VPRecipeBase &Recipe : *VPBB)
1122       for (VPValue *Def : Recipe.definedValues())
1123         assignSlot(Def);
1124 }
1125 
1126 bool vputils::onlyFirstLaneUsed(VPValue *Def) {
1127   return all_of(Def->users(),
1128                 [Def](VPUser *U) { return U->onlyFirstLaneUsed(Def); });
1129 }
1130 
1131 VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr,
1132                                                 ScalarEvolution &SE) {
1133   if (auto *E = dyn_cast<SCEVConstant>(Expr))
1134     return Plan.getOrAddExternalDef(E->getValue());
1135   if (auto *E = dyn_cast<SCEVUnknown>(Expr))
1136     return Plan.getOrAddExternalDef(E->getValue());
1137 
1138   VPBasicBlock *Preheader = Plan.getEntry()->getEntryBasicBlock();
1139   VPExpandSCEVRecipe *Step = new VPExpandSCEVRecipe(Expr, SE);
1140   Preheader->appendRecipe(Step);
1141   return Step;
1142 }
1143