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