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