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