xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision d8e7ca4a32bb533564ef033156d657b95fbc6b64)
1 //===- VPlan.cpp - Vectorizer Plan ----------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// This is the LLVM vectorization plan. It represents a candidate for
12 /// vectorization, allowing to plan and optimize how to vectorize a given loop
13 /// before generating LLVM-IR.
14 /// The vectorizer uses vectorization plans to estimate the costs of potential
15 /// candidates and if profitable to execute the desired plan, generating vector
16 /// LLVM-IR code.
17 ///
18 //===----------------------------------------------------------------------===//
19 
20 #include "VPlan.h"
21 #include "VPlanDominatorTree.h"
22 #include "llvm/ADT/DepthFirstIterator.h"
23 #include "llvm/ADT/PostOrderIterator.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/InstrTypes.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/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 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
60 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
61   const VPBlockBase *Block = this;
62   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
63     Block = Region->getEntry();
64   return cast<VPBasicBlock>(Block);
65 }
66 
67 VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
68   VPBlockBase *Block = this;
69   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
70     Block = Region->getEntry();
71   return cast<VPBasicBlock>(Block);
72 }
73 
74 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
75 const VPBasicBlock *VPBlockBase::getExitBasicBlock() const {
76   const VPBlockBase *Block = this;
77   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
78     Block = Region->getExit();
79   return cast<VPBasicBlock>(Block);
80 }
81 
82 VPBasicBlock *VPBlockBase::getExitBasicBlock() {
83   VPBlockBase *Block = this;
84   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
85     Block = Region->getExit();
86   return cast<VPBasicBlock>(Block);
87 }
88 
89 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
90   if (!Successors.empty() || !Parent)
91     return this;
92   assert(Parent->getExit() == this &&
93          "Block w/o successors not the exit of its parent.");
94   return Parent->getEnclosingBlockWithSuccessors();
95 }
96 
97 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
98   if (!Predecessors.empty() || !Parent)
99     return this;
100   assert(Parent->getEntry() == this &&
101          "Block w/o predecessors not the entry of its parent.");
102   return Parent->getEnclosingBlockWithPredecessors();
103 }
104 
105 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
106   SmallVector<VPBlockBase *, 8> Blocks;
107   for (VPBlockBase *Block : depth_first(Entry))
108     Blocks.push_back(Block);
109 
110   for (VPBlockBase *Block : Blocks)
111     delete Block;
112 }
113 
114 BasicBlock *
115 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
116   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
117   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
118   BasicBlock *PrevBB = CFG.PrevBB;
119   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
120                                          PrevBB->getParent(), CFG.LastBB);
121   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
122 
123   // Hook up the new basic block to its predecessors.
124   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
125     VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock();
126     auto &PredVPSuccessors = PredVPBB->getSuccessors();
127     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
128 
129     // In outer loop vectorization scenario, the predecessor BBlock may not yet
130     // be visited(backedge). Mark the VPBasicBlock for fixup at the end of
131     // vectorization. We do not encounter this case in inner loop vectorization
132     // as we start out by building a loop skeleton with the vector loop header
133     // and latch blocks. As a result, we never enter this function for the
134     // header block in the non VPlan-native path.
135     if (!PredBB) {
136       assert(EnableVPlanNativePath &&
137              "Unexpected null predecessor in non VPlan-native path");
138       CFG.VPBBsToFix.push_back(PredVPBB);
139       continue;
140     }
141 
142     assert(PredBB && "Predecessor basic-block not found building successor.");
143     auto *PredBBTerminator = PredBB->getTerminator();
144     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
145     if (isa<UnreachableInst>(PredBBTerminator)) {
146       assert(PredVPSuccessors.size() == 1 &&
147              "Predecessor ending w/o branch must have single successor.");
148       PredBBTerminator->eraseFromParent();
149       BranchInst::Create(NewBB, PredBB);
150     } else {
151       assert(PredVPSuccessors.size() == 2 &&
152              "Predecessor ending with branch must have two successors.");
153       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
154       assert(!PredBBTerminator->getSuccessor(idx) &&
155              "Trying to reset an existing successor block.");
156       PredBBTerminator->setSuccessor(idx, NewBB);
157     }
158   }
159   return NewBB;
160 }
161 
162 void VPBasicBlock::execute(VPTransformState *State) {
163   bool Replica = State->Instance &&
164                  !(State->Instance->Part == 0 && State->Instance->Lane == 0);
165   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
166   VPBlockBase *SingleHPred = nullptr;
167   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
168 
169   // 1. Create an IR basic block, or reuse the last one if possible.
170   // The last IR basic block is reused, as an optimization, in three cases:
171   // A. the first VPBB reuses the loop header BB - when PrevVPBB is null;
172   // B. when the current VPBB has a single (hierarchical) predecessor which
173   //    is PrevVPBB and the latter has a single (hierarchical) successor; and
174   // C. when the current VPBB is an entry of a region replica - where PrevVPBB
175   //    is the exit of this region from a previous instance, or the predecessor
176   //    of this region.
177   if (PrevVPBB && /* A */
178       !((SingleHPred = getSingleHierarchicalPredecessor()) &&
179         SingleHPred->getExitBasicBlock() == PrevVPBB &&
180         PrevVPBB->getSingleHierarchicalSuccessor()) && /* B */
181       !(Replica && getPredecessors().empty())) {       /* C */
182     NewBB = createEmptyBasicBlock(State->CFG);
183     State->Builder.SetInsertPoint(NewBB);
184     // Temporarily terminate with unreachable until CFG is rewired.
185     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
186     State->Builder.SetInsertPoint(Terminator);
187     // Register NewBB in its loop. In innermost loops its the same for all BB's.
188     Loop *L = State->LI->getLoopFor(State->CFG.LastBB);
189     L->addBasicBlockToLoop(NewBB, *State->LI);
190     State->CFG.PrevBB = NewBB;
191   }
192 
193   // 2. Fill the IR basic block with IR instructions.
194   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
195                     << " in BB:" << NewBB->getName() << '\n');
196 
197   State->CFG.VPBB2IRBB[this] = NewBB;
198   State->CFG.PrevVPBB = this;
199 
200   for (VPRecipeBase &Recipe : Recipes)
201     Recipe.execute(*State);
202 
203   VPValue *CBV;
204   if (EnableVPlanNativePath && (CBV = getCondBit())) {
205     Value *IRCBV = CBV->getUnderlyingValue();
206     assert(IRCBV && "Unexpected null underlying value for condition bit");
207 
208     // Condition bit value in a VPBasicBlock is used as the branch selector. In
209     // the VPlan-native path case, since all branches are uniform we generate a
210     // branch instruction using the condition value from vector lane 0 and dummy
211     // successors. The successors are fixed later when the successor blocks are
212     // visited.
213     Value *NewCond = State->Callback.getOrCreateVectorValues(IRCBV, 0);
214     NewCond = State->Builder.CreateExtractElement(NewCond,
215                                                   State->Builder.getInt32(0));
216 
217     // Replace the temporary unreachable terminator with the new conditional
218     // branch.
219     auto *CurrentTerminator = NewBB->getTerminator();
220     assert(isa<UnreachableInst>(CurrentTerminator) &&
221            "Expected to replace unreachable terminator with conditional "
222            "branch.");
223     auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond);
224     CondBr->setSuccessor(0, nullptr);
225     ReplaceInstWithInst(CurrentTerminator, CondBr);
226   }
227 
228   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
229 }
230 
231 void VPRegionBlock::execute(VPTransformState *State) {
232   ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry);
233 
234   if (!isReplicator()) {
235     // Visit the VPBlocks connected to "this", starting from it.
236     for (VPBlockBase *Block : RPOT) {
237       if (EnableVPlanNativePath) {
238         // The inner loop vectorization path does not represent loop preheader
239         // and exit blocks as part of the VPlan. In the VPlan-native path, skip
240         // vectorizing loop preheader block. In future, we may replace this
241         // check with the check for loop preheader.
242         if (Block->getNumPredecessors() == 0)
243           continue;
244 
245         // Skip vectorizing loop exit block. In future, we may replace this
246         // check with the check for loop exit.
247         if (Block->getNumSuccessors() == 0)
248           continue;
249       }
250 
251       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
252       Block->execute(State);
253     }
254     return;
255   }
256 
257   assert(!State->Instance && "Replicating a Region with non-null instance.");
258 
259   // Enter replicating mode.
260   State->Instance = {0, 0};
261 
262   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
263     State->Instance->Part = Part;
264     for (unsigned Lane = 0, VF = State->VF; Lane < VF; ++Lane) {
265       State->Instance->Lane = Lane;
266       // Visit the VPBlocks connected to \p this, starting from it.
267       for (VPBlockBase *Block : RPOT) {
268         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
269         Block->execute(State);
270       }
271     }
272   }
273 
274   // Exit replicating mode.
275   State->Instance.reset();
276 }
277 
278 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) {
279   Parent = InsertPos->getParent();
280   Parent->getRecipeList().insert(InsertPos->getIterator(), this);
281 }
282 
283 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() {
284   return getParent()->getRecipeList().erase(getIterator());
285 }
286 
287 void VPInstruction::generateInstruction(VPTransformState &State,
288                                         unsigned Part) {
289   IRBuilder<> &Builder = State.Builder;
290 
291   if (Instruction::isBinaryOp(getOpcode())) {
292     Value *A = State.get(getOperand(0), Part);
293     Value *B = State.get(getOperand(1), Part);
294     Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B);
295     State.set(this, V, Part);
296     return;
297   }
298 
299   switch (getOpcode()) {
300   case VPInstruction::Not: {
301     Value *A = State.get(getOperand(0), Part);
302     Value *V = Builder.CreateNot(A);
303     State.set(this, V, Part);
304     break;
305   }
306   default:
307     llvm_unreachable("Unsupported opcode for instruction");
308   }
309 }
310 
311 void VPInstruction::execute(VPTransformState &State) {
312   assert(!State.Instance && "VPInstruction executing an Instance");
313   for (unsigned Part = 0; Part < State.UF; ++Part)
314     generateInstruction(State, Part);
315 }
316 
317 void VPInstruction::print(raw_ostream &O, const Twine &Indent) const {
318   O << " +\n" << Indent << "\"EMIT ";
319   print(O);
320   O << "\\l\"";
321 }
322 
323 void VPInstruction::print(raw_ostream &O) const {
324   printAsOperand(O);
325   O << " = ";
326 
327   switch (getOpcode()) {
328   case VPInstruction::Not:
329     O << "not";
330     break;
331   default:
332     O << Instruction::getOpcodeName(getOpcode());
333   }
334 
335   for (const VPValue *Operand : operands()) {
336     O << " ";
337     Operand->printAsOperand(O);
338   }
339 }
340 
341 /// Generate the code inside the body of the vectorized loop. Assumes a single
342 /// LoopVectorBody basic-block was created for this. Introduce additional
343 /// basic-blocks as needed, and fill them all.
344 void VPlan::execute(VPTransformState *State) {
345   // 0. Set the reverse mapping from VPValues to Values for code generation.
346   for (auto &Entry : Value2VPValue)
347     State->VPValue2Value[Entry.second] = Entry.first;
348 
349   BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB;
350   BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor();
351   assert(VectorHeaderBB && "Loop preheader does not have a single successor.");
352   BasicBlock *VectorLatchBB = VectorHeaderBB;
353 
354   // 1. Make room to generate basic-blocks inside loop body if needed.
355   VectorLatchBB = VectorHeaderBB->splitBasicBlock(
356       VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch");
357   Loop *L = State->LI->getLoopFor(VectorHeaderBB);
358   L->addBasicBlockToLoop(VectorLatchBB, *State->LI);
359   // Remove the edge between Header and Latch to allow other connections.
360   // Temporarily terminate with unreachable until CFG is rewired.
361   // Note: this asserts the generated code's assumption that
362   // getFirstInsertionPt() can be dereferenced into an Instruction.
363   VectorHeaderBB->getTerminator()->eraseFromParent();
364   State->Builder.SetInsertPoint(VectorHeaderBB);
365   UnreachableInst *Terminator = State->Builder.CreateUnreachable();
366   State->Builder.SetInsertPoint(Terminator);
367 
368   // 2. Generate code in loop body.
369   State->CFG.PrevVPBB = nullptr;
370   State->CFG.PrevBB = VectorHeaderBB;
371   State->CFG.LastBB = VectorLatchBB;
372 
373   for (VPBlockBase *Block : depth_first(Entry))
374     Block->execute(State);
375 
376   // Setup branch terminator successors for VPBBs in VPBBsToFix based on
377   // VPBB's successors.
378   for (auto VPBB : State->CFG.VPBBsToFix) {
379     assert(EnableVPlanNativePath &&
380            "Unexpected VPBBsToFix in non VPlan-native path");
381     BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
382     assert(BB && "Unexpected null basic block for VPBB");
383 
384     unsigned Idx = 0;
385     auto *BBTerminator = BB->getTerminator();
386 
387     for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
388       VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
389       BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
390       ++Idx;
391     }
392   }
393 
394   // 3. Merge the temporary latch created with the last basic-block filled.
395   BasicBlock *LastBB = State->CFG.PrevBB;
396   // Connect LastBB to VectorLatchBB to facilitate their merge.
397   assert((EnableVPlanNativePath ||
398           isa<UnreachableInst>(LastBB->getTerminator())) &&
399          "Expected InnerLoop VPlan CFG to terminate with unreachable");
400   assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) &&
401          "Expected VPlan CFG to terminate with branch in NativePath");
402   LastBB->getTerminator()->eraseFromParent();
403   BranchInst::Create(VectorLatchBB, LastBB);
404 
405   // Merge LastBB with Latch.
406   bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI);
407   (void)Merged;
408   assert(Merged && "Could not merge last basic block with latch.");
409   VectorLatchBB = LastBB;
410 
411   // We do not attempt to preserve DT for outer loop vectorization currently.
412   if (!EnableVPlanNativePath)
413     updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB);
414 }
415 
416 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB,
417                                 BasicBlock *LoopLatchBB) {
418   BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor();
419   assert(LoopHeaderBB && "Loop preheader does not have a single successor.");
420   DT->addNewBlock(LoopHeaderBB, LoopPreHeaderBB);
421   // The vector body may be more than a single basic-block by this point.
422   // Update the dominator tree information inside the vector body by propagating
423   // it from header to latch, expecting only triangular control-flow, if any.
424   BasicBlock *PostDomSucc = nullptr;
425   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
426     // Get the list of successors of this block.
427     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
428     assert(Succs.size() <= 2 &&
429            "Basic block in vector loop has more than 2 successors.");
430     PostDomSucc = Succs[0];
431     if (Succs.size() == 1) {
432       assert(PostDomSucc->getSinglePredecessor() &&
433              "PostDom successor has more than one predecessor.");
434       DT->addNewBlock(PostDomSucc, BB);
435       continue;
436     }
437     BasicBlock *InterimSucc = Succs[1];
438     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
439       PostDomSucc = Succs[1];
440       InterimSucc = Succs[0];
441     }
442     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
443            "One successor of a basic block does not lead to the other.");
444     assert(InterimSucc->getSinglePredecessor() &&
445            "Interim successor has more than one predecessor.");
446     assert(pred_size(PostDomSucc) == 2 &&
447            "PostDom successor has more than two predecessors.");
448     DT->addNewBlock(InterimSucc, BB);
449     DT->addNewBlock(PostDomSucc, BB);
450   }
451 }
452 
453 const Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
454   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
455          Twine(getOrCreateBID(Block));
456 }
457 
458 const Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
459   const std::string &Name = Block->getName();
460   if (!Name.empty())
461     return Name;
462   return "VPB" + Twine(getOrCreateBID(Block));
463 }
464 
465 void VPlanPrinter::dump() {
466   Depth = 1;
467   bumpIndent(0);
468   OS << "digraph VPlan {\n";
469   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
470   if (!Plan.getName().empty())
471     OS << "\\n" << DOT::EscapeString(Plan.getName());
472   if (!Plan.Value2VPValue.empty()) {
473     OS << ", where:";
474     for (auto Entry : Plan.Value2VPValue) {
475       OS << "\\n" << *Entry.second;
476       OS << DOT::EscapeString(" := ");
477       Entry.first->printAsOperand(OS, false);
478     }
479   }
480   OS << "\"]\n";
481   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
482   OS << "edge [fontname=Courier, fontsize=30]\n";
483   OS << "compound=true\n";
484 
485   for (VPBlockBase *Block : depth_first(Plan.getEntry()))
486     dumpBlock(Block);
487 
488   OS << "}\n";
489 }
490 
491 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
492   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
493     dumpBasicBlock(BasicBlock);
494   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
495     dumpRegion(Region);
496   else
497     llvm_unreachable("Unsupported kind of VPBlock.");
498 }
499 
500 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
501                             bool Hidden, const Twine &Label) {
502   // Due to "dot" we print an edge between two regions as an edge between the
503   // exit basic block and the entry basic of the respective regions.
504   const VPBlockBase *Tail = From->getExitBasicBlock();
505   const VPBlockBase *Head = To->getEntryBasicBlock();
506   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
507   OS << " [ label=\"" << Label << '\"';
508   if (Tail != From)
509     OS << " ltail=" << getUID(From);
510   if (Head != To)
511     OS << " lhead=" << getUID(To);
512   if (Hidden)
513     OS << "; splines=none";
514   OS << "]\n";
515 }
516 
517 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
518   auto &Successors = Block->getSuccessors();
519   if (Successors.size() == 1)
520     drawEdge(Block, Successors.front(), false, "");
521   else if (Successors.size() == 2) {
522     drawEdge(Block, Successors.front(), false, "T");
523     drawEdge(Block, Successors.back(), false, "F");
524   } else {
525     unsigned SuccessorNumber = 0;
526     for (auto *Successor : Successors)
527       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
528   }
529 }
530 
531 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
532   OS << Indent << getUID(BasicBlock) << " [label =\n";
533   bumpIndent(1);
534   OS << Indent << "\"" << DOT::EscapeString(BasicBlock->getName()) << ":\\n\"";
535   bumpIndent(1);
536   for (const VPRecipeBase &Recipe : *BasicBlock)
537     Recipe.print(OS, Indent);
538 
539   // Dump the condition bit.
540   const VPValue *CBV = BasicBlock->getCondBit();
541   if (CBV) {
542     OS << " +\n" << Indent << " \"CondBit: ";
543     if (const VPInstruction *CBI = dyn_cast<VPInstruction>(CBV)) {
544       CBI->printAsOperand(OS);
545       OS << " (" << DOT::EscapeString(CBI->getParent()->getName()) << ")\\l\"";
546     } else {
547       CBV->printAsOperand(OS);
548       OS << "\"";
549     }
550   }
551 
552   bumpIndent(-2);
553   OS << "\n" << Indent << "]\n";
554   dumpEdges(BasicBlock);
555 }
556 
557 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
558   OS << Indent << "subgraph " << getUID(Region) << " {\n";
559   bumpIndent(1);
560   OS << Indent << "fontname=Courier\n"
561      << Indent << "label=\""
562      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
563      << DOT::EscapeString(Region->getName()) << "\"\n";
564   // Dump the blocks of the region.
565   assert(Region->getEntry() && "Region contains no inner blocks.");
566   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
567     dumpBlock(Block);
568   bumpIndent(-1);
569   OS << Indent << "}\n";
570   dumpEdges(Region);
571 }
572 
573 void VPlanPrinter::printAsIngredient(raw_ostream &O, Value *V) {
574   std::string IngredientString;
575   raw_string_ostream RSO(IngredientString);
576   if (auto *Inst = dyn_cast<Instruction>(V)) {
577     if (!Inst->getType()->isVoidTy()) {
578       Inst->printAsOperand(RSO, false);
579       RSO << " = ";
580     }
581     RSO << Inst->getOpcodeName() << " ";
582     unsigned E = Inst->getNumOperands();
583     if (E > 0) {
584       Inst->getOperand(0)->printAsOperand(RSO, false);
585       for (unsigned I = 1; I < E; ++I)
586         Inst->getOperand(I)->printAsOperand(RSO << ", ", false);
587     }
588   } else // !Inst
589     V->printAsOperand(RSO, false);
590   RSO.flush();
591   O << DOT::EscapeString(IngredientString);
592 }
593 
594 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent) const {
595   O << " +\n" << Indent << "\"WIDEN\\l\"";
596   for (auto &Instr : make_range(Begin, End))
597     O << " +\n" << Indent << "\"  " << VPlanIngredient(&Instr) << "\\l\"";
598 }
599 
600 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O,
601                                           const Twine &Indent) const {
602   O << " +\n" << Indent << "\"WIDEN-INDUCTION";
603   if (Trunc) {
604     O << "\\l\"";
605     O << " +\n" << Indent << "\"  " << VPlanIngredient(IV) << "\\l\"";
606     O << " +\n" << Indent << "\"  " << VPlanIngredient(Trunc) << "\\l\"";
607   } else
608     O << " " << VPlanIngredient(IV) << "\\l\"";
609 }
610 
611 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent) const {
612   O << " +\n" << Indent << "\"WIDEN-PHI " << VPlanIngredient(Phi) << "\\l\"";
613 }
614 
615 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent) const {
616   O << " +\n" << Indent << "\"BLEND ";
617   Phi->printAsOperand(O, false);
618   O << " =";
619   if (!User) {
620     // Not a User of any mask: not really blending, this is a
621     // single-predecessor phi.
622     O << " ";
623     Phi->getIncomingValue(0)->printAsOperand(O, false);
624   } else {
625     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) {
626       O << " ";
627       Phi->getIncomingValue(I)->printAsOperand(O, false);
628       O << "/";
629       User->getOperand(I)->printAsOperand(O);
630     }
631   }
632   O << "\\l\"";
633 }
634 
635 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent) const {
636   O << " +\n"
637     << Indent << "\"" << (IsUniform ? "CLONE " : "REPLICATE ")
638     << VPlanIngredient(Ingredient);
639   if (AlsoPack)
640     O << " (S->V)";
641   O << "\\l\"";
642 }
643 
644 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent) const {
645   O << " +\n"
646     << Indent << "\"PHI-PREDICATED-INSTRUCTION " << VPlanIngredient(PredInst)
647     << "\\l\"";
648 }
649 
650 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O,
651                                            const Twine &Indent) const {
652   O << " +\n" << Indent << "\"WIDEN " << VPlanIngredient(&Instr);
653   if (User) {
654     O << ", ";
655     User->getOperand(0)->printAsOperand(O);
656   }
657   O << "\\l\"";
658 }
659 
660 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
661