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