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