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