xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision 4c1a1d3cf97e1ede466e2ad318f2811283ca0fb1)
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 /// \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   assert(!Parent && "Recipe already in some VPBasicBlock");
280   assert(InsertPos->getParent() &&
281          "Insertion position not in any VPBasicBlock");
282   Parent = InsertPos->getParent();
283   Parent->getRecipeList().insert(InsertPos->getIterator(), this);
284 }
285 
286 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) {
287   assert(!Parent && "Recipe already in some VPBasicBlock");
288   assert(InsertPos->getParent() &&
289          "Insertion position not in any VPBasicBlock");
290   Parent = InsertPos->getParent();
291   Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this);
292 }
293 
294 void VPRecipeBase::removeFromParent() {
295   assert(getParent() && "Recipe not in any VPBasicBlock");
296   getParent()->getRecipeList().remove(getIterator());
297   Parent = nullptr;
298 }
299 
300 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() {
301   assert(getParent() && "Recipe not in any VPBasicBlock");
302   return getParent()->getRecipeList().erase(getIterator());
303 }
304 
305 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) {
306   removeFromParent();
307   insertAfter(InsertPos);
308 }
309 
310 void VPInstruction::generateInstruction(VPTransformState &State,
311                                         unsigned Part) {
312   IRBuilder<> &Builder = State.Builder;
313 
314   if (Instruction::isBinaryOp(getOpcode())) {
315     Value *A = State.get(getOperand(0), Part);
316     Value *B = State.get(getOperand(1), Part);
317     Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B);
318     State.set(this, V, Part);
319     return;
320   }
321 
322   switch (getOpcode()) {
323   case VPInstruction::Not: {
324     Value *A = State.get(getOperand(0), Part);
325     Value *V = Builder.CreateNot(A);
326     State.set(this, V, Part);
327     break;
328   }
329   case VPInstruction::ICmpULE: {
330     Value *IV = State.get(getOperand(0), Part);
331     Value *TC = State.get(getOperand(1), Part);
332     Value *V = Builder.CreateICmpULE(IV, TC);
333     State.set(this, V, Part);
334     break;
335   }
336   case Instruction::Select: {
337     Value *Cond = State.get(getOperand(0), Part);
338     Value *Op1 = State.get(getOperand(1), Part);
339     Value *Op2 = State.get(getOperand(2), Part);
340     Value *V = Builder.CreateSelect(Cond, Op1, Op2);
341     State.set(this, V, Part);
342     break;
343   }
344   default:
345     llvm_unreachable("Unsupported opcode for instruction");
346   }
347 }
348 
349 void VPInstruction::execute(VPTransformState &State) {
350   assert(!State.Instance && "VPInstruction executing an Instance");
351   for (unsigned Part = 0; Part < State.UF; ++Part)
352     generateInstruction(State, Part);
353 }
354 
355 void VPInstruction::print(raw_ostream &O, const Twine &Indent) const {
356   O << " +\n" << Indent << "\"EMIT ";
357   print(O);
358   O << "\\l\"";
359 }
360 
361 void VPInstruction::print(raw_ostream &O) const {
362   printAsOperand(O);
363   O << " = ";
364 
365   switch (getOpcode()) {
366   case VPInstruction::Not:
367     O << "not";
368     break;
369   case VPInstruction::ICmpULE:
370     O << "icmp ule";
371     break;
372   case VPInstruction::SLPLoad:
373     O << "combined load";
374     break;
375   case VPInstruction::SLPStore:
376     O << "combined store";
377     break;
378   default:
379     O << Instruction::getOpcodeName(getOpcode());
380   }
381 
382   for (const VPValue *Operand : operands()) {
383     O << " ";
384     Operand->printAsOperand(O);
385   }
386 }
387 
388 /// Generate the code inside the body of the vectorized loop. Assumes a single
389 /// LoopVectorBody basic-block was created for this. Introduce additional
390 /// basic-blocks as needed, and fill them all.
391 void VPlan::execute(VPTransformState *State) {
392   // -1. Check if the backedge taken count is needed, and if so build it.
393   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
394     Value *TC = State->TripCount;
395     IRBuilder<> Builder(State->CFG.PrevBB->getTerminator());
396     auto *TCMO = Builder.CreateSub(TC, ConstantInt::get(TC->getType(), 1),
397                                    "trip.count.minus.1");
398     Value2VPValue[TCMO] = BackedgeTakenCount;
399   }
400 
401   // 0. Set the reverse mapping from VPValues to Values for code generation.
402   for (auto &Entry : Value2VPValue)
403     State->VPValue2Value[Entry.second] = Entry.first;
404 
405   BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB;
406   BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor();
407   assert(VectorHeaderBB && "Loop preheader does not have a single successor.");
408 
409   // 1. Make room to generate basic-blocks inside loop body if needed.
410   BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock(
411       VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch");
412   Loop *L = State->LI->getLoopFor(VectorHeaderBB);
413   L->addBasicBlockToLoop(VectorLatchBB, *State->LI);
414   // Remove the edge between Header and Latch to allow other connections.
415   // Temporarily terminate with unreachable until CFG is rewired.
416   // Note: this asserts the generated code's assumption that
417   // getFirstInsertionPt() can be dereferenced into an Instruction.
418   VectorHeaderBB->getTerminator()->eraseFromParent();
419   State->Builder.SetInsertPoint(VectorHeaderBB);
420   UnreachableInst *Terminator = State->Builder.CreateUnreachable();
421   State->Builder.SetInsertPoint(Terminator);
422 
423   // 2. Generate code in loop body.
424   State->CFG.PrevVPBB = nullptr;
425   State->CFG.PrevBB = VectorHeaderBB;
426   State->CFG.LastBB = VectorLatchBB;
427 
428   for (VPBlockBase *Block : depth_first(Entry))
429     Block->execute(State);
430 
431   // Setup branch terminator successors for VPBBs in VPBBsToFix based on
432   // VPBB's successors.
433   for (auto VPBB : State->CFG.VPBBsToFix) {
434     assert(EnableVPlanNativePath &&
435            "Unexpected VPBBsToFix in non VPlan-native path");
436     BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
437     assert(BB && "Unexpected null basic block for VPBB");
438 
439     unsigned Idx = 0;
440     auto *BBTerminator = BB->getTerminator();
441 
442     for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
443       VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
444       BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
445       ++Idx;
446     }
447   }
448 
449   // 3. Merge the temporary latch created with the last basic-block filled.
450   BasicBlock *LastBB = State->CFG.PrevBB;
451   // Connect LastBB to VectorLatchBB to facilitate their merge.
452   assert((EnableVPlanNativePath ||
453           isa<UnreachableInst>(LastBB->getTerminator())) &&
454          "Expected InnerLoop VPlan CFG to terminate with unreachable");
455   assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) &&
456          "Expected VPlan CFG to terminate with branch in NativePath");
457   LastBB->getTerminator()->eraseFromParent();
458   BranchInst::Create(VectorLatchBB, LastBB);
459 
460   // Merge LastBB with Latch.
461   bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI);
462   (void)Merged;
463   assert(Merged && "Could not merge last basic block with latch.");
464   VectorLatchBB = LastBB;
465 
466   // We do not attempt to preserve DT for outer loop vectorization currently.
467   if (!EnableVPlanNativePath)
468     updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB);
469 }
470 
471 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB,
472                                 BasicBlock *LoopLatchBB) {
473   BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor();
474   assert(LoopHeaderBB && "Loop preheader does not have a single successor.");
475   DT->addNewBlock(LoopHeaderBB, LoopPreHeaderBB);
476   // The vector body may be more than a single basic-block by this point.
477   // Update the dominator tree information inside the vector body by propagating
478   // it from header to latch, expecting only triangular control-flow, if any.
479   BasicBlock *PostDomSucc = nullptr;
480   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
481     // Get the list of successors of this block.
482     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
483     assert(Succs.size() <= 2 &&
484            "Basic block in vector loop has more than 2 successors.");
485     PostDomSucc = Succs[0];
486     if (Succs.size() == 1) {
487       assert(PostDomSucc->getSinglePredecessor() &&
488              "PostDom successor has more than one predecessor.");
489       DT->addNewBlock(PostDomSucc, BB);
490       continue;
491     }
492     BasicBlock *InterimSucc = Succs[1];
493     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
494       PostDomSucc = Succs[1];
495       InterimSucc = Succs[0];
496     }
497     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
498            "One successor of a basic block does not lead to the other.");
499     assert(InterimSucc->getSinglePredecessor() &&
500            "Interim successor has more than one predecessor.");
501     assert(PostDomSucc->hasNPredecessors(2) &&
502            "PostDom successor has more than two predecessors.");
503     DT->addNewBlock(InterimSucc, BB);
504     DT->addNewBlock(PostDomSucc, BB);
505   }
506 }
507 
508 const Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
509   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
510          Twine(getOrCreateBID(Block));
511 }
512 
513 const Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
514   const std::string &Name = Block->getName();
515   if (!Name.empty())
516     return Name;
517   return "VPB" + Twine(getOrCreateBID(Block));
518 }
519 
520 void VPlanPrinter::dump() {
521   Depth = 1;
522   bumpIndent(0);
523   OS << "digraph VPlan {\n";
524   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
525   if (!Plan.getName().empty())
526     OS << "\\n" << DOT::EscapeString(Plan.getName());
527   if (!Plan.Value2VPValue.empty() || Plan.BackedgeTakenCount) {
528     OS << ", where:";
529     if (Plan.BackedgeTakenCount)
530       OS << "\\n"
531          << *Plan.getOrCreateBackedgeTakenCount() << " := BackedgeTakenCount";
532     for (auto Entry : Plan.Value2VPValue) {
533       OS << "\\n" << *Entry.second;
534       OS << DOT::EscapeString(" := ");
535       Entry.first->printAsOperand(OS, false);
536     }
537   }
538   OS << "\"]\n";
539   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
540   OS << "edge [fontname=Courier, fontsize=30]\n";
541   OS << "compound=true\n";
542 
543   for (VPBlockBase *Block : depth_first(Plan.getEntry()))
544     dumpBlock(Block);
545 
546   OS << "}\n";
547 }
548 
549 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
550   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
551     dumpBasicBlock(BasicBlock);
552   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
553     dumpRegion(Region);
554   else
555     llvm_unreachable("Unsupported kind of VPBlock.");
556 }
557 
558 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
559                             bool Hidden, const Twine &Label) {
560   // Due to "dot" we print an edge between two regions as an edge between the
561   // exit basic block and the entry basic of the respective regions.
562   const VPBlockBase *Tail = From->getExitBasicBlock();
563   const VPBlockBase *Head = To->getEntryBasicBlock();
564   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
565   OS << " [ label=\"" << Label << '\"';
566   if (Tail != From)
567     OS << " ltail=" << getUID(From);
568   if (Head != To)
569     OS << " lhead=" << getUID(To);
570   if (Hidden)
571     OS << "; splines=none";
572   OS << "]\n";
573 }
574 
575 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
576   auto &Successors = Block->getSuccessors();
577   if (Successors.size() == 1)
578     drawEdge(Block, Successors.front(), false, "");
579   else if (Successors.size() == 2) {
580     drawEdge(Block, Successors.front(), false, "T");
581     drawEdge(Block, Successors.back(), false, "F");
582   } else {
583     unsigned SuccessorNumber = 0;
584     for (auto *Successor : Successors)
585       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
586   }
587 }
588 
589 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
590   OS << Indent << getUID(BasicBlock) << " [label =\n";
591   bumpIndent(1);
592   OS << Indent << "\"" << DOT::EscapeString(BasicBlock->getName()) << ":\\n\"";
593   bumpIndent(1);
594 
595   // Dump the block predicate.
596   const VPValue *Pred = BasicBlock->getPredicate();
597   if (Pred) {
598     OS << " +\n" << Indent << " \"BlockPredicate: ";
599     if (const VPInstruction *PredI = dyn_cast<VPInstruction>(Pred)) {
600       PredI->printAsOperand(OS);
601       OS << " (" << DOT::EscapeString(PredI->getParent()->getName())
602          << ")\\l\"";
603     } else
604       Pred->printAsOperand(OS);
605   }
606 
607   for (const VPRecipeBase &Recipe : *BasicBlock)
608     Recipe.print(OS, Indent);
609 
610   // Dump the condition bit.
611   const VPValue *CBV = BasicBlock->getCondBit();
612   if (CBV) {
613     OS << " +\n" << Indent << " \"CondBit: ";
614     if (const VPInstruction *CBI = dyn_cast<VPInstruction>(CBV)) {
615       CBI->printAsOperand(OS);
616       OS << " (" << DOT::EscapeString(CBI->getParent()->getName()) << ")\\l\"";
617     } else {
618       CBV->printAsOperand(OS);
619       OS << "\"";
620     }
621   }
622 
623   bumpIndent(-2);
624   OS << "\n" << Indent << "]\n";
625   dumpEdges(BasicBlock);
626 }
627 
628 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
629   OS << Indent << "subgraph " << getUID(Region) << " {\n";
630   bumpIndent(1);
631   OS << Indent << "fontname=Courier\n"
632      << Indent << "label=\""
633      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
634      << DOT::EscapeString(Region->getName()) << "\"\n";
635   // Dump the blocks of the region.
636   assert(Region->getEntry() && "Region contains no inner blocks.");
637   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
638     dumpBlock(Block);
639   bumpIndent(-1);
640   OS << Indent << "}\n";
641   dumpEdges(Region);
642 }
643 
644 void VPlanPrinter::printAsIngredient(raw_ostream &O, Value *V) {
645   std::string IngredientString;
646   raw_string_ostream RSO(IngredientString);
647   if (auto *Inst = dyn_cast<Instruction>(V)) {
648     if (!Inst->getType()->isVoidTy()) {
649       Inst->printAsOperand(RSO, false);
650       RSO << " = ";
651     }
652     RSO << Inst->getOpcodeName() << " ";
653     unsigned E = Inst->getNumOperands();
654     if (E > 0) {
655       Inst->getOperand(0)->printAsOperand(RSO, false);
656       for (unsigned I = 1; I < E; ++I)
657         Inst->getOperand(I)->printAsOperand(RSO << ", ", false);
658     }
659   } else // !Inst
660     V->printAsOperand(RSO, false);
661   RSO.flush();
662   O << DOT::EscapeString(IngredientString);
663 }
664 
665 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent) const {
666   O << " +\n" << Indent << "\"WIDEN\\l\"";
667   for (auto &Instr : make_range(Begin, End))
668     O << " +\n" << Indent << "\"  " << VPlanIngredient(&Instr) << "\\l\"";
669 }
670 
671 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O,
672                                           const Twine &Indent) const {
673   O << " +\n" << Indent << "\"WIDEN-INDUCTION";
674   if (Trunc) {
675     O << "\\l\"";
676     O << " +\n" << Indent << "\"  " << VPlanIngredient(IV) << "\\l\"";
677     O << " +\n" << Indent << "\"  " << VPlanIngredient(Trunc) << "\\l\"";
678   } else
679     O << " " << VPlanIngredient(IV) << "\\l\"";
680 }
681 
682 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent) const {
683   O << " +\n" << Indent << "\"WIDEN-PHI " << VPlanIngredient(Phi) << "\\l\"";
684 }
685 
686 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent) const {
687   O << " +\n" << Indent << "\"BLEND ";
688   Phi->printAsOperand(O, false);
689   O << " =";
690   if (!User) {
691     // Not a User of any mask: not really blending, this is a
692     // single-predecessor phi.
693     O << " ";
694     Phi->getIncomingValue(0)->printAsOperand(O, false);
695   } else {
696     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) {
697       O << " ";
698       Phi->getIncomingValue(I)->printAsOperand(O, false);
699       O << "/";
700       User->getOperand(I)->printAsOperand(O);
701     }
702   }
703   O << "\\l\"";
704 }
705 
706 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent) const {
707   O << " +\n"
708     << Indent << "\"" << (IsUniform ? "CLONE " : "REPLICATE ")
709     << VPlanIngredient(Ingredient);
710   if (AlsoPack)
711     O << " (S->V)";
712   O << "\\l\"";
713 }
714 
715 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent) const {
716   O << " +\n"
717     << Indent << "\"PHI-PREDICATED-INSTRUCTION " << VPlanIngredient(PredInst)
718     << "\\l\"";
719 }
720 
721 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O,
722                                            const Twine &Indent) const {
723   O << " +\n" << Indent << "\"WIDEN " << VPlanIngredient(&Instr);
724   if (User) {
725     O << ", ";
726     User->getOperand(0)->printAsOperand(O);
727   }
728   O << "\\l\"";
729 }
730 
731 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
732 
733 void VPValue::replaceAllUsesWith(VPValue *New) {
734   for (VPUser *User : users())
735     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
736       if (User->getOperand(I) == this)
737         User->setOperand(I, New);
738 }
739 
740 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
741                                           Old2NewTy &Old2New,
742                                           InterleavedAccessInfo &IAI) {
743   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
744   for (VPBlockBase *Base : RPOT) {
745     visitBlock(Base, Old2New, IAI);
746   }
747 }
748 
749 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
750                                          InterleavedAccessInfo &IAI) {
751   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
752     for (VPRecipeBase &VPI : *VPBB) {
753       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
754       auto *VPInst = cast<VPInstruction>(&VPI);
755       auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue());
756       auto *IG = IAI.getInterleaveGroup(Inst);
757       if (!IG)
758         continue;
759 
760       auto NewIGIter = Old2New.find(IG);
761       if (NewIGIter == Old2New.end())
762         Old2New[IG] = new InterleaveGroup<VPInstruction>(
763             IG->getFactor(), IG->isReverse(), Align(IG->getAlignment()));
764 
765       if (Inst == IG->getInsertPos())
766         Old2New[IG]->setInsertPos(VPInst);
767 
768       InterleaveGroupMap[VPInst] = Old2New[IG];
769       InterleaveGroupMap[VPInst]->insertMember(
770           VPInst, IG->getIndex(Inst),
771           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
772                                 : IG->getFactor()));
773     }
774   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
775     visitRegion(Region, Old2New, IAI);
776   else
777     llvm_unreachable("Unsupported kind of VPBlock.");
778 }
779 
780 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
781                                                  InterleavedAccessInfo &IAI) {
782   Old2NewTy Old2New;
783   visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI);
784 }
785