xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision 6132212808e8dccedc9e5d85fea4390c2f38059a)
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   case VPInstruction::ActiveLaneMask: {
384     // Get first lane of vector induction variable.
385     Value *VIVElem0 = State.get(getOperand(0), {Part, 0});
386     // Get first lane of backedge-taken-count.
387     Value *ScalarBTC = State.get(getOperand(1), {Part, 0});
388 
389     auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
390     auto *PredTy = FixedVectorType::get(Int1Ty, State.VF);
391     Instruction *Call = Builder.CreateIntrinsic(
392         Intrinsic::get_active_lane_mask, {PredTy, ScalarBTC->getType()},
393         {VIVElem0, ScalarBTC}, nullptr, "active.lane.mask");
394     State.set(this, Call, Part);
395     break;
396   }
397   default:
398     llvm_unreachable("Unsupported opcode for instruction");
399   }
400 }
401 
402 void VPInstruction::execute(VPTransformState &State) {
403   assert(!State.Instance && "VPInstruction executing an Instance");
404   for (unsigned Part = 0; Part < State.UF; ++Part)
405     generateInstruction(State, Part);
406 }
407 
408 void VPInstruction::print(raw_ostream &O, const Twine &Indent,
409                           VPSlotTracker &SlotTracker) const {
410   O << "\"EMIT ";
411   print(O, SlotTracker);
412 }
413 
414 void VPInstruction::print(raw_ostream &O) const {
415   VPSlotTracker SlotTracker(getParent()->getPlan());
416   print(O, SlotTracker);
417 }
418 
419 void VPInstruction::print(raw_ostream &O, VPSlotTracker &SlotTracker) const {
420   if (hasResult()) {
421     printAsOperand(O, SlotTracker);
422     O << " = ";
423   }
424 
425   switch (getOpcode()) {
426   case VPInstruction::Not:
427     O << "not";
428     break;
429   case VPInstruction::ICmpULE:
430     O << "icmp ule";
431     break;
432   case VPInstruction::SLPLoad:
433     O << "combined load";
434     break;
435   case VPInstruction::SLPStore:
436     O << "combined store";
437     break;
438   case VPInstruction::ActiveLaneMask:
439     O << "active lane mask";
440     break;
441 
442   default:
443     O << Instruction::getOpcodeName(getOpcode());
444   }
445 
446   for (const VPValue *Operand : operands()) {
447     O << " ";
448     Operand->printAsOperand(O, SlotTracker);
449   }
450 }
451 
452 /// Generate the code inside the body of the vectorized loop. Assumes a single
453 /// LoopVectorBody basic-block was created for this. Introduce additional
454 /// basic-blocks as needed, and fill them all.
455 void VPlan::execute(VPTransformState *State) {
456   // -1. Check if the backedge taken count is needed, and if so build it.
457   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
458     Value *TC = State->TripCount;
459     IRBuilder<> Builder(State->CFG.PrevBB->getTerminator());
460     auto *TCMO = Builder.CreateSub(TC, ConstantInt::get(TC->getType(), 1),
461                                    "trip.count.minus.1");
462     auto VF = State->VF;
463     Value *VTCMO =
464         VF == 1 ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
465     for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part)
466       State->set(BackedgeTakenCount, VTCMO, Part);
467   }
468 
469   // 0. Set the reverse mapping from VPValues to Values for code generation.
470   for (auto &Entry : Value2VPValue)
471     State->VPValue2Value[Entry.second] = Entry.first;
472 
473   BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB;
474   BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor();
475   assert(VectorHeaderBB && "Loop preheader does not have a single successor.");
476 
477   // 1. Make room to generate basic-blocks inside loop body if needed.
478   BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock(
479       VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch");
480   Loop *L = State->LI->getLoopFor(VectorHeaderBB);
481   L->addBasicBlockToLoop(VectorLatchBB, *State->LI);
482   // Remove the edge between Header and Latch to allow other connections.
483   // Temporarily terminate with unreachable until CFG is rewired.
484   // Note: this asserts the generated code's assumption that
485   // getFirstInsertionPt() can be dereferenced into an Instruction.
486   VectorHeaderBB->getTerminator()->eraseFromParent();
487   State->Builder.SetInsertPoint(VectorHeaderBB);
488   UnreachableInst *Terminator = State->Builder.CreateUnreachable();
489   State->Builder.SetInsertPoint(Terminator);
490 
491   // 2. Generate code in loop body.
492   State->CFG.PrevVPBB = nullptr;
493   State->CFG.PrevBB = VectorHeaderBB;
494   State->CFG.LastBB = VectorLatchBB;
495 
496   for (VPBlockBase *Block : depth_first(Entry))
497     Block->execute(State);
498 
499   // Setup branch terminator successors for VPBBs in VPBBsToFix based on
500   // VPBB's successors.
501   for (auto VPBB : State->CFG.VPBBsToFix) {
502     assert(EnableVPlanNativePath &&
503            "Unexpected VPBBsToFix in non VPlan-native path");
504     BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
505     assert(BB && "Unexpected null basic block for VPBB");
506 
507     unsigned Idx = 0;
508     auto *BBTerminator = BB->getTerminator();
509 
510     for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
511       VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
512       BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
513       ++Idx;
514     }
515   }
516 
517   // 3. Merge the temporary latch created with the last basic-block filled.
518   BasicBlock *LastBB = State->CFG.PrevBB;
519   // Connect LastBB to VectorLatchBB to facilitate their merge.
520   assert((EnableVPlanNativePath ||
521           isa<UnreachableInst>(LastBB->getTerminator())) &&
522          "Expected InnerLoop VPlan CFG to terminate with unreachable");
523   assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) &&
524          "Expected VPlan CFG to terminate with branch in NativePath");
525   LastBB->getTerminator()->eraseFromParent();
526   BranchInst::Create(VectorLatchBB, LastBB);
527 
528   // Merge LastBB with Latch.
529   bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI);
530   (void)Merged;
531   assert(Merged && "Could not merge last basic block with latch.");
532   VectorLatchBB = LastBB;
533 
534   // We do not attempt to preserve DT for outer loop vectorization currently.
535   if (!EnableVPlanNativePath)
536     updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB,
537                         L->getExitBlock());
538 }
539 
540 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
541 LLVM_DUMP_METHOD
542 void VPlan::dump() const { dbgs() << *this << '\n'; }
543 #endif
544 
545 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB,
546                                 BasicBlock *LoopLatchBB,
547                                 BasicBlock *LoopExitBB) {
548   BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor();
549   assert(LoopHeaderBB && "Loop preheader does not have a single successor.");
550   // The vector body may be more than a single basic-block by this point.
551   // Update the dominator tree information inside the vector body by propagating
552   // it from header to latch, expecting only triangular control-flow, if any.
553   BasicBlock *PostDomSucc = nullptr;
554   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
555     // Get the list of successors of this block.
556     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
557     assert(Succs.size() <= 2 &&
558            "Basic block in vector loop has more than 2 successors.");
559     PostDomSucc = Succs[0];
560     if (Succs.size() == 1) {
561       assert(PostDomSucc->getSinglePredecessor() &&
562              "PostDom successor has more than one predecessor.");
563       DT->addNewBlock(PostDomSucc, BB);
564       continue;
565     }
566     BasicBlock *InterimSucc = Succs[1];
567     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
568       PostDomSucc = Succs[1];
569       InterimSucc = Succs[0];
570     }
571     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
572            "One successor of a basic block does not lead to the other.");
573     assert(InterimSucc->getSinglePredecessor() &&
574            "Interim successor has more than one predecessor.");
575     assert(PostDomSucc->hasNPredecessors(2) &&
576            "PostDom successor has more than two predecessors.");
577     DT->addNewBlock(InterimSucc, BB);
578     DT->addNewBlock(PostDomSucc, BB);
579   }
580   // Latch block is a new dominator for the loop exit.
581   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
582   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
583 }
584 
585 const Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
586   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
587          Twine(getOrCreateBID(Block));
588 }
589 
590 const Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
591   const std::string &Name = Block->getName();
592   if (!Name.empty())
593     return Name;
594   return "VPB" + Twine(getOrCreateBID(Block));
595 }
596 
597 void VPlanPrinter::dump() {
598   Depth = 1;
599   bumpIndent(0);
600   OS << "digraph VPlan {\n";
601   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
602   if (!Plan.getName().empty())
603     OS << "\\n" << DOT::EscapeString(Plan.getName());
604   if (Plan.BackedgeTakenCount) {
605     OS << ", where:\\n";
606     Plan.BackedgeTakenCount->print(OS, SlotTracker);
607     OS << " := BackedgeTakenCount";
608   }
609   OS << "\"]\n";
610   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
611   OS << "edge [fontname=Courier, fontsize=30]\n";
612   OS << "compound=true\n";
613 
614   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
615     dumpBlock(Block);
616 
617   OS << "}\n";
618 }
619 
620 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
621   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
622     dumpBasicBlock(BasicBlock);
623   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
624     dumpRegion(Region);
625   else
626     llvm_unreachable("Unsupported kind of VPBlock.");
627 }
628 
629 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
630                             bool Hidden, const Twine &Label) {
631   // Due to "dot" we print an edge between two regions as an edge between the
632   // exit basic block and the entry basic of the respective regions.
633   const VPBlockBase *Tail = From->getExitBasicBlock();
634   const VPBlockBase *Head = To->getEntryBasicBlock();
635   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
636   OS << " [ label=\"" << Label << '\"';
637   if (Tail != From)
638     OS << " ltail=" << getUID(From);
639   if (Head != To)
640     OS << " lhead=" << getUID(To);
641   if (Hidden)
642     OS << "; splines=none";
643   OS << "]\n";
644 }
645 
646 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
647   auto &Successors = Block->getSuccessors();
648   if (Successors.size() == 1)
649     drawEdge(Block, Successors.front(), false, "");
650   else if (Successors.size() == 2) {
651     drawEdge(Block, Successors.front(), false, "T");
652     drawEdge(Block, Successors.back(), false, "F");
653   } else {
654     unsigned SuccessorNumber = 0;
655     for (auto *Successor : Successors)
656       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
657   }
658 }
659 
660 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
661   OS << Indent << getUID(BasicBlock) << " [label =\n";
662   bumpIndent(1);
663   OS << Indent << "\"" << DOT::EscapeString(BasicBlock->getName()) << ":\\n\"";
664   bumpIndent(1);
665 
666   // Dump the block predicate.
667   const VPValue *Pred = BasicBlock->getPredicate();
668   if (Pred) {
669     OS << " +\n" << Indent << " \"BlockPredicate: ";
670     if (const VPInstruction *PredI = dyn_cast<VPInstruction>(Pred)) {
671       PredI->printAsOperand(OS, SlotTracker);
672       OS << " (" << DOT::EscapeString(PredI->getParent()->getName())
673          << ")\\l\"";
674     } else
675       Pred->printAsOperand(OS, SlotTracker);
676   }
677 
678   for (const VPRecipeBase &Recipe : *BasicBlock) {
679     OS << " +\n" << Indent;
680     Recipe.print(OS, Indent, SlotTracker);
681     OS << "\\l\"";
682   }
683 
684   // Dump the condition bit.
685   const VPValue *CBV = BasicBlock->getCondBit();
686   if (CBV) {
687     OS << " +\n" << Indent << " \"CondBit: ";
688     if (const VPInstruction *CBI = dyn_cast<VPInstruction>(CBV)) {
689       CBI->printAsOperand(OS, SlotTracker);
690       OS << " (" << DOT::EscapeString(CBI->getParent()->getName()) << ")\\l\"";
691     } else {
692       CBV->printAsOperand(OS, SlotTracker);
693       OS << "\"";
694     }
695   }
696 
697   bumpIndent(-2);
698   OS << "\n" << Indent << "]\n";
699   dumpEdges(BasicBlock);
700 }
701 
702 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
703   OS << Indent << "subgraph " << getUID(Region) << " {\n";
704   bumpIndent(1);
705   OS << Indent << "fontname=Courier\n"
706      << Indent << "label=\""
707      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
708      << DOT::EscapeString(Region->getName()) << "\"\n";
709   // Dump the blocks of the region.
710   assert(Region->getEntry() && "Region contains no inner blocks.");
711   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
712     dumpBlock(Block);
713   bumpIndent(-1);
714   OS << Indent << "}\n";
715   dumpEdges(Region);
716 }
717 
718 void VPlanPrinter::printAsIngredient(raw_ostream &O, Value *V) {
719   std::string IngredientString;
720   raw_string_ostream RSO(IngredientString);
721   if (auto *Inst = dyn_cast<Instruction>(V)) {
722     if (!Inst->getType()->isVoidTy()) {
723       Inst->printAsOperand(RSO, false);
724       RSO << " = ";
725     }
726     RSO << Inst->getOpcodeName() << " ";
727     unsigned E = Inst->getNumOperands();
728     if (E > 0) {
729       Inst->getOperand(0)->printAsOperand(RSO, false);
730       for (unsigned I = 1; I < E; ++I)
731         Inst->getOperand(I)->printAsOperand(RSO << ", ", false);
732     }
733   } else // !Inst
734     V->printAsOperand(RSO, false);
735   RSO.flush();
736   O << DOT::EscapeString(IngredientString);
737 }
738 
739 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent,
740                               VPSlotTracker &SlotTracker) const {
741   O << "\"WIDEN-CALL " << VPlanIngredient(&Ingredient);
742 }
743 
744 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent,
745                                 VPSlotTracker &SlotTracker) const {
746   O << "\"WIDEN-SELECT" << VPlanIngredient(&Ingredient)
747     << (InvariantCond ? " (condition is loop invariant)" : "");
748 }
749 
750 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent,
751                           VPSlotTracker &SlotTracker) const {
752   O << "\"WIDEN\\l\"";
753   O << "\"  " << VPlanIngredient(&Ingredient);
754 }
755 
756 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent,
757                                           VPSlotTracker &SlotTracker) const {
758   O << "\"WIDEN-INDUCTION";
759   if (Trunc) {
760     O << "\\l\"";
761     O << " +\n" << Indent << "\"  " << VPlanIngredient(IV) << "\\l\"";
762     O << " +\n" << Indent << "\"  " << VPlanIngredient(Trunc);
763   } else
764     O << " " << VPlanIngredient(IV);
765 }
766 
767 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent,
768                              VPSlotTracker &SlotTracker) const {
769   O << "\"WIDEN-GEP ";
770   O << (IsPtrLoopInvariant ? "Inv" : "Var");
771   size_t IndicesNumber = IsIndexLoopInvariant.size();
772   for (size_t I = 0; I < IndicesNumber; ++I)
773     O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]";
774   O << "\\l\"";
775   O << " +\n" << Indent << "\"  " << VPlanIngredient(GEP);
776 }
777 
778 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent,
779                              VPSlotTracker &SlotTracker) const {
780   O << "\"WIDEN-PHI " << VPlanIngredient(Phi);
781 }
782 
783 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent,
784                           VPSlotTracker &SlotTracker) const {
785   O << "\"BLEND ";
786   Phi->printAsOperand(O, false);
787   O << " =";
788   if (getNumIncomingValues() == 1) {
789     // Not a User of any mask: not really blending, this is a
790     // single-predecessor phi.
791     O << " ";
792     getIncomingValue(0)->printAsOperand(O, SlotTracker);
793   } else {
794     for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
795       O << " ";
796       getIncomingValue(I)->printAsOperand(O, SlotTracker);
797       O << "/";
798       getMask(I)->printAsOperand(O, SlotTracker);
799     }
800   }
801 }
802 
803 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent,
804                               VPSlotTracker &SlotTracker) const {
805   O << "\"" << (IsUniform ? "CLONE " : "REPLICATE ")
806     << VPlanIngredient(Ingredient);
807   if (AlsoPack)
808     O << " (S->V)";
809 }
810 
811 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent,
812                                 VPSlotTracker &SlotTracker) const {
813   O << "\"PHI-PREDICATED-INSTRUCTION " << VPlanIngredient(PredInst);
814 }
815 
816 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent,
817                                            VPSlotTracker &SlotTracker) const {
818   O << "\"WIDEN " << VPlanIngredient(&Instr);
819   O << ", ";
820   getAddr()->printAsOperand(O, SlotTracker);
821   VPValue *Mask = getMask();
822   if (Mask) {
823     O << ", ";
824     Mask->printAsOperand(O, SlotTracker);
825   }
826 }
827 
828 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) {
829   Value *CanonicalIV = State.CanonicalIV;
830   Type *STy = CanonicalIV->getType();
831   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
832   auto VF = State.VF;
833   Value *VStart = VF == 1
834                       ? CanonicalIV
835                       : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
836   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) {
837     SmallVector<Constant *, 8> Indices;
838     for (unsigned Lane = 0; Lane < VF; ++Lane)
839       Indices.push_back(ConstantInt::get(STy, Part * VF + Lane));
840     // If VF == 1, there is only one iteration in the loop above, thus the
841     // element pushed back into Indices is ConstantInt::get(STy, Part)
842     Constant *VStep = VF == 1 ? Indices.back() : ConstantVector::get(Indices);
843     // Add the consecutive indices to the vector value.
844     Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
845     State.set(getVPValue(), CanonicalVectorIV, Part);
846   }
847 }
848 
849 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent,
850                                      VPSlotTracker &SlotTracker) const {
851   O << "\"EMIT ";
852   getVPValue()->printAsOperand(O, SlotTracker);
853   O << " = WIDEN-CANONICAL-INDUCTION";
854 }
855 
856 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
857 
858 void VPValue::replaceAllUsesWith(VPValue *New) {
859   for (VPUser *User : users())
860     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
861       if (User->getOperand(I) == this)
862         User->setOperand(I, New);
863 }
864 
865 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
866   if (const Value *UV = getUnderlyingValue()) {
867     OS << "ir<";
868     UV->printAsOperand(OS, false);
869     OS << ">";
870     return;
871   }
872 
873   unsigned Slot = Tracker.getSlot(this);
874   if (Slot == unsigned(-1))
875     OS << "<badref>";
876   else
877     OS << "vp<%" << Tracker.getSlot(this) << ">";
878 }
879 
880 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
881                                           Old2NewTy &Old2New,
882                                           InterleavedAccessInfo &IAI) {
883   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
884   for (VPBlockBase *Base : RPOT) {
885     visitBlock(Base, Old2New, IAI);
886   }
887 }
888 
889 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
890                                          InterleavedAccessInfo &IAI) {
891   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
892     for (VPRecipeBase &VPI : *VPBB) {
893       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
894       auto *VPInst = cast<VPInstruction>(&VPI);
895       auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue());
896       auto *IG = IAI.getInterleaveGroup(Inst);
897       if (!IG)
898         continue;
899 
900       auto NewIGIter = Old2New.find(IG);
901       if (NewIGIter == Old2New.end())
902         Old2New[IG] = new InterleaveGroup<VPInstruction>(
903             IG->getFactor(), IG->isReverse(), IG->getAlign());
904 
905       if (Inst == IG->getInsertPos())
906         Old2New[IG]->setInsertPos(VPInst);
907 
908       InterleaveGroupMap[VPInst] = Old2New[IG];
909       InterleaveGroupMap[VPInst]->insertMember(
910           VPInst, IG->getIndex(Inst),
911           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
912                                 : IG->getFactor()));
913     }
914   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
915     visitRegion(Region, Old2New, IAI);
916   else
917     llvm_unreachable("Unsupported kind of VPBlock.");
918 }
919 
920 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
921                                                  InterleavedAccessInfo &IAI) {
922   Old2NewTy Old2New;
923   visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI);
924 }
925 
926 void VPSlotTracker::assignSlot(const VPValue *V) {
927   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
928   const Value *UV = V->getUnderlyingValue();
929   if (UV)
930     return;
931   const auto *VPI = dyn_cast<VPInstruction>(V);
932   if (VPI && !VPI->hasResult())
933     return;
934 
935   Slots[V] = NextSlot++;
936 }
937 
938 void VPSlotTracker::assignSlots(const VPBlockBase *VPBB) {
939   if (auto *Region = dyn_cast<VPRegionBlock>(VPBB))
940     assignSlots(Region);
941   else
942     assignSlots(cast<VPBasicBlock>(VPBB));
943 }
944 
945 void VPSlotTracker::assignSlots(const VPRegionBlock *Region) {
946   ReversePostOrderTraversal<const VPBlockBase *> RPOT(Region->getEntry());
947   for (const VPBlockBase *Block : RPOT)
948     assignSlots(Block);
949 }
950 
951 void VPSlotTracker::assignSlots(const VPBasicBlock *VPBB) {
952   for (const VPRecipeBase &Recipe : *VPBB) {
953     if (const auto *VPI = dyn_cast<VPInstruction>(&Recipe))
954       assignSlot(VPI);
955     else if (const auto *VPIV = dyn_cast<VPWidenCanonicalIVRecipe>(&Recipe))
956       assignSlot(VPIV->getVPValue());
957   }
958 }
959 
960 void VPSlotTracker::assignSlots(const VPlan &Plan) {
961 
962   for (const VPValue *V : Plan.VPExternalDefs)
963     assignSlot(V);
964 
965   for (auto &E : Plan.Value2VPValue)
966     if (!isa<VPInstruction>(E.second))
967       assignSlot(E.second);
968 
969   for (const VPValue *V : Plan.VPCBVs)
970     assignSlot(V);
971 
972   if (Plan.BackedgeTakenCount)
973     assignSlot(Plan.BackedgeTakenCount);
974 
975   ReversePostOrderTraversal<const VPBlockBase *> RPOT(Plan.getEntry());
976   for (const VPBlockBase *Block : RPOT)
977     assignSlots(Block);
978 }
979