xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision 1a5a1e97817c9a3db4d1f9795789c99790cf88e2)
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 "LoopVectorizationPlanner.h"
21 #include "VPlanCFG.h"
22 #include "VPlanDominatorTree.h"
23 #include "VPlanPatternMatch.h"
24 #include "VPlanTransforms.h"
25 #include "VPlanUtils.h"
26 #include "llvm/ADT/PostOrderIterator.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/Analysis/DomTreeUpdater.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/IR/BasicBlock.h"
34 #include "llvm/IR/CFG.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/GraphWriter.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/LoopVersioning.h"
47 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
48 #include <cassert>
49 #include <string>
50 #include <vector>
51 
52 using namespace llvm;
53 using namespace llvm::VPlanPatternMatch;
54 
55 namespace llvm {
56 extern cl::opt<bool> EnableVPlanNativePath;
57 }
58 
59 static cl::opt<bool> PrintVPlansInDotFormat(
60     "vplan-print-in-dot-format", cl::Hidden,
61     cl::desc("Use dot format instead of plain text when dumping VPlans"));
62 
63 #define DEBUG_TYPE "vplan"
64 
65 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
66 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
67   const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
68   VPSlotTracker SlotTracker(
69       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
70   V.print(OS, SlotTracker);
71   return OS;
72 }
73 #endif
74 
75 Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder,
76                                 const ElementCount &VF) const {
77   switch (LaneKind) {
78   case VPLane::Kind::ScalableLast:
79     // Lane = RuntimeVF - VF.getKnownMinValue() + Lane
80     return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF),
81                              Builder.getInt32(VF.getKnownMinValue() - Lane));
82   case VPLane::Kind::First:
83     return Builder.getInt32(Lane);
84   }
85   llvm_unreachable("Unknown lane kind");
86 }
87 
88 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)
89     : SubclassID(SC), UnderlyingVal(UV), Def(Def) {
90   if (Def)
91     Def->addDefinedValue(this);
92 }
93 
94 VPValue::~VPValue() {
95   assert(Users.empty() && "trying to delete a VPValue with remaining users");
96   if (Def)
97     Def->removeDefinedValue(this);
98 }
99 
100 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
101 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
102   if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def))
103     R->print(OS, "", SlotTracker);
104   else
105     printAsOperand(OS, SlotTracker);
106 }
107 
108 void VPValue::dump() const {
109   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def);
110   VPSlotTracker SlotTracker(
111       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
112   print(dbgs(), SlotTracker);
113   dbgs() << "\n";
114 }
115 
116 void VPDef::dump() const {
117   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this);
118   VPSlotTracker SlotTracker(
119       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
120   print(dbgs(), "", SlotTracker);
121   dbgs() << "\n";
122 }
123 #endif
124 
125 VPRecipeBase *VPValue::getDefiningRecipe() {
126   return cast_or_null<VPRecipeBase>(Def);
127 }
128 
129 const VPRecipeBase *VPValue::getDefiningRecipe() const {
130   return cast_or_null<VPRecipeBase>(Def);
131 }
132 
133 // Get the top-most entry block of \p Start. This is the entry block of the
134 // containing VPlan. This function is templated to support both const and non-const blocks
135 template <typename T> static T *getPlanEntry(T *Start) {
136   T *Next = Start;
137   T *Current = Start;
138   while ((Next = Next->getParent()))
139     Current = Next;
140 
141   SmallSetVector<T *, 8> WorkList;
142   WorkList.insert(Current);
143 
144   for (unsigned i = 0; i < WorkList.size(); i++) {
145     T *Current = WorkList[i];
146     if (Current->getNumPredecessors() == 0)
147       return Current;
148     auto &Predecessors = Current->getPredecessors();
149     WorkList.insert(Predecessors.begin(), Predecessors.end());
150   }
151 
152   llvm_unreachable("VPlan without any entry node without predecessors");
153 }
154 
155 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
156 
157 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
158 
159 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
160 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
161   const VPBlockBase *Block = this;
162   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
163     Block = Region->getEntry();
164   return cast<VPBasicBlock>(Block);
165 }
166 
167 VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
168   VPBlockBase *Block = this;
169   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
170     Block = Region->getEntry();
171   return cast<VPBasicBlock>(Block);
172 }
173 
174 void VPBlockBase::setPlan(VPlan *ParentPlan) {
175   assert(
176       (ParentPlan->getEntry() == this || ParentPlan->getPreheader() == this) &&
177       "Can only set plan on its entry or preheader block.");
178   Plan = ParentPlan;
179 }
180 
181 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
182 const VPBasicBlock *VPBlockBase::getExitingBasicBlock() const {
183   const VPBlockBase *Block = this;
184   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
185     Block = Region->getExiting();
186   return cast<VPBasicBlock>(Block);
187 }
188 
189 VPBasicBlock *VPBlockBase::getExitingBasicBlock() {
190   VPBlockBase *Block = this;
191   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
192     Block = Region->getExiting();
193   return cast<VPBasicBlock>(Block);
194 }
195 
196 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
197   if (!Successors.empty() || !Parent)
198     return this;
199   assert(Parent->getExiting() == this &&
200          "Block w/o successors not the exiting block of its parent.");
201   return Parent->getEnclosingBlockWithSuccessors();
202 }
203 
204 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
205   if (!Predecessors.empty() || !Parent)
206     return this;
207   assert(Parent->getEntry() == this &&
208          "Block w/o predecessors not the entry of its parent.");
209   return Parent->getEnclosingBlockWithPredecessors();
210 }
211 
212 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
213   for (VPBlockBase *Block : to_vector(vp_depth_first_shallow(Entry)))
214     delete Block;
215 }
216 
217 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
218   iterator It = begin();
219   while (It != end() && It->isPhi())
220     It++;
221   return It;
222 }
223 
224 VPTransformState::VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI,
225                                    DominatorTree *DT, IRBuilderBase &Builder,
226                                    InnerLoopVectorizer *ILV, VPlan *Plan,
227                                    LLVMContext &Ctx)
228     : VF(VF), UF(UF), CFG(DT), LI(LI), Builder(Builder), ILV(ILV), Plan(Plan),
229       LVer(nullptr),
230       TypeAnalysis(Plan->getCanonicalIV()->getScalarType(), Ctx) {}
231 
232 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) {
233   if (Def->isLiveIn())
234     return Def->getLiveInIRValue();
235 
236   if (hasScalarValue(Def, Instance)) {
237     return Data
238         .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)];
239   }
240   if (!Instance.Lane.isFirstLane() &&
241       vputils::isUniformAfterVectorization(Def) &&
242       hasScalarValue(Def, {Instance.Part, VPLane::getFirstLane()})) {
243     return Data.PerPartScalars[Def][Instance.Part][0];
244   }
245 
246   assert(hasVectorValue(Def, Instance.Part));
247   auto *VecPart = Data.PerPartOutput[Def][Instance.Part];
248   if (!VecPart->getType()->isVectorTy()) {
249     assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar");
250     return VecPart;
251   }
252   // TODO: Cache created scalar values.
253   Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF);
254   auto *Extract = Builder.CreateExtractElement(VecPart, Lane);
255   // set(Def, Extract, Instance);
256   return Extract;
257 }
258 
259 Value *VPTransformState::get(VPValue *Def, unsigned Part, bool NeedsScalar) {
260   if (NeedsScalar) {
261     assert((VF.isScalar() || Def->isLiveIn() || hasVectorValue(Def, Part) ||
262             !vputils::onlyFirstLaneUsed(Def) ||
263             (hasScalarValue(Def, VPIteration(Part, 0)) &&
264              Data.PerPartScalars[Def][Part].size() == 1)) &&
265            "Trying to access a single scalar per part but has multiple scalars "
266            "per part.");
267     return get(Def, VPIteration(Part, 0));
268   }
269 
270   // If Values have been set for this Def return the one relevant for \p Part.
271   if (hasVectorValue(Def, Part))
272     return Data.PerPartOutput[Def][Part];
273 
274   auto GetBroadcastInstrs = [this, Def](Value *V) {
275     bool SafeToHoist = Def->isDefinedOutsideVectorRegions();
276     if (VF.isScalar())
277       return V;
278     // Place the code for broadcasting invariant variables in the new preheader.
279     IRBuilder<>::InsertPointGuard Guard(Builder);
280     if (SafeToHoist) {
281       BasicBlock *LoopVectorPreHeader = CFG.VPBB2IRBB[cast<VPBasicBlock>(
282           Plan->getVectorLoopRegion()->getSinglePredecessor())];
283       if (LoopVectorPreHeader)
284         Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
285     }
286 
287     // Place the code for broadcasting invariant variables in the new preheader.
288     // Broadcast the scalar into all locations in the vector.
289     Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
290 
291     return Shuf;
292   };
293 
294   if (!hasScalarValue(Def, {Part, 0})) {
295     assert(Def->isLiveIn() && "expected a live-in");
296     if (Part != 0)
297       return get(Def, 0);
298     Value *IRV = Def->getLiveInIRValue();
299     Value *B = GetBroadcastInstrs(IRV);
300     set(Def, B, Part);
301     return B;
302   }
303 
304   Value *ScalarValue = get(Def, {Part, 0});
305   // If we aren't vectorizing, we can just copy the scalar map values over
306   // to the vector map.
307   if (VF.isScalar()) {
308     set(Def, ScalarValue, Part);
309     return ScalarValue;
310   }
311 
312   bool IsUniform = vputils::isUniformAfterVectorization(Def);
313 
314   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
315   // Check if there is a scalar value for the selected lane.
316   if (!hasScalarValue(Def, {Part, LastLane})) {
317     // At the moment, VPWidenIntOrFpInductionRecipes, VPScalarIVStepsRecipes and
318     // VPExpandSCEVRecipes can also be uniform.
319     assert((isa<VPWidenIntOrFpInductionRecipe>(Def->getDefiningRecipe()) ||
320             isa<VPScalarIVStepsRecipe>(Def->getDefiningRecipe()) ||
321             isa<VPExpandSCEVRecipe>(Def->getDefiningRecipe())) &&
322            "unexpected recipe found to be invariant");
323     IsUniform = true;
324     LastLane = 0;
325   }
326 
327   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
328   // Set the insert point after the last scalarized instruction or after the
329   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
330   // will directly follow the scalar definitions.
331   auto OldIP = Builder.saveIP();
332   auto NewIP =
333       isa<PHINode>(LastInst)
334           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
335           : std::next(BasicBlock::iterator(LastInst));
336   Builder.SetInsertPoint(&*NewIP);
337 
338   // However, if we are vectorizing, we need to construct the vector values.
339   // If the value is known to be uniform after vectorization, we can just
340   // broadcast the scalar value corresponding to lane zero for each unroll
341   // iteration. Otherwise, we construct the vector values using
342   // insertelement instructions. Since the resulting vectors are stored in
343   // State, we will only generate the insertelements once.
344   Value *VectorValue = nullptr;
345   if (IsUniform) {
346     VectorValue = GetBroadcastInstrs(ScalarValue);
347     set(Def, VectorValue, Part);
348   } else {
349     // Initialize packing with insertelements to start from undef.
350     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
351     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
352     set(Def, Undef, Part);
353     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
354       packScalarIntoVectorValue(Def, {Part, Lane});
355     VectorValue = get(Def, Part);
356   }
357   Builder.restoreIP(OldIP);
358   return VectorValue;
359 }
360 
361 BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) {
362   VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion();
363   return VPBB2IRBB[LoopRegion->getPreheaderVPBB()];
364 }
365 
366 void VPTransformState::addNewMetadata(Instruction *To,
367                                       const Instruction *Orig) {
368   // If the loop was versioned with memchecks, add the corresponding no-alias
369   // metadata.
370   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
371     LVer->annotateInstWithNoAlias(To, Orig);
372 }
373 
374 void VPTransformState::addMetadata(Value *To, Instruction *From) {
375   // No source instruction to transfer metadata from?
376   if (!From)
377     return;
378 
379   if (Instruction *ToI = dyn_cast<Instruction>(To)) {
380     propagateMetadata(ToI, From);
381     addNewMetadata(ToI, From);
382   }
383 }
384 
385 void VPTransformState::setDebugLocFrom(DebugLoc DL) {
386   const DILocation *DIL = DL;
387   // When a FSDiscriminator is enabled, we don't need to add the multiply
388   // factors to the discriminators.
389   if (DIL &&
390       Builder.GetInsertBlock()
391           ->getParent()
392           ->shouldEmitDebugInfoForProfiling() &&
393       !EnableFSDiscriminator) {
394     // FIXME: For scalable vectors, assume vscale=1.
395     auto NewDIL =
396         DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
397     if (NewDIL)
398       Builder.SetCurrentDebugLocation(*NewDIL);
399     else
400       LLVM_DEBUG(dbgs() << "Failed to create new discriminator: "
401                         << DIL->getFilename() << " Line: " << DIL->getLine());
402   } else
403     Builder.SetCurrentDebugLocation(DIL);
404 }
405 
406 void VPTransformState::packScalarIntoVectorValue(VPValue *Def,
407                                                  const VPIteration &Instance) {
408   Value *ScalarInst = get(Def, Instance);
409   Value *VectorValue = get(Def, Instance.Part);
410   VectorValue = Builder.CreateInsertElement(
411       VectorValue, ScalarInst, Instance.Lane.getAsRuntimeExpr(Builder, VF));
412   set(Def, VectorValue, Instance.Part);
413 }
414 
415 BasicBlock *
416 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
417   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
418   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
419   BasicBlock *PrevBB = CFG.PrevBB;
420   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
421                                          PrevBB->getParent(), CFG.ExitBB);
422   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
423 
424   // Hook up the new basic block to its predecessors.
425   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
426     VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();
427     auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();
428     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
429 
430     assert(PredBB && "Predecessor basic-block not found building successor.");
431     auto *PredBBTerminator = PredBB->getTerminator();
432     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
433 
434     auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator);
435     if (isa<UnreachableInst>(PredBBTerminator)) {
436       assert(PredVPSuccessors.size() == 1 &&
437              "Predecessor ending w/o branch must have single successor.");
438       DebugLoc DL = PredBBTerminator->getDebugLoc();
439       PredBBTerminator->eraseFromParent();
440       auto *Br = BranchInst::Create(NewBB, PredBB);
441       Br->setDebugLoc(DL);
442     } else if (TermBr && !TermBr->isConditional()) {
443       TermBr->setSuccessor(0, NewBB);
444     } else {
445       // Set each forward successor here when it is created, excluding
446       // backedges. A backward successor is set when the branch is created.
447       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
448       assert(!TermBr->getSuccessor(idx) &&
449              "Trying to reset an existing successor block.");
450       TermBr->setSuccessor(idx, NewBB);
451     }
452     CFG.DTU.applyUpdates({{DominatorTree::Insert, PredBB, NewBB}});
453   }
454   return NewBB;
455 }
456 
457 void VPIRBasicBlock::execute(VPTransformState *State) {
458   assert(getHierarchicalSuccessors().size() <= 2 &&
459          "VPIRBasicBlock can have at most two successors at the moment!");
460   State->Builder.SetInsertPoint(getIRBasicBlock()->getTerminator());
461   executeRecipes(State, getIRBasicBlock());
462   if (getSingleSuccessor()) {
463     assert(isa<UnreachableInst>(getIRBasicBlock()->getTerminator()));
464     auto *Br = State->Builder.CreateBr(getIRBasicBlock());
465     Br->setOperand(0, nullptr);
466     getIRBasicBlock()->getTerminator()->eraseFromParent();
467   }
468 
469   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
470     VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();
471     BasicBlock *PredBB = State->CFG.VPBB2IRBB[PredVPBB];
472     assert(PredBB && "Predecessor basic-block not found building successor.");
473     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
474 
475     auto *PredBBTerminator = PredBB->getTerminator();
476     auto *TermBr = cast<BranchInst>(PredBBTerminator);
477     // Set each forward successor here when it is created, excluding
478     // backedges. A backward successor is set when the branch is created.
479     const auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();
480     unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
481     assert(!TermBr->getSuccessor(idx) &&
482            "Trying to reset an existing successor block.");
483     TermBr->setSuccessor(idx, IRBB);
484     State->CFG.DTU.applyUpdates({{DominatorTree::Insert, PredBB, IRBB}});
485   }
486 }
487 
488 void VPBasicBlock::execute(VPTransformState *State) {
489   bool Replica = State->Instance && !State->Instance->isFirstIteration();
490   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
491   VPBlockBase *SingleHPred = nullptr;
492   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
493 
494   auto IsLoopRegion = [](VPBlockBase *BB) {
495     auto *R = dyn_cast<VPRegionBlock>(BB);
496     return R && !R->isReplicator();
497   };
498 
499   // 1. Create an IR basic block.
500   if (PrevVPBB && /* A */
501       !((SingleHPred = getSingleHierarchicalPredecessor()) &&
502         SingleHPred->getExitingBasicBlock() == PrevVPBB &&
503         PrevVPBB->getSingleHierarchicalSuccessor() &&
504         (SingleHPred->getParent() == getEnclosingLoopRegion() &&
505          !IsLoopRegion(SingleHPred))) &&         /* B */
506       !(Replica && getPredecessors().empty())) { /* C */
507     // The last IR basic block is reused, as an optimization, in three cases:
508     // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null;
509     // B. when the current VPBB has a single (hierarchical) predecessor which
510     //    is PrevVPBB and the latter has a single (hierarchical) successor which
511     //    both are in the same non-replicator region; and
512     // C. when the current VPBB is an entry of a region replica - where PrevVPBB
513     //    is the exiting VPBB of this region from a previous instance, or the
514     //    predecessor of this region.
515 
516     NewBB = createEmptyBasicBlock(State->CFG);
517     State->Builder.SetInsertPoint(NewBB);
518     // Temporarily terminate with unreachable until CFG is rewired.
519     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
520     // Register NewBB in its loop. In innermost loops its the same for all
521     // BB's.
522     if (State->CurrentVectorLoop)
523       State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI);
524     State->Builder.SetInsertPoint(Terminator);
525     State->CFG.PrevBB = NewBB;
526   }
527 
528   // 2. Fill the IR basic block with IR instructions.
529   executeRecipes(State, NewBB);
530 }
531 
532 void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
533   for (VPRecipeBase &R : Recipes) {
534     for (auto *Def : R.definedValues())
535       Def->replaceAllUsesWith(NewValue);
536 
537     for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
538       R.setOperand(I, NewValue);
539   }
540 }
541 
542 void VPBasicBlock::executeRecipes(VPTransformState *State, BasicBlock *BB) {
543   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
544                     << " in BB:" << BB->getName() << '\n');
545 
546   State->CFG.VPBB2IRBB[this] = BB;
547   State->CFG.PrevVPBB = this;
548 
549   for (VPRecipeBase &Recipe : Recipes)
550     Recipe.execute(*State);
551 
552   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *BB);
553 }
554 
555 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) {
556   assert((SplitAt == end() || SplitAt->getParent() == this) &&
557          "can only split at a position in the same block");
558 
559   SmallVector<VPBlockBase *, 2> Succs(successors());
560   // First, disconnect the current block from its successors.
561   for (VPBlockBase *Succ : Succs)
562     VPBlockUtils::disconnectBlocks(this, Succ);
563 
564   // Create new empty block after the block to split.
565   auto *SplitBlock = new VPBasicBlock(getName() + ".split");
566   VPBlockUtils::insertBlockAfter(SplitBlock, this);
567 
568   // Add successors for block to split to new block.
569   for (VPBlockBase *Succ : Succs)
570     VPBlockUtils::connectBlocks(SplitBlock, Succ);
571 
572   // Finally, move the recipes starting at SplitAt to new block.
573   for (VPRecipeBase &ToMove :
574        make_early_inc_range(make_range(SplitAt, this->end())))
575     ToMove.moveBefore(*SplitBlock, SplitBlock->end());
576 
577   return SplitBlock;
578 }
579 
580 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() {
581   VPRegionBlock *P = getParent();
582   if (P && P->isReplicator()) {
583     P = P->getParent();
584     assert(!cast<VPRegionBlock>(P)->isReplicator() &&
585            "unexpected nested replicate regions");
586   }
587   return P;
588 }
589 
590 static bool hasConditionalTerminator(const VPBasicBlock *VPBB) {
591   if (VPBB->empty()) {
592     assert(
593         VPBB->getNumSuccessors() < 2 &&
594         "block with multiple successors doesn't have a recipe as terminator");
595     return false;
596   }
597 
598   const VPRecipeBase *R = &VPBB->back();
599   bool IsCondBranch = isa<VPBranchOnMaskRecipe>(R) ||
600                       match(R, m_BranchOnCond(m_VPValue())) ||
601                       match(R, m_BranchOnCount(m_VPValue(), m_VPValue()));
602   (void)IsCondBranch;
603 
604   if (VPBB->getNumSuccessors() >= 2 ||
605       (VPBB->isExiting() && !VPBB->getParent()->isReplicator())) {
606     assert(IsCondBranch && "block with multiple successors not terminated by "
607                            "conditional branch recipe");
608 
609     return true;
610   }
611 
612   assert(
613       !IsCondBranch &&
614       "block with 0 or 1 successors terminated by conditional branch recipe");
615   return false;
616 }
617 
618 VPRecipeBase *VPBasicBlock::getTerminator() {
619   if (hasConditionalTerminator(this))
620     return &back();
621   return nullptr;
622 }
623 
624 const VPRecipeBase *VPBasicBlock::getTerminator() const {
625   if (hasConditionalTerminator(this))
626     return &back();
627   return nullptr;
628 }
629 
630 bool VPBasicBlock::isExiting() const {
631   return getParent() && getParent()->getExitingBasicBlock() == this;
632 }
633 
634 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
635 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {
636   if (getSuccessors().empty()) {
637     O << Indent << "No successors\n";
638   } else {
639     O << Indent << "Successor(s): ";
640     ListSeparator LS;
641     for (auto *Succ : getSuccessors())
642       O << LS << Succ->getName();
643     O << '\n';
644   }
645 }
646 
647 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
648                          VPSlotTracker &SlotTracker) const {
649   O << Indent << getName() << ":\n";
650 
651   auto RecipeIndent = Indent + "  ";
652   for (const VPRecipeBase &Recipe : *this) {
653     Recipe.print(O, RecipeIndent, SlotTracker);
654     O << '\n';
655   }
656 
657   printSuccessors(O, Indent);
658 }
659 #endif
660 
661 static std::pair<VPBlockBase *, VPBlockBase *> cloneFrom(VPBlockBase *Entry);
662 
663 // Clone the CFG for all nodes reachable from \p Entry, this includes cloning
664 // the blocks and their recipes. Operands of cloned recipes will NOT be updated.
665 // Remapping of operands must be done separately. Returns a pair with the new
666 // entry and exiting blocks of the cloned region. If \p Entry isn't part of a
667 // region, return nullptr for the exiting block.
668 static std::pair<VPBlockBase *, VPBlockBase *> cloneFrom(VPBlockBase *Entry) {
669   DenseMap<VPBlockBase *, VPBlockBase *> Old2NewVPBlocks;
670   VPBlockBase *Exiting = nullptr;
671   bool InRegion = Entry->getParent();
672   // First, clone blocks reachable from Entry.
673   for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) {
674     VPBlockBase *NewBB = BB->clone();
675     Old2NewVPBlocks[BB] = NewBB;
676     if (InRegion && BB->getNumSuccessors() == 0) {
677       assert(!Exiting && "Multiple exiting blocks?");
678       Exiting = BB;
679     }
680   }
681   assert((!InRegion || Exiting) && "regions must have a single exiting block");
682 
683   // Second, update the predecessors & successors of the cloned blocks.
684   for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) {
685     VPBlockBase *NewBB = Old2NewVPBlocks[BB];
686     SmallVector<VPBlockBase *> NewPreds;
687     for (VPBlockBase *Pred : BB->getPredecessors()) {
688       NewPreds.push_back(Old2NewVPBlocks[Pred]);
689     }
690     NewBB->setPredecessors(NewPreds);
691     SmallVector<VPBlockBase *> NewSuccs;
692     for (VPBlockBase *Succ : BB->successors()) {
693       NewSuccs.push_back(Old2NewVPBlocks[Succ]);
694     }
695     NewBB->setSuccessors(NewSuccs);
696   }
697 
698 #if !defined(NDEBUG)
699   // Verify that the order of predecessors and successors matches in the cloned
700   // version.
701   for (const auto &[OldBB, NewBB] :
702        zip(vp_depth_first_shallow(Entry),
703            vp_depth_first_shallow(Old2NewVPBlocks[Entry]))) {
704     for (const auto &[OldPred, NewPred] :
705          zip(OldBB->getPredecessors(), NewBB->getPredecessors()))
706       assert(NewPred == Old2NewVPBlocks[OldPred] && "Different predecessors");
707 
708     for (const auto &[OldSucc, NewSucc] :
709          zip(OldBB->successors(), NewBB->successors()))
710       assert(NewSucc == Old2NewVPBlocks[OldSucc] && "Different successors");
711   }
712 #endif
713 
714   return std::make_pair(Old2NewVPBlocks[Entry],
715                         Exiting ? Old2NewVPBlocks[Exiting] : nullptr);
716 }
717 
718 VPRegionBlock *VPRegionBlock::clone() {
719   const auto &[NewEntry, NewExiting] = cloneFrom(getEntry());
720   auto *NewRegion =
721       new VPRegionBlock(NewEntry, NewExiting, getName(), isReplicator());
722   for (VPBlockBase *Block : vp_depth_first_shallow(NewEntry))
723     Block->setParent(NewRegion);
724   return NewRegion;
725 }
726 
727 void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
728   for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
729     // Drop all references in VPBasicBlocks and replace all uses with
730     // DummyValue.
731     Block->dropAllReferences(NewValue);
732 }
733 
734 void VPRegionBlock::execute(VPTransformState *State) {
735   ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>
736       RPOT(Entry);
737 
738   if (!isReplicator()) {
739     // Create and register the new vector loop.
740     Loop *PrevLoop = State->CurrentVectorLoop;
741     State->CurrentVectorLoop = State->LI->AllocateLoop();
742     BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()];
743     Loop *ParentLoop = State->LI->getLoopFor(VectorPH);
744 
745     // Insert the new loop into the loop nest and register the new basic blocks
746     // before calling any utilities such as SCEV that require valid LoopInfo.
747     if (ParentLoop)
748       ParentLoop->addChildLoop(State->CurrentVectorLoop);
749     else
750       State->LI->addTopLevelLoop(State->CurrentVectorLoop);
751 
752     // Visit the VPBlocks connected to "this", starting from it.
753     for (VPBlockBase *Block : RPOT) {
754       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
755       Block->execute(State);
756     }
757 
758     State->CurrentVectorLoop = PrevLoop;
759     return;
760   }
761 
762   assert(!State->Instance && "Replicating a Region with non-null instance.");
763 
764   // Enter replicating mode.
765   State->Instance = VPIteration(0, 0);
766 
767   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
768     State->Instance->Part = Part;
769     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
770     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
771          ++Lane) {
772       State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);
773       // Visit the VPBlocks connected to \p this, starting from it.
774       for (VPBlockBase *Block : RPOT) {
775         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
776         Block->execute(State);
777       }
778     }
779   }
780 
781   // Exit replicating mode.
782   State->Instance.reset();
783 }
784 
785 InstructionCost VPBasicBlock::cost(ElementCount VF, VPCostContext &Ctx) {
786   InstructionCost Cost = 0;
787   for (VPRecipeBase &R : Recipes)
788     Cost += R.cost(VF, Ctx);
789   return Cost;
790 }
791 
792 InstructionCost VPRegionBlock::cost(ElementCount VF, VPCostContext &Ctx) {
793   if (!isReplicator()) {
794     InstructionCost Cost = 0;
795     for (VPBlockBase *Block : vp_depth_first_shallow(getEntry()))
796       Cost += Block->cost(VF, Ctx);
797     InstructionCost BackedgeCost =
798         Ctx.TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
799     LLVM_DEBUG(dbgs() << "Cost of " << BackedgeCost << " for VF " << VF
800                       << ": vector loop backedge\n");
801     Cost += BackedgeCost;
802     return Cost;
803   }
804 
805   // Compute the cost of a replicate region. Replicating isn't supported for
806   // scalable vectors, return an invalid cost for them.
807   // TODO: Discard scalable VPlans with replicate recipes earlier after
808   // construction.
809   if (VF.isScalable())
810     return InstructionCost::getInvalid();
811 
812   // First compute the cost of the conditionally executed recipes, followed by
813   // account for the branching cost, except if the mask is a header mask or
814   // uniform condition.
815   using namespace llvm::VPlanPatternMatch;
816   VPBasicBlock *Then = cast<VPBasicBlock>(getEntry()->getSuccessors()[0]);
817   InstructionCost ThenCost = Then->cost(VF, Ctx);
818 
819   // For the scalar case, we may not always execute the original predicated
820   // block, Thus, scale the block's cost by the probability of executing it.
821   if (VF.isScalar())
822     return ThenCost / getReciprocalPredBlockProb();
823 
824   return ThenCost;
825 }
826 
827 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
828 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent,
829                           VPSlotTracker &SlotTracker) const {
830   O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
831   auto NewIndent = Indent + "  ";
832   for (auto *BlockBase : vp_depth_first_shallow(Entry)) {
833     O << '\n';
834     BlockBase->print(O, NewIndent, SlotTracker);
835   }
836   O << Indent << "}\n";
837 
838   printSuccessors(O, Indent);
839 }
840 #endif
841 
842 VPlan::~VPlan() {
843   for (auto &KV : LiveOuts)
844     delete KV.second;
845   LiveOuts.clear();
846 
847   if (Entry) {
848     VPValue DummyValue;
849     for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
850       Block->dropAllReferences(&DummyValue);
851 
852     VPBlockBase::deleteCFG(Entry);
853 
854     Preheader->dropAllReferences(&DummyValue);
855     delete Preheader;
856   }
857   for (VPValue *VPV : VPLiveInsToFree)
858     delete VPV;
859   if (BackedgeTakenCount)
860     delete BackedgeTakenCount;
861 }
862 
863 VPlanPtr VPlan::createInitialVPlan(const SCEV *TripCount, ScalarEvolution &SE,
864                                    bool RequiresScalarEpilogueCheck,
865                                    bool TailFolded, Loop *TheLoop) {
866   VPIRBasicBlock *Entry = new VPIRBasicBlock(TheLoop->getLoopPreheader());
867   VPBasicBlock *VecPreheader = new VPBasicBlock("vector.ph");
868   auto Plan = std::make_unique<VPlan>(Entry, VecPreheader);
869   Plan->TripCount =
870       vputils::getOrCreateVPValueForSCEVExpr(*Plan, TripCount, SE);
871   // Create VPRegionBlock, with empty header and latch blocks, to be filled
872   // during processing later.
873   VPBasicBlock *HeaderVPBB = new VPBasicBlock("vector.body");
874   VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch");
875   VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB);
876   auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop",
877                                       false /*isReplicator*/);
878 
879   VPBlockUtils::insertBlockAfter(TopRegion, VecPreheader);
880   VPBasicBlock *MiddleVPBB = new VPBasicBlock("middle.block");
881   VPBlockUtils::insertBlockAfter(MiddleVPBB, TopRegion);
882 
883   VPBasicBlock *ScalarPH = new VPBasicBlock("scalar.ph");
884   if (!RequiresScalarEpilogueCheck) {
885     VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);
886     return Plan;
887   }
888 
889   // If needed, add a check in the middle block to see if we have completed
890   // all of the iterations in the first vector loop.  Three cases:
891   // 1) If (N - N%VF) == N, then we *don't* need to run the remainder.
892   //    Thus if tail is to be folded, we know we don't need to run the
893   //    remainder and we can set the condition to true.
894   // 2) If we require a scalar epilogue, there is no conditional branch as
895   //    we unconditionally branch to the scalar preheader.  Do nothing.
896   // 3) Otherwise, construct a runtime check.
897   BasicBlock *IRExitBlock = TheLoop->getUniqueExitBlock();
898   auto *VPExitBlock = new VPIRBasicBlock(IRExitBlock);
899   // The connection order corresponds to the operands of the conditional branch.
900   VPBlockUtils::insertBlockAfter(VPExitBlock, MiddleVPBB);
901   VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);
902 
903   auto *ScalarLatchTerm = TheLoop->getLoopLatch()->getTerminator();
904   // Here we use the same DebugLoc as the scalar loop latch terminator instead
905   // of the corresponding compare because they may have ended up with
906   // different line numbers and we want to avoid awkward line stepping while
907   // debugging. Eg. if the compare has got a line number inside the loop.
908   VPBuilder Builder(MiddleVPBB);
909   VPValue *Cmp =
910       TailFolded
911           ? Plan->getOrAddLiveIn(ConstantInt::getTrue(
912                 IntegerType::getInt1Ty(TripCount->getType()->getContext())))
913           : Builder.createICmp(CmpInst::ICMP_EQ, Plan->getTripCount(),
914                                &Plan->getVectorTripCount(),
915                                ScalarLatchTerm->getDebugLoc(), "cmp.n");
916   Builder.createNaryOp(VPInstruction::BranchOnCond, {Cmp},
917                        ScalarLatchTerm->getDebugLoc());
918   return Plan;
919 }
920 
921 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,
922                              Value *CanonicalIVStartValue,
923                              VPTransformState &State) {
924   // Check if the backedge taken count is needed, and if so build it.
925   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
926     IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
927     auto *TCMO = Builder.CreateSub(TripCountV,
928                                    ConstantInt::get(TripCountV->getType(), 1),
929                                    "trip.count.minus.1");
930     BackedgeTakenCount->setUnderlyingValue(TCMO);
931   }
932 
933   VectorTripCount.setUnderlyingValue(VectorTripCountV);
934 
935   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
936   // FIXME: Model VF * UF computation completely in VPlan.
937   assert(VFxUF.getNumUsers() && "VFxUF expected to always have users");
938   VFxUF.setUnderlyingValue(
939       createStepForVF(Builder, TripCountV->getType(), State.VF, State.UF));
940 
941   // When vectorizing the epilogue loop, the canonical induction start value
942   // needs to be changed from zero to the value after the main vector loop.
943   // FIXME: Improve modeling for canonical IV start values in the epilogue loop.
944   if (CanonicalIVStartValue) {
945     VPValue *VPV = getOrAddLiveIn(CanonicalIVStartValue);
946     auto *IV = getCanonicalIV();
947     assert(all_of(IV->users(),
948                   [](const VPUser *U) {
949                     return isa<VPScalarIVStepsRecipe>(U) ||
950                            isa<VPScalarCastRecipe>(U) ||
951                            isa<VPDerivedIVRecipe>(U) ||
952                            cast<VPInstruction>(U)->getOpcode() ==
953                                Instruction::Add;
954                   }) &&
955            "the canonical IV should only be used by its increment or "
956            "ScalarIVSteps when resetting the start value");
957     IV->setOperand(0, VPV);
958   }
959 }
960 
961 /// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p
962 /// VPBB are moved to the newly created VPIRBasicBlock.  VPBB must have a single
963 /// predecessor, which is rewired to the new VPIRBasicBlock. All successors of
964 /// VPBB, if any, are rewired to the new VPIRBasicBlock.
965 static void replaceVPBBWithIRVPBB(VPBasicBlock *VPBB, BasicBlock *IRBB) {
966   VPIRBasicBlock *IRMiddleVPBB = new VPIRBasicBlock(IRBB);
967   for (auto &R : make_early_inc_range(*VPBB))
968     R.moveBefore(*IRMiddleVPBB, IRMiddleVPBB->end());
969   VPBlockBase *PredVPBB = VPBB->getSinglePredecessor();
970   VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
971   VPBlockUtils::connectBlocks(PredVPBB, IRMiddleVPBB);
972   for (auto *Succ : to_vector(VPBB->getSuccessors())) {
973     VPBlockUtils::connectBlocks(IRMiddleVPBB, Succ);
974     VPBlockUtils::disconnectBlocks(VPBB, Succ);
975   }
976   delete VPBB;
977 }
978 
979 /// Generate the code inside the preheader and body of the vectorized loop.
980 /// Assumes a single pre-header basic-block was created for this. Introduce
981 /// additional basic-blocks as needed, and fill them all.
982 void VPlan::execute(VPTransformState *State) {
983   // Initialize CFG state.
984   State->CFG.PrevVPBB = nullptr;
985   State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();
986   BasicBlock *VectorPreHeader = State->CFG.PrevBB;
987   State->Builder.SetInsertPoint(VectorPreHeader->getTerminator());
988 
989   // Disconnect VectorPreHeader from ExitBB in both the CFG and DT.
990   cast<BranchInst>(VectorPreHeader->getTerminator())->setSuccessor(0, nullptr);
991   State->CFG.DTU.applyUpdates(
992       {{DominatorTree::Delete, VectorPreHeader, State->CFG.ExitBB}});
993 
994   // Replace regular VPBB's for the middle and scalar preheader blocks with
995   // VPIRBasicBlocks wrapping their IR blocks. The IR blocks are created during
996   // skeleton creation, so we can only create the VPIRBasicBlocks now during
997   // VPlan execution rather than earlier during VPlan construction.
998   BasicBlock *MiddleBB = State->CFG.ExitBB;
999   VPBasicBlock *MiddleVPBB =
1000       cast<VPBasicBlock>(getVectorLoopRegion()->getSingleSuccessor());
1001   // Find the VPBB for the scalar preheader, relying on the current structure
1002   // when creating the middle block and its successrs: if there's a single
1003   // predecessor, it must be the scalar preheader. Otherwise, the second
1004   // successor is the scalar preheader.
1005   BasicBlock *ScalarPh = MiddleBB->getSingleSuccessor();
1006   auto &MiddleSuccs = MiddleVPBB->getSuccessors();
1007   assert((MiddleSuccs.size() == 1 || MiddleSuccs.size() == 2) &&
1008          "middle block has unexpected successors");
1009   VPBasicBlock *ScalarPhVPBB = cast<VPBasicBlock>(
1010       MiddleSuccs.size() == 1 ? MiddleSuccs[0] : MiddleSuccs[1]);
1011   assert(!isa<VPIRBasicBlock>(ScalarPhVPBB) &&
1012          "scalar preheader cannot be wrapped already");
1013   replaceVPBBWithIRVPBB(ScalarPhVPBB, ScalarPh);
1014   replaceVPBBWithIRVPBB(MiddleVPBB, MiddleBB);
1015 
1016   // Disconnect the middle block from its single successor (the scalar loop
1017   // header) in both the CFG and DT. The branch will be recreated during VPlan
1018   // execution.
1019   auto *BrInst = new UnreachableInst(MiddleBB->getContext());
1020   BrInst->insertBefore(MiddleBB->getTerminator());
1021   MiddleBB->getTerminator()->eraseFromParent();
1022   State->CFG.DTU.applyUpdates({{DominatorTree::Delete, MiddleBB, ScalarPh}});
1023 
1024   // Generate code in the loop pre-header and body.
1025   for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
1026     Block->execute(State);
1027 
1028   VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock();
1029   BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB];
1030 
1031   // Fix the latch value of canonical, reduction and first-order recurrences
1032   // phis in the vector loop.
1033   VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
1034   for (VPRecipeBase &R : Header->phis()) {
1035     // Skip phi-like recipes that generate their backedege values themselves.
1036     if (isa<VPWidenPHIRecipe>(&R))
1037       continue;
1038 
1039     if (isa<VPWidenPointerInductionRecipe>(&R) ||
1040         isa<VPWidenIntOrFpInductionRecipe>(&R)) {
1041       PHINode *Phi = nullptr;
1042       if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {
1043         Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));
1044       } else {
1045         auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);
1046         assert(!WidenPhi->onlyScalarsGenerated(State->VF.isScalable()) &&
1047                "recipe generating only scalars should have been replaced");
1048         auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));
1049         Phi = cast<PHINode>(GEP->getPointerOperand());
1050       }
1051 
1052       Phi->setIncomingBlock(1, VectorLatchBB);
1053 
1054       // Move the last step to the end of the latch block. This ensures
1055       // consistent placement of all induction updates.
1056       Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));
1057       Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());
1058       continue;
1059     }
1060 
1061     auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
1062     // For  canonical IV, first-order recurrences and in-order reduction phis,
1063     // only a single part is generated, which provides the last part from the
1064     // previous iteration. For non-ordered reductions all UF parts are
1065     // generated.
1066     bool SinglePartNeeded =
1067         isa<VPCanonicalIVPHIRecipe>(PhiR) ||
1068         isa<VPFirstOrderRecurrencePHIRecipe, VPEVLBasedIVPHIRecipe>(PhiR) ||
1069         (isa<VPReductionPHIRecipe>(PhiR) &&
1070          cast<VPReductionPHIRecipe>(PhiR)->isOrdered());
1071     bool NeedsScalar =
1072         isa<VPCanonicalIVPHIRecipe, VPEVLBasedIVPHIRecipe>(PhiR) ||
1073         (isa<VPReductionPHIRecipe>(PhiR) &&
1074          cast<VPReductionPHIRecipe>(PhiR)->isInLoop());
1075     unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
1076 
1077     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
1078       Value *Phi = State->get(PhiR, Part, NeedsScalar);
1079       Value *Val =
1080           State->get(PhiR->getBackedgeValue(),
1081                      SinglePartNeeded ? State->UF - 1 : Part, NeedsScalar);
1082       cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
1083     }
1084   }
1085 
1086   State->CFG.DTU.flush();
1087   assert(State->CFG.DTU.getDomTree().verify(
1088              DominatorTree::VerificationLevel::Fast) &&
1089          "DT not preserved correctly");
1090 }
1091 
1092 InstructionCost VPlan::cost(ElementCount VF, VPCostContext &Ctx) {
1093   // For now only return the cost of the vector loop region, ignoring any other
1094   // blocks, like the preheader or middle blocks.
1095   return getVectorLoopRegion()->cost(VF, Ctx);
1096 }
1097 
1098 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1099 void VPlan::printLiveIns(raw_ostream &O) const {
1100   VPSlotTracker SlotTracker(this);
1101 
1102   if (VFxUF.getNumUsers() > 0) {
1103     O << "\nLive-in ";
1104     VFxUF.printAsOperand(O, SlotTracker);
1105     O << " = VF * UF";
1106   }
1107 
1108   if (VectorTripCount.getNumUsers() > 0) {
1109     O << "\nLive-in ";
1110     VectorTripCount.printAsOperand(O, SlotTracker);
1111     O << " = vector-trip-count";
1112   }
1113 
1114   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
1115     O << "\nLive-in ";
1116     BackedgeTakenCount->printAsOperand(O, SlotTracker);
1117     O << " = backedge-taken count";
1118   }
1119 
1120   O << "\n";
1121   if (TripCount->isLiveIn())
1122     O << "Live-in ";
1123   TripCount->printAsOperand(O, SlotTracker);
1124   O << " = original trip-count";
1125   O << "\n";
1126 }
1127 
1128 LLVM_DUMP_METHOD
1129 void VPlan::print(raw_ostream &O) const {
1130   VPSlotTracker SlotTracker(this);
1131 
1132   O << "VPlan '" << getName() << "' {";
1133 
1134   printLiveIns(O);
1135 
1136   if (!getPreheader()->empty()) {
1137     O << "\n";
1138     getPreheader()->print(O, "", SlotTracker);
1139   }
1140 
1141   for (const VPBlockBase *Block : vp_depth_first_shallow(getEntry())) {
1142     O << '\n';
1143     Block->print(O, "", SlotTracker);
1144   }
1145 
1146   if (!LiveOuts.empty())
1147     O << "\n";
1148   for (const auto &KV : LiveOuts) {
1149     KV.second->print(O, SlotTracker);
1150   }
1151 
1152   O << "}\n";
1153 }
1154 
1155 std::string VPlan::getName() const {
1156   std::string Out;
1157   raw_string_ostream RSO(Out);
1158   RSO << Name << " for ";
1159   if (!VFs.empty()) {
1160     RSO << "VF={" << VFs[0];
1161     for (ElementCount VF : drop_begin(VFs))
1162       RSO << "," << VF;
1163     RSO << "},";
1164   }
1165 
1166   if (UFs.empty()) {
1167     RSO << "UF>=1";
1168   } else {
1169     RSO << "UF={" << UFs[0];
1170     for (unsigned UF : drop_begin(UFs))
1171       RSO << "," << UF;
1172     RSO << "}";
1173   }
1174 
1175   return Out;
1176 }
1177 
1178 LLVM_DUMP_METHOD
1179 void VPlan::printDOT(raw_ostream &O) const {
1180   VPlanPrinter Printer(O, *this);
1181   Printer.dump();
1182 }
1183 
1184 LLVM_DUMP_METHOD
1185 void VPlan::dump() const { print(dbgs()); }
1186 #endif
1187 
1188 void VPlan::addLiveOut(PHINode *PN, VPValue *V) {
1189   assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists");
1190   LiveOuts.insert({PN, new VPLiveOut(PN, V)});
1191 }
1192 
1193 static void remapOperands(VPBlockBase *Entry, VPBlockBase *NewEntry,
1194                           DenseMap<VPValue *, VPValue *> &Old2NewVPValues) {
1195   // Update the operands of all cloned recipes starting at NewEntry. This
1196   // traverses all reachable blocks. This is done in two steps, to handle cycles
1197   // in PHI recipes.
1198   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>>
1199       OldDeepRPOT(Entry);
1200   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>>
1201       NewDeepRPOT(NewEntry);
1202   // First, collect all mappings from old to new VPValues defined by cloned
1203   // recipes.
1204   for (const auto &[OldBB, NewBB] :
1205        zip(VPBlockUtils::blocksOnly<VPBasicBlock>(OldDeepRPOT),
1206            VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT))) {
1207     assert(OldBB->getRecipeList().size() == NewBB->getRecipeList().size() &&
1208            "blocks must have the same number of recipes");
1209     for (const auto &[OldR, NewR] : zip(*OldBB, *NewBB)) {
1210       assert(OldR.getNumOperands() == NewR.getNumOperands() &&
1211              "recipes must have the same number of operands");
1212       assert(OldR.getNumDefinedValues() == NewR.getNumDefinedValues() &&
1213              "recipes must define the same number of operands");
1214       for (const auto &[OldV, NewV] :
1215            zip(OldR.definedValues(), NewR.definedValues()))
1216         Old2NewVPValues[OldV] = NewV;
1217     }
1218   }
1219 
1220   // Update all operands to use cloned VPValues.
1221   for (VPBasicBlock *NewBB :
1222        VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT)) {
1223     for (VPRecipeBase &NewR : *NewBB)
1224       for (unsigned I = 0, E = NewR.getNumOperands(); I != E; ++I) {
1225         VPValue *NewOp = Old2NewVPValues.lookup(NewR.getOperand(I));
1226         NewR.setOperand(I, NewOp);
1227       }
1228   }
1229 }
1230 
1231 VPlan *VPlan::duplicate() {
1232   // Clone blocks.
1233   VPBasicBlock *NewPreheader = Preheader->clone();
1234   const auto &[NewEntry, __] = cloneFrom(Entry);
1235 
1236   // Create VPlan, clone live-ins and remap operands in the cloned blocks.
1237   auto *NewPlan = new VPlan(NewPreheader, cast<VPBasicBlock>(NewEntry));
1238   DenseMap<VPValue *, VPValue *> Old2NewVPValues;
1239   for (VPValue *OldLiveIn : VPLiveInsToFree) {
1240     Old2NewVPValues[OldLiveIn] =
1241         NewPlan->getOrAddLiveIn(OldLiveIn->getLiveInIRValue());
1242   }
1243   Old2NewVPValues[&VectorTripCount] = &NewPlan->VectorTripCount;
1244   Old2NewVPValues[&VFxUF] = &NewPlan->VFxUF;
1245   if (BackedgeTakenCount) {
1246     NewPlan->BackedgeTakenCount = new VPValue();
1247     Old2NewVPValues[BackedgeTakenCount] = NewPlan->BackedgeTakenCount;
1248   }
1249   assert(TripCount && "trip count must be set");
1250   if (TripCount->isLiveIn())
1251     Old2NewVPValues[TripCount] =
1252         NewPlan->getOrAddLiveIn(TripCount->getLiveInIRValue());
1253   // else NewTripCount will be created and inserted into Old2NewVPValues when
1254   // TripCount is cloned. In any case NewPlan->TripCount is updated below.
1255 
1256   remapOperands(Preheader, NewPreheader, Old2NewVPValues);
1257   remapOperands(Entry, NewEntry, Old2NewVPValues);
1258 
1259   // Clone live-outs.
1260   for (const auto &[_, LO] : LiveOuts)
1261     NewPlan->addLiveOut(LO->getPhi(), Old2NewVPValues[LO->getOperand(0)]);
1262 
1263   // Initialize remaining fields of cloned VPlan.
1264   NewPlan->VFs = VFs;
1265   NewPlan->UFs = UFs;
1266   // TODO: Adjust names.
1267   NewPlan->Name = Name;
1268   assert(Old2NewVPValues.contains(TripCount) &&
1269          "TripCount must have been added to Old2NewVPValues");
1270   NewPlan->TripCount = Old2NewVPValues[TripCount];
1271   return NewPlan;
1272 }
1273 
1274 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1275 
1276 Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
1277   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
1278          Twine(getOrCreateBID(Block));
1279 }
1280 
1281 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
1282   const std::string &Name = Block->getName();
1283   if (!Name.empty())
1284     return Name;
1285   return "VPB" + Twine(getOrCreateBID(Block));
1286 }
1287 
1288 void VPlanPrinter::dump() {
1289   Depth = 1;
1290   bumpIndent(0);
1291   OS << "digraph VPlan {\n";
1292   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
1293   if (!Plan.getName().empty())
1294     OS << "\\n" << DOT::EscapeString(Plan.getName());
1295 
1296   {
1297     // Print live-ins.
1298   std::string Str;
1299   raw_string_ostream SS(Str);
1300   Plan.printLiveIns(SS);
1301   SmallVector<StringRef, 0> Lines;
1302   StringRef(Str).rtrim('\n').split(Lines, "\n");
1303   for (auto Line : Lines)
1304     OS << DOT::EscapeString(Line.str()) << "\\n";
1305   }
1306 
1307   OS << "\"]\n";
1308   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
1309   OS << "edge [fontname=Courier, fontsize=30]\n";
1310   OS << "compound=true\n";
1311 
1312   dumpBlock(Plan.getPreheader());
1313 
1314   for (const VPBlockBase *Block : vp_depth_first_shallow(Plan.getEntry()))
1315     dumpBlock(Block);
1316 
1317   OS << "}\n";
1318 }
1319 
1320 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
1321   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
1322     dumpBasicBlock(BasicBlock);
1323   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1324     dumpRegion(Region);
1325   else
1326     llvm_unreachable("Unsupported kind of VPBlock.");
1327 }
1328 
1329 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
1330                             bool Hidden, const Twine &Label) {
1331   // Due to "dot" we print an edge between two regions as an edge between the
1332   // exiting basic block and the entry basic of the respective regions.
1333   const VPBlockBase *Tail = From->getExitingBasicBlock();
1334   const VPBlockBase *Head = To->getEntryBasicBlock();
1335   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
1336   OS << " [ label=\"" << Label << '\"';
1337   if (Tail != From)
1338     OS << " ltail=" << getUID(From);
1339   if (Head != To)
1340     OS << " lhead=" << getUID(To);
1341   if (Hidden)
1342     OS << "; splines=none";
1343   OS << "]\n";
1344 }
1345 
1346 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
1347   auto &Successors = Block->getSuccessors();
1348   if (Successors.size() == 1)
1349     drawEdge(Block, Successors.front(), false, "");
1350   else if (Successors.size() == 2) {
1351     drawEdge(Block, Successors.front(), false, "T");
1352     drawEdge(Block, Successors.back(), false, "F");
1353   } else {
1354     unsigned SuccessorNumber = 0;
1355     for (auto *Successor : Successors)
1356       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
1357   }
1358 }
1359 
1360 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
1361   // Implement dot-formatted dump by performing plain-text dump into the
1362   // temporary storage followed by some post-processing.
1363   OS << Indent << getUID(BasicBlock) << " [label =\n";
1364   bumpIndent(1);
1365   std::string Str;
1366   raw_string_ostream SS(Str);
1367   // Use no indentation as we need to wrap the lines into quotes ourselves.
1368   BasicBlock->print(SS, "", SlotTracker);
1369 
1370   // We need to process each line of the output separately, so split
1371   // single-string plain-text dump.
1372   SmallVector<StringRef, 0> Lines;
1373   StringRef(Str).rtrim('\n').split(Lines, "\n");
1374 
1375   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
1376     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
1377   };
1378 
1379   // Don't need the "+" after the last line.
1380   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
1381     EmitLine(Line, " +\n");
1382   EmitLine(Lines.back(), "\n");
1383 
1384   bumpIndent(-1);
1385   OS << Indent << "]\n";
1386 
1387   dumpEdges(BasicBlock);
1388 }
1389 
1390 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
1391   OS << Indent << "subgraph " << getUID(Region) << " {\n";
1392   bumpIndent(1);
1393   OS << Indent << "fontname=Courier\n"
1394      << Indent << "label=\""
1395      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
1396      << DOT::EscapeString(Region->getName()) << "\"\n";
1397   // Dump the blocks of the region.
1398   assert(Region->getEntry() && "Region contains no inner blocks.");
1399   for (const VPBlockBase *Block : vp_depth_first_shallow(Region->getEntry()))
1400     dumpBlock(Block);
1401   bumpIndent(-1);
1402   OS << Indent << "}\n";
1403   dumpEdges(Region);
1404 }
1405 
1406 void VPlanIngredient::print(raw_ostream &O) const {
1407   if (auto *Inst = dyn_cast<Instruction>(V)) {
1408     if (!Inst->getType()->isVoidTy()) {
1409       Inst->printAsOperand(O, false);
1410       O << " = ";
1411     }
1412     O << Inst->getOpcodeName() << " ";
1413     unsigned E = Inst->getNumOperands();
1414     if (E > 0) {
1415       Inst->getOperand(0)->printAsOperand(O, false);
1416       for (unsigned I = 1; I < E; ++I)
1417         Inst->getOperand(I)->printAsOperand(O << ", ", false);
1418     }
1419   } else // !Inst
1420     V->printAsOperand(O, false);
1421 }
1422 
1423 #endif
1424 
1425 void VPValue::replaceAllUsesWith(VPValue *New) {
1426   replaceUsesWithIf(New, [](VPUser &, unsigned) { return true; });
1427 }
1428 
1429 void VPValue::replaceUsesWithIf(
1430     VPValue *New,
1431     llvm::function_ref<bool(VPUser &U, unsigned Idx)> ShouldReplace) {
1432   // Note that this early exit is required for correctness; the implementation
1433   // below relies on the number of users for this VPValue to decrease, which
1434   // isn't the case if this == New.
1435   if (this == New)
1436     return;
1437 
1438   for (unsigned J = 0; J < getNumUsers();) {
1439     VPUser *User = Users[J];
1440     bool RemovedUser = false;
1441     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) {
1442       if (User->getOperand(I) != this || !ShouldReplace(*User, I))
1443         continue;
1444 
1445       RemovedUser = true;
1446       User->setOperand(I, New);
1447     }
1448     // If a user got removed after updating the current user, the next user to
1449     // update will be moved to the current position, so we only need to
1450     // increment the index if the number of users did not change.
1451     if (!RemovedUser)
1452       J++;
1453   }
1454 }
1455 
1456 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1457 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1458   OS << Tracker.getOrCreateName(this);
1459 }
1460 
1461 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1462   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1463     Op->printAsOperand(O, SlotTracker);
1464   });
1465 }
1466 #endif
1467 
1468 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1469                                           Old2NewTy &Old2New,
1470                                           InterleavedAccessInfo &IAI) {
1471   ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>
1472       RPOT(Region->getEntry());
1473   for (VPBlockBase *Base : RPOT) {
1474     visitBlock(Base, Old2New, IAI);
1475   }
1476 }
1477 
1478 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1479                                          InterleavedAccessInfo &IAI) {
1480   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1481     for (VPRecipeBase &VPI : *VPBB) {
1482       if (isa<VPWidenPHIRecipe>(&VPI))
1483         continue;
1484       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1485       auto *VPInst = cast<VPInstruction>(&VPI);
1486 
1487       auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue());
1488       if (!Inst)
1489         continue;
1490       auto *IG = IAI.getInterleaveGroup(Inst);
1491       if (!IG)
1492         continue;
1493 
1494       auto NewIGIter = Old2New.find(IG);
1495       if (NewIGIter == Old2New.end())
1496         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1497             IG->getFactor(), IG->isReverse(), IG->getAlign());
1498 
1499       if (Inst == IG->getInsertPos())
1500         Old2New[IG]->setInsertPos(VPInst);
1501 
1502       InterleaveGroupMap[VPInst] = Old2New[IG];
1503       InterleaveGroupMap[VPInst]->insertMember(
1504           VPInst, IG->getIndex(Inst),
1505           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1506                                 : IG->getFactor()));
1507     }
1508   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1509     visitRegion(Region, Old2New, IAI);
1510   else
1511     llvm_unreachable("Unsupported kind of VPBlock.");
1512 }
1513 
1514 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1515                                                  InterleavedAccessInfo &IAI) {
1516   Old2NewTy Old2New;
1517   visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI);
1518 }
1519 
1520 void VPSlotTracker::assignName(const VPValue *V) {
1521   assert(!VPValue2Name.contains(V) && "VPValue already has a name!");
1522   auto *UV = V->getUnderlyingValue();
1523   if (!UV) {
1524     VPValue2Name[V] = (Twine("vp<%") + Twine(NextSlot) + ">").str();
1525     NextSlot++;
1526     return;
1527   }
1528 
1529   // Use the name of the underlying Value, wrapped in "ir<>", and versioned by
1530   // appending ".Number" to the name if there are multiple uses.
1531   std::string Name;
1532   raw_string_ostream S(Name);
1533   UV->printAsOperand(S, false);
1534   assert(!Name.empty() && "Name cannot be empty.");
1535   std::string BaseName = (Twine("ir<") + Name + Twine(">")).str();
1536 
1537   // First assign the base name for V.
1538   const auto &[A, _] = VPValue2Name.insert({V, BaseName});
1539   // Integer or FP constants with different types will result in he same string
1540   // due to stripping types.
1541   if (V->isLiveIn() && isa<ConstantInt, ConstantFP>(UV))
1542     return;
1543 
1544   // If it is already used by C > 0 other VPValues, increase the version counter
1545   // C and use it for V.
1546   const auto &[C, UseInserted] = BaseName2Version.insert({BaseName, 0});
1547   if (!UseInserted) {
1548     C->second++;
1549     A->second = (BaseName + Twine(".") + Twine(C->second)).str();
1550   }
1551 }
1552 
1553 void VPSlotTracker::assignNames(const VPlan &Plan) {
1554   if (Plan.VFxUF.getNumUsers() > 0)
1555     assignName(&Plan.VFxUF);
1556   assignName(&Plan.VectorTripCount);
1557   if (Plan.BackedgeTakenCount)
1558     assignName(Plan.BackedgeTakenCount);
1559   for (VPValue *LI : Plan.VPLiveInsToFree)
1560     assignName(LI);
1561   assignNames(Plan.getPreheader());
1562 
1563   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<const VPBlockBase *>>
1564       RPOT(VPBlockDeepTraversalWrapper<const VPBlockBase *>(Plan.getEntry()));
1565   for (const VPBasicBlock *VPBB :
1566        VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1567     assignNames(VPBB);
1568 }
1569 
1570 void VPSlotTracker::assignNames(const VPBasicBlock *VPBB) {
1571   for (const VPRecipeBase &Recipe : *VPBB)
1572     for (VPValue *Def : Recipe.definedValues())
1573       assignName(Def);
1574 }
1575 
1576 std::string VPSlotTracker::getOrCreateName(const VPValue *V) const {
1577   std::string Name = VPValue2Name.lookup(V);
1578   if (!Name.empty())
1579     return Name;
1580 
1581   // If no name was assigned, no VPlan was provided when creating the slot
1582   // tracker or it is not reachable from the provided VPlan. This can happen,
1583   // e.g. when trying to print a recipe that has not been inserted into a VPlan
1584   // in a debugger.
1585   // TODO: Update VPSlotTracker constructor to assign names to recipes &
1586   // VPValues not associated with a VPlan, instead of constructing names ad-hoc
1587   // here.
1588   const VPRecipeBase *DefR = V->getDefiningRecipe();
1589   (void)DefR;
1590   assert((!DefR || !DefR->getParent() || !DefR->getParent()->getPlan()) &&
1591          "VPValue defined by a recipe in a VPlan?");
1592 
1593   // Use the underlying value's name, if there is one.
1594   if (auto *UV = V->getUnderlyingValue()) {
1595     std::string Name;
1596     raw_string_ostream S(Name);
1597     UV->printAsOperand(S, false);
1598     return (Twine("ir<") + Name + ">").str();
1599   }
1600 
1601   return "<badref>";
1602 }
1603 
1604 bool LoopVectorizationPlanner::getDecisionAndClampRange(
1605     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
1606   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
1607   bool PredicateAtRangeStart = Predicate(Range.Start);
1608 
1609   for (ElementCount TmpVF : VFRange(Range.Start * 2, Range.End))
1610     if (Predicate(TmpVF) != PredicateAtRangeStart) {
1611       Range.End = TmpVF;
1612       break;
1613     }
1614 
1615   return PredicateAtRangeStart;
1616 }
1617 
1618 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
1619 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
1620 /// of VF's starting at a given VF and extending it as much as possible. Each
1621 /// vectorization decision can potentially shorten this sub-range during
1622 /// buildVPlan().
1623 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
1624                                            ElementCount MaxVF) {
1625   auto MaxVFTimes2 = MaxVF * 2;
1626   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFTimes2);) {
1627     VFRange SubRange = {VF, MaxVFTimes2};
1628     auto Plan = buildVPlan(SubRange);
1629     VPlanTransforms::optimize(*Plan, *PSE.getSE());
1630     VPlans.push_back(std::move(Plan));
1631     VF = SubRange.End;
1632   }
1633 }
1634 
1635 VPlan &LoopVectorizationPlanner::getPlanFor(ElementCount VF) const {
1636   assert(count_if(VPlans,
1637                   [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) ==
1638              1 &&
1639          "Multiple VPlans for VF.");
1640 
1641   for (const VPlanPtr &Plan : VPlans) {
1642     if (Plan->hasVF(VF))
1643       return *Plan.get();
1644   }
1645   llvm_unreachable("No plan found!");
1646 }
1647 
1648 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1649 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
1650   if (VPlans.empty()) {
1651     O << "LV: No VPlans built.\n";
1652     return;
1653   }
1654   for (const auto &Plan : VPlans)
1655     if (PrintVPlansInDotFormat)
1656       Plan->printDOT(O);
1657     else
1658       Plan->print(O);
1659 }
1660 #endif
1661