xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision 0dddf04caba55a64f8534518d65311bdac05cf39)
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/LoopInfo.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/CFG.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/Instruction.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/IR/Value.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/GenericDomTreeConstruction.h"
38 #include "llvm/Support/GraphWriter.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/LoopVersioning.h"
42 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
43 #include <cassert>
44 #include <string>
45 #include <vector>
46 
47 using namespace llvm;
48 extern cl::opt<bool> EnableVPlanNativePath;
49 
50 #define DEBUG_TYPE "vplan"
51 
52 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
53 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
54   const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
55   VPSlotTracker SlotTracker(
56       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
57   V.print(OS, SlotTracker);
58   return OS;
59 }
60 #endif
61 
62 Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder,
63                                 const ElementCount &VF) const {
64   switch (LaneKind) {
65   case VPLane::Kind::ScalableLast:
66     // Lane = RuntimeVF - VF.getKnownMinValue() + Lane
67     return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF),
68                              Builder.getInt32(VF.getKnownMinValue() - Lane));
69   case VPLane::Kind::First:
70     return Builder.getInt32(Lane);
71   }
72   llvm_unreachable("Unknown lane kind");
73 }
74 
75 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)
76     : SubclassID(SC), UnderlyingVal(UV), Def(Def) {
77   if (Def)
78     Def->addDefinedValue(this);
79 }
80 
81 VPValue::~VPValue() {
82   assert(Users.empty() && "trying to delete a VPValue with remaining users");
83   if (Def)
84     Def->removeDefinedValue(this);
85 }
86 
87 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
88 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
89   if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def))
90     R->print(OS, "", SlotTracker);
91   else
92     printAsOperand(OS, SlotTracker);
93 }
94 
95 void VPValue::dump() const {
96   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def);
97   VPSlotTracker SlotTracker(
98       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
99   print(dbgs(), SlotTracker);
100   dbgs() << "\n";
101 }
102 
103 void VPDef::dump() const {
104   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this);
105   VPSlotTracker SlotTracker(
106       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
107   print(dbgs(), "", SlotTracker);
108   dbgs() << "\n";
109 }
110 #endif
111 
112 // Get the top-most entry block of \p Start. This is the entry block of the
113 // containing VPlan. This function is templated to support both const and non-const blocks
114 template <typename T> static T *getPlanEntry(T *Start) {
115   T *Next = Start;
116   T *Current = Start;
117   while ((Next = Next->getParent()))
118     Current = Next;
119 
120   SmallSetVector<T *, 8> WorkList;
121   WorkList.insert(Current);
122 
123   for (unsigned i = 0; i < WorkList.size(); i++) {
124     T *Current = WorkList[i];
125     if (Current->getNumPredecessors() == 0)
126       return Current;
127     auto &Predecessors = Current->getPredecessors();
128     WorkList.insert(Predecessors.begin(), Predecessors.end());
129   }
130 
131   llvm_unreachable("VPlan without any entry node without predecessors");
132 }
133 
134 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
135 
136 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
137 
138 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
139 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
140   const VPBlockBase *Block = this;
141   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
142     Block = Region->getEntry();
143   return cast<VPBasicBlock>(Block);
144 }
145 
146 VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
147   VPBlockBase *Block = this;
148   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
149     Block = Region->getEntry();
150   return cast<VPBasicBlock>(Block);
151 }
152 
153 void VPBlockBase::setPlan(VPlan *ParentPlan) {
154   assert(ParentPlan->getEntry() == this &&
155          "Can only set plan on its entry block.");
156   Plan = ParentPlan;
157 }
158 
159 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
160 const VPBasicBlock *VPBlockBase::getExitingBasicBlock() const {
161   const VPBlockBase *Block = this;
162   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
163     Block = Region->getExiting();
164   return cast<VPBasicBlock>(Block);
165 }
166 
167 VPBasicBlock *VPBlockBase::getExitingBasicBlock() {
168   VPBlockBase *Block = this;
169   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
170     Block = Region->getExiting();
171   return cast<VPBasicBlock>(Block);
172 }
173 
174 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
175   if (!Successors.empty() || !Parent)
176     return this;
177   assert(Parent->getExiting() == this &&
178          "Block w/o successors not the exiting block of its parent.");
179   return Parent->getEnclosingBlockWithSuccessors();
180 }
181 
182 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
183   if (!Predecessors.empty() || !Parent)
184     return this;
185   assert(Parent->getEntry() == this &&
186          "Block w/o predecessors not the entry of its parent.");
187   return Parent->getEnclosingBlockWithPredecessors();
188 }
189 
190 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
191   SmallVector<VPBlockBase *, 8> Blocks(depth_first(Entry));
192 
193   for (VPBlockBase *Block : Blocks)
194     delete Block;
195 }
196 
197 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
198   iterator It = begin();
199   while (It != end() && It->isPhi())
200     It++;
201   return It;
202 }
203 
204 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) {
205   if (!Def->getDef())
206     return Def->getLiveInIRValue();
207 
208   if (hasScalarValue(Def, Instance)) {
209     return Data
210         .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)];
211   }
212 
213   assert(hasVectorValue(Def, Instance.Part));
214   auto *VecPart = Data.PerPartOutput[Def][Instance.Part];
215   if (!VecPart->getType()->isVectorTy()) {
216     assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar");
217     return VecPart;
218   }
219   // TODO: Cache created scalar values.
220   Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF);
221   auto *Extract = Builder.CreateExtractElement(VecPart, Lane);
222   // set(Def, Extract, Instance);
223   return Extract;
224 }
225 BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) {
226   VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion();
227   return VPBB2IRBB[LoopRegion->getPreheaderVPBB()];
228 }
229 
230 void VPTransformState::addNewMetadata(Instruction *To,
231                                       const Instruction *Orig) {
232   // If the loop was versioned with memchecks, add the corresponding no-alias
233   // metadata.
234   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
235     LVer->annotateInstWithNoAlias(To, Orig);
236 }
237 
238 void VPTransformState::addMetadata(Instruction *To, Instruction *From) {
239   propagateMetadata(To, From);
240   addNewMetadata(To, From);
241 }
242 
243 void VPTransformState::addMetadata(ArrayRef<Value *> To, Instruction *From) {
244   for (Value *V : To) {
245     if (Instruction *I = dyn_cast<Instruction>(V))
246       addMetadata(I, From);
247   }
248 }
249 
250 BasicBlock *
251 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
252   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
253   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
254   BasicBlock *PrevBB = CFG.PrevBB;
255   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
256                                          PrevBB->getParent(), CFG.ExitBB);
257   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
258 
259   // Hook up the new basic block to its predecessors.
260   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
261     VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();
262     auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();
263     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
264 
265     assert(PredBB && "Predecessor basic-block not found building successor.");
266     auto *PredBBTerminator = PredBB->getTerminator();
267     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
268 
269     auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator);
270     if (isa<UnreachableInst>(PredBBTerminator)) {
271       assert(PredVPSuccessors.size() == 1 &&
272              "Predecessor ending w/o branch must have single successor.");
273       DebugLoc DL = PredBBTerminator->getDebugLoc();
274       PredBBTerminator->eraseFromParent();
275       auto *Br = BranchInst::Create(NewBB, PredBB);
276       Br->setDebugLoc(DL);
277     } else if (TermBr && !TermBr->isConditional()) {
278       TermBr->setSuccessor(0, NewBB);
279     } else {
280       // Set each forward successor here when it is created, excluding
281       // backedges. A backward successor is set when the branch is created.
282       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
283       assert(!TermBr->getSuccessor(idx) &&
284              "Trying to reset an existing successor block.");
285       TermBr->setSuccessor(idx, NewBB);
286     }
287   }
288   return NewBB;
289 }
290 
291 void VPBasicBlock::execute(VPTransformState *State) {
292   bool Replica = State->Instance && !State->Instance->isFirstIteration();
293   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
294   VPBlockBase *SingleHPred = nullptr;
295   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
296 
297   auto IsLoopRegion = [](VPBlockBase *BB) {
298     auto *R = dyn_cast<VPRegionBlock>(BB);
299     return R && !R->isReplicator();
300   };
301 
302   // 1. Create an IR basic block, or reuse the last one or ExitBB if possible.
303   if (getPlan()->getVectorLoopRegion()->getSingleSuccessor() == this) {
304     // ExitBB can be re-used for the exit block of the Plan.
305     NewBB = State->CFG.ExitBB;
306     State->CFG.PrevBB = NewBB;
307 
308     // Update the branch instruction in the predecessor to branch to ExitBB.
309     VPBlockBase *PredVPB = getSingleHierarchicalPredecessor();
310     VPBasicBlock *ExitingVPBB = PredVPB->getExitingBasicBlock();
311     assert(PredVPB->getSingleSuccessor() == this &&
312            "predecessor must have the current block as only successor");
313     BasicBlock *ExitingBB = State->CFG.VPBB2IRBB[ExitingVPBB];
314     // The Exit block of a loop is always set to be successor 0 of the Exiting
315     // block.
316     cast<BranchInst>(ExitingBB->getTerminator())->setSuccessor(0, NewBB);
317   } else if (PrevVPBB && /* A */
318              !((SingleHPred = getSingleHierarchicalPredecessor()) &&
319                SingleHPred->getExitingBasicBlock() == PrevVPBB &&
320                PrevVPBB->getSingleHierarchicalSuccessor() &&
321                (SingleHPred->getParent() == getEnclosingLoopRegion() &&
322                 !IsLoopRegion(SingleHPred))) &&         /* B */
323              !(Replica && getPredecessors().empty())) { /* C */
324     // The last IR basic block is reused, as an optimization, in three cases:
325     // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null;
326     // B. when the current VPBB has a single (hierarchical) predecessor which
327     //    is PrevVPBB and the latter has a single (hierarchical) successor which
328     //    both are in the same non-replicator region; and
329     // C. when the current VPBB is an entry of a region replica - where PrevVPBB
330     //    is the exiting VPBB of this region from a previous instance, or the
331     //    predecessor of this region.
332 
333     NewBB = createEmptyBasicBlock(State->CFG);
334     State->Builder.SetInsertPoint(NewBB);
335     // Temporarily terminate with unreachable until CFG is rewired.
336     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
337     // Register NewBB in its loop. In innermost loops its the same for all
338     // BB's.
339     if (State->CurrentVectorLoop)
340       State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI);
341     State->Builder.SetInsertPoint(Terminator);
342     State->CFG.PrevBB = NewBB;
343   }
344 
345   // 2. Fill the IR basic block with IR instructions.
346   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
347                     << " in BB:" << NewBB->getName() << '\n');
348 
349   State->CFG.VPBB2IRBB[this] = NewBB;
350   State->CFG.PrevVPBB = this;
351 
352   for (VPRecipeBase &Recipe : Recipes)
353     Recipe.execute(*State);
354 
355   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
356 }
357 
358 void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
359   for (VPRecipeBase &R : Recipes) {
360     for (auto *Def : R.definedValues())
361       Def->replaceAllUsesWith(NewValue);
362 
363     for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
364       R.setOperand(I, NewValue);
365   }
366 }
367 
368 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) {
369   assert((SplitAt == end() || SplitAt->getParent() == this) &&
370          "can only split at a position in the same block");
371 
372   SmallVector<VPBlockBase *, 2> Succs(successors());
373   // First, disconnect the current block from its successors.
374   for (VPBlockBase *Succ : Succs)
375     VPBlockUtils::disconnectBlocks(this, Succ);
376 
377   // Create new empty block after the block to split.
378   auto *SplitBlock = new VPBasicBlock(getName() + ".split");
379   VPBlockUtils::insertBlockAfter(SplitBlock, this);
380 
381   // Add successors for block to split to new block.
382   for (VPBlockBase *Succ : Succs)
383     VPBlockUtils::connectBlocks(SplitBlock, Succ);
384 
385   // Finally, move the recipes starting at SplitAt to new block.
386   for (VPRecipeBase &ToMove :
387        make_early_inc_range(make_range(SplitAt, this->end())))
388     ToMove.moveBefore(*SplitBlock, SplitBlock->end());
389 
390   return SplitBlock;
391 }
392 
393 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() {
394   VPRegionBlock *P = getParent();
395   if (P && P->isReplicator()) {
396     P = P->getParent();
397     assert(!cast<VPRegionBlock>(P)->isReplicator() &&
398            "unexpected nested replicate regions");
399   }
400   return P;
401 }
402 
403 static bool hasConditionalTerminator(const VPBasicBlock *VPBB) {
404   if (VPBB->empty()) {
405     assert(
406         VPBB->getNumSuccessors() < 2 &&
407         "block with multiple successors doesn't have a recipe as terminator");
408     return false;
409   }
410 
411   const VPRecipeBase *R = &VPBB->back();
412   auto *VPI = dyn_cast<VPInstruction>(R);
413   bool IsCondBranch =
414       isa<VPBranchOnMaskRecipe>(R) ||
415       (VPI && (VPI->getOpcode() == VPInstruction::BranchOnCond ||
416                VPI->getOpcode() == VPInstruction::BranchOnCount));
417   (void)IsCondBranch;
418 
419   if (VPBB->getNumSuccessors() >= 2 || VPBB->isExiting()) {
420     assert(IsCondBranch && "block with multiple successors not terminated by "
421                            "conditional branch recipe");
422 
423     return true;
424   }
425 
426   assert(
427       !IsCondBranch &&
428       "block with 0 or 1 successors terminated by conditional branch recipe");
429   return false;
430 }
431 
432 VPRecipeBase *VPBasicBlock::getTerminator() {
433   if (hasConditionalTerminator(this))
434     return &back();
435   return nullptr;
436 }
437 
438 const VPRecipeBase *VPBasicBlock::getTerminator() const {
439   if (hasConditionalTerminator(this))
440     return &back();
441   return nullptr;
442 }
443 
444 bool VPBasicBlock::isExiting() const {
445   return getParent()->getExitingBasicBlock() == this;
446 }
447 
448 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
449 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {
450   if (getSuccessors().empty()) {
451     O << Indent << "No successors\n";
452   } else {
453     O << Indent << "Successor(s): ";
454     ListSeparator LS;
455     for (auto *Succ : getSuccessors())
456       O << LS << Succ->getName();
457     O << '\n';
458   }
459 }
460 
461 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
462                          VPSlotTracker &SlotTracker) const {
463   O << Indent << getName() << ":\n";
464 
465   auto RecipeIndent = Indent + "  ";
466   for (const VPRecipeBase &Recipe : *this) {
467     Recipe.print(O, RecipeIndent, SlotTracker);
468     O << '\n';
469   }
470 
471   printSuccessors(O, Indent);
472 }
473 #endif
474 
475 void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
476   for (VPBlockBase *Block : depth_first(Entry))
477     // Drop all references in VPBasicBlocks and replace all uses with
478     // DummyValue.
479     Block->dropAllReferences(NewValue);
480 }
481 
482 void VPRegionBlock::execute(VPTransformState *State) {
483   ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry);
484 
485   if (!isReplicator()) {
486     // Create and register the new vector loop.
487     Loop *PrevLoop = State->CurrentVectorLoop;
488     State->CurrentVectorLoop = State->LI->AllocateLoop();
489     BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()];
490     Loop *ParentLoop = State->LI->getLoopFor(VectorPH);
491 
492     // Insert the new loop into the loop nest and register the new basic blocks
493     // before calling any utilities such as SCEV that require valid LoopInfo.
494     if (ParentLoop)
495       ParentLoop->addChildLoop(State->CurrentVectorLoop);
496     else
497       State->LI->addTopLevelLoop(State->CurrentVectorLoop);
498 
499     // Visit the VPBlocks connected to "this", starting from it.
500     for (VPBlockBase *Block : RPOT) {
501       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
502       Block->execute(State);
503     }
504 
505     State->CurrentVectorLoop = PrevLoop;
506     return;
507   }
508 
509   assert(!State->Instance && "Replicating a Region with non-null instance.");
510 
511   // Enter replicating mode.
512   State->Instance = VPIteration(0, 0);
513 
514   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
515     State->Instance->Part = Part;
516     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
517     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
518          ++Lane) {
519       State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);
520       // Visit the VPBlocks connected to \p this, starting from it.
521       for (VPBlockBase *Block : RPOT) {
522         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
523         Block->execute(State);
524       }
525     }
526   }
527 
528   // Exit replicating mode.
529   State->Instance.reset();
530 }
531 
532 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
533 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent,
534                           VPSlotTracker &SlotTracker) const {
535   O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
536   auto NewIndent = Indent + "  ";
537   for (auto *BlockBase : depth_first(Entry)) {
538     O << '\n';
539     BlockBase->print(O, NewIndent, SlotTracker);
540   }
541   O << Indent << "}\n";
542 
543   printSuccessors(O, Indent);
544 }
545 #endif
546 
547 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,
548                              Value *CanonicalIVStartValue,
549                              VPTransformState &State,
550                              bool IsEpilogueVectorization) {
551 
552   VPBasicBlock *ExitingVPBB = getVectorLoopRegion()->getExitingBasicBlock();
553   auto *Term = dyn_cast<VPInstruction>(&ExitingVPBB->back());
554   // Try to simplify BranchOnCount to 'BranchOnCond true' if TC <= VF * UF when
555   // preparing to execute the plan for the main vector loop.
556   if (!IsEpilogueVectorization && Term &&
557       Term->getOpcode() == VPInstruction::BranchOnCount &&
558       isa<ConstantInt>(TripCountV)) {
559     ConstantInt *C = cast<ConstantInt>(TripCountV);
560     uint64_t TCVal = C->getZExtValue();
561     if (TCVal && TCVal <= State.VF.getKnownMinValue() * State.UF) {
562       auto *BOC =
563           new VPInstruction(VPInstruction::BranchOnCond,
564                             {getOrAddExternalDef(State.Builder.getTrue())});
565       Term->eraseFromParent();
566       ExitingVPBB->appendRecipe(BOC);
567       // TODO: Further simplifications are possible
568       //      1. Replace inductions with constants.
569       //      2. Replace vector loop region with VPBasicBlock.
570     }
571   }
572 
573   // Check if the trip count is needed, and if so build it.
574   if (TripCount && TripCount->getNumUsers()) {
575     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
576       State.set(TripCount, TripCountV, Part);
577   }
578 
579   // Check if the backedge taken count is needed, and if so build it.
580   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
581     IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
582     auto *TCMO = Builder.CreateSub(TripCountV,
583                                    ConstantInt::get(TripCountV->getType(), 1),
584                                    "trip.count.minus.1");
585     auto VF = State.VF;
586     Value *VTCMO =
587         VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
588     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
589       State.set(BackedgeTakenCount, VTCMO, Part);
590   }
591 
592   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
593     State.set(&VectorTripCount, VectorTripCountV, Part);
594 
595   // When vectorizing the epilogue loop, the canonical induction start value
596   // needs to be changed from zero to the value after the main vector loop.
597   if (CanonicalIVStartValue) {
598     VPValue *VPV = getOrAddExternalDef(CanonicalIVStartValue);
599     auto *IV = getCanonicalIV();
600     assert(all_of(IV->users(),
601                   [](const VPUser *U) {
602                     if (isa<VPScalarIVStepsRecipe>(U))
603                       return true;
604                     auto *VPI = cast<VPInstruction>(U);
605                     return VPI->getOpcode() ==
606                                VPInstruction::CanonicalIVIncrement ||
607                            VPI->getOpcode() ==
608                                VPInstruction::CanonicalIVIncrementNUW;
609                   }) &&
610            "the canonical IV should only be used by its increments or "
611            "ScalarIVSteps when "
612            "resetting the start value");
613     IV->setOperand(0, VPV);
614   }
615 }
616 
617 /// Generate the code inside the preheader and body of the vectorized loop.
618 /// Assumes a single pre-header basic-block was created for this. Introduce
619 /// additional basic-blocks as needed, and fill them all.
620 void VPlan::execute(VPTransformState *State) {
621   // Set the reverse mapping from VPValues to Values for code generation.
622   for (auto &Entry : Value2VPValue)
623     State->VPValue2Value[Entry.second] = Entry.first;
624 
625   // Initialize CFG state.
626   State->CFG.PrevVPBB = nullptr;
627   State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();
628   BasicBlock *VectorPreHeader = State->CFG.PrevBB;
629   State->Builder.SetInsertPoint(VectorPreHeader->getTerminator());
630 
631   // Generate code in the loop pre-header and body.
632   for (VPBlockBase *Block : depth_first(Entry))
633     Block->execute(State);
634 
635   VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock();
636   BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB];
637 
638   // Fix the latch value of canonical, reduction and first-order recurrences
639   // phis in the vector loop.
640   VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
641   for (VPRecipeBase &R : Header->phis()) {
642     // Skip phi-like recipes that generate their backedege values themselves.
643     if (isa<VPWidenPHIRecipe>(&R))
644       continue;
645 
646     if (isa<VPWidenPointerInductionRecipe>(&R) ||
647         isa<VPWidenIntOrFpInductionRecipe>(&R)) {
648       PHINode *Phi = nullptr;
649       if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {
650         Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));
651       } else {
652         auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);
653         // TODO: Split off the case that all users of a pointer phi are scalar
654         // from the VPWidenPointerInductionRecipe.
655         if (WidenPhi->onlyScalarsGenerated(State->VF))
656           continue;
657 
658         auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));
659         Phi = cast<PHINode>(GEP->getPointerOperand());
660       }
661 
662       Phi->setIncomingBlock(1, VectorLatchBB);
663 
664       // Move the last step to the end of the latch block. This ensures
665       // consistent placement of all induction updates.
666       Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));
667       Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());
668       continue;
669     }
670 
671     auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
672     // For  canonical IV, first-order recurrences and in-order reduction phis,
673     // only a single part is generated, which provides the last part from the
674     // previous iteration. For non-ordered reductions all UF parts are
675     // generated.
676     bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) ||
677                             isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) ||
678                             cast<VPReductionPHIRecipe>(PhiR)->isOrdered();
679     unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
680 
681     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
682       Value *Phi = State->get(PhiR, Part);
683       Value *Val = State->get(PhiR->getBackedgeValue(),
684                               SinglePartNeeded ? State->UF - 1 : Part);
685       cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
686     }
687   }
688 
689   // We do not attempt to preserve DT for outer loop vectorization currently.
690   if (!EnableVPlanNativePath) {
691     BasicBlock *VectorHeaderBB = State->CFG.VPBB2IRBB[Header];
692     State->DT->addNewBlock(VectorHeaderBB, VectorPreHeader);
693     updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB,
694                         State->CFG.ExitBB);
695   }
696 }
697 
698 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
699 LLVM_DUMP_METHOD
700 void VPlan::print(raw_ostream &O) const {
701   VPSlotTracker SlotTracker(this);
702 
703   O << "VPlan '" << Name << "' {";
704 
705   if (VectorTripCount.getNumUsers() > 0) {
706     O << "\nLive-in ";
707     VectorTripCount.printAsOperand(O, SlotTracker);
708     O << " = vector-trip-count\n";
709   }
710 
711   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
712     O << "\nLive-in ";
713     BackedgeTakenCount->printAsOperand(O, SlotTracker);
714     O << " = backedge-taken count\n";
715   }
716 
717   for (const VPBlockBase *Block : depth_first(getEntry())) {
718     O << '\n';
719     Block->print(O, "", SlotTracker);
720   }
721 
722   if (!LiveOuts.empty())
723     O << "\n";
724   for (auto &KV : LiveOuts) {
725     O << "Live-out ";
726     KV.second->getPhi()->printAsOperand(O);
727     O << " = ";
728     KV.second->getOperand(0)->printAsOperand(O, SlotTracker);
729     O << "\n";
730   }
731 
732   O << "}\n";
733 }
734 
735 LLVM_DUMP_METHOD
736 void VPlan::printDOT(raw_ostream &O) const {
737   VPlanPrinter Printer(O, *this);
738   Printer.dump();
739 }
740 
741 LLVM_DUMP_METHOD
742 void VPlan::dump() const { print(dbgs()); }
743 #endif
744 
745 void VPlan::addLiveOut(PHINode *PN, VPValue *V) {
746   assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists");
747   LiveOuts.insert({PN, new VPLiveOut(PN, V)});
748 }
749 
750 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB,
751                                 BasicBlock *LoopLatchBB,
752                                 BasicBlock *LoopExitBB) {
753   // The vector body may be more than a single basic-block by this point.
754   // Update the dominator tree information inside the vector body by propagating
755   // it from header to latch, expecting only triangular control-flow, if any.
756   BasicBlock *PostDomSucc = nullptr;
757   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
758     // Get the list of successors of this block.
759     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
760     assert(Succs.size() <= 2 &&
761            "Basic block in vector loop has more than 2 successors.");
762     PostDomSucc = Succs[0];
763     if (Succs.size() == 1) {
764       assert(PostDomSucc->getSinglePredecessor() &&
765              "PostDom successor has more than one predecessor.");
766       DT->addNewBlock(PostDomSucc, BB);
767       continue;
768     }
769     BasicBlock *InterimSucc = Succs[1];
770     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
771       PostDomSucc = Succs[1];
772       InterimSucc = Succs[0];
773     }
774     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
775            "One successor of a basic block does not lead to the other.");
776     assert(InterimSucc->getSinglePredecessor() &&
777            "Interim successor has more than one predecessor.");
778     assert(PostDomSucc->hasNPredecessors(2) &&
779            "PostDom successor has more than two predecessors.");
780     DT->addNewBlock(InterimSucc, BB);
781     DT->addNewBlock(PostDomSucc, BB);
782   }
783   // Latch block is a new dominator for the loop exit.
784   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
785   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
786 }
787 
788 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
789 
790 Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
791   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
792          Twine(getOrCreateBID(Block));
793 }
794 
795 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
796   const std::string &Name = Block->getName();
797   if (!Name.empty())
798     return Name;
799   return "VPB" + Twine(getOrCreateBID(Block));
800 }
801 
802 void VPlanPrinter::dump() {
803   Depth = 1;
804   bumpIndent(0);
805   OS << "digraph VPlan {\n";
806   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
807   if (!Plan.getName().empty())
808     OS << "\\n" << DOT::EscapeString(Plan.getName());
809   if (Plan.BackedgeTakenCount) {
810     OS << ", where:\\n";
811     Plan.BackedgeTakenCount->print(OS, SlotTracker);
812     OS << " := BackedgeTakenCount";
813   }
814   OS << "\"]\n";
815   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
816   OS << "edge [fontname=Courier, fontsize=30]\n";
817   OS << "compound=true\n";
818 
819   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
820     dumpBlock(Block);
821 
822   OS << "}\n";
823 }
824 
825 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
826   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
827     dumpBasicBlock(BasicBlock);
828   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
829     dumpRegion(Region);
830   else
831     llvm_unreachable("Unsupported kind of VPBlock.");
832 }
833 
834 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
835                             bool Hidden, const Twine &Label) {
836   // Due to "dot" we print an edge between two regions as an edge between the
837   // exiting basic block and the entry basic of the respective regions.
838   const VPBlockBase *Tail = From->getExitingBasicBlock();
839   const VPBlockBase *Head = To->getEntryBasicBlock();
840   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
841   OS << " [ label=\"" << Label << '\"';
842   if (Tail != From)
843     OS << " ltail=" << getUID(From);
844   if (Head != To)
845     OS << " lhead=" << getUID(To);
846   if (Hidden)
847     OS << "; splines=none";
848   OS << "]\n";
849 }
850 
851 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
852   auto &Successors = Block->getSuccessors();
853   if (Successors.size() == 1)
854     drawEdge(Block, Successors.front(), false, "");
855   else if (Successors.size() == 2) {
856     drawEdge(Block, Successors.front(), false, "T");
857     drawEdge(Block, Successors.back(), false, "F");
858   } else {
859     unsigned SuccessorNumber = 0;
860     for (auto *Successor : Successors)
861       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
862   }
863 }
864 
865 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
866   // Implement dot-formatted dump by performing plain-text dump into the
867   // temporary storage followed by some post-processing.
868   OS << Indent << getUID(BasicBlock) << " [label =\n";
869   bumpIndent(1);
870   std::string Str;
871   raw_string_ostream SS(Str);
872   // Use no indentation as we need to wrap the lines into quotes ourselves.
873   BasicBlock->print(SS, "", SlotTracker);
874 
875   // We need to process each line of the output separately, so split
876   // single-string plain-text dump.
877   SmallVector<StringRef, 0> Lines;
878   StringRef(Str).rtrim('\n').split(Lines, "\n");
879 
880   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
881     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
882   };
883 
884   // Don't need the "+" after the last line.
885   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
886     EmitLine(Line, " +\n");
887   EmitLine(Lines.back(), "\n");
888 
889   bumpIndent(-1);
890   OS << Indent << "]\n";
891 
892   dumpEdges(BasicBlock);
893 }
894 
895 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
896   OS << Indent << "subgraph " << getUID(Region) << " {\n";
897   bumpIndent(1);
898   OS << Indent << "fontname=Courier\n"
899      << Indent << "label=\""
900      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
901      << DOT::EscapeString(Region->getName()) << "\"\n";
902   // Dump the blocks of the region.
903   assert(Region->getEntry() && "Region contains no inner blocks.");
904   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
905     dumpBlock(Block);
906   bumpIndent(-1);
907   OS << Indent << "}\n";
908   dumpEdges(Region);
909 }
910 
911 void VPlanIngredient::print(raw_ostream &O) const {
912   if (auto *Inst = dyn_cast<Instruction>(V)) {
913     if (!Inst->getType()->isVoidTy()) {
914       Inst->printAsOperand(O, false);
915       O << " = ";
916     }
917     O << Inst->getOpcodeName() << " ";
918     unsigned E = Inst->getNumOperands();
919     if (E > 0) {
920       Inst->getOperand(0)->printAsOperand(O, false);
921       for (unsigned I = 1; I < E; ++I)
922         Inst->getOperand(I)->printAsOperand(O << ", ", false);
923     }
924   } else // !Inst
925     V->printAsOperand(O, false);
926 }
927 
928 #endif
929 
930 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
931 
932 void VPValue::replaceAllUsesWith(VPValue *New) {
933   for (unsigned J = 0; J < getNumUsers();) {
934     VPUser *User = Users[J];
935     unsigned NumUsers = getNumUsers();
936     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
937       if (User->getOperand(I) == this)
938         User->setOperand(I, New);
939     // If a user got removed after updating the current user, the next user to
940     // update will be moved to the current position, so we only need to
941     // increment the index if the number of users did not change.
942     if (NumUsers == getNumUsers())
943       J++;
944   }
945 }
946 
947 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
948 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
949   if (const Value *UV = getUnderlyingValue()) {
950     OS << "ir<";
951     UV->printAsOperand(OS, false);
952     OS << ">";
953     return;
954   }
955 
956   unsigned Slot = Tracker.getSlot(this);
957   if (Slot == unsigned(-1))
958     OS << "<badref>";
959   else
960     OS << "vp<%" << Tracker.getSlot(this) << ">";
961 }
962 
963 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
964   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
965     Op->printAsOperand(O, SlotTracker);
966   });
967 }
968 #endif
969 
970 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
971                                           Old2NewTy &Old2New,
972                                           InterleavedAccessInfo &IAI) {
973   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
974   for (VPBlockBase *Base : RPOT) {
975     visitBlock(Base, Old2New, IAI);
976   }
977 }
978 
979 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
980                                          InterleavedAccessInfo &IAI) {
981   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
982     for (VPRecipeBase &VPI : *VPBB) {
983       if (isa<VPHeaderPHIRecipe>(&VPI))
984         continue;
985       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
986       auto *VPInst = cast<VPInstruction>(&VPI);
987 
988       auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue());
989       if (!Inst)
990         continue;
991       auto *IG = IAI.getInterleaveGroup(Inst);
992       if (!IG)
993         continue;
994 
995       auto NewIGIter = Old2New.find(IG);
996       if (NewIGIter == Old2New.end())
997         Old2New[IG] = new InterleaveGroup<VPInstruction>(
998             IG->getFactor(), IG->isReverse(), IG->getAlign());
999 
1000       if (Inst == IG->getInsertPos())
1001         Old2New[IG]->setInsertPos(VPInst);
1002 
1003       InterleaveGroupMap[VPInst] = Old2New[IG];
1004       InterleaveGroupMap[VPInst]->insertMember(
1005           VPInst, IG->getIndex(Inst),
1006           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1007                                 : IG->getFactor()));
1008     }
1009   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1010     visitRegion(Region, Old2New, IAI);
1011   else
1012     llvm_unreachable("Unsupported kind of VPBlock.");
1013 }
1014 
1015 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1016                                                  InterleavedAccessInfo &IAI) {
1017   Old2NewTy Old2New;
1018   visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI);
1019 }
1020 
1021 void VPSlotTracker::assignSlot(const VPValue *V) {
1022   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
1023   Slots[V] = NextSlot++;
1024 }
1025 
1026 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1027 
1028   for (const auto &P : Plan.VPExternalDefs)
1029     assignSlot(P.second);
1030 
1031   assignSlot(&Plan.VectorTripCount);
1032   if (Plan.BackedgeTakenCount)
1033     assignSlot(Plan.BackedgeTakenCount);
1034 
1035   ReversePostOrderTraversal<
1036       VPBlockRecursiveTraversalWrapper<const VPBlockBase *>>
1037       RPOT(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>(
1038           Plan.getEntry()));
1039   for (const VPBasicBlock *VPBB :
1040        VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1041     for (const VPRecipeBase &Recipe : *VPBB)
1042       for (VPValue *Def : Recipe.definedValues())
1043         assignSlot(Def);
1044 }
1045 
1046 bool vputils::onlyFirstLaneUsed(VPValue *Def) {
1047   return all_of(Def->users(),
1048                 [Def](VPUser *U) { return U->onlyFirstLaneUsed(Def); });
1049 }
1050 
1051 VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr,
1052                                                 ScalarEvolution &SE) {
1053   if (auto *E = dyn_cast<SCEVConstant>(Expr))
1054     return Plan.getOrAddExternalDef(E->getValue());
1055   if (auto *E = dyn_cast<SCEVUnknown>(Expr))
1056     return Plan.getOrAddExternalDef(E->getValue());
1057 
1058   VPBasicBlock *Preheader = Plan.getEntry()->getEntryBasicBlock();
1059   VPValue *Step = new VPExpandSCEVRecipe(Expr, SE);
1060   Preheader->appendRecipe(cast<VPRecipeBase>(Step->getDef()));
1061   return Step;
1062 }
1063