xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision a0e1313c23296da1cf592f972ed97e5dea10b8ea)
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 "VPlanDominatorTree.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/PostOrderIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/IVDescriptors.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/CFG.h"
30 #include "llvm/IR/InstrTypes.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/ErrorHandling.h"
39 #include "llvm/Support/GenericDomTreeConstruction.h"
40 #include "llvm/Support/GraphWriter.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include <cassert>
44 #include <iterator>
45 #include <string>
46 #include <vector>
47 
48 using namespace llvm;
49 extern cl::opt<bool> EnableVPlanNativePath;
50 
51 #define DEBUG_TYPE "vplan"
52 
53 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
54 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
55   const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
56   VPSlotTracker SlotTracker(
57       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
58   V.print(OS, SlotTracker);
59   return OS;
60 }
61 #endif
62 
63 Value *VPLane::getAsRuntimeExpr(IRBuilder<> &Builder,
64                                 const ElementCount &VF) const {
65   switch (LaneKind) {
66   case VPLane::Kind::ScalableLast:
67     // Lane = RuntimeVF - VF.getKnownMinValue() + Lane
68     return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF),
69                              Builder.getInt32(VF.getKnownMinValue() - Lane));
70   case VPLane::Kind::First:
71     return Builder.getInt32(Lane);
72   }
73   llvm_unreachable("Unknown lane kind");
74 }
75 
76 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)
77     : SubclassID(SC), UnderlyingVal(UV), Def(Def) {
78   if (Def)
79     Def->addDefinedValue(this);
80 }
81 
82 VPValue::~VPValue() {
83   assert(Users.empty() && "trying to delete a VPValue with remaining users");
84   if (Def)
85     Def->removeDefinedValue(this);
86 }
87 
88 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
89 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
90   if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def))
91     R->print(OS, "", SlotTracker);
92   else
93     printAsOperand(OS, SlotTracker);
94 }
95 
96 void VPValue::dump() const {
97   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def);
98   VPSlotTracker SlotTracker(
99       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
100   print(dbgs(), SlotTracker);
101   dbgs() << "\n";
102 }
103 
104 void VPDef::dump() const {
105   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this);
106   VPSlotTracker SlotTracker(
107       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
108   print(dbgs(), "", SlotTracker);
109   dbgs() << "\n";
110 }
111 #endif
112 
113 // Get the top-most entry block of \p Start. This is the entry block of the
114 // containing VPlan. This function is templated to support both const and non-const blocks
115 template <typename T> static T *getPlanEntry(T *Start) {
116   T *Next = Start;
117   T *Current = Start;
118   while ((Next = Next->getParent()))
119     Current = Next;
120 
121   SmallSetVector<T *, 8> WorkList;
122   WorkList.insert(Current);
123 
124   for (unsigned i = 0; i < WorkList.size(); i++) {
125     T *Current = WorkList[i];
126     if (Current->getNumPredecessors() == 0)
127       return Current;
128     auto &Predecessors = Current->getPredecessors();
129     WorkList.insert(Predecessors.begin(), Predecessors.end());
130   }
131 
132   llvm_unreachable("VPlan without any entry node without predecessors");
133 }
134 
135 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
136 
137 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
138 
139 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
140 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
141   const VPBlockBase *Block = this;
142   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
143     Block = Region->getEntry();
144   return cast<VPBasicBlock>(Block);
145 }
146 
147 VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
148   VPBlockBase *Block = this;
149   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
150     Block = Region->getEntry();
151   return cast<VPBasicBlock>(Block);
152 }
153 
154 void VPBlockBase::setPlan(VPlan *ParentPlan) {
155   assert(ParentPlan->getEntry() == this &&
156          "Can only set plan on its entry block.");
157   Plan = ParentPlan;
158 }
159 
160 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
161 const VPBasicBlock *VPBlockBase::getExitBasicBlock() const {
162   const VPBlockBase *Block = this;
163   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
164     Block = Region->getExit();
165   return cast<VPBasicBlock>(Block);
166 }
167 
168 VPBasicBlock *VPBlockBase::getExitBasicBlock() {
169   VPBlockBase *Block = this;
170   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
171     Block = Region->getExit();
172   return cast<VPBasicBlock>(Block);
173 }
174 
175 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
176   if (!Successors.empty() || !Parent)
177     return this;
178   assert(Parent->getExit() == this &&
179          "Block w/o successors not the exit of its parent.");
180   return Parent->getEnclosingBlockWithSuccessors();
181 }
182 
183 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
184   if (!Predecessors.empty() || !Parent)
185     return this;
186   assert(Parent->getEntry() == this &&
187          "Block w/o predecessors not the entry of its parent.");
188   return Parent->getEnclosingBlockWithPredecessors();
189 }
190 
191 static VPValue *getSingleOperandOrNull(VPUser &U) {
192   if (U.getNumOperands() == 1)
193     return U.getOperand(0);
194 
195   return nullptr;
196 }
197 
198 static const VPValue *getSingleOperandOrNull(const VPUser &U) {
199   if (U.getNumOperands() == 1)
200     return U.getOperand(0);
201 
202   return nullptr;
203 }
204 
205 static void resetSingleOpUser(VPUser &U, VPValue *NewVal) {
206   assert(U.getNumOperands() <= 1 && "Didn't expect more than one operand!");
207   if (!NewVal) {
208     if (U.getNumOperands() == 1)
209       U.removeLastOperand();
210     return;
211   }
212 
213   if (U.getNumOperands() == 1)
214     U.setOperand(0, NewVal);
215   else
216     U.addOperand(NewVal);
217 }
218 
219 VPValue *VPBlockBase::getCondBit() {
220   return getSingleOperandOrNull(CondBitUser);
221 }
222 
223 const VPValue *VPBlockBase::getCondBit() const {
224   return getSingleOperandOrNull(CondBitUser);
225 }
226 
227 void VPBlockBase::setCondBit(VPValue *CV) {
228   resetSingleOpUser(CondBitUser, CV);
229 }
230 
231 VPValue *VPBlockBase::getPredicate() {
232   return getSingleOperandOrNull(PredicateUser);
233 }
234 
235 const VPValue *VPBlockBase::getPredicate() const {
236   return getSingleOperandOrNull(PredicateUser);
237 }
238 
239 void VPBlockBase::setPredicate(VPValue *CV) {
240   resetSingleOpUser(PredicateUser, CV);
241 }
242 
243 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
244   SmallVector<VPBlockBase *, 8> Blocks(depth_first(Entry));
245 
246   for (VPBlockBase *Block : Blocks)
247     delete Block;
248 }
249 
250 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
251   iterator It = begin();
252   while (It != end() && (isa<VPWidenPHIRecipe>(&*It) ||
253                          isa<VPWidenIntOrFpInductionRecipe>(&*It) ||
254                          isa<VPPredInstPHIRecipe>(&*It) ||
255                          isa<VPWidenCanonicalIVRecipe>(&*It)))
256     It++;
257   return It;
258 }
259 
260 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) {
261   if (!Def->getDef())
262     return Def->getLiveInIRValue();
263 
264   if (hasScalarValue(Def, Instance)) {
265     return Data
266         .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)];
267   }
268 
269   assert(hasVectorValue(Def, Instance.Part));
270   auto *VecPart = Data.PerPartOutput[Def][Instance.Part];
271   if (!VecPart->getType()->isVectorTy()) {
272     assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar");
273     return VecPart;
274   }
275   // TODO: Cache created scalar values.
276   Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF);
277   auto *Extract = Builder.CreateExtractElement(VecPart, Lane);
278   // set(Def, Extract, Instance);
279   return Extract;
280 }
281 
282 BasicBlock *
283 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
284   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
285   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
286   BasicBlock *PrevBB = CFG.PrevBB;
287   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
288                                          PrevBB->getParent(), CFG.LastBB);
289   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
290 
291   // Hook up the new basic block to its predecessors.
292   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
293     VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock();
294     auto &PredVPSuccessors = PredVPBB->getSuccessors();
295     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
296 
297     // In outer loop vectorization scenario, the predecessor BBlock may not yet
298     // be visited(backedge). Mark the VPBasicBlock for fixup at the end of
299     // vectorization. We do not encounter this case in inner loop vectorization
300     // as we start out by building a loop skeleton with the vector loop header
301     // and latch blocks. As a result, we never enter this function for the
302     // header block in the non VPlan-native path.
303     if (!PredBB) {
304       assert(EnableVPlanNativePath &&
305              "Unexpected null predecessor in non VPlan-native path");
306       CFG.VPBBsToFix.push_back(PredVPBB);
307       continue;
308     }
309 
310     assert(PredBB && "Predecessor basic-block not found building successor.");
311     auto *PredBBTerminator = PredBB->getTerminator();
312     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
313     if (isa<UnreachableInst>(PredBBTerminator)) {
314       assert(PredVPSuccessors.size() == 1 &&
315              "Predecessor ending w/o branch must have single successor.");
316       PredBBTerminator->eraseFromParent();
317       BranchInst::Create(NewBB, PredBB);
318     } else {
319       assert(PredVPSuccessors.size() == 2 &&
320              "Predecessor ending with branch must have two successors.");
321       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
322       assert(!PredBBTerminator->getSuccessor(idx) &&
323              "Trying to reset an existing successor block.");
324       PredBBTerminator->setSuccessor(idx, NewBB);
325     }
326   }
327   return NewBB;
328 }
329 
330 void VPBasicBlock::execute(VPTransformState *State) {
331   bool Replica = State->Instance && !State->Instance->isFirstIteration();
332   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
333   VPBlockBase *SingleHPred = nullptr;
334   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
335 
336   // 1. Create an IR basic block, or reuse the last one if possible.
337   // The last IR basic block is reused, as an optimization, in three cases:
338   // A. the first VPBB reuses the loop header BB - when PrevVPBB is null;
339   // B. when the current VPBB has a single (hierarchical) predecessor which
340   //    is PrevVPBB and the latter has a single (hierarchical) successor; and
341   // C. when the current VPBB is an entry of a region replica - where PrevVPBB
342   //    is the exit of this region from a previous instance, or the predecessor
343   //    of this region.
344   if (PrevVPBB && /* A */
345       !((SingleHPred = getSingleHierarchicalPredecessor()) &&
346         SingleHPred->getExitBasicBlock() == PrevVPBB &&
347         PrevVPBB->getSingleHierarchicalSuccessor()) && /* B */
348       !(Replica && getPredecessors().empty())) {       /* C */
349     NewBB = createEmptyBasicBlock(State->CFG);
350     State->Builder.SetInsertPoint(NewBB);
351     // Temporarily terminate with unreachable until CFG is rewired.
352     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
353     State->Builder.SetInsertPoint(Terminator);
354     // Register NewBB in its loop. In innermost loops its the same for all BB's.
355     Loop *L = State->LI->getLoopFor(State->CFG.LastBB);
356     L->addBasicBlockToLoop(NewBB, *State->LI);
357     State->CFG.PrevBB = NewBB;
358   }
359 
360   // 2. Fill the IR basic block with IR instructions.
361   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
362                     << " in BB:" << NewBB->getName() << '\n');
363 
364   State->CFG.VPBB2IRBB[this] = NewBB;
365   State->CFG.PrevVPBB = this;
366 
367   for (VPRecipeBase &Recipe : Recipes)
368     Recipe.execute(*State);
369 
370   VPValue *CBV;
371   if (EnableVPlanNativePath && (CBV = getCondBit())) {
372     assert(CBV->getUnderlyingValue() &&
373            "Unexpected null underlying value for condition bit");
374 
375     // Condition bit value in a VPBasicBlock is used as the branch selector. In
376     // the VPlan-native path case, since all branches are uniform we generate a
377     // branch instruction using the condition value from vector lane 0 and dummy
378     // successors. The successors are fixed later when the successor blocks are
379     // visited.
380     Value *NewCond = State->get(CBV, {0, 0});
381 
382     // Replace the temporary unreachable terminator with the new conditional
383     // branch.
384     auto *CurrentTerminator = NewBB->getTerminator();
385     assert(isa<UnreachableInst>(CurrentTerminator) &&
386            "Expected to replace unreachable terminator with conditional "
387            "branch.");
388     auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond);
389     CondBr->setSuccessor(0, nullptr);
390     ReplaceInstWithInst(CurrentTerminator, CondBr);
391   }
392 
393   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
394 }
395 
396 void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
397   for (VPRecipeBase &R : Recipes) {
398     for (auto *Def : R.definedValues())
399       Def->replaceAllUsesWith(NewValue);
400 
401     for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
402       R.setOperand(I, NewValue);
403   }
404 }
405 
406 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
407 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
408                          VPSlotTracker &SlotTracker) const {
409   O << Indent << getName() << ":\n";
410   if (const VPValue *Pred = getPredicate()) {
411     O << Indent << "BlockPredicate:";
412     Pred->printAsOperand(O, SlotTracker);
413     if (const auto *PredInst = dyn_cast<VPInstruction>(Pred))
414       O << " (" << PredInst->getParent()->getName() << ")";
415     O << '\n';
416   }
417 
418   auto RecipeIndent = Indent + "  ";
419   for (const VPRecipeBase &Recipe : *this) {
420     Recipe.print(O, RecipeIndent, SlotTracker);
421     O << '\n';
422   }
423 
424   if (getSuccessors().empty()) {
425     O << Indent << "No successors\n";
426   } else {
427     O << Indent << "Successor(s): ";
428     ListSeparator LS;
429     for (auto *Succ : getSuccessors())
430       O << LS << Succ->getName();
431     O << '\n';
432   }
433 
434   if (const VPValue *CBV = getCondBit()) {
435     O << Indent << "CondBit: ";
436     CBV->printAsOperand(O, SlotTracker);
437     if (const auto *CBI = dyn_cast<VPInstruction>(CBV))
438       O << " (" << CBI->getParent()->getName() << ")";
439     O << '\n';
440   }
441 }
442 #endif
443 
444 void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
445   for (VPBlockBase *Block : depth_first(Entry))
446     // Drop all references in VPBasicBlocks and replace all uses with
447     // DummyValue.
448     Block->dropAllReferences(NewValue);
449 }
450 
451 void VPRegionBlock::execute(VPTransformState *State) {
452   ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry);
453 
454   if (!isReplicator()) {
455     // Visit the VPBlocks connected to "this", starting from it.
456     for (VPBlockBase *Block : RPOT) {
457       if (EnableVPlanNativePath) {
458         // The inner loop vectorization path does not represent loop preheader
459         // and exit blocks as part of the VPlan. In the VPlan-native path, skip
460         // vectorizing loop preheader block. In future, we may replace this
461         // check with the check for loop preheader.
462         if (Block->getNumPredecessors() == 0)
463           continue;
464 
465         // Skip vectorizing loop exit block. In future, we may replace this
466         // check with the check for loop exit.
467         if (Block->getNumSuccessors() == 0)
468           continue;
469       }
470 
471       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
472       Block->execute(State);
473     }
474     return;
475   }
476 
477   assert(!State->Instance && "Replicating a Region with non-null instance.");
478 
479   // Enter replicating mode.
480   State->Instance = VPIteration(0, 0);
481 
482   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
483     State->Instance->Part = Part;
484     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
485     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
486          ++Lane) {
487       State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);
488       // Visit the VPBlocks connected to \p this, starting from it.
489       for (VPBlockBase *Block : RPOT) {
490         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
491         Block->execute(State);
492       }
493     }
494   }
495 
496   // Exit replicating mode.
497   State->Instance.reset();
498 }
499 
500 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
501 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent,
502                           VPSlotTracker &SlotTracker) const {
503   O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
504   auto NewIndent = Indent + "  ";
505   for (auto *BlockBase : depth_first(Entry)) {
506     O << '\n';
507     BlockBase->print(O, NewIndent, SlotTracker);
508   }
509   O << Indent << "}\n";
510 }
511 #endif
512 
513 bool VPRecipeBase::mayHaveSideEffects() const {
514   switch (getVPDefID()) {
515   case VPBranchOnMaskSC:
516     return false;
517   case VPBlendSC:
518   case VPWidenSC:
519   case VPWidenGEPSC:
520   case VPReductionSC:
521   case VPWidenSelectSC: {
522     const Instruction *I =
523         dyn_cast_or_null<Instruction>(getVPValue()->getUnderlyingValue());
524     (void)I;
525     assert((!I || !I->mayHaveSideEffects()) &&
526            "underlying instruction has side-effects");
527     return false;
528   }
529   case VPReplicateSC: {
530     auto *R = cast<VPReplicateRecipe>(this);
531     return R->getUnderlyingInstr()->mayHaveSideEffects();
532   }
533   default:
534     return true;
535   }
536 }
537 
538 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) {
539   assert(!Parent && "Recipe already in some VPBasicBlock");
540   assert(InsertPos->getParent() &&
541          "Insertion position not in any VPBasicBlock");
542   Parent = InsertPos->getParent();
543   Parent->getRecipeList().insert(InsertPos->getIterator(), this);
544 }
545 
546 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) {
547   assert(!Parent && "Recipe already in some VPBasicBlock");
548   assert(InsertPos->getParent() &&
549          "Insertion position not in any VPBasicBlock");
550   Parent = InsertPos->getParent();
551   Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this);
552 }
553 
554 void VPRecipeBase::removeFromParent() {
555   assert(getParent() && "Recipe not in any VPBasicBlock");
556   getParent()->getRecipeList().remove(getIterator());
557   Parent = nullptr;
558 }
559 
560 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() {
561   assert(getParent() && "Recipe not in any VPBasicBlock");
562   return getParent()->getRecipeList().erase(getIterator());
563 }
564 
565 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) {
566   removeFromParent();
567   insertAfter(InsertPos);
568 }
569 
570 void VPRecipeBase::moveBefore(VPBasicBlock &BB,
571                               iplist<VPRecipeBase>::iterator I) {
572   assert(I == BB.end() || I->getParent() == &BB);
573   removeFromParent();
574   Parent = &BB;
575   BB.getRecipeList().insert(I, this);
576 }
577 
578 void VPInstruction::generateInstruction(VPTransformState &State,
579                                         unsigned Part) {
580   IRBuilder<> &Builder = State.Builder;
581 
582   if (Instruction::isBinaryOp(getOpcode())) {
583     Value *A = State.get(getOperand(0), Part);
584     Value *B = State.get(getOperand(1), Part);
585     Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B);
586     State.set(this, V, Part);
587     return;
588   }
589 
590   switch (getOpcode()) {
591   case VPInstruction::Not: {
592     Value *A = State.get(getOperand(0), Part);
593     Value *V = Builder.CreateNot(A);
594     State.set(this, V, Part);
595     break;
596   }
597   case VPInstruction::ICmpULE: {
598     Value *IV = State.get(getOperand(0), Part);
599     Value *TC = State.get(getOperand(1), Part);
600     Value *V = Builder.CreateICmpULE(IV, TC);
601     State.set(this, V, Part);
602     break;
603   }
604   case Instruction::Select: {
605     Value *Cond = State.get(getOperand(0), Part);
606     Value *Op1 = State.get(getOperand(1), Part);
607     Value *Op2 = State.get(getOperand(2), Part);
608     Value *V = Builder.CreateSelect(Cond, Op1, Op2);
609     State.set(this, V, Part);
610     break;
611   }
612   case VPInstruction::ActiveLaneMask: {
613     // Get first lane of vector induction variable.
614     Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0));
615     // Get the original loop tripcount.
616     Value *ScalarTC = State.TripCount;
617 
618     auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
619     auto *PredTy = FixedVectorType::get(Int1Ty, State.VF.getKnownMinValue());
620     Instruction *Call = Builder.CreateIntrinsic(
621         Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()},
622         {VIVElem0, ScalarTC}, nullptr, "active.lane.mask");
623     State.set(this, Call, Part);
624     break;
625   }
626   default:
627     llvm_unreachable("Unsupported opcode for instruction");
628   }
629 }
630 
631 void VPInstruction::execute(VPTransformState &State) {
632   assert(!State.Instance && "VPInstruction executing an Instance");
633   for (unsigned Part = 0; Part < State.UF; ++Part)
634     generateInstruction(State, Part);
635 }
636 
637 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
638 void VPInstruction::dump() const {
639   VPSlotTracker SlotTracker(getParent()->getPlan());
640   print(dbgs(), "", SlotTracker);
641 }
642 
643 void VPInstruction::print(raw_ostream &O, const Twine &Indent,
644                           VPSlotTracker &SlotTracker) const {
645   O << Indent << "EMIT ";
646 
647   if (hasResult()) {
648     printAsOperand(O, SlotTracker);
649     O << " = ";
650   }
651 
652   switch (getOpcode()) {
653   case VPInstruction::Not:
654     O << "not";
655     break;
656   case VPInstruction::ICmpULE:
657     O << "icmp ule";
658     break;
659   case VPInstruction::SLPLoad:
660     O << "combined load";
661     break;
662   case VPInstruction::SLPStore:
663     O << "combined store";
664     break;
665   case VPInstruction::ActiveLaneMask:
666     O << "active lane mask";
667     break;
668 
669   default:
670     O << Instruction::getOpcodeName(getOpcode());
671   }
672 
673   for (const VPValue *Operand : operands()) {
674     O << " ";
675     Operand->printAsOperand(O, SlotTracker);
676   }
677 }
678 #endif
679 
680 /// Generate the code inside the body of the vectorized loop. Assumes a single
681 /// LoopVectorBody basic-block was created for this. Introduce additional
682 /// basic-blocks as needed, and fill them all.
683 void VPlan::execute(VPTransformState *State) {
684   // -1. Check if the backedge taken count is needed, and if so build it.
685   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
686     Value *TC = State->TripCount;
687     IRBuilder<> Builder(State->CFG.PrevBB->getTerminator());
688     auto *TCMO = Builder.CreateSub(TC, ConstantInt::get(TC->getType(), 1),
689                                    "trip.count.minus.1");
690     auto VF = State->VF;
691     Value *VTCMO =
692         VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
693     for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part)
694       State->set(BackedgeTakenCount, VTCMO, Part);
695   }
696 
697   // 0. Set the reverse mapping from VPValues to Values for code generation.
698   for (auto &Entry : Value2VPValue)
699     State->VPValue2Value[Entry.second] = Entry.first;
700 
701   BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB;
702   BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor();
703   assert(VectorHeaderBB && "Loop preheader does not have a single successor.");
704 
705   // 1. Make room to generate basic-blocks inside loop body if needed.
706   BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock(
707       VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch");
708   Loop *L = State->LI->getLoopFor(VectorHeaderBB);
709   L->addBasicBlockToLoop(VectorLatchBB, *State->LI);
710   // Remove the edge between Header and Latch to allow other connections.
711   // Temporarily terminate with unreachable until CFG is rewired.
712   // Note: this asserts the generated code's assumption that
713   // getFirstInsertionPt() can be dereferenced into an Instruction.
714   VectorHeaderBB->getTerminator()->eraseFromParent();
715   State->Builder.SetInsertPoint(VectorHeaderBB);
716   UnreachableInst *Terminator = State->Builder.CreateUnreachable();
717   State->Builder.SetInsertPoint(Terminator);
718 
719   // 2. Generate code in loop body.
720   State->CFG.PrevVPBB = nullptr;
721   State->CFG.PrevBB = VectorHeaderBB;
722   State->CFG.LastBB = VectorLatchBB;
723 
724   for (VPBlockBase *Block : depth_first(Entry))
725     Block->execute(State);
726 
727   // Setup branch terminator successors for VPBBs in VPBBsToFix based on
728   // VPBB's successors.
729   for (auto VPBB : State->CFG.VPBBsToFix) {
730     assert(EnableVPlanNativePath &&
731            "Unexpected VPBBsToFix in non VPlan-native path");
732     BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
733     assert(BB && "Unexpected null basic block for VPBB");
734 
735     unsigned Idx = 0;
736     auto *BBTerminator = BB->getTerminator();
737 
738     for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
739       VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
740       BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
741       ++Idx;
742     }
743   }
744 
745   // 3. Merge the temporary latch created with the last basic-block filled.
746   BasicBlock *LastBB = State->CFG.PrevBB;
747   // Connect LastBB to VectorLatchBB to facilitate their merge.
748   assert((EnableVPlanNativePath ||
749           isa<UnreachableInst>(LastBB->getTerminator())) &&
750          "Expected InnerLoop VPlan CFG to terminate with unreachable");
751   assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) &&
752          "Expected VPlan CFG to terminate with branch in NativePath");
753   LastBB->getTerminator()->eraseFromParent();
754   BranchInst::Create(VectorLatchBB, LastBB);
755 
756   // Merge LastBB with Latch.
757   bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI);
758   (void)Merged;
759   assert(Merged && "Could not merge last basic block with latch.");
760   VectorLatchBB = LastBB;
761 
762   // We do not attempt to preserve DT for outer loop vectorization currently.
763   if (!EnableVPlanNativePath)
764     updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB,
765                         L->getExitBlock());
766 }
767 
768 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
769 LLVM_DUMP_METHOD
770 void VPlan::print(raw_ostream &O) const {
771   VPSlotTracker SlotTracker(this);
772 
773   O << "VPlan '" << Name << "' {";
774   for (const VPBlockBase *Block : depth_first(getEntry())) {
775     O << '\n';
776     Block->print(O, "", SlotTracker);
777   }
778   O << "}\n";
779 }
780 
781 LLVM_DUMP_METHOD
782 void VPlan::printDOT(raw_ostream &O) const {
783   VPlanPrinter Printer(O, *this);
784   Printer.dump();
785 }
786 
787 LLVM_DUMP_METHOD
788 void VPlan::dump() const { print(dbgs()); }
789 #endif
790 
791 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB,
792                                 BasicBlock *LoopLatchBB,
793                                 BasicBlock *LoopExitBB) {
794   BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor();
795   assert(LoopHeaderBB && "Loop preheader does not have a single successor.");
796   // The vector body may be more than a single basic-block by this point.
797   // Update the dominator tree information inside the vector body by propagating
798   // it from header to latch, expecting only triangular control-flow, if any.
799   BasicBlock *PostDomSucc = nullptr;
800   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
801     // Get the list of successors of this block.
802     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
803     assert(Succs.size() <= 2 &&
804            "Basic block in vector loop has more than 2 successors.");
805     PostDomSucc = Succs[0];
806     if (Succs.size() == 1) {
807       assert(PostDomSucc->getSinglePredecessor() &&
808              "PostDom successor has more than one predecessor.");
809       DT->addNewBlock(PostDomSucc, BB);
810       continue;
811     }
812     BasicBlock *InterimSucc = Succs[1];
813     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
814       PostDomSucc = Succs[1];
815       InterimSucc = Succs[0];
816     }
817     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
818            "One successor of a basic block does not lead to the other.");
819     assert(InterimSucc->getSinglePredecessor() &&
820            "Interim successor has more than one predecessor.");
821     assert(PostDomSucc->hasNPredecessors(2) &&
822            "PostDom successor has more than two predecessors.");
823     DT->addNewBlock(InterimSucc, BB);
824     DT->addNewBlock(PostDomSucc, BB);
825   }
826   // Latch block is a new dominator for the loop exit.
827   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
828   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
829 }
830 
831 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
832 const Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
833   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
834          Twine(getOrCreateBID(Block));
835 }
836 
837 const Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
838   const std::string &Name = Block->getName();
839   if (!Name.empty())
840     return Name;
841   return "VPB" + Twine(getOrCreateBID(Block));
842 }
843 
844 void VPlanPrinter::dump() {
845   Depth = 1;
846   bumpIndent(0);
847   OS << "digraph VPlan {\n";
848   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
849   if (!Plan.getName().empty())
850     OS << "\\n" << DOT::EscapeString(Plan.getName());
851   if (Plan.BackedgeTakenCount) {
852     OS << ", where:\\n";
853     Plan.BackedgeTakenCount->print(OS, SlotTracker);
854     OS << " := BackedgeTakenCount";
855   }
856   OS << "\"]\n";
857   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
858   OS << "edge [fontname=Courier, fontsize=30]\n";
859   OS << "compound=true\n";
860 
861   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
862     dumpBlock(Block);
863 
864   OS << "}\n";
865 }
866 
867 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
868   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
869     dumpBasicBlock(BasicBlock);
870   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
871     dumpRegion(Region);
872   else
873     llvm_unreachable("Unsupported kind of VPBlock.");
874 }
875 
876 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
877                             bool Hidden, const Twine &Label) {
878   // Due to "dot" we print an edge between two regions as an edge between the
879   // exit basic block and the entry basic of the respective regions.
880   const VPBlockBase *Tail = From->getExitBasicBlock();
881   const VPBlockBase *Head = To->getEntryBasicBlock();
882   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
883   OS << " [ label=\"" << Label << '\"';
884   if (Tail != From)
885     OS << " ltail=" << getUID(From);
886   if (Head != To)
887     OS << " lhead=" << getUID(To);
888   if (Hidden)
889     OS << "; splines=none";
890   OS << "]\n";
891 }
892 
893 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
894   auto &Successors = Block->getSuccessors();
895   if (Successors.size() == 1)
896     drawEdge(Block, Successors.front(), false, "");
897   else if (Successors.size() == 2) {
898     drawEdge(Block, Successors.front(), false, "T");
899     drawEdge(Block, Successors.back(), false, "F");
900   } else {
901     unsigned SuccessorNumber = 0;
902     for (auto *Successor : Successors)
903       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
904   }
905 }
906 
907 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
908   // Implement dot-formatted dump by performing plain-text dump into the
909   // temporary storage followed by some post-processing.
910   OS << Indent << getUID(BasicBlock) << " [label =\n";
911   bumpIndent(1);
912   std::string Str;
913   raw_string_ostream SS(Str);
914   // Use no indentation as we need to wrap the lines into quotes ourselves.
915   BasicBlock->print(SS, "", SlotTracker);
916 
917   // We need to process each line of the output separately, so split
918   // single-string plain-text dump.
919   SmallVector<StringRef, 0> Lines;
920   StringRef(Str).rtrim('\n').split(Lines, "\n");
921 
922   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
923     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
924   };
925 
926   // Don't need the "+" after the last line.
927   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
928     EmitLine(Line, " +\n");
929   EmitLine(Lines.back(), "\n");
930 
931   bumpIndent(-1);
932   OS << Indent << "]\n";
933 
934   dumpEdges(BasicBlock);
935 }
936 
937 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
938   OS << Indent << "subgraph " << getUID(Region) << " {\n";
939   bumpIndent(1);
940   OS << Indent << "fontname=Courier\n"
941      << Indent << "label=\""
942      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
943      << DOT::EscapeString(Region->getName()) << "\"\n";
944   // Dump the blocks of the region.
945   assert(Region->getEntry() && "Region contains no inner blocks.");
946   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
947     dumpBlock(Block);
948   bumpIndent(-1);
949   OS << Indent << "}\n";
950   dumpEdges(Region);
951 }
952 
953 void VPlanIngredient::print(raw_ostream &O) const {
954   if (auto *Inst = dyn_cast<Instruction>(V)) {
955     if (!Inst->getType()->isVoidTy()) {
956       Inst->printAsOperand(O, false);
957       O << " = ";
958     }
959     O << Inst->getOpcodeName() << " ";
960     unsigned E = Inst->getNumOperands();
961     if (E > 0) {
962       Inst->getOperand(0)->printAsOperand(O, false);
963       for (unsigned I = 1; I < E; ++I)
964         Inst->getOperand(I)->printAsOperand(O << ", ", false);
965     }
966   } else // !Inst
967     V->printAsOperand(O, false);
968 }
969 
970 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent,
971                               VPSlotTracker &SlotTracker) const {
972   O << Indent << "WIDEN-CALL ";
973 
974   auto *CI = cast<CallInst>(getUnderlyingInstr());
975   if (CI->getType()->isVoidTy())
976     O << "void ";
977   else {
978     printAsOperand(O, SlotTracker);
979     O << " = ";
980   }
981 
982   O << "call @" << CI->getCalledFunction()->getName() << "(";
983   printOperands(O, SlotTracker);
984   O << ")";
985 }
986 
987 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent,
988                                 VPSlotTracker &SlotTracker) const {
989   O << Indent << "WIDEN-SELECT ";
990   printAsOperand(O, SlotTracker);
991   O << " = select ";
992   getOperand(0)->printAsOperand(O, SlotTracker);
993   O << ", ";
994   getOperand(1)->printAsOperand(O, SlotTracker);
995   O << ", ";
996   getOperand(2)->printAsOperand(O, SlotTracker);
997   O << (InvariantCond ? " (condition is loop invariant)" : "");
998 }
999 
1000 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent,
1001                           VPSlotTracker &SlotTracker) const {
1002   O << Indent << "WIDEN ";
1003   printAsOperand(O, SlotTracker);
1004   O << " = " << getUnderlyingInstr()->getOpcodeName() << " ";
1005   printOperands(O, SlotTracker);
1006 }
1007 
1008 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent,
1009                                           VPSlotTracker &SlotTracker) const {
1010   O << Indent << "WIDEN-INDUCTION";
1011   if (getTruncInst()) {
1012     O << "\\l\"";
1013     O << " +\n" << Indent << "\"  " << VPlanIngredient(IV) << "\\l\"";
1014     O << " +\n" << Indent << "\"  ";
1015     getVPValue(0)->printAsOperand(O, SlotTracker);
1016   } else
1017     O << " " << VPlanIngredient(IV);
1018 }
1019 
1020 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent,
1021                              VPSlotTracker &SlotTracker) const {
1022   O << Indent << "WIDEN-GEP ";
1023   O << (IsPtrLoopInvariant ? "Inv" : "Var");
1024   size_t IndicesNumber = IsIndexLoopInvariant.size();
1025   for (size_t I = 0; I < IndicesNumber; ++I)
1026     O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]";
1027 
1028   O << " ";
1029   printAsOperand(O, SlotTracker);
1030   O << " = getelementptr ";
1031   printOperands(O, SlotTracker);
1032 }
1033 
1034 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1035                              VPSlotTracker &SlotTracker) const {
1036   O << Indent << "WIDEN-PHI ";
1037 
1038   auto *OriginalPhi = cast<PHINode>(getUnderlyingValue());
1039   // Unless all incoming values are modeled in VPlan  print the original PHI
1040   // directly.
1041   // TODO: Remove once all VPWidenPHIRecipe instances keep all relevant incoming
1042   // values as VPValues.
1043   if (getNumOperands() != OriginalPhi->getNumOperands()) {
1044     O << VPlanIngredient(OriginalPhi);
1045     return;
1046   }
1047 
1048   printAsOperand(O, SlotTracker);
1049   O << " = phi ";
1050   printOperands(O, SlotTracker);
1051 }
1052 
1053 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent,
1054                           VPSlotTracker &SlotTracker) const {
1055   O << Indent << "BLEND ";
1056   Phi->printAsOperand(O, false);
1057   O << " =";
1058   if (getNumIncomingValues() == 1) {
1059     // Not a User of any mask: not really blending, this is a
1060     // single-predecessor phi.
1061     O << " ";
1062     getIncomingValue(0)->printAsOperand(O, SlotTracker);
1063   } else {
1064     for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
1065       O << " ";
1066       getIncomingValue(I)->printAsOperand(O, SlotTracker);
1067       O << "/";
1068       getMask(I)->printAsOperand(O, SlotTracker);
1069     }
1070   }
1071 }
1072 
1073 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent,
1074                               VPSlotTracker &SlotTracker) const {
1075   O << Indent << "REDUCE ";
1076   printAsOperand(O, SlotTracker);
1077   O << " = ";
1078   getChainOp()->printAsOperand(O, SlotTracker);
1079   O << " + reduce." << Instruction::getOpcodeName(RdxDesc->getOpcode())
1080     << " (";
1081   getVecOp()->printAsOperand(O, SlotTracker);
1082   if (getCondOp()) {
1083     O << ", ";
1084     getCondOp()->printAsOperand(O, SlotTracker);
1085   }
1086   O << ")";
1087 }
1088 
1089 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent,
1090                               VPSlotTracker &SlotTracker) const {
1091   O << Indent << (IsUniform ? "CLONE " : "REPLICATE ");
1092 
1093   if (!getUnderlyingInstr()->getType()->isVoidTy()) {
1094     printAsOperand(O, SlotTracker);
1095     O << " = ";
1096   }
1097   O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " ";
1098   printOperands(O, SlotTracker);
1099 
1100   if (AlsoPack)
1101     O << " (S->V)";
1102 }
1103 
1104 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1105                                 VPSlotTracker &SlotTracker) const {
1106   O << Indent << "PHI-PREDICATED-INSTRUCTION ";
1107   printAsOperand(O, SlotTracker);
1108   O << " = ";
1109   printOperands(O, SlotTracker);
1110 }
1111 
1112 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent,
1113                                            VPSlotTracker &SlotTracker) const {
1114   O << Indent << "WIDEN ";
1115 
1116   if (!isStore()) {
1117     getVPValue()->printAsOperand(O, SlotTracker);
1118     O << " = ";
1119   }
1120   O << Instruction::getOpcodeName(Ingredient.getOpcode()) << " ";
1121 
1122   printOperands(O, SlotTracker);
1123 }
1124 #endif
1125 
1126 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) {
1127   Value *CanonicalIV = State.CanonicalIV;
1128   Type *STy = CanonicalIV->getType();
1129   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
1130   ElementCount VF = State.VF;
1131   assert(!VF.isScalable() && "the code following assumes non scalables ECs");
1132   Value *VStart = VF.isScalar()
1133                       ? CanonicalIV
1134                       : Builder.CreateVectorSplat(VF.getKnownMinValue(),
1135                                                   CanonicalIV, "broadcast");
1136   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) {
1137     SmallVector<Constant *, 8> Indices;
1138     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
1139       Indices.push_back(
1140           ConstantInt::get(STy, Part * VF.getKnownMinValue() + Lane));
1141     // If VF == 1, there is only one iteration in the loop above, thus the
1142     // element pushed back into Indices is ConstantInt::get(STy, Part)
1143     Constant *VStep =
1144         VF.isScalar() ? Indices.back() : ConstantVector::get(Indices);
1145     // Add the consecutive indices to the vector value.
1146     Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
1147     State.set(getVPSingleValue(), CanonicalVectorIV, Part);
1148   }
1149 }
1150 
1151 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1152 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent,
1153                                      VPSlotTracker &SlotTracker) const {
1154   O << Indent << "EMIT ";
1155   getVPValue()->printAsOperand(O, SlotTracker);
1156   O << " = WIDEN-CANONICAL-INDUCTION";
1157 }
1158 #endif
1159 
1160 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
1161 
1162 void VPValue::replaceAllUsesWith(VPValue *New) {
1163   for (unsigned J = 0; J < getNumUsers();) {
1164     VPUser *User = Users[J];
1165     unsigned NumUsers = getNumUsers();
1166     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
1167       if (User->getOperand(I) == this)
1168         User->setOperand(I, New);
1169     // If a user got removed after updating the current user, the next user to
1170     // update will be moved to the current position, so we only need to
1171     // increment the index if the number of users did not change.
1172     if (NumUsers == getNumUsers())
1173       J++;
1174   }
1175 }
1176 
1177 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1178 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1179   if (const Value *UV = getUnderlyingValue()) {
1180     OS << "ir<";
1181     UV->printAsOperand(OS, false);
1182     OS << ">";
1183     return;
1184   }
1185 
1186   unsigned Slot = Tracker.getSlot(this);
1187   if (Slot == unsigned(-1))
1188     OS << "<badref>";
1189   else
1190     OS << "vp<%" << Tracker.getSlot(this) << ">";
1191 }
1192 
1193 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1194   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1195     Op->printAsOperand(O, SlotTracker);
1196   });
1197 }
1198 #endif
1199 
1200 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1201                                           Old2NewTy &Old2New,
1202                                           InterleavedAccessInfo &IAI) {
1203   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
1204   for (VPBlockBase *Base : RPOT) {
1205     visitBlock(Base, Old2New, IAI);
1206   }
1207 }
1208 
1209 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1210                                          InterleavedAccessInfo &IAI) {
1211   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1212     for (VPRecipeBase &VPI : *VPBB) {
1213       if (isa<VPWidenPHIRecipe>(&VPI))
1214         continue;
1215       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1216       auto *VPInst = cast<VPInstruction>(&VPI);
1217       auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue());
1218       auto *IG = IAI.getInterleaveGroup(Inst);
1219       if (!IG)
1220         continue;
1221 
1222       auto NewIGIter = Old2New.find(IG);
1223       if (NewIGIter == Old2New.end())
1224         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1225             IG->getFactor(), IG->isReverse(), IG->getAlign());
1226 
1227       if (Inst == IG->getInsertPos())
1228         Old2New[IG]->setInsertPos(VPInst);
1229 
1230       InterleaveGroupMap[VPInst] = Old2New[IG];
1231       InterleaveGroupMap[VPInst]->insertMember(
1232           VPInst, IG->getIndex(Inst),
1233           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1234                                 : IG->getFactor()));
1235     }
1236   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1237     visitRegion(Region, Old2New, IAI);
1238   else
1239     llvm_unreachable("Unsupported kind of VPBlock.");
1240 }
1241 
1242 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1243                                                  InterleavedAccessInfo &IAI) {
1244   Old2NewTy Old2New;
1245   visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI);
1246 }
1247 
1248 void VPSlotTracker::assignSlot(const VPValue *V) {
1249   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
1250   Slots[V] = NextSlot++;
1251 }
1252 
1253 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1254 
1255   for (const VPValue *V : Plan.VPExternalDefs)
1256     assignSlot(V);
1257 
1258   if (Plan.BackedgeTakenCount)
1259     assignSlot(Plan.BackedgeTakenCount);
1260 
1261   ReversePostOrderTraversal<
1262       VPBlockRecursiveTraversalWrapper<const VPBlockBase *>>
1263       RPOT(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>(
1264           Plan.getEntry()));
1265   for (const VPBasicBlock *VPBB :
1266        VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1267     for (const VPRecipeBase &Recipe : *VPBB)
1268       for (VPValue *Def : Recipe.definedValues())
1269         assignSlot(Def);
1270 }
1271