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 
551   VPBasicBlock *ExitingVPBB = getVectorLoopRegion()->getExitingBasicBlock();
552   auto *Term = dyn_cast<VPInstruction>(&ExitingVPBB->back());
553   // Try to simplify BranchOnCount to 'BranchOnCond true' if TC <= VF * UF when
554   // preparing to execute the plan for the main vector loop.
555   if (!CanonicalIVStartValue && Term &&
556       Term->getOpcode() == VPInstruction::BranchOnCount &&
557       isa<ConstantInt>(TripCountV)) {
558     ConstantInt *C = cast<ConstantInt>(TripCountV);
559     uint64_t TCVal = C->getZExtValue();
560     if (TCVal && TCVal <= State.VF.getKnownMinValue() * State.UF) {
561       auto *BOC =
562           new VPInstruction(VPInstruction::BranchOnCond,
563                             {getOrAddExternalDef(State.Builder.getTrue())});
564       Term->eraseFromParent();
565       ExitingVPBB->appendRecipe(BOC);
566       // TODO: Further simplifications are possible
567       //      1. Replace inductions with constants.
568       //      2. Replace vector loop region with VPBasicBlock.
569     }
570   }
571 
572   // Check if the trip count is needed, and if so build it.
573   if (TripCount && TripCount->getNumUsers()) {
574     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
575       State.set(TripCount, TripCountV, Part);
576   }
577 
578   // Check if the backedge taken count is needed, and if so build it.
579   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
580     IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
581     auto *TCMO = Builder.CreateSub(TripCountV,
582                                    ConstantInt::get(TripCountV->getType(), 1),
583                                    "trip.count.minus.1");
584     auto VF = State.VF;
585     Value *VTCMO =
586         VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
587     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
588       State.set(BackedgeTakenCount, VTCMO, Part);
589   }
590 
591   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
592     State.set(&VectorTripCount, VectorTripCountV, Part);
593 
594   // When vectorizing the epilogue loop, the canonical induction start value
595   // needs to be changed from zero to the value after the main vector loop.
596   if (CanonicalIVStartValue) {
597     VPValue *VPV = getOrAddExternalDef(CanonicalIVStartValue);
598     auto *IV = getCanonicalIV();
599     assert(all_of(IV->users(),
600                   [](const VPUser *U) {
601                     if (isa<VPScalarIVStepsRecipe>(U))
602                       return true;
603                     auto *VPI = cast<VPInstruction>(U);
604                     return VPI->getOpcode() ==
605                                VPInstruction::CanonicalIVIncrement ||
606                            VPI->getOpcode() ==
607                                VPInstruction::CanonicalIVIncrementNUW;
608                   }) &&
609            "the canonical IV should only be used by its increments or "
610            "ScalarIVSteps when "
611            "resetting the start value");
612     IV->setOperand(0, VPV);
613   }
614 }
615 
616 /// Generate the code inside the preheader and body of the vectorized loop.
617 /// Assumes a single pre-header basic-block was created for this. Introduce
618 /// additional basic-blocks as needed, and fill them all.
619 void VPlan::execute(VPTransformState *State) {
620   // Set the reverse mapping from VPValues to Values for code generation.
621   for (auto &Entry : Value2VPValue)
622     State->VPValue2Value[Entry.second] = Entry.first;
623 
624   // Initialize CFG state.
625   State->CFG.PrevVPBB = nullptr;
626   State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();
627   BasicBlock *VectorPreHeader = State->CFG.PrevBB;
628   State->Builder.SetInsertPoint(VectorPreHeader->getTerminator());
629 
630   // Generate code in the loop pre-header and body.
631   for (VPBlockBase *Block : depth_first(Entry))
632     Block->execute(State);
633 
634   VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock();
635   BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB];
636 
637   // Fix the latch value of canonical, reduction and first-order recurrences
638   // phis in the vector loop.
639   VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
640   for (VPRecipeBase &R : Header->phis()) {
641     // Skip phi-like recipes that generate their backedege values themselves.
642     if (isa<VPWidenPHIRecipe>(&R))
643       continue;
644 
645     if (isa<VPWidenPointerInductionRecipe>(&R) ||
646         isa<VPWidenIntOrFpInductionRecipe>(&R)) {
647       PHINode *Phi = nullptr;
648       if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {
649         Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));
650       } else {
651         auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);
652         // TODO: Split off the case that all users of a pointer phi are scalar
653         // from the VPWidenPointerInductionRecipe.
654         if (WidenPhi->onlyScalarsGenerated(State->VF))
655           continue;
656 
657         auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));
658         Phi = cast<PHINode>(GEP->getPointerOperand());
659       }
660 
661       Phi->setIncomingBlock(1, VectorLatchBB);
662 
663       // Move the last step to the end of the latch block. This ensures
664       // consistent placement of all induction updates.
665       Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));
666       Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());
667       continue;
668     }
669 
670     auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
671     // For  canonical IV, first-order recurrences and in-order reduction phis,
672     // only a single part is generated, which provides the last part from the
673     // previous iteration. For non-ordered reductions all UF parts are
674     // generated.
675     bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) ||
676                             isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) ||
677                             cast<VPReductionPHIRecipe>(PhiR)->isOrdered();
678     unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
679 
680     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
681       Value *Phi = State->get(PhiR, Part);
682       Value *Val = State->get(PhiR->getBackedgeValue(),
683                               SinglePartNeeded ? State->UF - 1 : Part);
684       cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
685     }
686   }
687 
688   // We do not attempt to preserve DT for outer loop vectorization currently.
689   if (!EnableVPlanNativePath) {
690     BasicBlock *VectorHeaderBB = State->CFG.VPBB2IRBB[Header];
691     State->DT->addNewBlock(VectorHeaderBB, VectorPreHeader);
692     updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB,
693                         State->CFG.ExitBB);
694   }
695 }
696 
697 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
698 LLVM_DUMP_METHOD
699 void VPlan::print(raw_ostream &O) const {
700   VPSlotTracker SlotTracker(this);
701 
702   O << "VPlan '" << Name << "' {";
703 
704   if (VectorTripCount.getNumUsers() > 0) {
705     O << "\nLive-in ";
706     VectorTripCount.printAsOperand(O, SlotTracker);
707     O << " = vector-trip-count\n";
708   }
709 
710   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
711     O << "\nLive-in ";
712     BackedgeTakenCount->printAsOperand(O, SlotTracker);
713     O << " = backedge-taken count\n";
714   }
715 
716   for (const VPBlockBase *Block : depth_first(getEntry())) {
717     O << '\n';
718     Block->print(O, "", SlotTracker);
719   }
720 
721   if (!LiveOuts.empty())
722     O << "\n";
723   for (auto &KV : LiveOuts) {
724     O << "Live-out ";
725     KV.second->getPhi()->printAsOperand(O);
726     O << " = ";
727     KV.second->getOperand(0)->printAsOperand(O, SlotTracker);
728     O << "\n";
729   }
730 
731   O << "}\n";
732 }
733 
734 LLVM_DUMP_METHOD
735 void VPlan::printDOT(raw_ostream &O) const {
736   VPlanPrinter Printer(O, *this);
737   Printer.dump();
738 }
739 
740 LLVM_DUMP_METHOD
741 void VPlan::dump() const { print(dbgs()); }
742 #endif
743 
744 void VPlan::addLiveOut(PHINode *PN, VPValue *V) {
745   assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists");
746   LiveOuts.insert({PN, new VPLiveOut(PN, V)});
747 }
748 
749 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB,
750                                 BasicBlock *LoopLatchBB,
751                                 BasicBlock *LoopExitBB) {
752   // The vector body may be more than a single basic-block by this point.
753   // Update the dominator tree information inside the vector body by propagating
754   // it from header to latch, expecting only triangular control-flow, if any.
755   BasicBlock *PostDomSucc = nullptr;
756   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
757     // Get the list of successors of this block.
758     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
759     assert(Succs.size() <= 2 &&
760            "Basic block in vector loop has more than 2 successors.");
761     PostDomSucc = Succs[0];
762     if (Succs.size() == 1) {
763       assert(PostDomSucc->getSinglePredecessor() &&
764              "PostDom successor has more than one predecessor.");
765       DT->addNewBlock(PostDomSucc, BB);
766       continue;
767     }
768     BasicBlock *InterimSucc = Succs[1];
769     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
770       PostDomSucc = Succs[1];
771       InterimSucc = Succs[0];
772     }
773     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
774            "One successor of a basic block does not lead to the other.");
775     assert(InterimSucc->getSinglePredecessor() &&
776            "Interim successor has more than one predecessor.");
777     assert(PostDomSucc->hasNPredecessors(2) &&
778            "PostDom successor has more than two predecessors.");
779     DT->addNewBlock(InterimSucc, BB);
780     DT->addNewBlock(PostDomSucc, BB);
781   }
782   // Latch block is a new dominator for the loop exit.
783   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
784   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
785 }
786 
787 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
788 
789 Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
790   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
791          Twine(getOrCreateBID(Block));
792 }
793 
794 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
795   const std::string &Name = Block->getName();
796   if (!Name.empty())
797     return Name;
798   return "VPB" + Twine(getOrCreateBID(Block));
799 }
800 
801 void VPlanPrinter::dump() {
802   Depth = 1;
803   bumpIndent(0);
804   OS << "digraph VPlan {\n";
805   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
806   if (!Plan.getName().empty())
807     OS << "\\n" << DOT::EscapeString(Plan.getName());
808   if (Plan.BackedgeTakenCount) {
809     OS << ", where:\\n";
810     Plan.BackedgeTakenCount->print(OS, SlotTracker);
811     OS << " := BackedgeTakenCount";
812   }
813   OS << "\"]\n";
814   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
815   OS << "edge [fontname=Courier, fontsize=30]\n";
816   OS << "compound=true\n";
817 
818   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
819     dumpBlock(Block);
820 
821   OS << "}\n";
822 }
823 
824 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
825   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
826     dumpBasicBlock(BasicBlock);
827   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
828     dumpRegion(Region);
829   else
830     llvm_unreachable("Unsupported kind of VPBlock.");
831 }
832 
833 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
834                             bool Hidden, const Twine &Label) {
835   // Due to "dot" we print an edge between two regions as an edge between the
836   // exiting basic block and the entry basic of the respective regions.
837   const VPBlockBase *Tail = From->getExitingBasicBlock();
838   const VPBlockBase *Head = To->getEntryBasicBlock();
839   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
840   OS << " [ label=\"" << Label << '\"';
841   if (Tail != From)
842     OS << " ltail=" << getUID(From);
843   if (Head != To)
844     OS << " lhead=" << getUID(To);
845   if (Hidden)
846     OS << "; splines=none";
847   OS << "]\n";
848 }
849 
850 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
851   auto &Successors = Block->getSuccessors();
852   if (Successors.size() == 1)
853     drawEdge(Block, Successors.front(), false, "");
854   else if (Successors.size() == 2) {
855     drawEdge(Block, Successors.front(), false, "T");
856     drawEdge(Block, Successors.back(), false, "F");
857   } else {
858     unsigned SuccessorNumber = 0;
859     for (auto *Successor : Successors)
860       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
861   }
862 }
863 
864 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
865   // Implement dot-formatted dump by performing plain-text dump into the
866   // temporary storage followed by some post-processing.
867   OS << Indent << getUID(BasicBlock) << " [label =\n";
868   bumpIndent(1);
869   std::string Str;
870   raw_string_ostream SS(Str);
871   // Use no indentation as we need to wrap the lines into quotes ourselves.
872   BasicBlock->print(SS, "", SlotTracker);
873 
874   // We need to process each line of the output separately, so split
875   // single-string plain-text dump.
876   SmallVector<StringRef, 0> Lines;
877   StringRef(Str).rtrim('\n').split(Lines, "\n");
878 
879   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
880     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
881   };
882 
883   // Don't need the "+" after the last line.
884   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
885     EmitLine(Line, " +\n");
886   EmitLine(Lines.back(), "\n");
887 
888   bumpIndent(-1);
889   OS << Indent << "]\n";
890 
891   dumpEdges(BasicBlock);
892 }
893 
894 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
895   OS << Indent << "subgraph " << getUID(Region) << " {\n";
896   bumpIndent(1);
897   OS << Indent << "fontname=Courier\n"
898      << Indent << "label=\""
899      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
900      << DOT::EscapeString(Region->getName()) << "\"\n";
901   // Dump the blocks of the region.
902   assert(Region->getEntry() && "Region contains no inner blocks.");
903   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
904     dumpBlock(Block);
905   bumpIndent(-1);
906   OS << Indent << "}\n";
907   dumpEdges(Region);
908 }
909 
910 void VPlanIngredient::print(raw_ostream &O) const {
911   if (auto *Inst = dyn_cast<Instruction>(V)) {
912     if (!Inst->getType()->isVoidTy()) {
913       Inst->printAsOperand(O, false);
914       O << " = ";
915     }
916     O << Inst->getOpcodeName() << " ";
917     unsigned E = Inst->getNumOperands();
918     if (E > 0) {
919       Inst->getOperand(0)->printAsOperand(O, false);
920       for (unsigned I = 1; I < E; ++I)
921         Inst->getOperand(I)->printAsOperand(O << ", ", false);
922     }
923   } else // !Inst
924     V->printAsOperand(O, false);
925 }
926 
927 #endif
928 
929 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
930 
931 void VPValue::replaceAllUsesWith(VPValue *New) {
932   for (unsigned J = 0; J < getNumUsers();) {
933     VPUser *User = Users[J];
934     unsigned NumUsers = getNumUsers();
935     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
936       if (User->getOperand(I) == this)
937         User->setOperand(I, New);
938     // If a user got removed after updating the current user, the next user to
939     // update will be moved to the current position, so we only need to
940     // increment the index if the number of users did not change.
941     if (NumUsers == getNumUsers())
942       J++;
943   }
944 }
945 
946 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
947 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
948   if (const Value *UV = getUnderlyingValue()) {
949     OS << "ir<";
950     UV->printAsOperand(OS, false);
951     OS << ">";
952     return;
953   }
954 
955   unsigned Slot = Tracker.getSlot(this);
956   if (Slot == unsigned(-1))
957     OS << "<badref>";
958   else
959     OS << "vp<%" << Tracker.getSlot(this) << ">";
960 }
961 
962 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
963   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
964     Op->printAsOperand(O, SlotTracker);
965   });
966 }
967 #endif
968 
969 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
970                                           Old2NewTy &Old2New,
971                                           InterleavedAccessInfo &IAI) {
972   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
973   for (VPBlockBase *Base : RPOT) {
974     visitBlock(Base, Old2New, IAI);
975   }
976 }
977 
978 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
979                                          InterleavedAccessInfo &IAI) {
980   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
981     for (VPRecipeBase &VPI : *VPBB) {
982       if (isa<VPHeaderPHIRecipe>(&VPI))
983         continue;
984       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
985       auto *VPInst = cast<VPInstruction>(&VPI);
986 
987       auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue());
988       if (!Inst)
989         continue;
990       auto *IG = IAI.getInterleaveGroup(Inst);
991       if (!IG)
992         continue;
993 
994       auto NewIGIter = Old2New.find(IG);
995       if (NewIGIter == Old2New.end())
996         Old2New[IG] = new InterleaveGroup<VPInstruction>(
997             IG->getFactor(), IG->isReverse(), IG->getAlign());
998 
999       if (Inst == IG->getInsertPos())
1000         Old2New[IG]->setInsertPos(VPInst);
1001 
1002       InterleaveGroupMap[VPInst] = Old2New[IG];
1003       InterleaveGroupMap[VPInst]->insertMember(
1004           VPInst, IG->getIndex(Inst),
1005           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1006                                 : IG->getFactor()));
1007     }
1008   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1009     visitRegion(Region, Old2New, IAI);
1010   else
1011     llvm_unreachable("Unsupported kind of VPBlock.");
1012 }
1013 
1014 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1015                                                  InterleavedAccessInfo &IAI) {
1016   Old2NewTy Old2New;
1017   visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI);
1018 }
1019 
1020 void VPSlotTracker::assignSlot(const VPValue *V) {
1021   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
1022   Slots[V] = NextSlot++;
1023 }
1024 
1025 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1026 
1027   for (const auto &P : Plan.VPExternalDefs)
1028     assignSlot(P.second);
1029 
1030   assignSlot(&Plan.VectorTripCount);
1031   if (Plan.BackedgeTakenCount)
1032     assignSlot(Plan.BackedgeTakenCount);
1033 
1034   ReversePostOrderTraversal<
1035       VPBlockRecursiveTraversalWrapper<const VPBlockBase *>>
1036       RPOT(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>(
1037           Plan.getEntry()));
1038   for (const VPBasicBlock *VPBB :
1039        VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1040     for (const VPRecipeBase &Recipe : *VPBB)
1041       for (VPValue *Def : Recipe.definedValues())
1042         assignSlot(Def);
1043 }
1044 
1045 bool vputils::onlyFirstLaneUsed(VPValue *Def) {
1046   return all_of(Def->users(),
1047                 [Def](VPUser *U) { return U->onlyFirstLaneUsed(Def); });
1048 }
1049 
1050 VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr,
1051                                                 ScalarEvolution &SE) {
1052   if (auto *E = dyn_cast<SCEVConstant>(Expr))
1053     return Plan.getOrAddExternalDef(E->getValue());
1054   if (auto *E = dyn_cast<SCEVUnknown>(Expr))
1055     return Plan.getOrAddExternalDef(E->getValue());
1056 
1057   VPBasicBlock *Preheader = Plan.getEntry()->getEntryBasicBlock();
1058   VPValue *Step = new VPExpandSCEVRecipe(Expr, SE);
1059   Preheader->appendRecipe(cast<VPRecipeBase>(Step->getDef()));
1060   return Step;
1061 }
1062