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/IRBuilder.h"
31 #include "llvm/IR/InstrTypes.h"
32 #include "llvm/IR/Instruction.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/GenericDomTreeConstruction.h"
41 #include "llvm/Support/GraphWriter.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
45 #include <cassert>
46 #include <iterator>
47 #include <string>
48 #include <vector>
49 
50 using namespace llvm;
51 extern cl::opt<bool> EnableVPlanNativePath;
52 
53 #define DEBUG_TYPE "vplan"
54 
55 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
56 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
57   const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
58   VPSlotTracker SlotTracker(
59       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
60   V.print(OS, SlotTracker);
61   return OS;
62 }
63 #endif
64 
65 Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder,
66                                 const ElementCount &VF) const {
67   switch (LaneKind) {
68   case VPLane::Kind::ScalableLast:
69     // Lane = RuntimeVF - VF.getKnownMinValue() + Lane
70     return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF),
71                              Builder.getInt32(VF.getKnownMinValue() - Lane));
72   case VPLane::Kind::First:
73     return Builder.getInt32(Lane);
74   }
75   llvm_unreachable("Unknown lane kind");
76 }
77 
78 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)
79     : SubclassID(SC), UnderlyingVal(UV), Def(Def) {
80   if (Def)
81     Def->addDefinedValue(this);
82 }
83 
84 VPValue::~VPValue() {
85   assert(Users.empty() && "trying to delete a VPValue with remaining users");
86   if (Def)
87     Def->removeDefinedValue(this);
88 }
89 
90 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
91 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
92   if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def))
93     R->print(OS, "", SlotTracker);
94   else
95     printAsOperand(OS, SlotTracker);
96 }
97 
98 void VPValue::dump() const {
99   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def);
100   VPSlotTracker SlotTracker(
101       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
102   print(dbgs(), SlotTracker);
103   dbgs() << "\n";
104 }
105 
106 void VPDef::dump() const {
107   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this);
108   VPSlotTracker SlotTracker(
109       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
110   print(dbgs(), "", SlotTracker);
111   dbgs() << "\n";
112 }
113 #endif
114 
115 // Get the top-most entry block of \p Start. This is the entry block of the
116 // containing VPlan. This function is templated to support both const and non-const blocks
117 template <typename T> static T *getPlanEntry(T *Start) {
118   T *Next = Start;
119   T *Current = Start;
120   while ((Next = Next->getParent()))
121     Current = Next;
122 
123   SmallSetVector<T *, 8> WorkList;
124   WorkList.insert(Current);
125 
126   for (unsigned i = 0; i < WorkList.size(); i++) {
127     T *Current = WorkList[i];
128     if (Current->getNumPredecessors() == 0)
129       return Current;
130     auto &Predecessors = Current->getPredecessors();
131     WorkList.insert(Predecessors.begin(), Predecessors.end());
132   }
133 
134   llvm_unreachable("VPlan without any entry node without predecessors");
135 }
136 
137 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
138 
139 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
140 
141 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
142 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
143   const VPBlockBase *Block = this;
144   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
145     Block = Region->getEntry();
146   return cast<VPBasicBlock>(Block);
147 }
148 
149 VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
150   VPBlockBase *Block = this;
151   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
152     Block = Region->getEntry();
153   return cast<VPBasicBlock>(Block);
154 }
155 
156 void VPBlockBase::setPlan(VPlan *ParentPlan) {
157   assert(ParentPlan->getEntry() == this &&
158          "Can only set plan on its entry block.");
159   Plan = ParentPlan;
160 }
161 
162 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
163 const VPBasicBlock *VPBlockBase::getExitBasicBlock() const {
164   const VPBlockBase *Block = this;
165   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
166     Block = Region->getExit();
167   return cast<VPBasicBlock>(Block);
168 }
169 
170 VPBasicBlock *VPBlockBase::getExitBasicBlock() {
171   VPBlockBase *Block = this;
172   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
173     Block = Region->getExit();
174   return cast<VPBasicBlock>(Block);
175 }
176 
177 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
178   if (!Successors.empty() || !Parent)
179     return this;
180   assert(Parent->getExit() == this &&
181          "Block w/o successors not the exit of its parent.");
182   return Parent->getEnclosingBlockWithSuccessors();
183 }
184 
185 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
186   if (!Predecessors.empty() || !Parent)
187     return this;
188   assert(Parent->getEntry() == this &&
189          "Block w/o predecessors not the entry of its parent.");
190   return Parent->getEnclosingBlockWithPredecessors();
191 }
192 
193 VPValue *VPBlockBase::getCondBit() {
194   return CondBitUser.getSingleOperandOrNull();
195 }
196 
197 const VPValue *VPBlockBase::getCondBit() const {
198   return CondBitUser.getSingleOperandOrNull();
199 }
200 
201 void VPBlockBase::setCondBit(VPValue *CV) { CondBitUser.resetSingleOpUser(CV); }
202 
203 VPValue *VPBlockBase::getPredicate() {
204   return PredicateUser.getSingleOperandOrNull();
205 }
206 
207 const VPValue *VPBlockBase::getPredicate() const {
208   return PredicateUser.getSingleOperandOrNull();
209 }
210 
211 void VPBlockBase::setPredicate(VPValue *CV) {
212   PredicateUser.resetSingleOpUser(CV);
213 }
214 
215 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
216   SmallVector<VPBlockBase *, 8> Blocks(depth_first(Entry));
217 
218   for (VPBlockBase *Block : Blocks)
219     delete Block;
220 }
221 
222 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
223   iterator It = begin();
224   while (It != end() && It->isPhi())
225     It++;
226   return It;
227 }
228 
229 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) {
230   if (!Def->getDef())
231     return Def->getLiveInIRValue();
232 
233   if (hasScalarValue(Def, Instance)) {
234     return Data
235         .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)];
236   }
237 
238   assert(hasVectorValue(Def, Instance.Part));
239   auto *VecPart = Data.PerPartOutput[Def][Instance.Part];
240   if (!VecPart->getType()->isVectorTy()) {
241     assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar");
242     return VecPart;
243   }
244   // TODO: Cache created scalar values.
245   Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF);
246   auto *Extract = Builder.CreateExtractElement(VecPart, Lane);
247   // set(Def, Extract, Instance);
248   return Extract;
249 }
250 
251 BasicBlock *
252 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
253   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
254   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
255   BasicBlock *PrevBB = CFG.PrevBB;
256   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
257                                          PrevBB->getParent(), CFG.LastBB);
258   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
259 
260   // Hook up the new basic block to its predecessors.
261   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
262     VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock();
263     auto &PredVPSuccessors = PredVPBB->getSuccessors();
264     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
265 
266     // In outer loop vectorization scenario, the predecessor BBlock may not yet
267     // be visited(backedge). Mark the VPBasicBlock for fixup at the end of
268     // vectorization. We do not encounter this case in inner loop vectorization
269     // as we start out by building a loop skeleton with the vector loop header
270     // and latch blocks. As a result, we never enter this function for the
271     // header block in the non VPlan-native path.
272     if (!PredBB) {
273       assert(EnableVPlanNativePath &&
274              "Unexpected null predecessor in non VPlan-native path");
275       CFG.VPBBsToFix.push_back(PredVPBB);
276       continue;
277     }
278 
279     assert(PredBB && "Predecessor basic-block not found building successor.");
280     auto *PredBBTerminator = PredBB->getTerminator();
281     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
282     if (isa<UnreachableInst>(PredBBTerminator)) {
283       assert(PredVPSuccessors.size() == 1 &&
284              "Predecessor ending w/o branch must have single successor.");
285       PredBBTerminator->eraseFromParent();
286       BranchInst::Create(NewBB, PredBB);
287     } else {
288       assert(PredVPSuccessors.size() == 2 &&
289              "Predecessor ending with branch must have two successors.");
290       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
291       assert(!PredBBTerminator->getSuccessor(idx) &&
292              "Trying to reset an existing successor block.");
293       PredBBTerminator->setSuccessor(idx, NewBB);
294     }
295   }
296   return NewBB;
297 }
298 
299 void VPBasicBlock::execute(VPTransformState *State) {
300   bool Replica = State->Instance && !State->Instance->isFirstIteration();
301   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
302   VPBlockBase *SingleHPred = nullptr;
303   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
304 
305   // 1. Create an IR basic block, or reuse the last one if possible.
306   // The last IR basic block is reused, as an optimization, in three cases:
307   // A. the first VPBB reuses the loop header BB - when PrevVPBB is null;
308   // B. when the current VPBB has a single (hierarchical) predecessor which
309   //    is PrevVPBB and the latter has a single (hierarchical) successor; and
310   // C. when the current VPBB is an entry of a region replica - where PrevVPBB
311   //    is the exit of this region from a previous instance, or the predecessor
312   //    of this region.
313   if (PrevVPBB && /* A */
314       !((SingleHPred = getSingleHierarchicalPredecessor()) &&
315         SingleHPred->getExitBasicBlock() == PrevVPBB &&
316         PrevVPBB->getSingleHierarchicalSuccessor()) && /* B */
317       !(Replica && getPredecessors().empty())) {       /* C */
318     NewBB = createEmptyBasicBlock(State->CFG);
319     State->Builder.SetInsertPoint(NewBB);
320     // Temporarily terminate with unreachable until CFG is rewired.
321     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
322     State->Builder.SetInsertPoint(Terminator);
323     // Register NewBB in its loop. In innermost loops its the same for all BB's.
324     Loop *L = State->LI->getLoopFor(State->CFG.LastBB);
325     L->addBasicBlockToLoop(NewBB, *State->LI);
326     State->CFG.PrevBB = NewBB;
327   }
328 
329   // 2. Fill the IR basic block with IR instructions.
330   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
331                     << " in BB:" << NewBB->getName() << '\n');
332 
333   State->CFG.VPBB2IRBB[this] = NewBB;
334   State->CFG.PrevVPBB = this;
335 
336   for (VPRecipeBase &Recipe : Recipes)
337     Recipe.execute(*State);
338 
339   VPValue *CBV;
340   if (EnableVPlanNativePath && (CBV = getCondBit())) {
341     assert(CBV->getUnderlyingValue() &&
342            "Unexpected null underlying value for condition bit");
343 
344     // Condition bit value in a VPBasicBlock is used as the branch selector. In
345     // the VPlan-native path case, since all branches are uniform we generate a
346     // branch instruction using the condition value from vector lane 0 and dummy
347     // successors. The successors are fixed later when the successor blocks are
348     // visited.
349     Value *NewCond = State->get(CBV, {0, 0});
350 
351     // Replace the temporary unreachable terminator with the new conditional
352     // branch.
353     auto *CurrentTerminator = NewBB->getTerminator();
354     assert(isa<UnreachableInst>(CurrentTerminator) &&
355            "Expected to replace unreachable terminator with conditional "
356            "branch.");
357     auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond);
358     CondBr->setSuccessor(0, nullptr);
359     ReplaceInstWithInst(CurrentTerminator, CondBr);
360   }
361 
362   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
363 }
364 
365 void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
366   for (VPRecipeBase &R : Recipes) {
367     for (auto *Def : R.definedValues())
368       Def->replaceAllUsesWith(NewValue);
369 
370     for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
371       R.setOperand(I, NewValue);
372   }
373 }
374 
375 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) {
376   assert((SplitAt == end() || SplitAt->getParent() == this) &&
377          "can only split at a position in the same block");
378 
379   SmallVector<VPBlockBase *, 2> Succs(successors());
380   // First, disconnect the current block from its successors.
381   for (VPBlockBase *Succ : Succs)
382     VPBlockUtils::disconnectBlocks(this, Succ);
383 
384   // Create new empty block after the block to split.
385   auto *SplitBlock = new VPBasicBlock(getName() + ".split");
386   VPBlockUtils::insertBlockAfter(SplitBlock, this);
387 
388   // Add successors for block to split to new block.
389   for (VPBlockBase *Succ : Succs)
390     VPBlockUtils::connectBlocks(SplitBlock, Succ);
391 
392   // Finally, move the recipes starting at SplitAt to new block.
393   for (VPRecipeBase &ToMove :
394        make_early_inc_range(make_range(SplitAt, this->end())))
395     ToMove.moveBefore(*SplitBlock, SplitBlock->end());
396 
397   return SplitBlock;
398 }
399 
400 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
401 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {
402   if (getSuccessors().empty()) {
403     O << Indent << "No successors\n";
404   } else {
405     O << Indent << "Successor(s): ";
406     ListSeparator LS;
407     for (auto *Succ : getSuccessors())
408       O << LS << Succ->getName();
409     O << '\n';
410   }
411 }
412 
413 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
414                          VPSlotTracker &SlotTracker) const {
415   O << Indent << getName() << ":\n";
416   if (const VPValue *Pred = getPredicate()) {
417     O << Indent << "BlockPredicate:";
418     Pred->printAsOperand(O, SlotTracker);
419     if (const auto *PredInst = dyn_cast<VPInstruction>(Pred))
420       O << " (" << PredInst->getParent()->getName() << ")";
421     O << '\n';
422   }
423 
424   auto RecipeIndent = Indent + "  ";
425   for (const VPRecipeBase &Recipe : *this) {
426     Recipe.print(O, RecipeIndent, SlotTracker);
427     O << '\n';
428   }
429 
430   printSuccessors(O, Indent);
431 
432   if (const VPValue *CBV = getCondBit()) {
433     O << Indent << "CondBit: ";
434     CBV->printAsOperand(O, SlotTracker);
435     if (const auto *CBI = dyn_cast<VPInstruction>(CBV))
436       O << " (" << CBI->getParent()->getName() << ")";
437     O << '\n';
438   }
439 }
440 #endif
441 
442 void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
443   for (VPBlockBase *Block : depth_first(Entry))
444     // Drop all references in VPBasicBlocks and replace all uses with
445     // DummyValue.
446     Block->dropAllReferences(NewValue);
447 }
448 
449 void VPRegionBlock::execute(VPTransformState *State) {
450   ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry);
451 
452   if (!isReplicator()) {
453     // Visit the VPBlocks connected to "this", starting from it.
454     for (VPBlockBase *Block : RPOT) {
455       if (EnableVPlanNativePath) {
456         // The inner loop vectorization path does not represent loop preheader
457         // and exit blocks as part of the VPlan. In the VPlan-native path, skip
458         // vectorizing loop preheader block. In future, we may replace this
459         // check with the check for loop preheader.
460         if (Block->getNumPredecessors() == 0)
461           continue;
462 
463         // Skip vectorizing loop exit block. In future, we may replace this
464         // check with the check for loop exit.
465         if (Block->getNumSuccessors() == 0)
466           continue;
467       }
468 
469       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
470       Block->execute(State);
471     }
472     return;
473   }
474 
475   assert(!State->Instance && "Replicating a Region with non-null instance.");
476 
477   // Enter replicating mode.
478   State->Instance = VPIteration(0, 0);
479 
480   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
481     State->Instance->Part = Part;
482     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
483     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
484          ++Lane) {
485       State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);
486       // Visit the VPBlocks connected to \p this, starting from it.
487       for (VPBlockBase *Block : RPOT) {
488         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
489         Block->execute(State);
490       }
491     }
492   }
493 
494   // Exit replicating mode.
495   State->Instance.reset();
496 }
497 
498 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
499 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent,
500                           VPSlotTracker &SlotTracker) const {
501   O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
502   auto NewIndent = Indent + "  ";
503   for (auto *BlockBase : depth_first(Entry)) {
504     O << '\n';
505     BlockBase->print(O, NewIndent, SlotTracker);
506   }
507   O << Indent << "}\n";
508 
509   printSuccessors(O, Indent);
510 }
511 #endif
512 
513 bool VPRecipeBase::mayWriteToMemory() const {
514   switch (getVPDefID()) {
515   case VPWidenMemoryInstructionSC: {
516     return cast<VPWidenMemoryInstructionRecipe>(this)->isStore();
517   }
518   case VPReplicateSC:
519   case VPWidenCallSC:
520     return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
521         ->mayWriteToMemory();
522   case VPBranchOnMaskSC:
523     return false;
524   case VPWidenIntOrFpInductionSC:
525   case VPWidenCanonicalIVSC:
526   case VPWidenPHISC:
527   case VPBlendSC:
528   case VPWidenSC:
529   case VPWidenGEPSC:
530   case VPReductionSC:
531   case VPWidenSelectSC: {
532     const Instruction *I =
533         dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
534     (void)I;
535     assert((!I || !I->mayWriteToMemory()) &&
536            "underlying instruction may write to memory");
537     return false;
538   }
539   default:
540     return true;
541   }
542 }
543 
544 bool VPRecipeBase::mayReadFromMemory() const {
545   switch (getVPDefID()) {
546   case VPWidenMemoryInstructionSC: {
547     return !cast<VPWidenMemoryInstructionRecipe>(this)->isStore();
548   }
549   case VPReplicateSC:
550   case VPWidenCallSC:
551     return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
552         ->mayReadFromMemory();
553   case VPBranchOnMaskSC:
554     return false;
555   case VPWidenIntOrFpInductionSC:
556   case VPWidenCanonicalIVSC:
557   case VPWidenPHISC:
558   case VPBlendSC:
559   case VPWidenSC:
560   case VPWidenGEPSC:
561   case VPReductionSC:
562   case VPWidenSelectSC: {
563     const Instruction *I =
564         dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
565     (void)I;
566     assert((!I || !I->mayReadFromMemory()) &&
567            "underlying instruction may read from memory");
568     return false;
569   }
570   default:
571     return true;
572   }
573 }
574 
575 bool VPRecipeBase::mayHaveSideEffects() const {
576   switch (getVPDefID()) {
577   case VPBranchOnMaskSC:
578     return false;
579   case VPWidenIntOrFpInductionSC:
580   case VPWidenCanonicalIVSC:
581   case VPWidenPHISC:
582   case VPBlendSC:
583   case VPWidenSC:
584   case VPWidenGEPSC:
585   case VPReductionSC:
586   case VPWidenSelectSC: {
587     const Instruction *I =
588         dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
589     (void)I;
590     assert((!I || !I->mayHaveSideEffects()) &&
591            "underlying instruction has side-effects");
592     return false;
593   }
594   case VPReplicateSC: {
595     auto *R = cast<VPReplicateRecipe>(this);
596     return R->getUnderlyingInstr()->mayHaveSideEffects();
597   }
598   default:
599     return true;
600   }
601 }
602 
603 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) {
604   assert(!Parent && "Recipe already in some VPBasicBlock");
605   assert(InsertPos->getParent() &&
606          "Insertion position not in any VPBasicBlock");
607   Parent = InsertPos->getParent();
608   Parent->getRecipeList().insert(InsertPos->getIterator(), this);
609 }
610 
611 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) {
612   assert(!Parent && "Recipe already in some VPBasicBlock");
613   assert(InsertPos->getParent() &&
614          "Insertion position not in any VPBasicBlock");
615   Parent = InsertPos->getParent();
616   Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this);
617 }
618 
619 void VPRecipeBase::removeFromParent() {
620   assert(getParent() && "Recipe not in any VPBasicBlock");
621   getParent()->getRecipeList().remove(getIterator());
622   Parent = nullptr;
623 }
624 
625 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() {
626   assert(getParent() && "Recipe not in any VPBasicBlock");
627   return getParent()->getRecipeList().erase(getIterator());
628 }
629 
630 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) {
631   removeFromParent();
632   insertAfter(InsertPos);
633 }
634 
635 void VPRecipeBase::moveBefore(VPBasicBlock &BB,
636                               iplist<VPRecipeBase>::iterator I) {
637   assert(I == BB.end() || I->getParent() == &BB);
638   removeFromParent();
639   Parent = &BB;
640   BB.getRecipeList().insert(I, this);
641 }
642 
643 void VPInstruction::generateInstruction(VPTransformState &State,
644                                         unsigned Part) {
645   IRBuilderBase &Builder = State.Builder;
646   Builder.SetCurrentDebugLocation(DL);
647 
648   if (Instruction::isBinaryOp(getOpcode())) {
649     Value *A = State.get(getOperand(0), Part);
650     Value *B = State.get(getOperand(1), Part);
651     Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B);
652     State.set(this, V, Part);
653     return;
654   }
655 
656   switch (getOpcode()) {
657   case VPInstruction::Not: {
658     Value *A = State.get(getOperand(0), Part);
659     Value *V = Builder.CreateNot(A);
660     State.set(this, V, Part);
661     break;
662   }
663   case VPInstruction::ICmpULE: {
664     Value *IV = State.get(getOperand(0), Part);
665     Value *TC = State.get(getOperand(1), Part);
666     Value *V = Builder.CreateICmpULE(IV, TC);
667     State.set(this, V, Part);
668     break;
669   }
670   case Instruction::Select: {
671     Value *Cond = State.get(getOperand(0), Part);
672     Value *Op1 = State.get(getOperand(1), Part);
673     Value *Op2 = State.get(getOperand(2), Part);
674     Value *V = Builder.CreateSelect(Cond, Op1, Op2);
675     State.set(this, V, Part);
676     break;
677   }
678   case VPInstruction::ActiveLaneMask: {
679     // Get first lane of vector induction variable.
680     Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0));
681     // Get the original loop tripcount.
682     Value *ScalarTC = State.get(getOperand(1), Part);
683 
684     auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
685     auto *PredTy = VectorType::get(Int1Ty, State.VF);
686     Instruction *Call = Builder.CreateIntrinsic(
687         Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()},
688         {VIVElem0, ScalarTC}, nullptr, "active.lane.mask");
689     State.set(this, Call, Part);
690     break;
691   }
692   case VPInstruction::FirstOrderRecurrenceSplice: {
693     // Generate code to combine the previous and current values in vector v3.
694     //
695     //   vector.ph:
696     //     v_init = vector(..., ..., ..., a[-1])
697     //     br vector.body
698     //
699     //   vector.body
700     //     i = phi [0, vector.ph], [i+4, vector.body]
701     //     v1 = phi [v_init, vector.ph], [v2, vector.body]
702     //     v2 = a[i, i+1, i+2, i+3];
703     //     v3 = vector(v1(3), v2(0, 1, 2))
704 
705     // For the first part, use the recurrence phi (v1), otherwise v2.
706     auto *V1 = State.get(getOperand(0), 0);
707     Value *PartMinus1 = Part == 0 ? V1 : State.get(getOperand(1), Part - 1);
708     if (!PartMinus1->getType()->isVectorTy()) {
709       State.set(this, PartMinus1, Part);
710     } else {
711       Value *V2 = State.get(getOperand(1), Part);
712       State.set(this, Builder.CreateVectorSplice(PartMinus1, V2, -1), Part);
713     }
714     break;
715   }
716 
717   case VPInstruction::CanonicalIVIncrement:
718   case VPInstruction::CanonicalIVIncrementNUW: {
719     Value *Next = nullptr;
720     if (Part == 0) {
721       bool IsNUW = getOpcode() == VPInstruction::CanonicalIVIncrementNUW;
722       auto *Phi = State.get(getOperand(0), 0);
723       // The loop step is equal to the vectorization factor (num of SIMD
724       // elements) times the unroll factor (num of SIMD instructions).
725       Value *Step =
726           createStepForVF(Builder, Phi->getType(), State.VF, State.UF);
727       Next = Builder.CreateAdd(Phi, Step, "index.next", IsNUW, false);
728     } else {
729       Next = State.get(this, 0);
730     }
731 
732     State.set(this, Next, Part);
733     break;
734   }
735   case VPInstruction::BranchOnCount: {
736     if (Part != 0)
737       break;
738     // First create the compare.
739     Value *IV = State.get(getOperand(0), Part);
740     Value *TC = State.get(getOperand(1), Part);
741     Value *Cond = Builder.CreateICmpEQ(IV, TC);
742 
743     // Now create the branch.
744     auto *Plan = getParent()->getPlan();
745     VPRegionBlock *TopRegion = Plan->getVectorLoopRegion();
746     VPBasicBlock *Header = TopRegion->getEntry()->getEntryBasicBlock();
747     if (Header->empty()) {
748       assert(EnableVPlanNativePath &&
749              "empty entry block only expected in VPlanNativePath");
750       Header = cast<VPBasicBlock>(Header->getSingleSuccessor());
751     }
752     // TODO: Once the exit block is modeled in VPlan, use it instead of going
753     // through State.CFG.LastBB.
754     BasicBlock *Exit =
755         cast<BranchInst>(State.CFG.LastBB->getTerminator())->getSuccessor(0);
756 
757     Builder.CreateCondBr(Cond, Exit, State.CFG.VPBB2IRBB[Header]);
758     Builder.GetInsertBlock()->getTerminator()->eraseFromParent();
759     break;
760   }
761   default:
762     llvm_unreachable("Unsupported opcode for instruction");
763   }
764 }
765 
766 void VPInstruction::execute(VPTransformState &State) {
767   assert(!State.Instance && "VPInstruction executing an Instance");
768   IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
769   State.Builder.setFastMathFlags(FMF);
770   for (unsigned Part = 0; Part < State.UF; ++Part)
771     generateInstruction(State, Part);
772 }
773 
774 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
775 void VPInstruction::dump() const {
776   VPSlotTracker SlotTracker(getParent()->getPlan());
777   print(dbgs(), "", SlotTracker);
778 }
779 
780 void VPInstruction::print(raw_ostream &O, const Twine &Indent,
781                           VPSlotTracker &SlotTracker) const {
782   O << Indent << "EMIT ";
783 
784   if (hasResult()) {
785     printAsOperand(O, SlotTracker);
786     O << " = ";
787   }
788 
789   switch (getOpcode()) {
790   case VPInstruction::Not:
791     O << "not";
792     break;
793   case VPInstruction::ICmpULE:
794     O << "icmp ule";
795     break;
796   case VPInstruction::SLPLoad:
797     O << "combined load";
798     break;
799   case VPInstruction::SLPStore:
800     O << "combined store";
801     break;
802   case VPInstruction::ActiveLaneMask:
803     O << "active lane mask";
804     break;
805   case VPInstruction::FirstOrderRecurrenceSplice:
806     O << "first-order splice";
807     break;
808   case VPInstruction::CanonicalIVIncrement:
809     O << "VF * UF + ";
810     break;
811   case VPInstruction::CanonicalIVIncrementNUW:
812     O << "VF * UF +(nuw) ";
813     break;
814   case VPInstruction::BranchOnCount:
815     O << "branch-on-count ";
816     break;
817   default:
818     O << Instruction::getOpcodeName(getOpcode());
819   }
820 
821   O << FMF;
822 
823   for (const VPValue *Operand : operands()) {
824     O << " ";
825     Operand->printAsOperand(O, SlotTracker);
826   }
827 
828   if (DL) {
829     O << ", !dbg ";
830     DL.print(O);
831   }
832 }
833 #endif
834 
835 void VPInstruction::setFastMathFlags(FastMathFlags FMFNew) {
836   // Make sure the VPInstruction is a floating-point operation.
837   assert((Opcode == Instruction::FAdd || Opcode == Instruction::FMul ||
838           Opcode == Instruction::FNeg || Opcode == Instruction::FSub ||
839           Opcode == Instruction::FDiv || Opcode == Instruction::FRem ||
840           Opcode == Instruction::FCmp) &&
841          "this op can't take fast-math flags");
842   FMF = FMFNew;
843 }
844 
845 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,
846                              Value *CanonicalIVStartValue,
847                              VPTransformState &State) {
848   // Check if the trip count is needed, and if so build it.
849   if (TripCount && TripCount->getNumUsers()) {
850     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
851       State.set(TripCount, TripCountV, Part);
852   }
853 
854   // Check if the backedge taken count is needed, and if so build it.
855   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
856     IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
857     auto *TCMO = Builder.CreateSub(TripCountV,
858                                    ConstantInt::get(TripCountV->getType(), 1),
859                                    "trip.count.minus.1");
860     auto VF = State.VF;
861     Value *VTCMO =
862         VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
863     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
864       State.set(BackedgeTakenCount, VTCMO, Part);
865   }
866 
867   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
868     State.set(&VectorTripCount, VectorTripCountV, Part);
869 
870   // When vectorizing the epilogue loop, the canonical induction start value
871   // needs to be changed from zero to the value after the main vector loop.
872   if (CanonicalIVStartValue) {
873     VPValue *VPV = new VPValue(CanonicalIVStartValue);
874     addExternalDef(VPV);
875     auto *IV = getCanonicalIV();
876     assert(all_of(IV->users(),
877                   [](const VPUser *U) {
878                     auto *VPI = cast<VPInstruction>(U);
879                     return VPI->getOpcode() ==
880                                VPInstruction::CanonicalIVIncrement ||
881                            VPI->getOpcode() ==
882                                VPInstruction::CanonicalIVIncrementNUW;
883                   }) &&
884            "the canonical IV should only be used by its increments when "
885            "resetting the start value");
886     IV->setOperand(0, VPV);
887   }
888 }
889 
890 /// Generate the code inside the body of the vectorized loop. Assumes a single
891 /// LoopVectorBody basic-block was created for this. Introduce additional
892 /// basic-blocks as needed, and fill them all.
893 void VPlan::execute(VPTransformState *State) {
894   // 0. Set the reverse mapping from VPValues to Values for code generation.
895   for (auto &Entry : Value2VPValue)
896     State->VPValue2Value[Entry.second] = Entry.first;
897 
898   BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB;
899   State->CFG.VectorPreHeader = VectorPreHeaderBB;
900   BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor();
901   assert(VectorHeaderBB && "Loop preheader does not have a single successor.");
902 
903   // 1. Make room to generate basic-blocks inside loop body if needed.
904   BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock(
905       VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch");
906   Loop *L = State->LI->getLoopFor(VectorHeaderBB);
907   L->addBasicBlockToLoop(VectorLatchBB, *State->LI);
908   // Remove the edge between Header and Latch to allow other connections.
909   // Temporarily terminate with unreachable until CFG is rewired.
910   // Note: this asserts the generated code's assumption that
911   // getFirstInsertionPt() can be dereferenced into an Instruction.
912   VectorHeaderBB->getTerminator()->eraseFromParent();
913   State->Builder.SetInsertPoint(VectorHeaderBB);
914   UnreachableInst *Terminator = State->Builder.CreateUnreachable();
915   State->Builder.SetInsertPoint(Terminator);
916 
917   // 2. Generate code in loop body.
918   State->CFG.PrevVPBB = nullptr;
919   State->CFG.PrevBB = VectorHeaderBB;
920   State->CFG.LastBB = VectorLatchBB;
921 
922   for (VPBlockBase *Block : depth_first(Entry))
923     Block->execute(State);
924 
925   // Setup branch terminator successors for VPBBs in VPBBsToFix based on
926   // VPBB's successors.
927   for (auto VPBB : State->CFG.VPBBsToFix) {
928     assert(EnableVPlanNativePath &&
929            "Unexpected VPBBsToFix in non VPlan-native path");
930     BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
931     assert(BB && "Unexpected null basic block for VPBB");
932 
933     unsigned Idx = 0;
934     auto *BBTerminator = BB->getTerminator();
935 
936     for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
937       VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
938       BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
939       ++Idx;
940     }
941   }
942 
943   // 3. Merge the temporary latch created with the last basic-block filled.
944   BasicBlock *LastBB = State->CFG.PrevBB;
945   assert(isa<BranchInst>(LastBB->getTerminator()) &&
946          "Expected VPlan CFG to terminate with branch");
947 
948   // Move both the branch and check from LastBB to VectorLatchBB.
949   auto *LastBranch = cast<BranchInst>(LastBB->getTerminator());
950   LastBranch->moveBefore(VectorLatchBB->getTerminator());
951   VectorLatchBB->getTerminator()->eraseFromParent();
952   // Move condition so it is guaranteed to be next to branch. This is only done
953   // to avoid excessive test updates.
954   // TODO: Remove special handling once the increments for all inductions are
955   // modeled explicitly in VPlan.
956   cast<Instruction>(LastBranch->getCondition())->moveBefore(LastBranch);
957   // Connect LastBB to VectorLatchBB to facilitate their merge.
958   BranchInst::Create(VectorLatchBB, LastBB);
959 
960   // Merge LastBB with Latch.
961   bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI);
962   (void)Merged;
963   assert(Merged && "Could not merge last basic block with latch.");
964   VectorLatchBB = LastBB;
965 
966   // Fix the latch value of canonical, reduction and first-order recurrences
967   // phis in the vector loop.
968   VPBasicBlock *Header = Entry->getEntryBasicBlock();
969   if (Header->empty()) {
970     assert(EnableVPlanNativePath);
971     Header = cast<VPBasicBlock>(Header->getSingleSuccessor());
972   }
973   for (VPRecipeBase &R : Header->phis()) {
974     // Skip phi-like recipes that generate their backedege values themselves.
975     // TODO: Model their backedge values explicitly.
976     if (isa<VPWidenIntOrFpInductionRecipe>(&R) || isa<VPWidenPHIRecipe>(&R))
977       continue;
978 
979     auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
980     // For  canonical IV, first-order recurrences and in-order reduction phis,
981     // only a single part is generated, which provides the last part from the
982     // previous iteration. For non-ordered reductions all UF parts are
983     // generated.
984     bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) ||
985                             isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) ||
986                             cast<VPReductionPHIRecipe>(PhiR)->isOrdered();
987     unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
988 
989     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
990       Value *Phi = State->get(PhiR, Part);
991       Value *Val = State->get(PhiR->getBackedgeValue(),
992                               SinglePartNeeded ? State->UF - 1 : Part);
993       cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
994     }
995   }
996 
997   // We do not attempt to preserve DT for outer loop vectorization currently.
998   if (!EnableVPlanNativePath)
999     updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB,
1000                         L->getExitBlock());
1001 }
1002 
1003 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1004 LLVM_DUMP_METHOD
1005 void VPlan::print(raw_ostream &O) const {
1006   VPSlotTracker SlotTracker(this);
1007 
1008   O << "VPlan '" << Name << "' {";
1009 
1010   if (VectorTripCount.getNumUsers() > 0) {
1011     O << "\nLive-in ";
1012     VectorTripCount.printAsOperand(O, SlotTracker);
1013     O << " = vector-trip-count\n";
1014   }
1015 
1016   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
1017     O << "\nLive-in ";
1018     BackedgeTakenCount->printAsOperand(O, SlotTracker);
1019     O << " = backedge-taken count\n";
1020   }
1021 
1022   for (const VPBlockBase *Block : depth_first(getEntry())) {
1023     O << '\n';
1024     Block->print(O, "", SlotTracker);
1025   }
1026   O << "}\n";
1027 }
1028 
1029 LLVM_DUMP_METHOD
1030 void VPlan::printDOT(raw_ostream &O) const {
1031   VPlanPrinter Printer(O, *this);
1032   Printer.dump();
1033 }
1034 
1035 LLVM_DUMP_METHOD
1036 void VPlan::dump() const { print(dbgs()); }
1037 #endif
1038 
1039 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB,
1040                                 BasicBlock *LoopLatchBB,
1041                                 BasicBlock *LoopExitBB) {
1042   BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor();
1043   assert(LoopHeaderBB && "Loop preheader does not have a single successor.");
1044   // The vector body may be more than a single basic-block by this point.
1045   // Update the dominator tree information inside the vector body by propagating
1046   // it from header to latch, expecting only triangular control-flow, if any.
1047   BasicBlock *PostDomSucc = nullptr;
1048   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
1049     // Get the list of successors of this block.
1050     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
1051     assert(Succs.size() <= 2 &&
1052            "Basic block in vector loop has more than 2 successors.");
1053     PostDomSucc = Succs[0];
1054     if (Succs.size() == 1) {
1055       assert(PostDomSucc->getSinglePredecessor() &&
1056              "PostDom successor has more than one predecessor.");
1057       DT->addNewBlock(PostDomSucc, BB);
1058       continue;
1059     }
1060     BasicBlock *InterimSucc = Succs[1];
1061     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
1062       PostDomSucc = Succs[1];
1063       InterimSucc = Succs[0];
1064     }
1065     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
1066            "One successor of a basic block does not lead to the other.");
1067     assert(InterimSucc->getSinglePredecessor() &&
1068            "Interim successor has more than one predecessor.");
1069     assert(PostDomSucc->hasNPredecessors(2) &&
1070            "PostDom successor has more than two predecessors.");
1071     DT->addNewBlock(InterimSucc, BB);
1072     DT->addNewBlock(PostDomSucc, BB);
1073   }
1074   // Latch block is a new dominator for the loop exit.
1075   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
1076   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
1077 }
1078 
1079 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1080 Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
1081   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
1082          Twine(getOrCreateBID(Block));
1083 }
1084 
1085 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
1086   const std::string &Name = Block->getName();
1087   if (!Name.empty())
1088     return Name;
1089   return "VPB" + Twine(getOrCreateBID(Block));
1090 }
1091 
1092 void VPlanPrinter::dump() {
1093   Depth = 1;
1094   bumpIndent(0);
1095   OS << "digraph VPlan {\n";
1096   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
1097   if (!Plan.getName().empty())
1098     OS << "\\n" << DOT::EscapeString(Plan.getName());
1099   if (Plan.BackedgeTakenCount) {
1100     OS << ", where:\\n";
1101     Plan.BackedgeTakenCount->print(OS, SlotTracker);
1102     OS << " := BackedgeTakenCount";
1103   }
1104   OS << "\"]\n";
1105   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
1106   OS << "edge [fontname=Courier, fontsize=30]\n";
1107   OS << "compound=true\n";
1108 
1109   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
1110     dumpBlock(Block);
1111 
1112   OS << "}\n";
1113 }
1114 
1115 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
1116   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
1117     dumpBasicBlock(BasicBlock);
1118   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1119     dumpRegion(Region);
1120   else
1121     llvm_unreachable("Unsupported kind of VPBlock.");
1122 }
1123 
1124 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
1125                             bool Hidden, const Twine &Label) {
1126   // Due to "dot" we print an edge between two regions as an edge between the
1127   // exit basic block and the entry basic of the respective regions.
1128   const VPBlockBase *Tail = From->getExitBasicBlock();
1129   const VPBlockBase *Head = To->getEntryBasicBlock();
1130   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
1131   OS << " [ label=\"" << Label << '\"';
1132   if (Tail != From)
1133     OS << " ltail=" << getUID(From);
1134   if (Head != To)
1135     OS << " lhead=" << getUID(To);
1136   if (Hidden)
1137     OS << "; splines=none";
1138   OS << "]\n";
1139 }
1140 
1141 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
1142   auto &Successors = Block->getSuccessors();
1143   if (Successors.size() == 1)
1144     drawEdge(Block, Successors.front(), false, "");
1145   else if (Successors.size() == 2) {
1146     drawEdge(Block, Successors.front(), false, "T");
1147     drawEdge(Block, Successors.back(), false, "F");
1148   } else {
1149     unsigned SuccessorNumber = 0;
1150     for (auto *Successor : Successors)
1151       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
1152   }
1153 }
1154 
1155 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
1156   // Implement dot-formatted dump by performing plain-text dump into the
1157   // temporary storage followed by some post-processing.
1158   OS << Indent << getUID(BasicBlock) << " [label =\n";
1159   bumpIndent(1);
1160   std::string Str;
1161   raw_string_ostream SS(Str);
1162   // Use no indentation as we need to wrap the lines into quotes ourselves.
1163   BasicBlock->print(SS, "", SlotTracker);
1164 
1165   // We need to process each line of the output separately, so split
1166   // single-string plain-text dump.
1167   SmallVector<StringRef, 0> Lines;
1168   StringRef(Str).rtrim('\n').split(Lines, "\n");
1169 
1170   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
1171     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
1172   };
1173 
1174   // Don't need the "+" after the last line.
1175   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
1176     EmitLine(Line, " +\n");
1177   EmitLine(Lines.back(), "\n");
1178 
1179   bumpIndent(-1);
1180   OS << Indent << "]\n";
1181 
1182   dumpEdges(BasicBlock);
1183 }
1184 
1185 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
1186   OS << Indent << "subgraph " << getUID(Region) << " {\n";
1187   bumpIndent(1);
1188   OS << Indent << "fontname=Courier\n"
1189      << Indent << "label=\""
1190      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
1191      << DOT::EscapeString(Region->getName()) << "\"\n";
1192   // Dump the blocks of the region.
1193   assert(Region->getEntry() && "Region contains no inner blocks.");
1194   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
1195     dumpBlock(Block);
1196   bumpIndent(-1);
1197   OS << Indent << "}\n";
1198   dumpEdges(Region);
1199 }
1200 
1201 void VPlanIngredient::print(raw_ostream &O) const {
1202   if (auto *Inst = dyn_cast<Instruction>(V)) {
1203     if (!Inst->getType()->isVoidTy()) {
1204       Inst->printAsOperand(O, false);
1205       O << " = ";
1206     }
1207     O << Inst->getOpcodeName() << " ";
1208     unsigned E = Inst->getNumOperands();
1209     if (E > 0) {
1210       Inst->getOperand(0)->printAsOperand(O, false);
1211       for (unsigned I = 1; I < E; ++I)
1212         Inst->getOperand(I)->printAsOperand(O << ", ", false);
1213     }
1214   } else // !Inst
1215     V->printAsOperand(O, false);
1216 }
1217 
1218 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent,
1219                               VPSlotTracker &SlotTracker) const {
1220   O << Indent << "WIDEN-CALL ";
1221 
1222   auto *CI = cast<CallInst>(getUnderlyingInstr());
1223   if (CI->getType()->isVoidTy())
1224     O << "void ";
1225   else {
1226     printAsOperand(O, SlotTracker);
1227     O << " = ";
1228   }
1229 
1230   O << "call @" << CI->getCalledFunction()->getName() << "(";
1231   printOperands(O, SlotTracker);
1232   O << ")";
1233 }
1234 
1235 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent,
1236                                 VPSlotTracker &SlotTracker) const {
1237   O << Indent << "WIDEN-SELECT ";
1238   printAsOperand(O, SlotTracker);
1239   O << " = select ";
1240   getOperand(0)->printAsOperand(O, SlotTracker);
1241   O << ", ";
1242   getOperand(1)->printAsOperand(O, SlotTracker);
1243   O << ", ";
1244   getOperand(2)->printAsOperand(O, SlotTracker);
1245   O << (InvariantCond ? " (condition is loop invariant)" : "");
1246 }
1247 
1248 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent,
1249                           VPSlotTracker &SlotTracker) const {
1250   O << Indent << "WIDEN ";
1251   printAsOperand(O, SlotTracker);
1252   O << " = " << getUnderlyingInstr()->getOpcodeName() << " ";
1253   printOperands(O, SlotTracker);
1254 }
1255 
1256 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent,
1257                                           VPSlotTracker &SlotTracker) const {
1258   O << Indent << "WIDEN-INDUCTION";
1259   if (getTruncInst()) {
1260     O << "\\l\"";
1261     O << " +\n" << Indent << "\"  " << VPlanIngredient(IV) << "\\l\"";
1262     O << " +\n" << Indent << "\"  ";
1263     getVPValue(0)->printAsOperand(O, SlotTracker);
1264   } else
1265     O << " " << VPlanIngredient(IV);
1266 }
1267 #endif
1268 
1269 bool VPWidenIntOrFpInductionRecipe::isCanonical() const {
1270   auto *StartC = dyn_cast<ConstantInt>(getStartValue()->getLiveInIRValue());
1271   auto *StepC = dyn_cast<SCEVConstant>(getInductionDescriptor().getStep());
1272   return StartC && StartC->isZero() && StepC && StepC->isOne();
1273 }
1274 
1275 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1276 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent,
1277                              VPSlotTracker &SlotTracker) const {
1278   O << Indent << "WIDEN-GEP ";
1279   O << (IsPtrLoopInvariant ? "Inv" : "Var");
1280   size_t IndicesNumber = IsIndexLoopInvariant.size();
1281   for (size_t I = 0; I < IndicesNumber; ++I)
1282     O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]";
1283 
1284   O << " ";
1285   printAsOperand(O, SlotTracker);
1286   O << " = getelementptr ";
1287   printOperands(O, SlotTracker);
1288 }
1289 
1290 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1291                              VPSlotTracker &SlotTracker) const {
1292   O << Indent << "WIDEN-PHI ";
1293 
1294   auto *OriginalPhi = cast<PHINode>(getUnderlyingValue());
1295   // Unless all incoming values are modeled in VPlan  print the original PHI
1296   // directly.
1297   // TODO: Remove once all VPWidenPHIRecipe instances keep all relevant incoming
1298   // values as VPValues.
1299   if (getNumOperands() != OriginalPhi->getNumOperands()) {
1300     O << VPlanIngredient(OriginalPhi);
1301     return;
1302   }
1303 
1304   printAsOperand(O, SlotTracker);
1305   O << " = phi ";
1306   printOperands(O, SlotTracker);
1307 }
1308 
1309 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent,
1310                           VPSlotTracker &SlotTracker) const {
1311   O << Indent << "BLEND ";
1312   Phi->printAsOperand(O, false);
1313   O << " =";
1314   if (getNumIncomingValues() == 1) {
1315     // Not a User of any mask: not really blending, this is a
1316     // single-predecessor phi.
1317     O << " ";
1318     getIncomingValue(0)->printAsOperand(O, SlotTracker);
1319   } else {
1320     for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
1321       O << " ";
1322       getIncomingValue(I)->printAsOperand(O, SlotTracker);
1323       O << "/";
1324       getMask(I)->printAsOperand(O, SlotTracker);
1325     }
1326   }
1327 }
1328 
1329 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent,
1330                               VPSlotTracker &SlotTracker) const {
1331   O << Indent << "REDUCE ";
1332   printAsOperand(O, SlotTracker);
1333   O << " = ";
1334   getChainOp()->printAsOperand(O, SlotTracker);
1335   O << " +";
1336   if (isa<FPMathOperator>(getUnderlyingInstr()))
1337     O << getUnderlyingInstr()->getFastMathFlags();
1338   O << " reduce." << Instruction::getOpcodeName(RdxDesc->getOpcode()) << " (";
1339   getVecOp()->printAsOperand(O, SlotTracker);
1340   if (getCondOp()) {
1341     O << ", ";
1342     getCondOp()->printAsOperand(O, SlotTracker);
1343   }
1344   O << ")";
1345 }
1346 
1347 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent,
1348                               VPSlotTracker &SlotTracker) const {
1349   O << Indent << (IsUniform ? "CLONE " : "REPLICATE ");
1350 
1351   if (!getUnderlyingInstr()->getType()->isVoidTy()) {
1352     printAsOperand(O, SlotTracker);
1353     O << " = ";
1354   }
1355   O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " ";
1356   printOperands(O, SlotTracker);
1357 
1358   if (AlsoPack)
1359     O << " (S->V)";
1360 }
1361 
1362 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1363                                 VPSlotTracker &SlotTracker) const {
1364   O << Indent << "PHI-PREDICATED-INSTRUCTION ";
1365   printAsOperand(O, SlotTracker);
1366   O << " = ";
1367   printOperands(O, SlotTracker);
1368 }
1369 
1370 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent,
1371                                            VPSlotTracker &SlotTracker) const {
1372   O << Indent << "WIDEN ";
1373 
1374   if (!isStore()) {
1375     printAsOperand(O, SlotTracker);
1376     O << " = ";
1377   }
1378   O << Instruction::getOpcodeName(Ingredient.getOpcode()) << " ";
1379 
1380   printOperands(O, SlotTracker);
1381 }
1382 #endif
1383 
1384 void VPCanonicalIVPHIRecipe::execute(VPTransformState &State) {
1385   Value *Start = getStartValue()->getLiveInIRValue();
1386   PHINode *EntryPart = PHINode::Create(
1387       Start->getType(), 2, "index", &*State.CFG.PrevBB->getFirstInsertionPt());
1388   EntryPart->addIncoming(Start, State.CFG.VectorPreHeader);
1389   EntryPart->setDebugLoc(DL);
1390   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
1391     State.set(this, EntryPart, Part);
1392 }
1393 
1394 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1395 void VPCanonicalIVPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1396                                    VPSlotTracker &SlotTracker) const {
1397   O << Indent << "EMIT ";
1398   printAsOperand(O, SlotTracker);
1399   O << " = CANONICAL-INDUCTION";
1400 }
1401 #endif
1402 
1403 void VPExpandSCEVRecipe::execute(VPTransformState &State) {
1404   assert(!State.Instance && "cannot be used in per-lane");
1405   const DataLayout &DL =
1406       State.CFG.VectorPreHeader->getModule()->getDataLayout();
1407   SCEVExpander Exp(SE, DL, "induction");
1408   Value *Res = Exp.expandCodeFor(Expr, Expr->getType(),
1409                                  State.CFG.VectorPreHeader->getTerminator());
1410 
1411   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
1412     State.set(this, Res, Part);
1413 }
1414 
1415 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1416 void VPExpandSCEVRecipe::print(raw_ostream &O, const Twine &Indent,
1417                                VPSlotTracker &SlotTracker) const {
1418   O << Indent << "EMIT ";
1419   getVPSingleValue()->printAsOperand(O, SlotTracker);
1420   O << " = EXPAND SCEV " << *Expr;
1421 }
1422 #endif
1423 
1424 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) {
1425   Value *CanonicalIV = State.get(getOperand(0), 0);
1426   Type *STy = CanonicalIV->getType();
1427   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
1428   ElementCount VF = State.VF;
1429   Value *VStart = VF.isScalar()
1430                       ? CanonicalIV
1431                       : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
1432   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) {
1433     Value *VStep = createStepForVF(Builder, STy, VF, Part);
1434     if (VF.isVector()) {
1435       VStep = Builder.CreateVectorSplat(VF, VStep);
1436       VStep = Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
1437     }
1438     Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
1439     State.set(this, CanonicalVectorIV, Part);
1440   }
1441 }
1442 
1443 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1444 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent,
1445                                      VPSlotTracker &SlotTracker) const {
1446   O << Indent << "EMIT ";
1447   printAsOperand(O, SlotTracker);
1448   O << " = WIDEN-CANONICAL-INDUCTION ";
1449   printOperands(O, SlotTracker);
1450 }
1451 #endif
1452 
1453 void VPFirstOrderRecurrencePHIRecipe::execute(VPTransformState &State) {
1454   auto &Builder = State.Builder;
1455   // Create a vector from the initial value.
1456   auto *VectorInit = getStartValue()->getLiveInIRValue();
1457 
1458   Type *VecTy = State.VF.isScalar()
1459                     ? VectorInit->getType()
1460                     : VectorType::get(VectorInit->getType(), State.VF);
1461 
1462   if (State.VF.isVector()) {
1463     auto *IdxTy = Builder.getInt32Ty();
1464     auto *One = ConstantInt::get(IdxTy, 1);
1465     IRBuilder<>::InsertPointGuard Guard(Builder);
1466     Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator());
1467     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
1468     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
1469     VectorInit = Builder.CreateInsertElement(
1470         PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
1471   }
1472 
1473   // Create a phi node for the new recurrence.
1474   PHINode *EntryPart = PHINode::Create(
1475       VecTy, 2, "vector.recur", &*State.CFG.PrevBB->getFirstInsertionPt());
1476   EntryPart->addIncoming(VectorInit, State.CFG.VectorPreHeader);
1477   State.set(this, EntryPart, 0);
1478 }
1479 
1480 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1481 void VPFirstOrderRecurrencePHIRecipe::print(raw_ostream &O, const Twine &Indent,
1482                                             VPSlotTracker &SlotTracker) const {
1483   O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
1484   printAsOperand(O, SlotTracker);
1485   O << " = phi ";
1486   printOperands(O, SlotTracker);
1487 }
1488 #endif
1489 
1490 void VPReductionPHIRecipe::execute(VPTransformState &State) {
1491   PHINode *PN = cast<PHINode>(getUnderlyingValue());
1492   auto &Builder = State.Builder;
1493 
1494   // In order to support recurrences we need to be able to vectorize Phi nodes.
1495   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
1496   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
1497   // this value when we vectorize all of the instructions that use the PHI.
1498   bool ScalarPHI = State.VF.isScalar() || IsInLoop;
1499   Type *VecTy =
1500       ScalarPHI ? PN->getType() : VectorType::get(PN->getType(), State.VF);
1501 
1502   BasicBlock *HeaderBB = State.CFG.PrevBB;
1503   assert(State.LI->getLoopFor(HeaderBB)->getHeader() == HeaderBB &&
1504          "recipe must be in the vector loop header");
1505   unsigned LastPartForNewPhi = isOrdered() ? 1 : State.UF;
1506   for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
1507     Value *EntryPart =
1508         PHINode::Create(VecTy, 2, "vec.phi", &*HeaderBB->getFirstInsertionPt());
1509     State.set(this, EntryPart, Part);
1510   }
1511 
1512   // Reductions do not have to start at zero. They can start with
1513   // any loop invariant values.
1514   VPValue *StartVPV = getStartValue();
1515   Value *StartV = StartVPV->getLiveInIRValue();
1516 
1517   Value *Iden = nullptr;
1518   RecurKind RK = RdxDesc.getRecurrenceKind();
1519   if (RecurrenceDescriptor::isMinMaxRecurrenceKind(RK) ||
1520       RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK)) {
1521     // MinMax reduction have the start value as their identify.
1522     if (ScalarPHI) {
1523       Iden = StartV;
1524     } else {
1525       IRBuilderBase::InsertPointGuard IPBuilder(Builder);
1526       Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator());
1527       StartV = Iden =
1528           Builder.CreateVectorSplat(State.VF, StartV, "minmax.ident");
1529     }
1530   } else {
1531     Iden = RdxDesc.getRecurrenceIdentity(RK, VecTy->getScalarType(),
1532                                          RdxDesc.getFastMathFlags());
1533 
1534     if (!ScalarPHI) {
1535       Iden = Builder.CreateVectorSplat(State.VF, Iden);
1536       IRBuilderBase::InsertPointGuard IPBuilder(Builder);
1537       Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator());
1538       Constant *Zero = Builder.getInt32(0);
1539       StartV = Builder.CreateInsertElement(Iden, StartV, Zero);
1540     }
1541   }
1542 
1543   for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
1544     Value *EntryPart = State.get(this, Part);
1545     // Make sure to add the reduction start value only to the
1546     // first unroll part.
1547     Value *StartVal = (Part == 0) ? StartV : Iden;
1548     cast<PHINode>(EntryPart)->addIncoming(StartVal, State.CFG.VectorPreHeader);
1549   }
1550 }
1551 
1552 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1553 void VPReductionPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1554                                  VPSlotTracker &SlotTracker) const {
1555   O << Indent << "WIDEN-REDUCTION-PHI ";
1556 
1557   printAsOperand(O, SlotTracker);
1558   O << " = phi ";
1559   printOperands(O, SlotTracker);
1560 }
1561 #endif
1562 
1563 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
1564 
1565 void VPValue::replaceAllUsesWith(VPValue *New) {
1566   for (unsigned J = 0; J < getNumUsers();) {
1567     VPUser *User = Users[J];
1568     unsigned NumUsers = getNumUsers();
1569     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
1570       if (User->getOperand(I) == this)
1571         User->setOperand(I, New);
1572     // If a user got removed after updating the current user, the next user to
1573     // update will be moved to the current position, so we only need to
1574     // increment the index if the number of users did not change.
1575     if (NumUsers == getNumUsers())
1576       J++;
1577   }
1578 }
1579 
1580 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1581 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1582   if (const Value *UV = getUnderlyingValue()) {
1583     OS << "ir<";
1584     UV->printAsOperand(OS, false);
1585     OS << ">";
1586     return;
1587   }
1588 
1589   unsigned Slot = Tracker.getSlot(this);
1590   if (Slot == unsigned(-1))
1591     OS << "<badref>";
1592   else
1593     OS << "vp<%" << Tracker.getSlot(this) << ">";
1594 }
1595 
1596 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1597   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1598     Op->printAsOperand(O, SlotTracker);
1599   });
1600 }
1601 #endif
1602 
1603 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1604                                           Old2NewTy &Old2New,
1605                                           InterleavedAccessInfo &IAI) {
1606   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
1607   for (VPBlockBase *Base : RPOT) {
1608     visitBlock(Base, Old2New, IAI);
1609   }
1610 }
1611 
1612 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1613                                          InterleavedAccessInfo &IAI) {
1614   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1615     for (VPRecipeBase &VPI : *VPBB) {
1616       if (isa<VPHeaderPHIRecipe>(&VPI))
1617         continue;
1618       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1619       auto *VPInst = cast<VPInstruction>(&VPI);
1620       auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue());
1621       auto *IG = IAI.getInterleaveGroup(Inst);
1622       if (!IG)
1623         continue;
1624 
1625       auto NewIGIter = Old2New.find(IG);
1626       if (NewIGIter == Old2New.end())
1627         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1628             IG->getFactor(), IG->isReverse(), IG->getAlign());
1629 
1630       if (Inst == IG->getInsertPos())
1631         Old2New[IG]->setInsertPos(VPInst);
1632 
1633       InterleaveGroupMap[VPInst] = Old2New[IG];
1634       InterleaveGroupMap[VPInst]->insertMember(
1635           VPInst, IG->getIndex(Inst),
1636           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1637                                 : IG->getFactor()));
1638     }
1639   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1640     visitRegion(Region, Old2New, IAI);
1641   else
1642     llvm_unreachable("Unsupported kind of VPBlock.");
1643 }
1644 
1645 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1646                                                  InterleavedAccessInfo &IAI) {
1647   Old2NewTy Old2New;
1648   visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI);
1649 }
1650 
1651 void VPSlotTracker::assignSlot(const VPValue *V) {
1652   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
1653   Slots[V] = NextSlot++;
1654 }
1655 
1656 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1657 
1658   for (const VPValue *V : Plan.VPExternalDefs)
1659     assignSlot(V);
1660 
1661   assignSlot(&Plan.VectorTripCount);
1662   if (Plan.BackedgeTakenCount)
1663     assignSlot(Plan.BackedgeTakenCount);
1664 
1665   ReversePostOrderTraversal<
1666       VPBlockRecursiveTraversalWrapper<const VPBlockBase *>>
1667       RPOT(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>(
1668           Plan.getEntry()));
1669   for (const VPBasicBlock *VPBB :
1670        VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1671     for (const VPRecipeBase &Recipe : *VPBB)
1672       for (VPValue *Def : Recipe.definedValues())
1673         assignSlot(Def);
1674 }
1675 
1676 bool vputils::onlyFirstLaneUsed(VPValue *Def) {
1677   return all_of(Def->users(), [Def](VPUser *U) {
1678     return cast<VPRecipeBase>(U)->onlyFirstLaneUsed(Def);
1679   });
1680 }
1681