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