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