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