xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision f5fe7abe8a8c8150b7b305bae963b429f15ea217)
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/SmallVector.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/CFG.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.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 <cassert>
42 #include <iterator>
43 #include <string>
44 #include <vector>
45 
46 using namespace llvm;
47 extern cl::opt<bool> EnableVPlanNativePath;
48 
49 #define DEBUG_TYPE "vplan"
50 
51 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
52   const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
53   VPSlotTracker SlotTracker(
54       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
55   V.print(OS, SlotTracker);
56   return OS;
57 }
58 
59 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
60   if (const VPInstruction *Instr = dyn_cast<VPInstruction>(this))
61     Instr->print(OS, SlotTracker);
62   else
63     printAsOperand(OS, SlotTracker);
64 }
65 
66 void VPValue::dump() const {
67   const VPInstruction *Instr = dyn_cast<VPInstruction>(this);
68   VPSlotTracker SlotTracker(
69       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
70   print(dbgs(), SlotTracker);
71   dbgs() << "\n";
72 }
73 
74 void VPRecipeBase::dump() const {
75   VPSlotTracker SlotTracker(nullptr);
76   print(dbgs(), "", SlotTracker);
77   dbgs() << "\n";
78 }
79 
80 // Get the top-most entry block of \p Start. This is the entry block of the
81 // containing VPlan. This function is templated to support both const and non-const blocks
82 template <typename T> static T *getPlanEntry(T *Start) {
83   T *Next = Start;
84   T *Current = Start;
85   while ((Next = Next->getParent()))
86     Current = Next;
87 
88   SmallSetVector<T *, 8> WorkList;
89   WorkList.insert(Current);
90 
91   for (unsigned i = 0; i < WorkList.size(); i++) {
92     T *Current = WorkList[i];
93     if (Current->getNumPredecessors() == 0)
94       return Current;
95     auto &Predecessors = Current->getPredecessors();
96     WorkList.insert(Predecessors.begin(), Predecessors.end());
97   }
98 
99   llvm_unreachable("VPlan without any entry node without predecessors");
100 }
101 
102 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
103 
104 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
105 
106 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
107 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
108   const VPBlockBase *Block = this;
109   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
110     Block = Region->getEntry();
111   return cast<VPBasicBlock>(Block);
112 }
113 
114 VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
115   VPBlockBase *Block = this;
116   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
117     Block = Region->getEntry();
118   return cast<VPBasicBlock>(Block);
119 }
120 
121 void VPBlockBase::setPlan(VPlan *ParentPlan) {
122   assert(ParentPlan->getEntry() == this &&
123          "Can only set plan on its entry block.");
124   Plan = ParentPlan;
125 }
126 
127 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
128 const VPBasicBlock *VPBlockBase::getExitBasicBlock() const {
129   const VPBlockBase *Block = this;
130   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
131     Block = Region->getExit();
132   return cast<VPBasicBlock>(Block);
133 }
134 
135 VPBasicBlock *VPBlockBase::getExitBasicBlock() {
136   VPBlockBase *Block = this;
137   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
138     Block = Region->getExit();
139   return cast<VPBasicBlock>(Block);
140 }
141 
142 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
143   if (!Successors.empty() || !Parent)
144     return this;
145   assert(Parent->getExit() == this &&
146          "Block w/o successors not the exit of its parent.");
147   return Parent->getEnclosingBlockWithSuccessors();
148 }
149 
150 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
151   if (!Predecessors.empty() || !Parent)
152     return this;
153   assert(Parent->getEntry() == this &&
154          "Block w/o predecessors not the entry of its parent.");
155   return Parent->getEnclosingBlockWithPredecessors();
156 }
157 
158 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
159   SmallVector<VPBlockBase *, 8> Blocks;
160   for (VPBlockBase *Block : depth_first(Entry))
161     Blocks.push_back(Block);
162 
163   for (VPBlockBase *Block : Blocks)
164     delete Block;
165 }
166 
167 BasicBlock *
168 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
169   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
170   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
171   BasicBlock *PrevBB = CFG.PrevBB;
172   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
173                                          PrevBB->getParent(), CFG.LastBB);
174   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
175 
176   // Hook up the new basic block to its predecessors.
177   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
178     VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock();
179     auto &PredVPSuccessors = PredVPBB->getSuccessors();
180     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
181 
182     // In outer loop vectorization scenario, the predecessor BBlock may not yet
183     // be visited(backedge). Mark the VPBasicBlock for fixup at the end of
184     // vectorization. We do not encounter this case in inner loop vectorization
185     // as we start out by building a loop skeleton with the vector loop header
186     // and latch blocks. As a result, we never enter this function for the
187     // header block in the non VPlan-native path.
188     if (!PredBB) {
189       assert(EnableVPlanNativePath &&
190              "Unexpected null predecessor in non VPlan-native path");
191       CFG.VPBBsToFix.push_back(PredVPBB);
192       continue;
193     }
194 
195     assert(PredBB && "Predecessor basic-block not found building successor.");
196     auto *PredBBTerminator = PredBB->getTerminator();
197     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
198     if (isa<UnreachableInst>(PredBBTerminator)) {
199       assert(PredVPSuccessors.size() == 1 &&
200              "Predecessor ending w/o branch must have single successor.");
201       PredBBTerminator->eraseFromParent();
202       BranchInst::Create(NewBB, PredBB);
203     } else {
204       assert(PredVPSuccessors.size() == 2 &&
205              "Predecessor ending with branch must have two successors.");
206       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
207       assert(!PredBBTerminator->getSuccessor(idx) &&
208              "Trying to reset an existing successor block.");
209       PredBBTerminator->setSuccessor(idx, NewBB);
210     }
211   }
212   return NewBB;
213 }
214 
215 void VPBasicBlock::execute(VPTransformState *State) {
216   bool Replica = State->Instance &&
217                  !(State->Instance->Part == 0 && State->Instance->Lane == 0);
218   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
219   VPBlockBase *SingleHPred = nullptr;
220   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
221 
222   // 1. Create an IR basic block, or reuse the last one if possible.
223   // The last IR basic block is reused, as an optimization, in three cases:
224   // A. the first VPBB reuses the loop header BB - when PrevVPBB is null;
225   // B. when the current VPBB has a single (hierarchical) predecessor which
226   //    is PrevVPBB and the latter has a single (hierarchical) successor; and
227   // C. when the current VPBB is an entry of a region replica - where PrevVPBB
228   //    is the exit of this region from a previous instance, or the predecessor
229   //    of this region.
230   if (PrevVPBB && /* A */
231       !((SingleHPred = getSingleHierarchicalPredecessor()) &&
232         SingleHPred->getExitBasicBlock() == PrevVPBB &&
233         PrevVPBB->getSingleHierarchicalSuccessor()) && /* B */
234       !(Replica && getPredecessors().empty())) {       /* C */
235     NewBB = createEmptyBasicBlock(State->CFG);
236     State->Builder.SetInsertPoint(NewBB);
237     // Temporarily terminate with unreachable until CFG is rewired.
238     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
239     State->Builder.SetInsertPoint(Terminator);
240     // Register NewBB in its loop. In innermost loops its the same for all BB's.
241     Loop *L = State->LI->getLoopFor(State->CFG.LastBB);
242     L->addBasicBlockToLoop(NewBB, *State->LI);
243     State->CFG.PrevBB = NewBB;
244   }
245 
246   // 2. Fill the IR basic block with IR instructions.
247   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
248                     << " in BB:" << NewBB->getName() << '\n');
249 
250   State->CFG.VPBB2IRBB[this] = NewBB;
251   State->CFG.PrevVPBB = this;
252 
253   for (VPRecipeBase &Recipe : Recipes)
254     Recipe.execute(*State);
255 
256   VPValue *CBV;
257   if (EnableVPlanNativePath && (CBV = getCondBit())) {
258     Value *IRCBV = CBV->getUnderlyingValue();
259     assert(IRCBV && "Unexpected null underlying value for condition bit");
260 
261     // Condition bit value in a VPBasicBlock is used as the branch selector. In
262     // the VPlan-native path case, since all branches are uniform we generate a
263     // branch instruction using the condition value from vector lane 0 and dummy
264     // successors. The successors are fixed later when the successor blocks are
265     // visited.
266     Value *NewCond = State->Callback.getOrCreateVectorValues(IRCBV, 0);
267     NewCond = State->Builder.CreateExtractElement(NewCond,
268                                                   State->Builder.getInt32(0));
269 
270     // Replace the temporary unreachable terminator with the new conditional
271     // branch.
272     auto *CurrentTerminator = NewBB->getTerminator();
273     assert(isa<UnreachableInst>(CurrentTerminator) &&
274            "Expected to replace unreachable terminator with conditional "
275            "branch.");
276     auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond);
277     CondBr->setSuccessor(0, nullptr);
278     ReplaceInstWithInst(CurrentTerminator, CondBr);
279   }
280 
281   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
282 }
283 
284 void VPRegionBlock::execute(VPTransformState *State) {
285   ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry);
286 
287   if (!isReplicator()) {
288     // Visit the VPBlocks connected to "this", starting from it.
289     for (VPBlockBase *Block : RPOT) {
290       if (EnableVPlanNativePath) {
291         // The inner loop vectorization path does not represent loop preheader
292         // and exit blocks as part of the VPlan. In the VPlan-native path, skip
293         // vectorizing loop preheader block. In future, we may replace this
294         // check with the check for loop preheader.
295         if (Block->getNumPredecessors() == 0)
296           continue;
297 
298         // Skip vectorizing loop exit block. In future, we may replace this
299         // check with the check for loop exit.
300         if (Block->getNumSuccessors() == 0)
301           continue;
302       }
303 
304       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
305       Block->execute(State);
306     }
307     return;
308   }
309 
310   assert(!State->Instance && "Replicating a Region with non-null instance.");
311 
312   // Enter replicating mode.
313   State->Instance = {0, 0};
314 
315   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
316     State->Instance->Part = Part;
317     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
318     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
319          ++Lane) {
320       State->Instance->Lane = Lane;
321       // Visit the VPBlocks connected to \p this, starting from it.
322       for (VPBlockBase *Block : RPOT) {
323         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
324         Block->execute(State);
325       }
326     }
327   }
328 
329   // Exit replicating mode.
330   State->Instance.reset();
331 }
332 
333 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) {
334   assert(!Parent && "Recipe already in some VPBasicBlock");
335   assert(InsertPos->getParent() &&
336          "Insertion position not in any VPBasicBlock");
337   Parent = InsertPos->getParent();
338   Parent->getRecipeList().insert(InsertPos->getIterator(), this);
339 }
340 
341 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) {
342   assert(!Parent && "Recipe already in some VPBasicBlock");
343   assert(InsertPos->getParent() &&
344          "Insertion position not in any VPBasicBlock");
345   Parent = InsertPos->getParent();
346   Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this);
347 }
348 
349 void VPRecipeBase::removeFromParent() {
350   assert(getParent() && "Recipe not in any VPBasicBlock");
351   getParent()->getRecipeList().remove(getIterator());
352   Parent = nullptr;
353 }
354 
355 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() {
356   assert(getParent() && "Recipe not in any VPBasicBlock");
357   return getParent()->getRecipeList().erase(getIterator());
358 }
359 
360 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) {
361   removeFromParent();
362   insertAfter(InsertPos);
363 }
364 
365 void VPInstruction::generateInstruction(VPTransformState &State,
366                                         unsigned Part) {
367   IRBuilder<> &Builder = State.Builder;
368 
369   if (Instruction::isBinaryOp(getOpcode())) {
370     Value *A = State.get(getOperand(0), Part);
371     Value *B = State.get(getOperand(1), Part);
372     Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B);
373     State.set(this, V, Part);
374     return;
375   }
376 
377   switch (getOpcode()) {
378   case VPInstruction::Not: {
379     Value *A = State.get(getOperand(0), Part);
380     Value *V = Builder.CreateNot(A);
381     State.set(this, V, Part);
382     break;
383   }
384   case VPInstruction::ICmpULE: {
385     Value *IV = State.get(getOperand(0), Part);
386     Value *TC = State.get(getOperand(1), Part);
387     Value *V = Builder.CreateICmpULE(IV, TC);
388     State.set(this, V, Part);
389     break;
390   }
391   case Instruction::Select: {
392     Value *Cond = State.get(getOperand(0), Part);
393     Value *Op1 = State.get(getOperand(1), Part);
394     Value *Op2 = State.get(getOperand(2), Part);
395     Value *V = Builder.CreateSelect(Cond, Op1, Op2);
396     State.set(this, V, Part);
397     break;
398   }
399   case VPInstruction::ActiveLaneMask: {
400     // Get first lane of vector induction variable.
401     Value *VIVElem0 = State.get(getOperand(0), {Part, 0});
402     // Get the original loop tripcount.
403     Value *ScalarTC = State.TripCount;
404 
405     auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
406     auto *PredTy = FixedVectorType::get(Int1Ty, State.VF.getKnownMinValue());
407     Instruction *Call = Builder.CreateIntrinsic(
408         Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()},
409         {VIVElem0, ScalarTC}, nullptr, "active.lane.mask");
410     State.set(this, Call, Part);
411     break;
412   }
413   default:
414     llvm_unreachable("Unsupported opcode for instruction");
415   }
416 }
417 
418 void VPInstruction::execute(VPTransformState &State) {
419   assert(!State.Instance && "VPInstruction executing an Instance");
420   for (unsigned Part = 0; Part < State.UF; ++Part)
421     generateInstruction(State, Part);
422 }
423 
424 void VPInstruction::print(raw_ostream &O, const Twine &Indent,
425                           VPSlotTracker &SlotTracker) const {
426   O << "\"EMIT ";
427   print(O, SlotTracker);
428 }
429 
430 void VPInstruction::print(raw_ostream &O) const {
431   VPSlotTracker SlotTracker(getParent()->getPlan());
432   print(O, SlotTracker);
433 }
434 
435 void VPInstruction::print(raw_ostream &O, VPSlotTracker &SlotTracker) const {
436   if (hasResult()) {
437     printAsOperand(O, SlotTracker);
438     O << " = ";
439   }
440 
441   switch (getOpcode()) {
442   case VPInstruction::Not:
443     O << "not";
444     break;
445   case VPInstruction::ICmpULE:
446     O << "icmp ule";
447     break;
448   case VPInstruction::SLPLoad:
449     O << "combined load";
450     break;
451   case VPInstruction::SLPStore:
452     O << "combined store";
453     break;
454   case VPInstruction::ActiveLaneMask:
455     O << "active lane mask";
456     break;
457 
458   default:
459     O << Instruction::getOpcodeName(getOpcode());
460   }
461 
462   for (const VPValue *Operand : operands()) {
463     O << " ";
464     Operand->printAsOperand(O, SlotTracker);
465   }
466 }
467 
468 /// Generate the code inside the body of the vectorized loop. Assumes a single
469 /// LoopVectorBody basic-block was created for this. Introduce additional
470 /// basic-blocks as needed, and fill them all.
471 void VPlan::execute(VPTransformState *State) {
472   // -1. Check if the backedge taken count is needed, and if so build it.
473   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
474     Value *TC = State->TripCount;
475     IRBuilder<> Builder(State->CFG.PrevBB->getTerminator());
476     auto *TCMO = Builder.CreateSub(TC, ConstantInt::get(TC->getType(), 1),
477                                    "trip.count.minus.1");
478     auto VF = State->VF;
479     Value *VTCMO =
480         VF == 1 ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
481     for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part)
482       State->set(BackedgeTakenCount, VTCMO, Part);
483   }
484 
485   // 0. Set the reverse mapping from VPValues to Values for code generation.
486   for (auto &Entry : Value2VPValue)
487     State->VPValue2Value[Entry.second] = Entry.first;
488 
489   BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB;
490   BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor();
491   assert(VectorHeaderBB && "Loop preheader does not have a single successor.");
492 
493   // 1. Make room to generate basic-blocks inside loop body if needed.
494   BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock(
495       VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch");
496   Loop *L = State->LI->getLoopFor(VectorHeaderBB);
497   L->addBasicBlockToLoop(VectorLatchBB, *State->LI);
498   // Remove the edge between Header and Latch to allow other connections.
499   // Temporarily terminate with unreachable until CFG is rewired.
500   // Note: this asserts the generated code's assumption that
501   // getFirstInsertionPt() can be dereferenced into an Instruction.
502   VectorHeaderBB->getTerminator()->eraseFromParent();
503   State->Builder.SetInsertPoint(VectorHeaderBB);
504   UnreachableInst *Terminator = State->Builder.CreateUnreachable();
505   State->Builder.SetInsertPoint(Terminator);
506 
507   // 2. Generate code in loop body.
508   State->CFG.PrevVPBB = nullptr;
509   State->CFG.PrevBB = VectorHeaderBB;
510   State->CFG.LastBB = VectorLatchBB;
511 
512   for (VPBlockBase *Block : depth_first(Entry))
513     Block->execute(State);
514 
515   // Setup branch terminator successors for VPBBs in VPBBsToFix based on
516   // VPBB's successors.
517   for (auto VPBB : State->CFG.VPBBsToFix) {
518     assert(EnableVPlanNativePath &&
519            "Unexpected VPBBsToFix in non VPlan-native path");
520     BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
521     assert(BB && "Unexpected null basic block for VPBB");
522 
523     unsigned Idx = 0;
524     auto *BBTerminator = BB->getTerminator();
525 
526     for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
527       VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
528       BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
529       ++Idx;
530     }
531   }
532 
533   // 3. Merge the temporary latch created with the last basic-block filled.
534   BasicBlock *LastBB = State->CFG.PrevBB;
535   // Connect LastBB to VectorLatchBB to facilitate their merge.
536   assert((EnableVPlanNativePath ||
537           isa<UnreachableInst>(LastBB->getTerminator())) &&
538          "Expected InnerLoop VPlan CFG to terminate with unreachable");
539   assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) &&
540          "Expected VPlan CFG to terminate with branch in NativePath");
541   LastBB->getTerminator()->eraseFromParent();
542   BranchInst::Create(VectorLatchBB, LastBB);
543 
544   // Merge LastBB with Latch.
545   bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI);
546   (void)Merged;
547   assert(Merged && "Could not merge last basic block with latch.");
548   VectorLatchBB = LastBB;
549 
550   // We do not attempt to preserve DT for outer loop vectorization currently.
551   if (!EnableVPlanNativePath)
552     updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB,
553                         L->getExitBlock());
554 }
555 
556 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
557 LLVM_DUMP_METHOD
558 void VPlan::dump() const { dbgs() << *this << '\n'; }
559 #endif
560 
561 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB,
562                                 BasicBlock *LoopLatchBB,
563                                 BasicBlock *LoopExitBB) {
564   BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor();
565   assert(LoopHeaderBB && "Loop preheader does not have a single successor.");
566   // The vector body may be more than a single basic-block by this point.
567   // Update the dominator tree information inside the vector body by propagating
568   // it from header to latch, expecting only triangular control-flow, if any.
569   BasicBlock *PostDomSucc = nullptr;
570   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
571     // Get the list of successors of this block.
572     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
573     assert(Succs.size() <= 2 &&
574            "Basic block in vector loop has more than 2 successors.");
575     PostDomSucc = Succs[0];
576     if (Succs.size() == 1) {
577       assert(PostDomSucc->getSinglePredecessor() &&
578              "PostDom successor has more than one predecessor.");
579       DT->addNewBlock(PostDomSucc, BB);
580       continue;
581     }
582     BasicBlock *InterimSucc = Succs[1];
583     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
584       PostDomSucc = Succs[1];
585       InterimSucc = Succs[0];
586     }
587     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
588            "One successor of a basic block does not lead to the other.");
589     assert(InterimSucc->getSinglePredecessor() &&
590            "Interim successor has more than one predecessor.");
591     assert(PostDomSucc->hasNPredecessors(2) &&
592            "PostDom successor has more than two predecessors.");
593     DT->addNewBlock(InterimSucc, BB);
594     DT->addNewBlock(PostDomSucc, BB);
595   }
596   // Latch block is a new dominator for the loop exit.
597   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
598   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
599 }
600 
601 const Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
602   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
603          Twine(getOrCreateBID(Block));
604 }
605 
606 const Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
607   const std::string &Name = Block->getName();
608   if (!Name.empty())
609     return Name;
610   return "VPB" + Twine(getOrCreateBID(Block));
611 }
612 
613 void VPlanPrinter::dump() {
614   Depth = 1;
615   bumpIndent(0);
616   OS << "digraph VPlan {\n";
617   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
618   if (!Plan.getName().empty())
619     OS << "\\n" << DOT::EscapeString(Plan.getName());
620   if (Plan.BackedgeTakenCount) {
621     OS << ", where:\\n";
622     Plan.BackedgeTakenCount->print(OS, SlotTracker);
623     OS << " := BackedgeTakenCount";
624   }
625   OS << "\"]\n";
626   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
627   OS << "edge [fontname=Courier, fontsize=30]\n";
628   OS << "compound=true\n";
629 
630   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
631     dumpBlock(Block);
632 
633   OS << "}\n";
634 }
635 
636 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
637   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
638     dumpBasicBlock(BasicBlock);
639   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
640     dumpRegion(Region);
641   else
642     llvm_unreachable("Unsupported kind of VPBlock.");
643 }
644 
645 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
646                             bool Hidden, const Twine &Label) {
647   // Due to "dot" we print an edge between two regions as an edge between the
648   // exit basic block and the entry basic of the respective regions.
649   const VPBlockBase *Tail = From->getExitBasicBlock();
650   const VPBlockBase *Head = To->getEntryBasicBlock();
651   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
652   OS << " [ label=\"" << Label << '\"';
653   if (Tail != From)
654     OS << " ltail=" << getUID(From);
655   if (Head != To)
656     OS << " lhead=" << getUID(To);
657   if (Hidden)
658     OS << "; splines=none";
659   OS << "]\n";
660 }
661 
662 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
663   auto &Successors = Block->getSuccessors();
664   if (Successors.size() == 1)
665     drawEdge(Block, Successors.front(), false, "");
666   else if (Successors.size() == 2) {
667     drawEdge(Block, Successors.front(), false, "T");
668     drawEdge(Block, Successors.back(), false, "F");
669   } else {
670     unsigned SuccessorNumber = 0;
671     for (auto *Successor : Successors)
672       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
673   }
674 }
675 
676 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
677   OS << Indent << getUID(BasicBlock) << " [label =\n";
678   bumpIndent(1);
679   OS << Indent << "\"" << DOT::EscapeString(BasicBlock->getName()) << ":\\n\"";
680   bumpIndent(1);
681 
682   // Dump the block predicate.
683   const VPValue *Pred = BasicBlock->getPredicate();
684   if (Pred) {
685     OS << " +\n" << Indent << " \"BlockPredicate: ";
686     if (const VPInstruction *PredI = dyn_cast<VPInstruction>(Pred)) {
687       PredI->printAsOperand(OS, SlotTracker);
688       OS << " (" << DOT::EscapeString(PredI->getParent()->getName())
689          << ")\\l\"";
690     } else
691       Pred->printAsOperand(OS, SlotTracker);
692   }
693 
694   for (const VPRecipeBase &Recipe : *BasicBlock) {
695     OS << " +\n" << Indent;
696     Recipe.print(OS, Indent, SlotTracker);
697     OS << "\\l\"";
698   }
699 
700   // Dump the condition bit.
701   const VPValue *CBV = BasicBlock->getCondBit();
702   if (CBV) {
703     OS << " +\n" << Indent << " \"CondBit: ";
704     if (const VPInstruction *CBI = dyn_cast<VPInstruction>(CBV)) {
705       CBI->printAsOperand(OS, SlotTracker);
706       OS << " (" << DOT::EscapeString(CBI->getParent()->getName()) << ")\\l\"";
707     } else {
708       CBV->printAsOperand(OS, SlotTracker);
709       OS << "\"";
710     }
711   }
712 
713   bumpIndent(-2);
714   OS << "\n" << Indent << "]\n";
715   dumpEdges(BasicBlock);
716 }
717 
718 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
719   OS << Indent << "subgraph " << getUID(Region) << " {\n";
720   bumpIndent(1);
721   OS << Indent << "fontname=Courier\n"
722      << Indent << "label=\""
723      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
724      << DOT::EscapeString(Region->getName()) << "\"\n";
725   // Dump the blocks of the region.
726   assert(Region->getEntry() && "Region contains no inner blocks.");
727   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
728     dumpBlock(Block);
729   bumpIndent(-1);
730   OS << Indent << "}\n";
731   dumpEdges(Region);
732 }
733 
734 void VPlanPrinter::printAsIngredient(raw_ostream &O, Value *V) {
735   std::string IngredientString;
736   raw_string_ostream RSO(IngredientString);
737   if (auto *Inst = dyn_cast<Instruction>(V)) {
738     if (!Inst->getType()->isVoidTy()) {
739       Inst->printAsOperand(RSO, false);
740       RSO << " = ";
741     }
742     RSO << Inst->getOpcodeName() << " ";
743     unsigned E = Inst->getNumOperands();
744     if (E > 0) {
745       Inst->getOperand(0)->printAsOperand(RSO, false);
746       for (unsigned I = 1; I < E; ++I)
747         Inst->getOperand(I)->printAsOperand(RSO << ", ", false);
748     }
749   } else // !Inst
750     V->printAsOperand(RSO, false);
751   RSO.flush();
752   O << DOT::EscapeString(IngredientString);
753 }
754 
755 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent,
756                               VPSlotTracker &SlotTracker) const {
757   O << "\"WIDEN-CALL " << VPlanIngredient(&Ingredient);
758 }
759 
760 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent,
761                                 VPSlotTracker &SlotTracker) const {
762   O << "\"WIDEN-SELECT" << VPlanIngredient(&Ingredient)
763     << (InvariantCond ? " (condition is loop invariant)" : "");
764 }
765 
766 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent,
767                           VPSlotTracker &SlotTracker) const {
768   O << "\"WIDEN\\l\"";
769   O << "\"  " << VPlanIngredient(&Ingredient);
770 }
771 
772 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent,
773                                           VPSlotTracker &SlotTracker) const {
774   O << "\"WIDEN-INDUCTION";
775   if (Trunc) {
776     O << "\\l\"";
777     O << " +\n" << Indent << "\"  " << VPlanIngredient(IV) << "\\l\"";
778     O << " +\n" << Indent << "\"  " << VPlanIngredient(Trunc);
779   } else
780     O << " " << VPlanIngredient(IV);
781 }
782 
783 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent,
784                              VPSlotTracker &SlotTracker) const {
785   O << "\"WIDEN-GEP ";
786   O << (IsPtrLoopInvariant ? "Inv" : "Var");
787   size_t IndicesNumber = IsIndexLoopInvariant.size();
788   for (size_t I = 0; I < IndicesNumber; ++I)
789     O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]";
790   O << "\\l\"";
791   O << " +\n" << Indent << "\"  " << VPlanIngredient(GEP);
792 }
793 
794 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent,
795                              VPSlotTracker &SlotTracker) const {
796   O << "\"WIDEN-PHI " << VPlanIngredient(Phi);
797 }
798 
799 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent,
800                           VPSlotTracker &SlotTracker) const {
801   O << "\"BLEND ";
802   Phi->printAsOperand(O, false);
803   O << " =";
804   if (getNumIncomingValues() == 1) {
805     // Not a User of any mask: not really blending, this is a
806     // single-predecessor phi.
807     O << " ";
808     getIncomingValue(0)->printAsOperand(O, SlotTracker);
809   } else {
810     for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
811       O << " ";
812       getIncomingValue(I)->printAsOperand(O, SlotTracker);
813       O << "/";
814       getMask(I)->printAsOperand(O, SlotTracker);
815     }
816   }
817 }
818 
819 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent,
820                               VPSlotTracker &SlotTracker) const {
821   O << "\"REDUCE of" << *I << " as ";
822   ChainOp->printAsOperand(O, SlotTracker);
823   O << " + reduce(";
824   VecOp->printAsOperand(O, SlotTracker);
825   O << ")";
826 }
827 
828 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent,
829                               VPSlotTracker &SlotTracker) const {
830   O << "\"" << (IsUniform ? "CLONE " : "REPLICATE ")
831     << VPlanIngredient(Ingredient);
832   if (AlsoPack)
833     O << " (S->V)";
834 }
835 
836 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent,
837                                 VPSlotTracker &SlotTracker) const {
838   O << "\"PHI-PREDICATED-INSTRUCTION " << VPlanIngredient(PredInst);
839 }
840 
841 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent,
842                                            VPSlotTracker &SlotTracker) const {
843   O << "\"WIDEN " << VPlanIngredient(&Instr);
844   O << ", ";
845   getAddr()->printAsOperand(O, SlotTracker);
846   VPValue *Mask = getMask();
847   if (Mask) {
848     O << ", ";
849     Mask->printAsOperand(O, SlotTracker);
850   }
851 }
852 
853 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) {
854   Value *CanonicalIV = State.CanonicalIV;
855   Type *STy = CanonicalIV->getType();
856   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
857   ElementCount VF = State.VF;
858   assert(!VF.isScalable() && "the code following assumes non scalables ECs");
859   Value *VStart = VF.isScalar()
860                       ? CanonicalIV
861                       : Builder.CreateVectorSplat(VF.getKnownMinValue(),
862                                                   CanonicalIV, "broadcast");
863   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) {
864     SmallVector<Constant *, 8> Indices;
865     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
866       Indices.push_back(
867           ConstantInt::get(STy, Part * VF.getKnownMinValue() + Lane));
868     // If VF == 1, there is only one iteration in the loop above, thus the
869     // element pushed back into Indices is ConstantInt::get(STy, Part)
870     Constant *VStep = VF == 1 ? Indices.back() : ConstantVector::get(Indices);
871     // Add the consecutive indices to the vector value.
872     Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
873     State.set(getVPValue(), CanonicalVectorIV, Part);
874   }
875 }
876 
877 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent,
878                                      VPSlotTracker &SlotTracker) const {
879   O << "\"EMIT ";
880   getVPValue()->printAsOperand(O, SlotTracker);
881   O << " = WIDEN-CANONICAL-INDUCTION";
882 }
883 
884 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
885 
886 void VPValue::replaceAllUsesWith(VPValue *New) {
887   for (unsigned J = 0; J < getNumUsers();) {
888     VPUser *User = Users[J];
889     unsigned NumUsers = getNumUsers();
890     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
891       if (User->getOperand(I) == this)
892         User->setOperand(I, New);
893     // If a user got removed after updating the current user, the next user to
894     // update will be moved to the current position, so we only need to
895     // increment the index if the number of users did not change.
896     if (NumUsers == getNumUsers())
897       J++;
898   }
899 }
900 
901 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
902   if (const Value *UV = getUnderlyingValue()) {
903     OS << "ir<";
904     UV->printAsOperand(OS, false);
905     OS << ">";
906     return;
907   }
908 
909   unsigned Slot = Tracker.getSlot(this);
910   if (Slot == unsigned(-1))
911     OS << "<badref>";
912   else
913     OS << "vp<%" << Tracker.getSlot(this) << ">";
914 }
915 
916 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
917                                           Old2NewTy &Old2New,
918                                           InterleavedAccessInfo &IAI) {
919   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
920   for (VPBlockBase *Base : RPOT) {
921     visitBlock(Base, Old2New, IAI);
922   }
923 }
924 
925 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
926                                          InterleavedAccessInfo &IAI) {
927   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
928     for (VPRecipeBase &VPI : *VPBB) {
929       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
930       auto *VPInst = cast<VPInstruction>(&VPI);
931       auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue());
932       auto *IG = IAI.getInterleaveGroup(Inst);
933       if (!IG)
934         continue;
935 
936       auto NewIGIter = Old2New.find(IG);
937       if (NewIGIter == Old2New.end())
938         Old2New[IG] = new InterleaveGroup<VPInstruction>(
939             IG->getFactor(), IG->isReverse(), IG->getAlign());
940 
941       if (Inst == IG->getInsertPos())
942         Old2New[IG]->setInsertPos(VPInst);
943 
944       InterleaveGroupMap[VPInst] = Old2New[IG];
945       InterleaveGroupMap[VPInst]->insertMember(
946           VPInst, IG->getIndex(Inst),
947           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
948                                 : IG->getFactor()));
949     }
950   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
951     visitRegion(Region, Old2New, IAI);
952   else
953     llvm_unreachable("Unsupported kind of VPBlock.");
954 }
955 
956 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
957                                                  InterleavedAccessInfo &IAI) {
958   Old2NewTy Old2New;
959   visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI);
960 }
961 
962 void VPSlotTracker::assignSlot(const VPValue *V) {
963   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
964   const Value *UV = V->getUnderlyingValue();
965   if (UV)
966     return;
967   const auto *VPI = dyn_cast<VPInstruction>(V);
968   if (VPI && !VPI->hasResult())
969     return;
970 
971   Slots[V] = NextSlot++;
972 }
973 
974 void VPSlotTracker::assignSlots(const VPBlockBase *VPBB) {
975   if (auto *Region = dyn_cast<VPRegionBlock>(VPBB))
976     assignSlots(Region);
977   else
978     assignSlots(cast<VPBasicBlock>(VPBB));
979 }
980 
981 void VPSlotTracker::assignSlots(const VPRegionBlock *Region) {
982   ReversePostOrderTraversal<const VPBlockBase *> RPOT(Region->getEntry());
983   for (const VPBlockBase *Block : RPOT)
984     assignSlots(Block);
985 }
986 
987 void VPSlotTracker::assignSlots(const VPBasicBlock *VPBB) {
988   for (const VPRecipeBase &Recipe : *VPBB) {
989     if (const auto *VPI = dyn_cast<VPInstruction>(&Recipe))
990       assignSlot(VPI);
991     else if (const auto *VPIV = dyn_cast<VPWidenCanonicalIVRecipe>(&Recipe))
992       assignSlot(VPIV->getVPValue());
993   }
994 }
995 
996 void VPSlotTracker::assignSlots(const VPlan &Plan) {
997 
998   for (const VPValue *V : Plan.VPExternalDefs)
999     assignSlot(V);
1000 
1001   for (auto &E : Plan.Value2VPValue)
1002     if (!isa<VPInstruction>(E.second))
1003       assignSlot(E.second);
1004 
1005   for (const VPValue *V : Plan.VPCBVs)
1006     assignSlot(V);
1007 
1008   if (Plan.BackedgeTakenCount)
1009     assignSlot(Plan.BackedgeTakenCount);
1010 
1011   ReversePostOrderTraversal<const VPBlockBase *> RPOT(Plan.getEntry());
1012   for (const VPBlockBase *Block : RPOT)
1013     assignSlots(Block);
1014 }
1015