xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision a002271972fb3fb2877bdb4abf9275b2c1291036)
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 
450     // Update the branch instruction in the predecessor to branch to ExitBB.
451     VPBlockBase *PredVPB = getSingleHierarchicalPredecessor();
452     VPBasicBlock *ExitingVPBB = PredVPB->getExitingBasicBlock();
453     assert(PredVPB->getSingleSuccessor() == this &&
454            "predecessor must have the current block as only successor");
455     BasicBlock *ExitingBB = State->CFG.VPBB2IRBB[ExitingVPBB];
456     // The Exit block of a loop is always set to be successor 0 of the Exiting
457     // block.
458     cast<BranchInst>(ExitingBB->getTerminator())->setSuccessor(0, NewBB);
459   } else if (PrevVPBB && /* A */
460              !((SingleHPred = getSingleHierarchicalPredecessor()) &&
461                SingleHPred->getExitingBasicBlock() == PrevVPBB &&
462                PrevVPBB->getSingleHierarchicalSuccessor() &&
463                (SingleHPred->getParent() == getEnclosingLoopRegion() &&
464                 !IsLoopRegion(SingleHPred))) &&         /* B */
465              !(Replica && getPredecessors().empty())) { /* C */
466     // The last IR basic block is reused, as an optimization, in three cases:
467     // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null;
468     // B. when the current VPBB has a single (hierarchical) predecessor which
469     //    is PrevVPBB and the latter has a single (hierarchical) successor which
470     //    both are in the same non-replicator region; and
471     // C. when the current VPBB is an entry of a region replica - where PrevVPBB
472     //    is the exiting VPBB of this region from a previous instance, or the
473     //    predecessor of this region.
474 
475     NewBB = createEmptyBasicBlock(State->CFG);
476     State->Builder.SetInsertPoint(NewBB);
477     // Temporarily terminate with unreachable until CFG is rewired.
478     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
479     // Register NewBB in its loop. In innermost loops its the same for all
480     // BB's.
481     if (State->CurrentVectorLoop)
482       State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI);
483     State->Builder.SetInsertPoint(Terminator);
484     State->CFG.PrevBB = NewBB;
485   }
486 
487   // 2. Fill the IR basic block with IR instructions.
488   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
489                     << " in BB:" << NewBB->getName() << '\n');
490 
491   State->CFG.VPBB2IRBB[this] = NewBB;
492   State->CFG.PrevVPBB = this;
493 
494   for (VPRecipeBase &Recipe : Recipes)
495     Recipe.execute(*State);
496 
497   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
498 }
499 
500 void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
501   for (VPRecipeBase &R : Recipes) {
502     for (auto *Def : R.definedValues())
503       Def->replaceAllUsesWith(NewValue);
504 
505     for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
506       R.setOperand(I, NewValue);
507   }
508 }
509 
510 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) {
511   assert((SplitAt == end() || SplitAt->getParent() == this) &&
512          "can only split at a position in the same block");
513 
514   SmallVector<VPBlockBase *, 2> Succs(successors());
515   // First, disconnect the current block from its successors.
516   for (VPBlockBase *Succ : Succs)
517     VPBlockUtils::disconnectBlocks(this, Succ);
518 
519   // Create new empty block after the block to split.
520   auto *SplitBlock = new VPBasicBlock(getName() + ".split");
521   VPBlockUtils::insertBlockAfter(SplitBlock, this);
522 
523   // Add successors for block to split to new block.
524   for (VPBlockBase *Succ : Succs)
525     VPBlockUtils::connectBlocks(SplitBlock, Succ);
526 
527   // Finally, move the recipes starting at SplitAt to new block.
528   for (VPRecipeBase &ToMove :
529        make_early_inc_range(make_range(SplitAt, this->end())))
530     ToMove.moveBefore(*SplitBlock, SplitBlock->end());
531 
532   return SplitBlock;
533 }
534 
535 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() {
536   VPRegionBlock *P = getParent();
537   if (P && P->isReplicator()) {
538     P = P->getParent();
539     assert(!cast<VPRegionBlock>(P)->isReplicator() &&
540            "unexpected nested replicate regions");
541   }
542   return P;
543 }
544 
545 static bool hasConditionalTerminator(const VPBasicBlock *VPBB) {
546   if (VPBB->empty()) {
547     assert(
548         VPBB->getNumSuccessors() < 2 &&
549         "block with multiple successors doesn't have a recipe as terminator");
550     return false;
551   }
552 
553   const VPRecipeBase *R = &VPBB->back();
554   auto *VPI = dyn_cast<VPInstruction>(R);
555   bool IsCondBranch =
556       isa<VPBranchOnMaskRecipe>(R) ||
557       (VPI && (VPI->getOpcode() == VPInstruction::BranchOnCond ||
558                VPI->getOpcode() == VPInstruction::BranchOnCount));
559   (void)IsCondBranch;
560 
561   if (VPBB->getNumSuccessors() >= 2 || VPBB->isExiting()) {
562     assert(IsCondBranch && "block with multiple successors not terminated by "
563                            "conditional branch recipe");
564 
565     return true;
566   }
567 
568   assert(
569       !IsCondBranch &&
570       "block with 0 or 1 successors terminated by conditional branch recipe");
571   return false;
572 }
573 
574 VPRecipeBase *VPBasicBlock::getTerminator() {
575   if (hasConditionalTerminator(this))
576     return &back();
577   return nullptr;
578 }
579 
580 const VPRecipeBase *VPBasicBlock::getTerminator() const {
581   if (hasConditionalTerminator(this))
582     return &back();
583   return nullptr;
584 }
585 
586 bool VPBasicBlock::isExiting() const {
587   return getParent()->getExitingBasicBlock() == this;
588 }
589 
590 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
591 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {
592   if (getSuccessors().empty()) {
593     O << Indent << "No successors\n";
594   } else {
595     O << Indent << "Successor(s): ";
596     ListSeparator LS;
597     for (auto *Succ : getSuccessors())
598       O << LS << Succ->getName();
599     O << '\n';
600   }
601 }
602 
603 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
604                          VPSlotTracker &SlotTracker) const {
605   O << Indent << getName() << ":\n";
606 
607   auto RecipeIndent = Indent + "  ";
608   for (const VPRecipeBase &Recipe : *this) {
609     Recipe.print(O, RecipeIndent, SlotTracker);
610     O << '\n';
611   }
612 
613   printSuccessors(O, Indent);
614 }
615 #endif
616 
617 void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
618   for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
619     // Drop all references in VPBasicBlocks and replace all uses with
620     // DummyValue.
621     Block->dropAllReferences(NewValue);
622 }
623 
624 void VPRegionBlock::execute(VPTransformState *State) {
625   ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>
626       RPOT(Entry);
627 
628   if (!isReplicator()) {
629     // Create and register the new vector loop.
630     Loop *PrevLoop = State->CurrentVectorLoop;
631     State->CurrentVectorLoop = State->LI->AllocateLoop();
632     BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()];
633     Loop *ParentLoop = State->LI->getLoopFor(VectorPH);
634 
635     // Insert the new loop into the loop nest and register the new basic blocks
636     // before calling any utilities such as SCEV that require valid LoopInfo.
637     if (ParentLoop)
638       ParentLoop->addChildLoop(State->CurrentVectorLoop);
639     else
640       State->LI->addTopLevelLoop(State->CurrentVectorLoop);
641 
642     // Visit the VPBlocks connected to "this", starting from it.
643     for (VPBlockBase *Block : RPOT) {
644       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
645       Block->execute(State);
646     }
647 
648     State->CurrentVectorLoop = PrevLoop;
649     return;
650   }
651 
652   assert(!State->Instance && "Replicating a Region with non-null instance.");
653 
654   // Enter replicating mode.
655   State->Instance = VPIteration(0, 0);
656 
657   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
658     State->Instance->Part = Part;
659     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
660     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
661          ++Lane) {
662       State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);
663       // Visit the VPBlocks connected to \p this, starting from it.
664       for (VPBlockBase *Block : RPOT) {
665         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
666         Block->execute(State);
667       }
668     }
669   }
670 
671   // Exit replicating mode.
672   State->Instance.reset();
673 }
674 
675 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
676 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent,
677                           VPSlotTracker &SlotTracker) const {
678   O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
679   auto NewIndent = Indent + "  ";
680   for (auto *BlockBase : vp_depth_first_shallow(Entry)) {
681     O << '\n';
682     BlockBase->print(O, NewIndent, SlotTracker);
683   }
684   O << Indent << "}\n";
685 
686   printSuccessors(O, Indent);
687 }
688 #endif
689 
690 VPlan::~VPlan() {
691   for (auto &KV : LiveOuts)
692     delete KV.second;
693   LiveOuts.clear();
694 
695   if (Entry) {
696     VPValue DummyValue;
697     for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
698       Block->dropAllReferences(&DummyValue);
699 
700     VPBlockBase::deleteCFG(Entry);
701 
702     Preheader->dropAllReferences(&DummyValue);
703     delete Preheader;
704   }
705   for (VPValue *VPV : VPLiveInsToFree)
706     delete VPV;
707   if (BackedgeTakenCount)
708     delete BackedgeTakenCount;
709 }
710 
711 VPlanPtr VPlan::createInitialVPlan(const SCEV *TripCount, ScalarEvolution &SE) {
712   VPBasicBlock *Preheader = new VPBasicBlock("ph");
713   VPBasicBlock *VecPreheader = new VPBasicBlock("vector.ph");
714   auto Plan = std::make_unique<VPlan>(Preheader, VecPreheader);
715   Plan->TripCount =
716       vputils::getOrCreateVPValueForSCEVExpr(*Plan, TripCount, SE);
717   return Plan;
718 }
719 
720 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,
721                              Value *CanonicalIVStartValue,
722                              VPTransformState &State,
723                              bool IsEpilogueVectorization) {
724   // Check if the backedge taken count is needed, and if so build it.
725   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
726     IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
727     auto *TCMO = Builder.CreateSub(TripCountV,
728                                    ConstantInt::get(TripCountV->getType(), 1),
729                                    "trip.count.minus.1");
730     auto VF = State.VF;
731     Value *VTCMO =
732         VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
733     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
734       State.set(BackedgeTakenCount, VTCMO, Part);
735   }
736 
737   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
738     State.set(&VectorTripCount, VectorTripCountV, Part);
739 
740   // When vectorizing the epilogue loop, the canonical induction start value
741   // needs to be changed from zero to the value after the main vector loop.
742   // FIXME: Improve modeling for canonical IV start values in the epilogue loop.
743   if (CanonicalIVStartValue) {
744     VPValue *VPV = getVPValueOrAddLiveIn(CanonicalIVStartValue);
745     auto *IV = getCanonicalIV();
746     assert(all_of(IV->users(),
747                   [](const VPUser *U) {
748                     return isa<VPScalarIVStepsRecipe>(U) ||
749                            isa<VPDerivedIVRecipe>(U) ||
750                            cast<VPInstruction>(U)->getOpcode() ==
751                                VPInstruction::CanonicalIVIncrement;
752                   }) &&
753            "the canonical IV should only be used by its increment or "
754            "ScalarIVSteps when resetting the start value");
755     IV->setOperand(0, VPV);
756   }
757 }
758 
759 /// Generate the code inside the preheader and body of the vectorized loop.
760 /// Assumes a single pre-header basic-block was created for this. Introduce
761 /// additional basic-blocks as needed, and fill them all.
762 void VPlan::execute(VPTransformState *State) {
763   // Set the reverse mapping from VPValues to Values for code generation.
764   for (auto &Entry : Value2VPValue)
765     State->VPValue2Value[Entry.second] = Entry.first;
766 
767   // Initialize CFG state.
768   State->CFG.PrevVPBB = nullptr;
769   State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();
770   BasicBlock *VectorPreHeader = State->CFG.PrevBB;
771   State->Builder.SetInsertPoint(VectorPreHeader->getTerminator());
772 
773   // Generate code in the loop pre-header and body.
774   for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
775     Block->execute(State);
776 
777   VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock();
778   BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB];
779 
780   // Fix the latch value of canonical, reduction and first-order recurrences
781   // phis in the vector loop.
782   VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
783   for (VPRecipeBase &R : Header->phis()) {
784     // Skip phi-like recipes that generate their backedege values themselves.
785     if (isa<VPWidenPHIRecipe>(&R))
786       continue;
787 
788     if (isa<VPWidenPointerInductionRecipe>(&R) ||
789         isa<VPWidenIntOrFpInductionRecipe>(&R)) {
790       PHINode *Phi = nullptr;
791       if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {
792         Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));
793       } else {
794         auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);
795         // TODO: Split off the case that all users of a pointer phi are scalar
796         // from the VPWidenPointerInductionRecipe.
797         if (WidenPhi->onlyScalarsGenerated(State->VF))
798           continue;
799 
800         auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));
801         Phi = cast<PHINode>(GEP->getPointerOperand());
802       }
803 
804       Phi->setIncomingBlock(1, VectorLatchBB);
805 
806       // Move the last step to the end of the latch block. This ensures
807       // consistent placement of all induction updates.
808       Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));
809       Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());
810       continue;
811     }
812 
813     auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
814     // For  canonical IV, first-order recurrences and in-order reduction phis,
815     // only a single part is generated, which provides the last part from the
816     // previous iteration. For non-ordered reductions all UF parts are
817     // generated.
818     bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) ||
819                             isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) ||
820                             (isa<VPReductionPHIRecipe>(PhiR) &&
821                              cast<VPReductionPHIRecipe>(PhiR)->isOrdered());
822     unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
823 
824     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
825       Value *Phi = State->get(PhiR, Part);
826       Value *Val = State->get(PhiR->getBackedgeValue(),
827                               SinglePartNeeded ? State->UF - 1 : Part);
828       cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
829     }
830   }
831 
832   // We do not attempt to preserve DT for outer loop vectorization currently.
833   if (!EnableVPlanNativePath) {
834     BasicBlock *VectorHeaderBB = State->CFG.VPBB2IRBB[Header];
835     State->DT->addNewBlock(VectorHeaderBB, VectorPreHeader);
836     updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB,
837                         State->CFG.ExitBB);
838   }
839 }
840 
841 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
842 LLVM_DUMP_METHOD
843 void VPlan::print(raw_ostream &O) const {
844   VPSlotTracker SlotTracker(this);
845 
846   O << "VPlan '" << getName() << "' {";
847 
848   if (VectorTripCount.getNumUsers() > 0) {
849     O << "\nLive-in ";
850     VectorTripCount.printAsOperand(O, SlotTracker);
851     O << " = vector-trip-count";
852   }
853 
854   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
855     O << "\nLive-in ";
856     BackedgeTakenCount->printAsOperand(O, SlotTracker);
857     O << " = backedge-taken count";
858   }
859 
860   O << "\n";
861   if (TripCount->isLiveIn())
862     O << "Live-in ";
863   TripCount->printAsOperand(O, SlotTracker);
864   O << " = original trip-count";
865   O << "\n";
866 
867   if (!getPreheader()->empty()) {
868     O << "\n";
869     getPreheader()->print(O, "", SlotTracker);
870   }
871 
872   for (const VPBlockBase *Block : vp_depth_first_shallow(getEntry())) {
873     O << '\n';
874     Block->print(O, "", SlotTracker);
875   }
876 
877   if (!LiveOuts.empty())
878     O << "\n";
879   for (const auto &KV : LiveOuts) {
880     KV.second->print(O, SlotTracker);
881   }
882 
883   O << "}\n";
884 }
885 
886 std::string VPlan::getName() const {
887   std::string Out;
888   raw_string_ostream RSO(Out);
889   RSO << Name << " for ";
890   if (!VFs.empty()) {
891     RSO << "VF={" << VFs[0];
892     for (ElementCount VF : drop_begin(VFs))
893       RSO << "," << VF;
894     RSO << "},";
895   }
896 
897   if (UFs.empty()) {
898     RSO << "UF>=1";
899   } else {
900     RSO << "UF={" << UFs[0];
901     for (unsigned UF : drop_begin(UFs))
902       RSO << "," << UF;
903     RSO << "}";
904   }
905 
906   return Out;
907 }
908 
909 LLVM_DUMP_METHOD
910 void VPlan::printDOT(raw_ostream &O) const {
911   VPlanPrinter Printer(O, *this);
912   Printer.dump();
913 }
914 
915 LLVM_DUMP_METHOD
916 void VPlan::dump() const { print(dbgs()); }
917 #endif
918 
919 void VPlan::addLiveOut(PHINode *PN, VPValue *V) {
920   assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists");
921   LiveOuts.insert({PN, new VPLiveOut(PN, V)});
922 }
923 
924 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB,
925                                 BasicBlock *LoopLatchBB,
926                                 BasicBlock *LoopExitBB) {
927   // The vector body may be more than a single basic-block by this point.
928   // Update the dominator tree information inside the vector body by propagating
929   // it from header to latch, expecting only triangular control-flow, if any.
930   BasicBlock *PostDomSucc = nullptr;
931   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
932     // Get the list of successors of this block.
933     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
934     assert(Succs.size() <= 2 &&
935            "Basic block in vector loop has more than 2 successors.");
936     PostDomSucc = Succs[0];
937     if (Succs.size() == 1) {
938       assert(PostDomSucc->getSinglePredecessor() &&
939              "PostDom successor has more than one predecessor.");
940       DT->addNewBlock(PostDomSucc, BB);
941       continue;
942     }
943     BasicBlock *InterimSucc = Succs[1];
944     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
945       PostDomSucc = Succs[1];
946       InterimSucc = Succs[0];
947     }
948     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
949            "One successor of a basic block does not lead to the other.");
950     assert(InterimSucc->getSinglePredecessor() &&
951            "Interim successor has more than one predecessor.");
952     assert(PostDomSucc->hasNPredecessors(2) &&
953            "PostDom successor has more than two predecessors.");
954     DT->addNewBlock(InterimSucc, BB);
955     DT->addNewBlock(PostDomSucc, BB);
956   }
957   // Latch block is a new dominator for the loop exit.
958   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
959   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
960 }
961 
962 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
963 
964 Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
965   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
966          Twine(getOrCreateBID(Block));
967 }
968 
969 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
970   const std::string &Name = Block->getName();
971   if (!Name.empty())
972     return Name;
973   return "VPB" + Twine(getOrCreateBID(Block));
974 }
975 
976 void VPlanPrinter::dump() {
977   Depth = 1;
978   bumpIndent(0);
979   OS << "digraph VPlan {\n";
980   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
981   if (!Plan.getName().empty())
982     OS << "\\n" << DOT::EscapeString(Plan.getName());
983   if (Plan.BackedgeTakenCount) {
984     OS << ", where:\\n";
985     Plan.BackedgeTakenCount->print(OS, SlotTracker);
986     OS << " := BackedgeTakenCount";
987   }
988   OS << "\"]\n";
989   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
990   OS << "edge [fontname=Courier, fontsize=30]\n";
991   OS << "compound=true\n";
992 
993   dumpBlock(Plan.getPreheader());
994 
995   for (const VPBlockBase *Block : vp_depth_first_shallow(Plan.getEntry()))
996     dumpBlock(Block);
997 
998   OS << "}\n";
999 }
1000 
1001 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
1002   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
1003     dumpBasicBlock(BasicBlock);
1004   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1005     dumpRegion(Region);
1006   else
1007     llvm_unreachable("Unsupported kind of VPBlock.");
1008 }
1009 
1010 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
1011                             bool Hidden, const Twine &Label) {
1012   // Due to "dot" we print an edge between two regions as an edge between the
1013   // exiting basic block and the entry basic of the respective regions.
1014   const VPBlockBase *Tail = From->getExitingBasicBlock();
1015   const VPBlockBase *Head = To->getEntryBasicBlock();
1016   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
1017   OS << " [ label=\"" << Label << '\"';
1018   if (Tail != From)
1019     OS << " ltail=" << getUID(From);
1020   if (Head != To)
1021     OS << " lhead=" << getUID(To);
1022   if (Hidden)
1023     OS << "; splines=none";
1024   OS << "]\n";
1025 }
1026 
1027 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
1028   auto &Successors = Block->getSuccessors();
1029   if (Successors.size() == 1)
1030     drawEdge(Block, Successors.front(), false, "");
1031   else if (Successors.size() == 2) {
1032     drawEdge(Block, Successors.front(), false, "T");
1033     drawEdge(Block, Successors.back(), false, "F");
1034   } else {
1035     unsigned SuccessorNumber = 0;
1036     for (auto *Successor : Successors)
1037       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
1038   }
1039 }
1040 
1041 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
1042   // Implement dot-formatted dump by performing plain-text dump into the
1043   // temporary storage followed by some post-processing.
1044   OS << Indent << getUID(BasicBlock) << " [label =\n";
1045   bumpIndent(1);
1046   std::string Str;
1047   raw_string_ostream SS(Str);
1048   // Use no indentation as we need to wrap the lines into quotes ourselves.
1049   BasicBlock->print(SS, "", SlotTracker);
1050 
1051   // We need to process each line of the output separately, so split
1052   // single-string plain-text dump.
1053   SmallVector<StringRef, 0> Lines;
1054   StringRef(Str).rtrim('\n').split(Lines, "\n");
1055 
1056   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
1057     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
1058   };
1059 
1060   // Don't need the "+" after the last line.
1061   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
1062     EmitLine(Line, " +\n");
1063   EmitLine(Lines.back(), "\n");
1064 
1065   bumpIndent(-1);
1066   OS << Indent << "]\n";
1067 
1068   dumpEdges(BasicBlock);
1069 }
1070 
1071 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
1072   OS << Indent << "subgraph " << getUID(Region) << " {\n";
1073   bumpIndent(1);
1074   OS << Indent << "fontname=Courier\n"
1075      << Indent << "label=\""
1076      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
1077      << DOT::EscapeString(Region->getName()) << "\"\n";
1078   // Dump the blocks of the region.
1079   assert(Region->getEntry() && "Region contains no inner blocks.");
1080   for (const VPBlockBase *Block : vp_depth_first_shallow(Region->getEntry()))
1081     dumpBlock(Block);
1082   bumpIndent(-1);
1083   OS << Indent << "}\n";
1084   dumpEdges(Region);
1085 }
1086 
1087 void VPlanIngredient::print(raw_ostream &O) const {
1088   if (auto *Inst = dyn_cast<Instruction>(V)) {
1089     if (!Inst->getType()->isVoidTy()) {
1090       Inst->printAsOperand(O, false);
1091       O << " = ";
1092     }
1093     O << Inst->getOpcodeName() << " ";
1094     unsigned E = Inst->getNumOperands();
1095     if (E > 0) {
1096       Inst->getOperand(0)->printAsOperand(O, false);
1097       for (unsigned I = 1; I < E; ++I)
1098         Inst->getOperand(I)->printAsOperand(O << ", ", false);
1099     }
1100   } else // !Inst
1101     V->printAsOperand(O, false);
1102 }
1103 
1104 #endif
1105 
1106 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
1107 
1108 void VPValue::replaceAllUsesWith(VPValue *New) {
1109   for (unsigned J = 0; J < getNumUsers();) {
1110     VPUser *User = Users[J];
1111     unsigned NumUsers = getNumUsers();
1112     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
1113       if (User->getOperand(I) == this)
1114         User->setOperand(I, New);
1115     // If a user got removed after updating the current user, the next user to
1116     // update will be moved to the current position, so we only need to
1117     // increment the index if the number of users did not change.
1118     if (NumUsers == getNumUsers())
1119       J++;
1120   }
1121 }
1122 
1123 void VPValue::replaceUsesWithIf(
1124     VPValue *New,
1125     llvm::function_ref<bool(VPUser &U, unsigned Idx)> ShouldReplace) {
1126   for (unsigned J = 0; J < getNumUsers();) {
1127     VPUser *User = Users[J];
1128     unsigned NumUsers = getNumUsers();
1129     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) {
1130       if (User->getOperand(I) != this || !ShouldReplace(*User, I))
1131         continue;
1132 
1133       User->setOperand(I, New);
1134     }
1135     // If a user got removed after updating the current user, the next user to
1136     // update will be moved to the current position, so we only need to
1137     // increment the index if the number of users did not change.
1138     if (NumUsers == getNumUsers())
1139       J++;
1140   }
1141 }
1142 
1143 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1144 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1145   if (const Value *UV = getUnderlyingValue()) {
1146     OS << "ir<";
1147     UV->printAsOperand(OS, false);
1148     OS << ">";
1149     return;
1150   }
1151 
1152   unsigned Slot = Tracker.getSlot(this);
1153   if (Slot == unsigned(-1))
1154     OS << "<badref>";
1155   else
1156     OS << "vp<%" << Tracker.getSlot(this) << ">";
1157 }
1158 
1159 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1160   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1161     Op->printAsOperand(O, SlotTracker);
1162   });
1163 }
1164 #endif
1165 
1166 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1167                                           Old2NewTy &Old2New,
1168                                           InterleavedAccessInfo &IAI) {
1169   ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>
1170       RPOT(Region->getEntry());
1171   for (VPBlockBase *Base : RPOT) {
1172     visitBlock(Base, Old2New, IAI);
1173   }
1174 }
1175 
1176 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1177                                          InterleavedAccessInfo &IAI) {
1178   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1179     for (VPRecipeBase &VPI : *VPBB) {
1180       if (isa<VPHeaderPHIRecipe>(&VPI))
1181         continue;
1182       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1183       auto *VPInst = cast<VPInstruction>(&VPI);
1184 
1185       auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue());
1186       if (!Inst)
1187         continue;
1188       auto *IG = IAI.getInterleaveGroup(Inst);
1189       if (!IG)
1190         continue;
1191 
1192       auto NewIGIter = Old2New.find(IG);
1193       if (NewIGIter == Old2New.end())
1194         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1195             IG->getFactor(), IG->isReverse(), IG->getAlign());
1196 
1197       if (Inst == IG->getInsertPos())
1198         Old2New[IG]->setInsertPos(VPInst);
1199 
1200       InterleaveGroupMap[VPInst] = Old2New[IG];
1201       InterleaveGroupMap[VPInst]->insertMember(
1202           VPInst, IG->getIndex(Inst),
1203           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1204                                 : IG->getFactor()));
1205     }
1206   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1207     visitRegion(Region, Old2New, IAI);
1208   else
1209     llvm_unreachable("Unsupported kind of VPBlock.");
1210 }
1211 
1212 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1213                                                  InterleavedAccessInfo &IAI) {
1214   Old2NewTy Old2New;
1215   visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI);
1216 }
1217 
1218 void VPSlotTracker::assignSlot(const VPValue *V) {
1219   assert(!Slots.contains(V) && "VPValue already has a slot!");
1220   Slots[V] = NextSlot++;
1221 }
1222 
1223 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1224   assignSlot(&Plan.VectorTripCount);
1225   if (Plan.BackedgeTakenCount)
1226     assignSlot(Plan.BackedgeTakenCount);
1227   assignSlots(Plan.getPreheader());
1228 
1229   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<const VPBlockBase *>>
1230       RPOT(VPBlockDeepTraversalWrapper<const VPBlockBase *>(Plan.getEntry()));
1231   for (const VPBasicBlock *VPBB :
1232        VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1233     assignSlots(VPBB);
1234 }
1235 
1236 void VPSlotTracker::assignSlots(const VPBasicBlock *VPBB) {
1237   for (const VPRecipeBase &Recipe : *VPBB)
1238     for (VPValue *Def : Recipe.definedValues())
1239       assignSlot(Def);
1240 }
1241 
1242 bool vputils::onlyFirstLaneUsed(VPValue *Def) {
1243   return all_of(Def->users(),
1244                 [Def](VPUser *U) { return U->onlyFirstLaneUsed(Def); });
1245 }
1246 
1247 VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr,
1248                                                 ScalarEvolution &SE) {
1249   if (auto *Expanded = Plan.getSCEVExpansion(Expr))
1250     return Expanded;
1251   VPValue *Expanded = nullptr;
1252   if (auto *E = dyn_cast<SCEVConstant>(Expr))
1253     Expanded = Plan.getVPValueOrAddLiveIn(E->getValue());
1254   else if (auto *E = dyn_cast<SCEVUnknown>(Expr))
1255     Expanded = Plan.getVPValueOrAddLiveIn(E->getValue());
1256   else {
1257     Expanded = new VPExpandSCEVRecipe(Expr, SE);
1258     Plan.getPreheader()->appendRecipe(Expanded->getDefiningRecipe());
1259   }
1260   Plan.addSCEVExpansion(Expr, Expanded);
1261   return Expanded;
1262 }
1263