xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision a6b06b785cda1bb94dd05f29d66892ccb44cf0cd)
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 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) {
514   assert(!Parent && "Recipe already in some VPBasicBlock");
515   assert(InsertPos->getParent() &&
516          "Insertion position not in any VPBasicBlock");
517   Parent = InsertPos->getParent();
518   Parent->getRecipeList().insert(InsertPos->getIterator(), this);
519 }
520 
521 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) {
522   assert(!Parent && "Recipe already in some VPBasicBlock");
523   assert(InsertPos->getParent() &&
524          "Insertion position not in any VPBasicBlock");
525   Parent = InsertPos->getParent();
526   Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this);
527 }
528 
529 void VPRecipeBase::removeFromParent() {
530   assert(getParent() && "Recipe not in any VPBasicBlock");
531   getParent()->getRecipeList().remove(getIterator());
532   Parent = nullptr;
533 }
534 
535 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() {
536   assert(getParent() && "Recipe not in any VPBasicBlock");
537   return getParent()->getRecipeList().erase(getIterator());
538 }
539 
540 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) {
541   removeFromParent();
542   insertAfter(InsertPos);
543 }
544 
545 void VPRecipeBase::moveBefore(VPBasicBlock &BB,
546                               iplist<VPRecipeBase>::iterator I) {
547   assert(I == BB.end() || I->getParent() == &BB);
548   removeFromParent();
549   Parent = &BB;
550   BB.getRecipeList().insert(I, this);
551 }
552 
553 void VPInstruction::generateInstruction(VPTransformState &State,
554                                         unsigned Part) {
555   IRBuilder<> &Builder = State.Builder;
556 
557   if (Instruction::isBinaryOp(getOpcode())) {
558     Value *A = State.get(getOperand(0), Part);
559     Value *B = State.get(getOperand(1), Part);
560     Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B);
561     State.set(this, V, Part);
562     return;
563   }
564 
565   switch (getOpcode()) {
566   case VPInstruction::Not: {
567     Value *A = State.get(getOperand(0), Part);
568     Value *V = Builder.CreateNot(A);
569     State.set(this, V, Part);
570     break;
571   }
572   case VPInstruction::ICmpULE: {
573     Value *IV = State.get(getOperand(0), Part);
574     Value *TC = State.get(getOperand(1), Part);
575     Value *V = Builder.CreateICmpULE(IV, TC);
576     State.set(this, V, Part);
577     break;
578   }
579   case Instruction::Select: {
580     Value *Cond = State.get(getOperand(0), Part);
581     Value *Op1 = State.get(getOperand(1), Part);
582     Value *Op2 = State.get(getOperand(2), Part);
583     Value *V = Builder.CreateSelect(Cond, Op1, Op2);
584     State.set(this, V, Part);
585     break;
586   }
587   case VPInstruction::ActiveLaneMask: {
588     // Get first lane of vector induction variable.
589     Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0));
590     // Get the original loop tripcount.
591     Value *ScalarTC = State.TripCount;
592 
593     auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
594     auto *PredTy = FixedVectorType::get(Int1Ty, State.VF.getKnownMinValue());
595     Instruction *Call = Builder.CreateIntrinsic(
596         Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()},
597         {VIVElem0, ScalarTC}, nullptr, "active.lane.mask");
598     State.set(this, Call, Part);
599     break;
600   }
601   default:
602     llvm_unreachable("Unsupported opcode for instruction");
603   }
604 }
605 
606 void VPInstruction::execute(VPTransformState &State) {
607   assert(!State.Instance && "VPInstruction executing an Instance");
608   for (unsigned Part = 0; Part < State.UF; ++Part)
609     generateInstruction(State, Part);
610 }
611 
612 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
613 void VPInstruction::dump() const {
614   VPSlotTracker SlotTracker(getParent()->getPlan());
615   print(dbgs(), "", SlotTracker);
616 }
617 
618 void VPInstruction::print(raw_ostream &O, const Twine &Indent,
619                           VPSlotTracker &SlotTracker) const {
620   O << Indent << "EMIT ";
621 
622   if (hasResult()) {
623     printAsOperand(O, SlotTracker);
624     O << " = ";
625   }
626 
627   switch (getOpcode()) {
628   case VPInstruction::Not:
629     O << "not";
630     break;
631   case VPInstruction::ICmpULE:
632     O << "icmp ule";
633     break;
634   case VPInstruction::SLPLoad:
635     O << "combined load";
636     break;
637   case VPInstruction::SLPStore:
638     O << "combined store";
639     break;
640   case VPInstruction::ActiveLaneMask:
641     O << "active lane mask";
642     break;
643 
644   default:
645     O << Instruction::getOpcodeName(getOpcode());
646   }
647 
648   for (const VPValue *Operand : operands()) {
649     O << " ";
650     Operand->printAsOperand(O, SlotTracker);
651   }
652 }
653 #endif
654 
655 /// Generate the code inside the body of the vectorized loop. Assumes a single
656 /// LoopVectorBody basic-block was created for this. Introduce additional
657 /// basic-blocks as needed, and fill them all.
658 void VPlan::execute(VPTransformState *State) {
659   // -1. Check if the backedge taken count is needed, and if so build it.
660   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
661     Value *TC = State->TripCount;
662     IRBuilder<> Builder(State->CFG.PrevBB->getTerminator());
663     auto *TCMO = Builder.CreateSub(TC, ConstantInt::get(TC->getType(), 1),
664                                    "trip.count.minus.1");
665     auto VF = State->VF;
666     Value *VTCMO =
667         VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
668     for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part)
669       State->set(BackedgeTakenCount, VTCMO, Part);
670   }
671 
672   // 0. Set the reverse mapping from VPValues to Values for code generation.
673   for (auto &Entry : Value2VPValue)
674     State->VPValue2Value[Entry.second] = Entry.first;
675 
676   BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB;
677   BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor();
678   assert(VectorHeaderBB && "Loop preheader does not have a single successor.");
679 
680   // 1. Make room to generate basic-blocks inside loop body if needed.
681   BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock(
682       VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch");
683   Loop *L = State->LI->getLoopFor(VectorHeaderBB);
684   L->addBasicBlockToLoop(VectorLatchBB, *State->LI);
685   // Remove the edge between Header and Latch to allow other connections.
686   // Temporarily terminate with unreachable until CFG is rewired.
687   // Note: this asserts the generated code's assumption that
688   // getFirstInsertionPt() can be dereferenced into an Instruction.
689   VectorHeaderBB->getTerminator()->eraseFromParent();
690   State->Builder.SetInsertPoint(VectorHeaderBB);
691   UnreachableInst *Terminator = State->Builder.CreateUnreachable();
692   State->Builder.SetInsertPoint(Terminator);
693 
694   // 2. Generate code in loop body.
695   State->CFG.PrevVPBB = nullptr;
696   State->CFG.PrevBB = VectorHeaderBB;
697   State->CFG.LastBB = VectorLatchBB;
698 
699   for (VPBlockBase *Block : depth_first(Entry))
700     Block->execute(State);
701 
702   // Setup branch terminator successors for VPBBs in VPBBsToFix based on
703   // VPBB's successors.
704   for (auto VPBB : State->CFG.VPBBsToFix) {
705     assert(EnableVPlanNativePath &&
706            "Unexpected VPBBsToFix in non VPlan-native path");
707     BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
708     assert(BB && "Unexpected null basic block for VPBB");
709 
710     unsigned Idx = 0;
711     auto *BBTerminator = BB->getTerminator();
712 
713     for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
714       VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
715       BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
716       ++Idx;
717     }
718   }
719 
720   // 3. Merge the temporary latch created with the last basic-block filled.
721   BasicBlock *LastBB = State->CFG.PrevBB;
722   // Connect LastBB to VectorLatchBB to facilitate their merge.
723   assert((EnableVPlanNativePath ||
724           isa<UnreachableInst>(LastBB->getTerminator())) &&
725          "Expected InnerLoop VPlan CFG to terminate with unreachable");
726   assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) &&
727          "Expected VPlan CFG to terminate with branch in NativePath");
728   LastBB->getTerminator()->eraseFromParent();
729   BranchInst::Create(VectorLatchBB, LastBB);
730 
731   // Merge LastBB with Latch.
732   bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI);
733   (void)Merged;
734   assert(Merged && "Could not merge last basic block with latch.");
735   VectorLatchBB = LastBB;
736 
737   // We do not attempt to preserve DT for outer loop vectorization currently.
738   if (!EnableVPlanNativePath)
739     updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB,
740                         L->getExitBlock());
741 }
742 
743 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
744 LLVM_DUMP_METHOD
745 void VPlan::print(raw_ostream &O) const {
746   VPSlotTracker SlotTracker(this);
747 
748   O << "VPlan '" << Name << "' {";
749   for (const VPBlockBase *Block : depth_first(getEntry())) {
750     O << '\n';
751     Block->print(O, "", SlotTracker);
752   }
753   O << "}\n";
754 }
755 
756 LLVM_DUMP_METHOD
757 void VPlan::printDOT(raw_ostream &O) const {
758   VPlanPrinter Printer(O, *this);
759   Printer.dump();
760 }
761 
762 LLVM_DUMP_METHOD
763 void VPlan::dump() const { print(dbgs()); }
764 #endif
765 
766 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB,
767                                 BasicBlock *LoopLatchBB,
768                                 BasicBlock *LoopExitBB) {
769   BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor();
770   assert(LoopHeaderBB && "Loop preheader does not have a single successor.");
771   // The vector body may be more than a single basic-block by this point.
772   // Update the dominator tree information inside the vector body by propagating
773   // it from header to latch, expecting only triangular control-flow, if any.
774   BasicBlock *PostDomSucc = nullptr;
775   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
776     // Get the list of successors of this block.
777     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
778     assert(Succs.size() <= 2 &&
779            "Basic block in vector loop has more than 2 successors.");
780     PostDomSucc = Succs[0];
781     if (Succs.size() == 1) {
782       assert(PostDomSucc->getSinglePredecessor() &&
783              "PostDom successor has more than one predecessor.");
784       DT->addNewBlock(PostDomSucc, BB);
785       continue;
786     }
787     BasicBlock *InterimSucc = Succs[1];
788     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
789       PostDomSucc = Succs[1];
790       InterimSucc = Succs[0];
791     }
792     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
793            "One successor of a basic block does not lead to the other.");
794     assert(InterimSucc->getSinglePredecessor() &&
795            "Interim successor has more than one predecessor.");
796     assert(PostDomSucc->hasNPredecessors(2) &&
797            "PostDom successor has more than two predecessors.");
798     DT->addNewBlock(InterimSucc, BB);
799     DT->addNewBlock(PostDomSucc, BB);
800   }
801   // Latch block is a new dominator for the loop exit.
802   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
803   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
804 }
805 
806 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
807 const Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
808   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
809          Twine(getOrCreateBID(Block));
810 }
811 
812 const Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
813   const std::string &Name = Block->getName();
814   if (!Name.empty())
815     return Name;
816   return "VPB" + Twine(getOrCreateBID(Block));
817 }
818 
819 void VPlanPrinter::dump() {
820   Depth = 1;
821   bumpIndent(0);
822   OS << "digraph VPlan {\n";
823   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
824   if (!Plan.getName().empty())
825     OS << "\\n" << DOT::EscapeString(Plan.getName());
826   if (Plan.BackedgeTakenCount) {
827     OS << ", where:\\n";
828     Plan.BackedgeTakenCount->print(OS, SlotTracker);
829     OS << " := BackedgeTakenCount";
830   }
831   OS << "\"]\n";
832   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
833   OS << "edge [fontname=Courier, fontsize=30]\n";
834   OS << "compound=true\n";
835 
836   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
837     dumpBlock(Block);
838 
839   OS << "}\n";
840 }
841 
842 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
843   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
844     dumpBasicBlock(BasicBlock);
845   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
846     dumpRegion(Region);
847   else
848     llvm_unreachable("Unsupported kind of VPBlock.");
849 }
850 
851 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
852                             bool Hidden, const Twine &Label) {
853   // Due to "dot" we print an edge between two regions as an edge between the
854   // exit basic block and the entry basic of the respective regions.
855   const VPBlockBase *Tail = From->getExitBasicBlock();
856   const VPBlockBase *Head = To->getEntryBasicBlock();
857   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
858   OS << " [ label=\"" << Label << '\"';
859   if (Tail != From)
860     OS << " ltail=" << getUID(From);
861   if (Head != To)
862     OS << " lhead=" << getUID(To);
863   if (Hidden)
864     OS << "; splines=none";
865   OS << "]\n";
866 }
867 
868 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
869   auto &Successors = Block->getSuccessors();
870   if (Successors.size() == 1)
871     drawEdge(Block, Successors.front(), false, "");
872   else if (Successors.size() == 2) {
873     drawEdge(Block, Successors.front(), false, "T");
874     drawEdge(Block, Successors.back(), false, "F");
875   } else {
876     unsigned SuccessorNumber = 0;
877     for (auto *Successor : Successors)
878       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
879   }
880 }
881 
882 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
883   // Implement dot-formatted dump by performing plain-text dump into the
884   // temporary storage followed by some post-processing.
885   OS << Indent << getUID(BasicBlock) << " [label =\n";
886   bumpIndent(1);
887   std::string Str;
888   raw_string_ostream SS(Str);
889   // Use no indentation as we need to wrap the lines into quotes ourselves.
890   BasicBlock->print(SS, "", SlotTracker);
891 
892   // We need to process each line of the output separately, so split
893   // single-string plain-text dump.
894   SmallVector<StringRef, 0> Lines;
895   StringRef(Str).rtrim('\n').split(Lines, "\n");
896 
897   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
898     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
899   };
900 
901   // Don't need the "+" after the last line.
902   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
903     EmitLine(Line, " +\n");
904   EmitLine(Lines.back(), "\n");
905 
906   bumpIndent(-1);
907   OS << Indent << "]\n";
908 
909   dumpEdges(BasicBlock);
910 }
911 
912 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
913   OS << Indent << "subgraph " << getUID(Region) << " {\n";
914   bumpIndent(1);
915   OS << Indent << "fontname=Courier\n"
916      << Indent << "label=\""
917      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
918      << DOT::EscapeString(Region->getName()) << "\"\n";
919   // Dump the blocks of the region.
920   assert(Region->getEntry() && "Region contains no inner blocks.");
921   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
922     dumpBlock(Block);
923   bumpIndent(-1);
924   OS << Indent << "}\n";
925   dumpEdges(Region);
926 }
927 
928 void VPlanIngredient::print(raw_ostream &O) const {
929   if (auto *Inst = dyn_cast<Instruction>(V)) {
930     if (!Inst->getType()->isVoidTy()) {
931       Inst->printAsOperand(O, false);
932       O << " = ";
933     }
934     O << Inst->getOpcodeName() << " ";
935     unsigned E = Inst->getNumOperands();
936     if (E > 0) {
937       Inst->getOperand(0)->printAsOperand(O, false);
938       for (unsigned I = 1; I < E; ++I)
939         Inst->getOperand(I)->printAsOperand(O << ", ", false);
940     }
941   } else // !Inst
942     V->printAsOperand(O, false);
943 }
944 
945 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent,
946                               VPSlotTracker &SlotTracker) const {
947   O << Indent << "WIDEN-CALL ";
948 
949   auto *CI = cast<CallInst>(getUnderlyingInstr());
950   if (CI->getType()->isVoidTy())
951     O << "void ";
952   else {
953     printAsOperand(O, SlotTracker);
954     O << " = ";
955   }
956 
957   O << "call @" << CI->getCalledFunction()->getName() << "(";
958   printOperands(O, SlotTracker);
959   O << ")";
960 }
961 
962 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent,
963                                 VPSlotTracker &SlotTracker) const {
964   O << Indent << "WIDEN-SELECT ";
965   printAsOperand(O, SlotTracker);
966   O << " = select ";
967   getOperand(0)->printAsOperand(O, SlotTracker);
968   O << ", ";
969   getOperand(1)->printAsOperand(O, SlotTracker);
970   O << ", ";
971   getOperand(2)->printAsOperand(O, SlotTracker);
972   O << (InvariantCond ? " (condition is loop invariant)" : "");
973 }
974 
975 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent,
976                           VPSlotTracker &SlotTracker) const {
977   O << Indent << "WIDEN ";
978   printAsOperand(O, SlotTracker);
979   O << " = " << getUnderlyingInstr()->getOpcodeName() << " ";
980   printOperands(O, SlotTracker);
981 }
982 
983 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent,
984                                           VPSlotTracker &SlotTracker) const {
985   O << Indent << "WIDEN-INDUCTION";
986   if (getTruncInst()) {
987     O << "\\l\"";
988     O << " +\n" << Indent << "\"  " << VPlanIngredient(IV) << "\\l\"";
989     O << " +\n" << Indent << "\"  ";
990     getVPValue(0)->printAsOperand(O, SlotTracker);
991   } else
992     O << " " << VPlanIngredient(IV);
993 }
994 
995 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent,
996                              VPSlotTracker &SlotTracker) const {
997   O << Indent << "WIDEN-GEP ";
998   O << (IsPtrLoopInvariant ? "Inv" : "Var");
999   size_t IndicesNumber = IsIndexLoopInvariant.size();
1000   for (size_t I = 0; I < IndicesNumber; ++I)
1001     O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]";
1002 
1003   O << " ";
1004   printAsOperand(O, SlotTracker);
1005   O << " = getelementptr ";
1006   printOperands(O, SlotTracker);
1007 }
1008 
1009 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1010                              VPSlotTracker &SlotTracker) const {
1011   O << Indent << "WIDEN-PHI ";
1012 
1013   auto *OriginalPhi = cast<PHINode>(getUnderlyingValue());
1014   // Unless all incoming values are modeled in VPlan  print the original PHI
1015   // directly.
1016   // TODO: Remove once all VPWidenPHIRecipe instances keep all relevant incoming
1017   // values as VPValues.
1018   if (getNumOperands() != OriginalPhi->getNumOperands()) {
1019     O << VPlanIngredient(OriginalPhi);
1020     return;
1021   }
1022 
1023   printAsOperand(O, SlotTracker);
1024   O << " = phi ";
1025   printOperands(O, SlotTracker);
1026 }
1027 
1028 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent,
1029                           VPSlotTracker &SlotTracker) const {
1030   O << Indent << "BLEND ";
1031   Phi->printAsOperand(O, false);
1032   O << " =";
1033   if (getNumIncomingValues() == 1) {
1034     // Not a User of any mask: not really blending, this is a
1035     // single-predecessor phi.
1036     O << " ";
1037     getIncomingValue(0)->printAsOperand(O, SlotTracker);
1038   } else {
1039     for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
1040       O << " ";
1041       getIncomingValue(I)->printAsOperand(O, SlotTracker);
1042       O << "/";
1043       getMask(I)->printAsOperand(O, SlotTracker);
1044     }
1045   }
1046 }
1047 
1048 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent,
1049                               VPSlotTracker &SlotTracker) const {
1050   O << Indent << "REDUCE ";
1051   printAsOperand(O, SlotTracker);
1052   O << " = ";
1053   getChainOp()->printAsOperand(O, SlotTracker);
1054   O << " + reduce." << Instruction::getOpcodeName(RdxDesc->getOpcode())
1055     << " (";
1056   getVecOp()->printAsOperand(O, SlotTracker);
1057   if (getCondOp()) {
1058     O << ", ";
1059     getCondOp()->printAsOperand(O, SlotTracker);
1060   }
1061   O << ")";
1062 }
1063 
1064 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent,
1065                               VPSlotTracker &SlotTracker) const {
1066   O << Indent << (IsUniform ? "CLONE " : "REPLICATE ");
1067 
1068   if (!getUnderlyingInstr()->getType()->isVoidTy()) {
1069     printAsOperand(O, SlotTracker);
1070     O << " = ";
1071   }
1072   O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " ";
1073   printOperands(O, SlotTracker);
1074 
1075   if (AlsoPack)
1076     O << " (S->V)";
1077 }
1078 
1079 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1080                                 VPSlotTracker &SlotTracker) const {
1081   O << Indent << "PHI-PREDICATED-INSTRUCTION ";
1082   printAsOperand(O, SlotTracker);
1083   O << " = ";
1084   printOperands(O, SlotTracker);
1085 }
1086 
1087 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent,
1088                                            VPSlotTracker &SlotTracker) const {
1089   O << Indent << "WIDEN ";
1090 
1091   if (!isStore()) {
1092     getVPValue()->printAsOperand(O, SlotTracker);
1093     O << " = ";
1094   }
1095   O << Instruction::getOpcodeName(Ingredient.getOpcode()) << " ";
1096 
1097   printOperands(O, SlotTracker);
1098 }
1099 #endif
1100 
1101 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) {
1102   Value *CanonicalIV = State.CanonicalIV;
1103   Type *STy = CanonicalIV->getType();
1104   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
1105   ElementCount VF = State.VF;
1106   assert(!VF.isScalable() && "the code following assumes non scalables ECs");
1107   Value *VStart = VF.isScalar()
1108                       ? CanonicalIV
1109                       : Builder.CreateVectorSplat(VF.getKnownMinValue(),
1110                                                   CanonicalIV, "broadcast");
1111   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) {
1112     SmallVector<Constant *, 8> Indices;
1113     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
1114       Indices.push_back(
1115           ConstantInt::get(STy, Part * VF.getKnownMinValue() + Lane));
1116     // If VF == 1, there is only one iteration in the loop above, thus the
1117     // element pushed back into Indices is ConstantInt::get(STy, Part)
1118     Constant *VStep =
1119         VF.isScalar() ? Indices.back() : ConstantVector::get(Indices);
1120     // Add the consecutive indices to the vector value.
1121     Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
1122     State.set(getVPValue(), CanonicalVectorIV, Part);
1123   }
1124 }
1125 
1126 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1127 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent,
1128                                      VPSlotTracker &SlotTracker) const {
1129   O << Indent << "EMIT ";
1130   getVPValue()->printAsOperand(O, SlotTracker);
1131   O << " = WIDEN-CANONICAL-INDUCTION";
1132 }
1133 #endif
1134 
1135 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
1136 
1137 void VPValue::replaceAllUsesWith(VPValue *New) {
1138   for (unsigned J = 0; J < getNumUsers();) {
1139     VPUser *User = Users[J];
1140     unsigned NumUsers = getNumUsers();
1141     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
1142       if (User->getOperand(I) == this)
1143         User->setOperand(I, New);
1144     // If a user got removed after updating the current user, the next user to
1145     // update will be moved to the current position, so we only need to
1146     // increment the index if the number of users did not change.
1147     if (NumUsers == getNumUsers())
1148       J++;
1149   }
1150 }
1151 
1152 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1153 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1154   if (const Value *UV = getUnderlyingValue()) {
1155     OS << "ir<";
1156     UV->printAsOperand(OS, false);
1157     OS << ">";
1158     return;
1159   }
1160 
1161   unsigned Slot = Tracker.getSlot(this);
1162   if (Slot == unsigned(-1))
1163     OS << "<badref>";
1164   else
1165     OS << "vp<%" << Tracker.getSlot(this) << ">";
1166 }
1167 
1168 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1169   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1170     Op->printAsOperand(O, SlotTracker);
1171   });
1172 }
1173 #endif
1174 
1175 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1176                                           Old2NewTy &Old2New,
1177                                           InterleavedAccessInfo &IAI) {
1178   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
1179   for (VPBlockBase *Base : RPOT) {
1180     visitBlock(Base, Old2New, IAI);
1181   }
1182 }
1183 
1184 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1185                                          InterleavedAccessInfo &IAI) {
1186   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1187     for (VPRecipeBase &VPI : *VPBB) {
1188       if (isa<VPWidenPHIRecipe>(&VPI))
1189         continue;
1190       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1191       auto *VPInst = cast<VPInstruction>(&VPI);
1192       auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue());
1193       auto *IG = IAI.getInterleaveGroup(Inst);
1194       if (!IG)
1195         continue;
1196 
1197       auto NewIGIter = Old2New.find(IG);
1198       if (NewIGIter == Old2New.end())
1199         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1200             IG->getFactor(), IG->isReverse(), IG->getAlign());
1201 
1202       if (Inst == IG->getInsertPos())
1203         Old2New[IG]->setInsertPos(VPInst);
1204 
1205       InterleaveGroupMap[VPInst] = Old2New[IG];
1206       InterleaveGroupMap[VPInst]->insertMember(
1207           VPInst, IG->getIndex(Inst),
1208           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1209                                 : IG->getFactor()));
1210     }
1211   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1212     visitRegion(Region, Old2New, IAI);
1213   else
1214     llvm_unreachable("Unsupported kind of VPBlock.");
1215 }
1216 
1217 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1218                                                  InterleavedAccessInfo &IAI) {
1219   Old2NewTy Old2New;
1220   visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI);
1221 }
1222 
1223 void VPSlotTracker::assignSlot(const VPValue *V) {
1224   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
1225   Slots[V] = NextSlot++;
1226 }
1227 
1228 void VPSlotTracker::assignSlots(const VPBlockBase *VPBB) {
1229   if (auto *Region = dyn_cast<VPRegionBlock>(VPBB))
1230     assignSlots(Region);
1231   else
1232     assignSlots(cast<VPBasicBlock>(VPBB));
1233 }
1234 
1235 void VPSlotTracker::assignSlots(const VPRegionBlock *Region) {
1236   ReversePostOrderTraversal<const VPBlockBase *> RPOT(Region->getEntry());
1237   for (const VPBlockBase *Block : RPOT)
1238     assignSlots(Block);
1239 }
1240 
1241 void VPSlotTracker::assignSlots(const VPBasicBlock *VPBB) {
1242   for (const VPRecipeBase &Recipe : *VPBB) {
1243     for (VPValue *Def : Recipe.definedValues())
1244       assignSlot(Def);
1245   }
1246 }
1247 
1248 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1249 
1250   for (const VPValue *V : Plan.VPExternalDefs)
1251     assignSlot(V);
1252 
1253   if (Plan.BackedgeTakenCount)
1254     assignSlot(Plan.BackedgeTakenCount);
1255 
1256   ReversePostOrderTraversal<const VPBlockBase *> RPOT(Plan.getEntry());
1257   for (const VPBlockBase *Block : RPOT)
1258     assignSlots(Block);
1259 }
1260