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