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