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/STLExtras.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/IVDescriptors.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/CFG.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/Value.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/GenericDomTreeConstruction.h"
40 #include "llvm/Support/GraphWriter.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
44 #include <cassert>
45 #include <string>
46 #include <vector>
47 
48 using namespace llvm;
49 extern cl::opt<bool> EnableVPlanNativePath;
50 
51 #define DEBUG_TYPE "vplan"
52 
53 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
54 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
55   const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
56   VPSlotTracker SlotTracker(
57       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
58   V.print(OS, SlotTracker);
59   return OS;
60 }
61 #endif
62 
63 Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder,
64                                 const ElementCount &VF) const {
65   switch (LaneKind) {
66   case VPLane::Kind::ScalableLast:
67     // Lane = RuntimeVF - VF.getKnownMinValue() + Lane
68     return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF),
69                              Builder.getInt32(VF.getKnownMinValue() - Lane));
70   case VPLane::Kind::First:
71     return Builder.getInt32(Lane);
72   }
73   llvm_unreachable("Unknown lane kind");
74 }
75 
76 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)
77     : SubclassID(SC), UnderlyingVal(UV), Def(Def) {
78   if (Def)
79     Def->addDefinedValue(this);
80 }
81 
82 VPValue::~VPValue() {
83   assert(Users.empty() && "trying to delete a VPValue with remaining users");
84   if (Def)
85     Def->removeDefinedValue(this);
86 }
87 
88 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
89 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
90   if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def))
91     R->print(OS, "", SlotTracker);
92   else
93     printAsOperand(OS, SlotTracker);
94 }
95 
96 void VPValue::dump() const {
97   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def);
98   VPSlotTracker SlotTracker(
99       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
100   print(dbgs(), SlotTracker);
101   dbgs() << "\n";
102 }
103 
104 void VPDef::dump() const {
105   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this);
106   VPSlotTracker SlotTracker(
107       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
108   print(dbgs(), "", SlotTracker);
109   dbgs() << "\n";
110 }
111 #endif
112 
113 // Get the top-most entry block of \p Start. This is the entry block of the
114 // containing VPlan. This function is templated to support both const and non-const blocks
115 template <typename T> static T *getPlanEntry(T *Start) {
116   T *Next = Start;
117   T *Current = Start;
118   while ((Next = Next->getParent()))
119     Current = Next;
120 
121   SmallSetVector<T *, 8> WorkList;
122   WorkList.insert(Current);
123 
124   for (unsigned i = 0; i < WorkList.size(); i++) {
125     T *Current = WorkList[i];
126     if (Current->getNumPredecessors() == 0)
127       return Current;
128     auto &Predecessors = Current->getPredecessors();
129     WorkList.insert(Predecessors.begin(), Predecessors.end());
130   }
131 
132   llvm_unreachable("VPlan without any entry node without predecessors");
133 }
134 
135 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
136 
137 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
138 
139 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
140 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
141   const VPBlockBase *Block = this;
142   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
143     Block = Region->getEntry();
144   return cast<VPBasicBlock>(Block);
145 }
146 
147 VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
148   VPBlockBase *Block = this;
149   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
150     Block = Region->getEntry();
151   return cast<VPBasicBlock>(Block);
152 }
153 
154 void VPBlockBase::setPlan(VPlan *ParentPlan) {
155   assert(ParentPlan->getEntry() == this &&
156          "Can only set plan on its entry block.");
157   Plan = ParentPlan;
158 }
159 
160 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
161 const VPBasicBlock *VPBlockBase::getExitBasicBlock() const {
162   const VPBlockBase *Block = this;
163   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
164     Block = Region->getExit();
165   return cast<VPBasicBlock>(Block);
166 }
167 
168 VPBasicBlock *VPBlockBase::getExitBasicBlock() {
169   VPBlockBase *Block = this;
170   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
171     Block = Region->getExit();
172   return cast<VPBasicBlock>(Block);
173 }
174 
175 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
176   if (!Successors.empty() || !Parent)
177     return this;
178   assert(Parent->getExit() == this &&
179          "Block w/o successors not the exit of its parent.");
180   return Parent->getEnclosingBlockWithSuccessors();
181 }
182 
183 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
184   if (!Predecessors.empty() || !Parent)
185     return this;
186   assert(Parent->getEntry() == this &&
187          "Block w/o predecessors not the entry of its parent.");
188   return Parent->getEnclosingBlockWithPredecessors();
189 }
190 
191 VPValue *VPBlockBase::getCondBit() {
192   return CondBitUser.getSingleOperandOrNull();
193 }
194 
195 const VPValue *VPBlockBase::getCondBit() const {
196   return CondBitUser.getSingleOperandOrNull();
197 }
198 
199 void VPBlockBase::setCondBit(VPValue *CV) { CondBitUser.resetSingleOpUser(CV); }
200 
201 VPValue *VPBlockBase::getPredicate() {
202   return PredicateUser.getSingleOperandOrNull();
203 }
204 
205 const VPValue *VPBlockBase::getPredicate() const {
206   return PredicateUser.getSingleOperandOrNull();
207 }
208 
209 void VPBlockBase::setPredicate(VPValue *CV) {
210   PredicateUser.resetSingleOpUser(CV);
211 }
212 
213 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
214   SmallVector<VPBlockBase *, 8> Blocks(depth_first(Entry));
215 
216   for (VPBlockBase *Block : Blocks)
217     delete Block;
218 }
219 
220 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
221   iterator It = begin();
222   while (It != end() && It->isPhi())
223     It++;
224   return It;
225 }
226 
227 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) {
228   if (!Def->getDef())
229     return Def->getLiveInIRValue();
230 
231   if (hasScalarValue(Def, Instance)) {
232     return Data
233         .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)];
234   }
235 
236   assert(hasVectorValue(Def, Instance.Part));
237   auto *VecPart = Data.PerPartOutput[Def][Instance.Part];
238   if (!VecPart->getType()->isVectorTy()) {
239     assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar");
240     return VecPart;
241   }
242   // TODO: Cache created scalar values.
243   Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF);
244   auto *Extract = Builder.CreateExtractElement(VecPart, Lane);
245   // set(Def, Extract, Instance);
246   return Extract;
247 }
248 BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) {
249   VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion();
250   return VPBB2IRBB[LoopRegion->getPreheaderVPBB()];
251 }
252 
253 BasicBlock *
254 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
255   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
256   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
257   BasicBlock *PrevBB = CFG.PrevBB;
258   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
259                                          PrevBB->getParent(), CFG.ExitBB);
260   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
261 
262   // Hook up the new basic block to its predecessors.
263   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
264     VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock();
265     auto &PredVPSuccessors = PredVPBB->getSuccessors();
266     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
267 
268     // In outer loop vectorization scenario, the predecessor BBlock may not yet
269     // be visited(backedge). Mark the VPBasicBlock for fixup at the end of
270     // vectorization. We do not encounter this case in inner loop vectorization
271     // as we start out by building a loop skeleton with the vector loop header
272     // and latch blocks. As a result, we never enter this function for the
273     // header block in the non VPlan-native path.
274     if (!PredBB) {
275       assert(EnableVPlanNativePath &&
276              "Unexpected null predecessor in non VPlan-native path");
277       CFG.VPBBsToFix.push_back(PredVPBB);
278       continue;
279     }
280 
281     assert(PredBB && "Predecessor basic-block not found building successor.");
282     auto *PredBBTerminator = PredBB->getTerminator();
283     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
284 
285     auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator);
286     if (isa<UnreachableInst>(PredBBTerminator)) {
287       assert(PredVPSuccessors.size() == 1 &&
288              "Predecessor ending w/o branch must have single successor.");
289       DebugLoc DL = PredBBTerminator->getDebugLoc();
290       PredBBTerminator->eraseFromParent();
291       auto *Br = BranchInst::Create(NewBB, PredBB);
292       Br->setDebugLoc(DL);
293     } else if (TermBr && !TermBr->isConditional()) {
294       TermBr->setSuccessor(0, NewBB);
295     } else if (PredVPSuccessors.size() == 2) {
296       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
297       assert(!PredBBTerminator->getSuccessor(idx) &&
298              "Trying to reset an existing successor block.");
299       PredBBTerminator->setSuccessor(idx, NewBB);
300     } else {
301       // PredVPBB is the exit block of a loop region. Connect its successor
302       // outside the region.
303       auto *LoopRegion = cast<VPRegionBlock>(PredVPBB->getParent());
304       assert(!LoopRegion->isReplicator() &&
305              "predecessor must be in a loop region");
306       assert(PredVPSuccessors.empty() &&
307              LoopRegion->getExitBasicBlock() == PredVPBB &&
308              "PredVPBB must be the exit block of its parent region");
309       assert(this == LoopRegion->getSingleSuccessor() &&
310              "the current block must be the single successor of the region");
311       PredBBTerminator->setSuccessor(0, NewBB);
312       PredBBTerminator->setSuccessor(
313           1, CFG.VPBB2IRBB[LoopRegion->getEntryBasicBlock()]);
314     }
315   }
316   return NewBB;
317 }
318 
319 void VPBasicBlock::execute(VPTransformState *State) {
320   bool Replica = State->Instance && !State->Instance->isFirstIteration();
321   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
322   VPBlockBase *SingleHPred = nullptr;
323   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
324 
325   auto IsLoopRegion = [](VPBlockBase *BB) {
326     auto *R = dyn_cast<VPRegionBlock>(BB);
327     return R && !R->isReplicator();
328   };
329 
330   // 1. Create an IR basic block, or reuse the last one or ExitBB if possible.
331   if (getPlan()->getVectorLoopRegion()->getSingleSuccessor() == this) {
332     // ExitBB can be re-used for the exit block of the Plan.
333     NewBB = State->CFG.ExitBB;
334     State->CFG.PrevBB = NewBB;
335   } else if (PrevVPBB && /* A */
336              !((SingleHPred = getSingleHierarchicalPredecessor()) &&
337                SingleHPred->getExitBasicBlock() == PrevVPBB &&
338                PrevVPBB->getSingleHierarchicalSuccessor() &&
339                (SingleHPred->getParent() == getEnclosingLoopRegion() &&
340                 !IsLoopRegion(SingleHPred))) &&         /* B */
341              !(Replica && getPredecessors().empty())) { /* C */
342     // The last IR basic block is reused, as an optimization, in three cases:
343     // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null;
344     // B. when the current VPBB has a single (hierarchical) predecessor which
345     //    is PrevVPBB and the latter has a single (hierarchical) successor which
346     //    both are in the same non-replicator region; and
347     // C. when the current VPBB is an entry of a region replica - where PrevVPBB
348     //    is the exit of this region from a previous instance, or the
349     //    predecessor of this region.
350 
351     NewBB = createEmptyBasicBlock(State->CFG);
352     State->Builder.SetInsertPoint(NewBB);
353     // Temporarily terminate with unreachable until CFG is rewired.
354     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
355     // Register NewBB in its loop. In innermost loops its the same for all
356     // BB's.
357     if (State->CurrentVectorLoop)
358       State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI);
359     State->Builder.SetInsertPoint(Terminator);
360     State->CFG.PrevBB = NewBB;
361   }
362 
363   // 2. Fill the IR basic block with IR instructions.
364   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
365                     << " in BB:" << NewBB->getName() << '\n');
366 
367   State->CFG.VPBB2IRBB[this] = NewBB;
368   State->CFG.PrevVPBB = this;
369 
370   for (VPRecipeBase &Recipe : Recipes)
371     Recipe.execute(*State);
372 
373   VPValue *CBV;
374   if (EnableVPlanNativePath && (CBV = getCondBit())) {
375     assert(CBV->getUnderlyingValue() &&
376            "Unexpected null underlying value for condition bit");
377 
378     // Condition bit value in a VPBasicBlock is used as the branch selector. In
379     // the VPlan-native path case, since all branches are uniform we generate a
380     // branch instruction using the condition value from vector lane 0 and dummy
381     // successors. The successors are fixed later when the successor blocks are
382     // visited.
383     Value *NewCond = State->get(CBV, {0, 0});
384 
385     // Replace the temporary unreachable terminator with the new conditional
386     // branch.
387     auto *CurrentTerminator = NewBB->getTerminator();
388     assert(isa<UnreachableInst>(CurrentTerminator) &&
389            "Expected to replace unreachable terminator with conditional "
390            "branch.");
391     auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond);
392     CondBr->setSuccessor(0, nullptr);
393     ReplaceInstWithInst(CurrentTerminator, CondBr);
394   }
395 
396   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
397 }
398 
399 void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
400   for (VPRecipeBase &R : Recipes) {
401     for (auto *Def : R.definedValues())
402       Def->replaceAllUsesWith(NewValue);
403 
404     for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
405       R.setOperand(I, NewValue);
406   }
407 }
408 
409 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) {
410   assert((SplitAt == end() || SplitAt->getParent() == this) &&
411          "can only split at a position in the same block");
412 
413   SmallVector<VPBlockBase *, 2> Succs(successors());
414   // First, disconnect the current block from its successors.
415   for (VPBlockBase *Succ : Succs)
416     VPBlockUtils::disconnectBlocks(this, Succ);
417 
418   // Create new empty block after the block to split.
419   auto *SplitBlock = new VPBasicBlock(getName() + ".split");
420   VPBlockUtils::insertBlockAfter(SplitBlock, this);
421 
422   // Add successors for block to split to new block.
423   for (VPBlockBase *Succ : Succs)
424     VPBlockUtils::connectBlocks(SplitBlock, Succ);
425 
426   // Finally, move the recipes starting at SplitAt to new block.
427   for (VPRecipeBase &ToMove :
428        make_early_inc_range(make_range(SplitAt, this->end())))
429     ToMove.moveBefore(*SplitBlock, SplitBlock->end());
430 
431   return SplitBlock;
432 }
433 
434 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() {
435   VPRegionBlock *P = getParent();
436   if (P && P->isReplicator()) {
437     P = P->getParent();
438     assert(!cast<VPRegionBlock>(P)->isReplicator() &&
439            "unexpected nested replicate regions");
440   }
441   return P;
442 }
443 
444 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
445 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {
446   if (getSuccessors().empty()) {
447     O << Indent << "No successors\n";
448   } else {
449     O << Indent << "Successor(s): ";
450     ListSeparator LS;
451     for (auto *Succ : getSuccessors())
452       O << LS << Succ->getName();
453     O << '\n';
454   }
455 }
456 
457 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
458                          VPSlotTracker &SlotTracker) const {
459   O << Indent << getName() << ":\n";
460   if (const VPValue *Pred = getPredicate()) {
461     O << Indent << "BlockPredicate:";
462     Pred->printAsOperand(O, SlotTracker);
463     if (const auto *PredInst = dyn_cast<VPInstruction>(Pred))
464       O << " (" << PredInst->getParent()->getName() << ")";
465     O << '\n';
466   }
467 
468   auto RecipeIndent = Indent + "  ";
469   for (const VPRecipeBase &Recipe : *this) {
470     Recipe.print(O, RecipeIndent, SlotTracker);
471     O << '\n';
472   }
473 
474   printSuccessors(O, Indent);
475 
476   if (const VPValue *CBV = getCondBit()) {
477     O << Indent << "CondBit: ";
478     CBV->printAsOperand(O, SlotTracker);
479     if (const auto *CBI = dyn_cast<VPInstruction>(CBV))
480       O << " (" << CBI->getParent()->getName() << ")";
481     O << '\n';
482   }
483 }
484 #endif
485 
486 void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
487   for (VPBlockBase *Block : depth_first(Entry))
488     // Drop all references in VPBasicBlocks and replace all uses with
489     // DummyValue.
490     Block->dropAllReferences(NewValue);
491 }
492 
493 void VPRegionBlock::execute(VPTransformState *State) {
494   ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry);
495 
496   if (!isReplicator()) {
497     // Create and register the new vector loop.
498     Loop *PrevLoop = State->CurrentVectorLoop;
499     State->CurrentVectorLoop = State->LI->AllocateLoop();
500     BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()];
501     Loop *ParentLoop = State->LI->getLoopFor(VectorPH);
502 
503     // Insert the new loop into the loop nest and register the new basic blocks
504     // before calling any utilities such as SCEV that require valid LoopInfo.
505     if (ParentLoop)
506       ParentLoop->addChildLoop(State->CurrentVectorLoop);
507     else
508       State->LI->addTopLevelLoop(State->CurrentVectorLoop);
509 
510     // Visit the VPBlocks connected to "this", starting from it.
511     for (VPBlockBase *Block : RPOT) {
512       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
513       Block->execute(State);
514     }
515 
516     State->CurrentVectorLoop = PrevLoop;
517     return;
518   }
519 
520   assert(!State->Instance && "Replicating a Region with non-null instance.");
521 
522   // Enter replicating mode.
523   State->Instance = VPIteration(0, 0);
524 
525   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
526     State->Instance->Part = Part;
527     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
528     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
529          ++Lane) {
530       State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);
531       // Visit the VPBlocks connected to \p this, starting from it.
532       for (VPBlockBase *Block : RPOT) {
533         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
534         Block->execute(State);
535       }
536     }
537   }
538 
539   // Exit replicating mode.
540   State->Instance.reset();
541 }
542 
543 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
544 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent,
545                           VPSlotTracker &SlotTracker) const {
546   O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
547   auto NewIndent = Indent + "  ";
548   for (auto *BlockBase : depth_first(Entry)) {
549     O << '\n';
550     BlockBase->print(O, NewIndent, SlotTracker);
551   }
552   O << Indent << "}\n";
553 
554   printSuccessors(O, Indent);
555 }
556 #endif
557 
558 bool VPRecipeBase::mayWriteToMemory() const {
559   switch (getVPDefID()) {
560   case VPWidenMemoryInstructionSC: {
561     return cast<VPWidenMemoryInstructionRecipe>(this)->isStore();
562   }
563   case VPReplicateSC:
564   case VPWidenCallSC:
565     return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
566         ->mayWriteToMemory();
567   case VPBranchOnMaskSC:
568     return false;
569   case VPWidenIntOrFpInductionSC:
570   case VPWidenCanonicalIVSC:
571   case VPWidenPHISC:
572   case VPBlendSC:
573   case VPWidenSC:
574   case VPWidenGEPSC:
575   case VPReductionSC:
576   case VPWidenSelectSC: {
577     const Instruction *I =
578         dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
579     (void)I;
580     assert((!I || !I->mayWriteToMemory()) &&
581            "underlying instruction may write to memory");
582     return false;
583   }
584   default:
585     return true;
586   }
587 }
588 
589 bool VPRecipeBase::mayReadFromMemory() const {
590   switch (getVPDefID()) {
591   case VPWidenMemoryInstructionSC: {
592     return !cast<VPWidenMemoryInstructionRecipe>(this)->isStore();
593   }
594   case VPReplicateSC:
595   case VPWidenCallSC:
596     return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
597         ->mayReadFromMemory();
598   case VPBranchOnMaskSC:
599     return false;
600   case VPWidenIntOrFpInductionSC:
601   case VPWidenCanonicalIVSC:
602   case VPWidenPHISC:
603   case VPBlendSC:
604   case VPWidenSC:
605   case VPWidenGEPSC:
606   case VPReductionSC:
607   case VPWidenSelectSC: {
608     const Instruction *I =
609         dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
610     (void)I;
611     assert((!I || !I->mayReadFromMemory()) &&
612            "underlying instruction may read from memory");
613     return false;
614   }
615   default:
616     return true;
617   }
618 }
619 
620 bool VPRecipeBase::mayHaveSideEffects() const {
621   switch (getVPDefID()) {
622   case VPBranchOnMaskSC:
623     return false;
624   case VPWidenIntOrFpInductionSC:
625   case VPWidenPointerInductionSC:
626   case VPWidenCanonicalIVSC:
627   case VPWidenPHISC:
628   case VPBlendSC:
629   case VPWidenSC:
630   case VPWidenGEPSC:
631   case VPReductionSC:
632   case VPWidenSelectSC:
633   case VPScalarIVStepsSC: {
634     const Instruction *I =
635         dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
636     (void)I;
637     assert((!I || !I->mayHaveSideEffects()) &&
638            "underlying instruction has side-effects");
639     return false;
640   }
641   case VPReplicateSC: {
642     auto *R = cast<VPReplicateRecipe>(this);
643     return R->getUnderlyingInstr()->mayHaveSideEffects();
644   }
645   default:
646     return true;
647   }
648 }
649 
650 void VPLiveOut::fixPhi(VPlan &Plan, VPTransformState &State) {
651   auto Lane = VPLane::getLastLaneForVF(State.VF);
652   VPValue *ExitValue = getOperand(0);
653   if (Plan.isUniformAfterVectorization(ExitValue))
654     Lane = VPLane::getFirstLane();
655   Phi->addIncoming(State.get(ExitValue, VPIteration(State.UF - 1, Lane)),
656                    State.Builder.GetInsertBlock());
657 }
658 
659 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) {
660   assert(!Parent && "Recipe already in some VPBasicBlock");
661   assert(InsertPos->getParent() &&
662          "Insertion position not in any VPBasicBlock");
663   Parent = InsertPos->getParent();
664   Parent->getRecipeList().insert(InsertPos->getIterator(), this);
665 }
666 
667 void VPRecipeBase::insertBefore(VPBasicBlock &BB,
668                                 iplist<VPRecipeBase>::iterator I) {
669   assert(!Parent && "Recipe already in some VPBasicBlock");
670   assert(I == BB.end() || I->getParent() == &BB);
671   Parent = &BB;
672   BB.getRecipeList().insert(I, this);
673 }
674 
675 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) {
676   assert(!Parent && "Recipe already in some VPBasicBlock");
677   assert(InsertPos->getParent() &&
678          "Insertion position not in any VPBasicBlock");
679   Parent = InsertPos->getParent();
680   Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this);
681 }
682 
683 void VPRecipeBase::removeFromParent() {
684   assert(getParent() && "Recipe not in any VPBasicBlock");
685   getParent()->getRecipeList().remove(getIterator());
686   Parent = nullptr;
687 }
688 
689 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() {
690   assert(getParent() && "Recipe not in any VPBasicBlock");
691   return getParent()->getRecipeList().erase(getIterator());
692 }
693 
694 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) {
695   removeFromParent();
696   insertAfter(InsertPos);
697 }
698 
699 void VPRecipeBase::moveBefore(VPBasicBlock &BB,
700                               iplist<VPRecipeBase>::iterator I) {
701   removeFromParent();
702   insertBefore(BB, I);
703 }
704 
705 void VPInstruction::generateInstruction(VPTransformState &State,
706                                         unsigned Part) {
707   IRBuilderBase &Builder = State.Builder;
708   Builder.SetCurrentDebugLocation(DL);
709 
710   if (Instruction::isBinaryOp(getOpcode())) {
711     Value *A = State.get(getOperand(0), Part);
712     Value *B = State.get(getOperand(1), Part);
713     Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B);
714     State.set(this, V, Part);
715     return;
716   }
717 
718   switch (getOpcode()) {
719   case VPInstruction::Not: {
720     Value *A = State.get(getOperand(0), Part);
721     Value *V = Builder.CreateNot(A);
722     State.set(this, V, Part);
723     break;
724   }
725   case VPInstruction::ICmpULE: {
726     Value *IV = State.get(getOperand(0), Part);
727     Value *TC = State.get(getOperand(1), Part);
728     Value *V = Builder.CreateICmpULE(IV, TC);
729     State.set(this, V, Part);
730     break;
731   }
732   case Instruction::Select: {
733     Value *Cond = State.get(getOperand(0), Part);
734     Value *Op1 = State.get(getOperand(1), Part);
735     Value *Op2 = State.get(getOperand(2), Part);
736     Value *V = Builder.CreateSelect(Cond, Op1, Op2);
737     State.set(this, V, Part);
738     break;
739   }
740   case VPInstruction::ActiveLaneMask: {
741     // Get first lane of vector induction variable.
742     Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0));
743     // Get the original loop tripcount.
744     Value *ScalarTC = State.get(getOperand(1), Part);
745 
746     auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
747     auto *PredTy = VectorType::get(Int1Ty, State.VF);
748     Instruction *Call = Builder.CreateIntrinsic(
749         Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()},
750         {VIVElem0, ScalarTC}, nullptr, "active.lane.mask");
751     State.set(this, Call, Part);
752     break;
753   }
754   case VPInstruction::FirstOrderRecurrenceSplice: {
755     // Generate code to combine the previous and current values in vector v3.
756     //
757     //   vector.ph:
758     //     v_init = vector(..., ..., ..., a[-1])
759     //     br vector.body
760     //
761     //   vector.body
762     //     i = phi [0, vector.ph], [i+4, vector.body]
763     //     v1 = phi [v_init, vector.ph], [v2, vector.body]
764     //     v2 = a[i, i+1, i+2, i+3];
765     //     v3 = vector(v1(3), v2(0, 1, 2))
766 
767     // For the first part, use the recurrence phi (v1), otherwise v2.
768     auto *V1 = State.get(getOperand(0), 0);
769     Value *PartMinus1 = Part == 0 ? V1 : State.get(getOperand(1), Part - 1);
770     if (!PartMinus1->getType()->isVectorTy()) {
771       State.set(this, PartMinus1, Part);
772     } else {
773       Value *V2 = State.get(getOperand(1), Part);
774       State.set(this, Builder.CreateVectorSplice(PartMinus1, V2, -1), Part);
775     }
776     break;
777   }
778 
779   case VPInstruction::CanonicalIVIncrement:
780   case VPInstruction::CanonicalIVIncrementNUW: {
781     Value *Next = nullptr;
782     if (Part == 0) {
783       bool IsNUW = getOpcode() == VPInstruction::CanonicalIVIncrementNUW;
784       auto *Phi = State.get(getOperand(0), 0);
785       // The loop step is equal to the vectorization factor (num of SIMD
786       // elements) times the unroll factor (num of SIMD instructions).
787       Value *Step =
788           createStepForVF(Builder, Phi->getType(), State.VF, State.UF);
789       Next = Builder.CreateAdd(Phi, Step, "index.next", IsNUW, false);
790     } else {
791       Next = State.get(this, 0);
792     }
793 
794     State.set(this, Next, Part);
795     break;
796   }
797   case VPInstruction::BranchOnCount: {
798     if (Part != 0)
799       break;
800     // First create the compare.
801     Value *IV = State.get(getOperand(0), Part);
802     Value *TC = State.get(getOperand(1), Part);
803     Value *Cond = Builder.CreateICmpEQ(IV, TC);
804 
805     // Now create the branch.
806     auto *Plan = getParent()->getPlan();
807     VPRegionBlock *TopRegion = Plan->getVectorLoopRegion();
808     VPBasicBlock *Header = TopRegion->getEntry()->getEntryBasicBlock();
809     if (Header->empty()) {
810       assert(EnableVPlanNativePath &&
811              "empty entry block only expected in VPlanNativePath");
812       Header = cast<VPBasicBlock>(Header->getSingleSuccessor());
813     }
814     // TODO: Once the exit block is modeled in VPlan, use it instead of going
815     // through State.CFG.ExitBB.
816     BasicBlock *Exit = State.CFG.ExitBB;
817 
818     Builder.CreateCondBr(Cond, Exit, State.CFG.VPBB2IRBB[Header]);
819     Builder.GetInsertBlock()->getTerminator()->eraseFromParent();
820     break;
821   }
822   default:
823     llvm_unreachable("Unsupported opcode for instruction");
824   }
825 }
826 
827 void VPInstruction::execute(VPTransformState &State) {
828   assert(!State.Instance && "VPInstruction executing an Instance");
829   IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
830   State.Builder.setFastMathFlags(FMF);
831   for (unsigned Part = 0; Part < State.UF; ++Part)
832     generateInstruction(State, Part);
833 }
834 
835 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
836 void VPInstruction::dump() const {
837   VPSlotTracker SlotTracker(getParent()->getPlan());
838   print(dbgs(), "", SlotTracker);
839 }
840 
841 void VPInstruction::print(raw_ostream &O, const Twine &Indent,
842                           VPSlotTracker &SlotTracker) const {
843   O << Indent << "EMIT ";
844 
845   if (hasResult()) {
846     printAsOperand(O, SlotTracker);
847     O << " = ";
848   }
849 
850   switch (getOpcode()) {
851   case VPInstruction::Not:
852     O << "not";
853     break;
854   case VPInstruction::ICmpULE:
855     O << "icmp ule";
856     break;
857   case VPInstruction::SLPLoad:
858     O << "combined load";
859     break;
860   case VPInstruction::SLPStore:
861     O << "combined store";
862     break;
863   case VPInstruction::ActiveLaneMask:
864     O << "active lane mask";
865     break;
866   case VPInstruction::FirstOrderRecurrenceSplice:
867     O << "first-order splice";
868     break;
869   case VPInstruction::CanonicalIVIncrement:
870     O << "VF * UF + ";
871     break;
872   case VPInstruction::CanonicalIVIncrementNUW:
873     O << "VF * UF +(nuw) ";
874     break;
875   case VPInstruction::BranchOnCount:
876     O << "branch-on-count ";
877     break;
878   default:
879     O << Instruction::getOpcodeName(getOpcode());
880   }
881 
882   O << FMF;
883 
884   for (const VPValue *Operand : operands()) {
885     O << " ";
886     Operand->printAsOperand(O, SlotTracker);
887   }
888 
889   if (DL) {
890     O << ", !dbg ";
891     DL.print(O);
892   }
893 }
894 #endif
895 
896 void VPInstruction::setFastMathFlags(FastMathFlags FMFNew) {
897   // Make sure the VPInstruction is a floating-point operation.
898   assert((Opcode == Instruction::FAdd || Opcode == Instruction::FMul ||
899           Opcode == Instruction::FNeg || Opcode == Instruction::FSub ||
900           Opcode == Instruction::FDiv || Opcode == Instruction::FRem ||
901           Opcode == Instruction::FCmp) &&
902          "this op can't take fast-math flags");
903   FMF = FMFNew;
904 }
905 
906 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,
907                              Value *CanonicalIVStartValue,
908                              VPTransformState &State) {
909   // Check if the trip count is needed, and if so build it.
910   if (TripCount && TripCount->getNumUsers()) {
911     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
912       State.set(TripCount, TripCountV, Part);
913   }
914 
915   // Check if the backedge taken count is needed, and if so build it.
916   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
917     IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
918     auto *TCMO = Builder.CreateSub(TripCountV,
919                                    ConstantInt::get(TripCountV->getType(), 1),
920                                    "trip.count.minus.1");
921     auto VF = State.VF;
922     Value *VTCMO =
923         VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
924     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
925       State.set(BackedgeTakenCount, VTCMO, Part);
926   }
927 
928   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
929     State.set(&VectorTripCount, VectorTripCountV, Part);
930 
931   // When vectorizing the epilogue loop, the canonical induction start value
932   // needs to be changed from zero to the value after the main vector loop.
933   if (CanonicalIVStartValue) {
934     VPValue *VPV = getOrAddExternalDef(CanonicalIVStartValue);
935     auto *IV = getCanonicalIV();
936     assert(all_of(IV->users(),
937                   [](const VPUser *U) {
938                     if (isa<VPScalarIVStepsRecipe>(U))
939                       return true;
940                     auto *VPI = cast<VPInstruction>(U);
941                     return VPI->getOpcode() ==
942                                VPInstruction::CanonicalIVIncrement ||
943                            VPI->getOpcode() ==
944                                VPInstruction::CanonicalIVIncrementNUW;
945                   }) &&
946            "the canonical IV should only be used by its increments or "
947            "ScalarIVSteps when "
948            "resetting the start value");
949     IV->setOperand(0, VPV);
950   }
951 }
952 
953 /// Generate the code inside the preheader and body of the vectorized loop.
954 /// Assumes a single pre-header basic-block was created for this. Introduce
955 /// additional basic-blocks as needed, and fill them all.
956 void VPlan::execute(VPTransformState *State) {
957   // Set the reverse mapping from VPValues to Values for code generation.
958   for (auto &Entry : Value2VPValue)
959     State->VPValue2Value[Entry.second] = Entry.first;
960 
961   // Initialize CFG state.
962   State->CFG.PrevVPBB = nullptr;
963   State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();
964   BasicBlock *VectorPreHeader = State->CFG.PrevBB;
965   State->Builder.SetInsertPoint(VectorPreHeader->getTerminator());
966 
967   // Generate code in the loop pre-header and body.
968   for (VPBlockBase *Block : depth_first(Entry))
969     Block->execute(State);
970 
971   // Setup branch terminator successors for VPBBs in VPBBsToFix based on
972   // VPBB's successors.
973   for (auto VPBB : State->CFG.VPBBsToFix) {
974     assert(EnableVPlanNativePath &&
975            "Unexpected VPBBsToFix in non VPlan-native path");
976     BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
977     assert(BB && "Unexpected null basic block for VPBB");
978 
979     unsigned Idx = 0;
980     auto *BBTerminator = BB->getTerminator();
981 
982     for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
983       VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
984       BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
985       ++Idx;
986     }
987   }
988 
989   VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitBasicBlock();
990   BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB];
991 
992   // Fix the latch value of canonical, reduction and first-order recurrences
993   // phis in the vector loop.
994   VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
995   for (VPRecipeBase &R : Header->phis()) {
996     // Skip phi-like recipes that generate their backedege values themselves.
997     if (isa<VPWidenPHIRecipe>(&R))
998       continue;
999 
1000     if (isa<VPWidenPointerInductionRecipe>(&R) ||
1001         isa<VPWidenIntOrFpInductionRecipe>(&R)) {
1002       PHINode *Phi = nullptr;
1003       if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {
1004         Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));
1005       } else {
1006         auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);
1007         // TODO: Split off the case that all users of a pointer phi are scalar
1008         // from the VPWidenPointerInductionRecipe.
1009         if (all_of(WidenPhi->users(), [WidenPhi](const VPUser *U) {
1010               return U->usesScalars(WidenPhi);
1011             }))
1012           continue;
1013 
1014         auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));
1015         Phi = cast<PHINode>(GEP->getPointerOperand());
1016       }
1017 
1018       Phi->setIncomingBlock(1, VectorLatchBB);
1019 
1020       // Move the last step to the end of the latch block. This ensures
1021       // consistent placement of all induction updates.
1022       Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));
1023       Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());
1024       continue;
1025     }
1026 
1027     auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
1028     // For  canonical IV, first-order recurrences and in-order reduction phis,
1029     // only a single part is generated, which provides the last part from the
1030     // previous iteration. For non-ordered reductions all UF parts are
1031     // generated.
1032     bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) ||
1033                             isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) ||
1034                             cast<VPReductionPHIRecipe>(PhiR)->isOrdered();
1035     unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
1036 
1037     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
1038       Value *Phi = State->get(PhiR, Part);
1039       Value *Val = State->get(PhiR->getBackedgeValue(),
1040                               SinglePartNeeded ? State->UF - 1 : Part);
1041       cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
1042     }
1043   }
1044 
1045   // We do not attempt to preserve DT for outer loop vectorization currently.
1046   if (!EnableVPlanNativePath) {
1047     BasicBlock *VectorHeaderBB = State->CFG.VPBB2IRBB[Header];
1048     State->DT->addNewBlock(VectorHeaderBB, VectorPreHeader);
1049     updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB,
1050                         State->CFG.ExitBB);
1051   }
1052 }
1053 
1054 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1055 LLVM_DUMP_METHOD
1056 void VPlan::print(raw_ostream &O) const {
1057   VPSlotTracker SlotTracker(this);
1058 
1059   O << "VPlan '" << Name << "' {";
1060 
1061   if (VectorTripCount.getNumUsers() > 0) {
1062     O << "\nLive-in ";
1063     VectorTripCount.printAsOperand(O, SlotTracker);
1064     O << " = vector-trip-count\n";
1065   }
1066 
1067   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
1068     O << "\nLive-in ";
1069     BackedgeTakenCount->printAsOperand(O, SlotTracker);
1070     O << " = backedge-taken count\n";
1071   }
1072 
1073   for (const VPBlockBase *Block : depth_first(getEntry())) {
1074     O << '\n';
1075     Block->print(O, "", SlotTracker);
1076   }
1077 
1078   if (!LiveOuts.empty())
1079     O << "\n";
1080   for (auto &KV : LiveOuts) {
1081     O << "Live-out ";
1082     KV.second->getPhi()->printAsOperand(O);
1083     O << " = ";
1084     KV.second->getOperand(0)->printAsOperand(O, SlotTracker);
1085     O << "\n";
1086   }
1087 
1088   O << "}\n";
1089 }
1090 
1091 LLVM_DUMP_METHOD
1092 void VPlan::printDOT(raw_ostream &O) const {
1093   VPlanPrinter Printer(O, *this);
1094   Printer.dump();
1095 }
1096 
1097 LLVM_DUMP_METHOD
1098 void VPlan::dump() const { print(dbgs()); }
1099 #endif
1100 
1101 void VPlan::addLiveOut(PHINode *PN, VPValue *V) {
1102   assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists");
1103   LiveOuts.insert({PN, new VPLiveOut(PN, V)});
1104 }
1105 
1106 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB,
1107                                 BasicBlock *LoopLatchBB,
1108                                 BasicBlock *LoopExitBB) {
1109   // The vector body may be more than a single basic-block by this point.
1110   // Update the dominator tree information inside the vector body by propagating
1111   // it from header to latch, expecting only triangular control-flow, if any.
1112   BasicBlock *PostDomSucc = nullptr;
1113   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
1114     // Get the list of successors of this block.
1115     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
1116     assert(Succs.size() <= 2 &&
1117            "Basic block in vector loop has more than 2 successors.");
1118     PostDomSucc = Succs[0];
1119     if (Succs.size() == 1) {
1120       assert(PostDomSucc->getSinglePredecessor() &&
1121              "PostDom successor has more than one predecessor.");
1122       DT->addNewBlock(PostDomSucc, BB);
1123       continue;
1124     }
1125     BasicBlock *InterimSucc = Succs[1];
1126     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
1127       PostDomSucc = Succs[1];
1128       InterimSucc = Succs[0];
1129     }
1130     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
1131            "One successor of a basic block does not lead to the other.");
1132     assert(InterimSucc->getSinglePredecessor() &&
1133            "Interim successor has more than one predecessor.");
1134     assert(PostDomSucc->hasNPredecessors(2) &&
1135            "PostDom successor has more than two predecessors.");
1136     DT->addNewBlock(InterimSucc, BB);
1137     DT->addNewBlock(PostDomSucc, BB);
1138   }
1139   // Latch block is a new dominator for the loop exit.
1140   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
1141   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
1142 }
1143 
1144 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1145 Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
1146   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
1147          Twine(getOrCreateBID(Block));
1148 }
1149 
1150 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
1151   const std::string &Name = Block->getName();
1152   if (!Name.empty())
1153     return Name;
1154   return "VPB" + Twine(getOrCreateBID(Block));
1155 }
1156 
1157 void VPlanPrinter::dump() {
1158   Depth = 1;
1159   bumpIndent(0);
1160   OS << "digraph VPlan {\n";
1161   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
1162   if (!Plan.getName().empty())
1163     OS << "\\n" << DOT::EscapeString(Plan.getName());
1164   if (Plan.BackedgeTakenCount) {
1165     OS << ", where:\\n";
1166     Plan.BackedgeTakenCount->print(OS, SlotTracker);
1167     OS << " := BackedgeTakenCount";
1168   }
1169   OS << "\"]\n";
1170   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
1171   OS << "edge [fontname=Courier, fontsize=30]\n";
1172   OS << "compound=true\n";
1173 
1174   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
1175     dumpBlock(Block);
1176 
1177   OS << "}\n";
1178 }
1179 
1180 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
1181   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
1182     dumpBasicBlock(BasicBlock);
1183   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1184     dumpRegion(Region);
1185   else
1186     llvm_unreachable("Unsupported kind of VPBlock.");
1187 }
1188 
1189 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
1190                             bool Hidden, const Twine &Label) {
1191   // Due to "dot" we print an edge between two regions as an edge between the
1192   // exit basic block and the entry basic of the respective regions.
1193   const VPBlockBase *Tail = From->getExitBasicBlock();
1194   const VPBlockBase *Head = To->getEntryBasicBlock();
1195   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
1196   OS << " [ label=\"" << Label << '\"';
1197   if (Tail != From)
1198     OS << " ltail=" << getUID(From);
1199   if (Head != To)
1200     OS << " lhead=" << getUID(To);
1201   if (Hidden)
1202     OS << "; splines=none";
1203   OS << "]\n";
1204 }
1205 
1206 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
1207   auto &Successors = Block->getSuccessors();
1208   if (Successors.size() == 1)
1209     drawEdge(Block, Successors.front(), false, "");
1210   else if (Successors.size() == 2) {
1211     drawEdge(Block, Successors.front(), false, "T");
1212     drawEdge(Block, Successors.back(), false, "F");
1213   } else {
1214     unsigned SuccessorNumber = 0;
1215     for (auto *Successor : Successors)
1216       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
1217   }
1218 }
1219 
1220 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
1221   // Implement dot-formatted dump by performing plain-text dump into the
1222   // temporary storage followed by some post-processing.
1223   OS << Indent << getUID(BasicBlock) << " [label =\n";
1224   bumpIndent(1);
1225   std::string Str;
1226   raw_string_ostream SS(Str);
1227   // Use no indentation as we need to wrap the lines into quotes ourselves.
1228   BasicBlock->print(SS, "", SlotTracker);
1229 
1230   // We need to process each line of the output separately, so split
1231   // single-string plain-text dump.
1232   SmallVector<StringRef, 0> Lines;
1233   StringRef(Str).rtrim('\n').split(Lines, "\n");
1234 
1235   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
1236     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
1237   };
1238 
1239   // Don't need the "+" after the last line.
1240   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
1241     EmitLine(Line, " +\n");
1242   EmitLine(Lines.back(), "\n");
1243 
1244   bumpIndent(-1);
1245   OS << Indent << "]\n";
1246 
1247   dumpEdges(BasicBlock);
1248 }
1249 
1250 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
1251   OS << Indent << "subgraph " << getUID(Region) << " {\n";
1252   bumpIndent(1);
1253   OS << Indent << "fontname=Courier\n"
1254      << Indent << "label=\""
1255      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
1256      << DOT::EscapeString(Region->getName()) << "\"\n";
1257   // Dump the blocks of the region.
1258   assert(Region->getEntry() && "Region contains no inner blocks.");
1259   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
1260     dumpBlock(Block);
1261   bumpIndent(-1);
1262   OS << Indent << "}\n";
1263   dumpEdges(Region);
1264 }
1265 
1266 void VPlanIngredient::print(raw_ostream &O) const {
1267   if (auto *Inst = dyn_cast<Instruction>(V)) {
1268     if (!Inst->getType()->isVoidTy()) {
1269       Inst->printAsOperand(O, false);
1270       O << " = ";
1271     }
1272     O << Inst->getOpcodeName() << " ";
1273     unsigned E = Inst->getNumOperands();
1274     if (E > 0) {
1275       Inst->getOperand(0)->printAsOperand(O, false);
1276       for (unsigned I = 1; I < E; ++I)
1277         Inst->getOperand(I)->printAsOperand(O << ", ", false);
1278     }
1279   } else // !Inst
1280     V->printAsOperand(O, false);
1281 }
1282 
1283 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent,
1284                               VPSlotTracker &SlotTracker) const {
1285   O << Indent << "WIDEN-CALL ";
1286 
1287   auto *CI = cast<CallInst>(getUnderlyingInstr());
1288   if (CI->getType()->isVoidTy())
1289     O << "void ";
1290   else {
1291     printAsOperand(O, SlotTracker);
1292     O << " = ";
1293   }
1294 
1295   O << "call @" << CI->getCalledFunction()->getName() << "(";
1296   printOperands(O, SlotTracker);
1297   O << ")";
1298 }
1299 
1300 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent,
1301                                 VPSlotTracker &SlotTracker) const {
1302   O << Indent << "WIDEN-SELECT ";
1303   printAsOperand(O, SlotTracker);
1304   O << " = select ";
1305   getOperand(0)->printAsOperand(O, SlotTracker);
1306   O << ", ";
1307   getOperand(1)->printAsOperand(O, SlotTracker);
1308   O << ", ";
1309   getOperand(2)->printAsOperand(O, SlotTracker);
1310   O << (InvariantCond ? " (condition is loop invariant)" : "");
1311 }
1312 
1313 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent,
1314                           VPSlotTracker &SlotTracker) const {
1315   O << Indent << "WIDEN ";
1316   printAsOperand(O, SlotTracker);
1317   O << " = " << getUnderlyingInstr()->getOpcodeName() << " ";
1318   printOperands(O, SlotTracker);
1319 }
1320 
1321 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent,
1322                                           VPSlotTracker &SlotTracker) const {
1323   O << Indent << "WIDEN-INDUCTION";
1324   if (getTruncInst()) {
1325     O << "\\l\"";
1326     O << " +\n" << Indent << "\"  " << VPlanIngredient(IV) << "\\l\"";
1327     O << " +\n" << Indent << "\"  ";
1328     getVPValue(0)->printAsOperand(O, SlotTracker);
1329   } else
1330     O << " " << VPlanIngredient(IV);
1331 
1332   O << ", ";
1333   getStepValue()->printAsOperand(O, SlotTracker);
1334 }
1335 
1336 void VPWidenPointerInductionRecipe::print(raw_ostream &O, const Twine &Indent,
1337                                           VPSlotTracker &SlotTracker) const {
1338   O << Indent << "EMIT ";
1339   printAsOperand(O, SlotTracker);
1340   O << " = WIDEN-POINTER-INDUCTION ";
1341   getStartValue()->printAsOperand(O, SlotTracker);
1342   O << ", " << *IndDesc.getStep();
1343 }
1344 
1345 #endif
1346 
1347 bool VPWidenIntOrFpInductionRecipe::isCanonical() const {
1348   auto *StartC = dyn_cast<ConstantInt>(getStartValue()->getLiveInIRValue());
1349   auto *StepC = dyn_cast<SCEVConstant>(getInductionDescriptor().getStep());
1350   return StartC && StartC->isZero() && StepC && StepC->isOne();
1351 }
1352 
1353 VPCanonicalIVPHIRecipe *VPScalarIVStepsRecipe::getCanonicalIV() const {
1354   return cast<VPCanonicalIVPHIRecipe>(getOperand(0));
1355 }
1356 
1357 bool VPScalarIVStepsRecipe::isCanonical() const {
1358   auto *CanIV = getCanonicalIV();
1359   // The start value of the steps-recipe must match the start value of the
1360   // canonical induction and it must step by 1.
1361   if (CanIV->getStartValue() != getStartValue())
1362     return false;
1363   auto *StepVPV = getStepValue();
1364   if (StepVPV->getDef())
1365     return false;
1366   auto *StepC = dyn_cast_or_null<ConstantInt>(StepVPV->getLiveInIRValue());
1367   return StepC && StepC->isOne();
1368 }
1369 
1370 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1371 void VPScalarIVStepsRecipe::print(raw_ostream &O, const Twine &Indent,
1372                                   VPSlotTracker &SlotTracker) const {
1373   O << Indent;
1374   printAsOperand(O, SlotTracker);
1375   O << Indent << "= SCALAR-STEPS ";
1376   printOperands(O, SlotTracker);
1377 }
1378 
1379 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent,
1380                              VPSlotTracker &SlotTracker) const {
1381   O << Indent << "WIDEN-GEP ";
1382   O << (IsPtrLoopInvariant ? "Inv" : "Var");
1383   size_t IndicesNumber = IsIndexLoopInvariant.size();
1384   for (size_t I = 0; I < IndicesNumber; ++I)
1385     O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]";
1386 
1387   O << " ";
1388   printAsOperand(O, SlotTracker);
1389   O << " = getelementptr ";
1390   printOperands(O, SlotTracker);
1391 }
1392 
1393 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1394                              VPSlotTracker &SlotTracker) const {
1395   O << Indent << "WIDEN-PHI ";
1396 
1397   auto *OriginalPhi = cast<PHINode>(getUnderlyingValue());
1398   // Unless all incoming values are modeled in VPlan  print the original PHI
1399   // directly.
1400   // TODO: Remove once all VPWidenPHIRecipe instances keep all relevant incoming
1401   // values as VPValues.
1402   if (getNumOperands() != OriginalPhi->getNumOperands()) {
1403     O << VPlanIngredient(OriginalPhi);
1404     return;
1405   }
1406 
1407   printAsOperand(O, SlotTracker);
1408   O << " = phi ";
1409   printOperands(O, SlotTracker);
1410 }
1411 
1412 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent,
1413                           VPSlotTracker &SlotTracker) const {
1414   O << Indent << "BLEND ";
1415   Phi->printAsOperand(O, false);
1416   O << " =";
1417   if (getNumIncomingValues() == 1) {
1418     // Not a User of any mask: not really blending, this is a
1419     // single-predecessor phi.
1420     O << " ";
1421     getIncomingValue(0)->printAsOperand(O, SlotTracker);
1422   } else {
1423     for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
1424       O << " ";
1425       getIncomingValue(I)->printAsOperand(O, SlotTracker);
1426       O << "/";
1427       getMask(I)->printAsOperand(O, SlotTracker);
1428     }
1429   }
1430 }
1431 
1432 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent,
1433                               VPSlotTracker &SlotTracker) const {
1434   O << Indent << "REDUCE ";
1435   printAsOperand(O, SlotTracker);
1436   O << " = ";
1437   getChainOp()->printAsOperand(O, SlotTracker);
1438   O << " +";
1439   if (isa<FPMathOperator>(getUnderlyingInstr()))
1440     O << getUnderlyingInstr()->getFastMathFlags();
1441   O << " reduce." << Instruction::getOpcodeName(RdxDesc->getOpcode()) << " (";
1442   getVecOp()->printAsOperand(O, SlotTracker);
1443   if (getCondOp()) {
1444     O << ", ";
1445     getCondOp()->printAsOperand(O, SlotTracker);
1446   }
1447   O << ")";
1448   if (RdxDesc->IntermediateStore)
1449     O << " (with final reduction value stored in invariant address sank "
1450          "outside of loop)";
1451 }
1452 
1453 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent,
1454                               VPSlotTracker &SlotTracker) const {
1455   O << Indent << (IsUniform ? "CLONE " : "REPLICATE ");
1456 
1457   if (!getUnderlyingInstr()->getType()->isVoidTy()) {
1458     printAsOperand(O, SlotTracker);
1459     O << " = ";
1460   }
1461   if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
1462     O << "call @" << CB->getCalledFunction()->getName() << "(";
1463     interleaveComma(make_range(op_begin(), op_begin() + (getNumOperands() - 1)),
1464                     O, [&O, &SlotTracker](VPValue *Op) {
1465                       Op->printAsOperand(O, SlotTracker);
1466                     });
1467     O << ")";
1468   } else {
1469     O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " ";
1470     printOperands(O, SlotTracker);
1471   }
1472 
1473   if (AlsoPack)
1474     O << " (S->V)";
1475 }
1476 
1477 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1478                                 VPSlotTracker &SlotTracker) const {
1479   O << Indent << "PHI-PREDICATED-INSTRUCTION ";
1480   printAsOperand(O, SlotTracker);
1481   O << " = ";
1482   printOperands(O, SlotTracker);
1483 }
1484 
1485 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent,
1486                                            VPSlotTracker &SlotTracker) const {
1487   O << Indent << "WIDEN ";
1488 
1489   if (!isStore()) {
1490     getVPSingleValue()->printAsOperand(O, SlotTracker);
1491     O << " = ";
1492   }
1493   O << Instruction::getOpcodeName(Ingredient.getOpcode()) << " ";
1494 
1495   printOperands(O, SlotTracker);
1496 }
1497 #endif
1498 
1499 void VPCanonicalIVPHIRecipe::execute(VPTransformState &State) {
1500   Value *Start = getStartValue()->getLiveInIRValue();
1501   PHINode *EntryPart = PHINode::Create(
1502       Start->getType(), 2, "index", &*State.CFG.PrevBB->getFirstInsertionPt());
1503 
1504   BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
1505   EntryPart->addIncoming(Start, VectorPH);
1506   EntryPart->setDebugLoc(DL);
1507   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
1508     State.set(this, EntryPart, Part);
1509 }
1510 
1511 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1512 void VPCanonicalIVPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1513                                    VPSlotTracker &SlotTracker) const {
1514   O << Indent << "EMIT ";
1515   printAsOperand(O, SlotTracker);
1516   O << " = CANONICAL-INDUCTION";
1517 }
1518 #endif
1519 
1520 void VPExpandSCEVRecipe::execute(VPTransformState &State) {
1521   assert(!State.Instance && "cannot be used in per-lane");
1522   const DataLayout &DL = State.CFG.PrevBB->getModule()->getDataLayout();
1523   SCEVExpander Exp(SE, DL, "induction");
1524 
1525   Value *Res = Exp.expandCodeFor(Expr, Expr->getType(),
1526                                  &*State.Builder.GetInsertPoint());
1527 
1528   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
1529     State.set(this, Res, Part);
1530 }
1531 
1532 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1533 void VPExpandSCEVRecipe::print(raw_ostream &O, const Twine &Indent,
1534                                VPSlotTracker &SlotTracker) const {
1535   O << Indent << "EMIT ";
1536   getVPSingleValue()->printAsOperand(O, SlotTracker);
1537   O << " = EXPAND SCEV " << *Expr;
1538 }
1539 #endif
1540 
1541 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) {
1542   Value *CanonicalIV = State.get(getOperand(0), 0);
1543   Type *STy = CanonicalIV->getType();
1544   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
1545   ElementCount VF = State.VF;
1546   Value *VStart = VF.isScalar()
1547                       ? CanonicalIV
1548                       : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
1549   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) {
1550     Value *VStep = createStepForVF(Builder, STy, VF, Part);
1551     if (VF.isVector()) {
1552       VStep = Builder.CreateVectorSplat(VF, VStep);
1553       VStep = Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
1554     }
1555     Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
1556     State.set(this, CanonicalVectorIV, Part);
1557   }
1558 }
1559 
1560 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1561 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent,
1562                                      VPSlotTracker &SlotTracker) const {
1563   O << Indent << "EMIT ";
1564   printAsOperand(O, SlotTracker);
1565   O << " = WIDEN-CANONICAL-INDUCTION ";
1566   printOperands(O, SlotTracker);
1567 }
1568 #endif
1569 
1570 void VPFirstOrderRecurrencePHIRecipe::execute(VPTransformState &State) {
1571   auto &Builder = State.Builder;
1572   // Create a vector from the initial value.
1573   auto *VectorInit = getStartValue()->getLiveInIRValue();
1574 
1575   Type *VecTy = State.VF.isScalar()
1576                     ? VectorInit->getType()
1577                     : VectorType::get(VectorInit->getType(), State.VF);
1578 
1579   BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
1580   if (State.VF.isVector()) {
1581     auto *IdxTy = Builder.getInt32Ty();
1582     auto *One = ConstantInt::get(IdxTy, 1);
1583     IRBuilder<>::InsertPointGuard Guard(Builder);
1584     Builder.SetInsertPoint(VectorPH->getTerminator());
1585     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
1586     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
1587     VectorInit = Builder.CreateInsertElement(
1588         PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
1589   }
1590 
1591   // Create a phi node for the new recurrence.
1592   PHINode *EntryPart = PHINode::Create(
1593       VecTy, 2, "vector.recur", &*State.CFG.PrevBB->getFirstInsertionPt());
1594   EntryPart->addIncoming(VectorInit, VectorPH);
1595   State.set(this, EntryPart, 0);
1596 }
1597 
1598 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1599 void VPFirstOrderRecurrencePHIRecipe::print(raw_ostream &O, const Twine &Indent,
1600                                             VPSlotTracker &SlotTracker) const {
1601   O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
1602   printAsOperand(O, SlotTracker);
1603   O << " = phi ";
1604   printOperands(O, SlotTracker);
1605 }
1606 #endif
1607 
1608 void VPReductionPHIRecipe::execute(VPTransformState &State) {
1609   PHINode *PN = cast<PHINode>(getUnderlyingValue());
1610   auto &Builder = State.Builder;
1611 
1612   // In order to support recurrences we need to be able to vectorize Phi nodes.
1613   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
1614   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
1615   // this value when we vectorize all of the instructions that use the PHI.
1616   bool ScalarPHI = State.VF.isScalar() || IsInLoop;
1617   Type *VecTy =
1618       ScalarPHI ? PN->getType() : VectorType::get(PN->getType(), State.VF);
1619 
1620   BasicBlock *HeaderBB = State.CFG.PrevBB;
1621   assert(State.CurrentVectorLoop->getHeader() == HeaderBB &&
1622          "recipe must be in the vector loop header");
1623   unsigned LastPartForNewPhi = isOrdered() ? 1 : State.UF;
1624   for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
1625     Value *EntryPart =
1626         PHINode::Create(VecTy, 2, "vec.phi", &*HeaderBB->getFirstInsertionPt());
1627     State.set(this, EntryPart, Part);
1628   }
1629 
1630   BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
1631 
1632   // Reductions do not have to start at zero. They can start with
1633   // any loop invariant values.
1634   VPValue *StartVPV = getStartValue();
1635   Value *StartV = StartVPV->getLiveInIRValue();
1636 
1637   Value *Iden = nullptr;
1638   RecurKind RK = RdxDesc.getRecurrenceKind();
1639   if (RecurrenceDescriptor::isMinMaxRecurrenceKind(RK) ||
1640       RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK)) {
1641     // MinMax reduction have the start value as their identify.
1642     if (ScalarPHI) {
1643       Iden = StartV;
1644     } else {
1645       IRBuilderBase::InsertPointGuard IPBuilder(Builder);
1646       Builder.SetInsertPoint(VectorPH->getTerminator());
1647       StartV = Iden =
1648           Builder.CreateVectorSplat(State.VF, StartV, "minmax.ident");
1649     }
1650   } else {
1651     Iden = RdxDesc.getRecurrenceIdentity(RK, VecTy->getScalarType(),
1652                                          RdxDesc.getFastMathFlags());
1653 
1654     if (!ScalarPHI) {
1655       Iden = Builder.CreateVectorSplat(State.VF, Iden);
1656       IRBuilderBase::InsertPointGuard IPBuilder(Builder);
1657       Builder.SetInsertPoint(VectorPH->getTerminator());
1658       Constant *Zero = Builder.getInt32(0);
1659       StartV = Builder.CreateInsertElement(Iden, StartV, Zero);
1660     }
1661   }
1662 
1663   for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
1664     Value *EntryPart = State.get(this, Part);
1665     // Make sure to add the reduction start value only to the
1666     // first unroll part.
1667     Value *StartVal = (Part == 0) ? StartV : Iden;
1668     cast<PHINode>(EntryPart)->addIncoming(StartVal, VectorPH);
1669   }
1670 }
1671 
1672 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1673 void VPReductionPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1674                                  VPSlotTracker &SlotTracker) const {
1675   O << Indent << "WIDEN-REDUCTION-PHI ";
1676 
1677   printAsOperand(O, SlotTracker);
1678   O << " = phi ";
1679   printOperands(O, SlotTracker);
1680 }
1681 #endif
1682 
1683 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
1684 
1685 void VPValue::replaceAllUsesWith(VPValue *New) {
1686   for (unsigned J = 0; J < getNumUsers();) {
1687     VPUser *User = Users[J];
1688     unsigned NumUsers = getNumUsers();
1689     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
1690       if (User->getOperand(I) == this)
1691         User->setOperand(I, New);
1692     // If a user got removed after updating the current user, the next user to
1693     // update will be moved to the current position, so we only need to
1694     // increment the index if the number of users did not change.
1695     if (NumUsers == getNumUsers())
1696       J++;
1697   }
1698 }
1699 
1700 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1701 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1702   if (const Value *UV = getUnderlyingValue()) {
1703     OS << "ir<";
1704     UV->printAsOperand(OS, false);
1705     OS << ">";
1706     return;
1707   }
1708 
1709   unsigned Slot = Tracker.getSlot(this);
1710   if (Slot == unsigned(-1))
1711     OS << "<badref>";
1712   else
1713     OS << "vp<%" << Tracker.getSlot(this) << ">";
1714 }
1715 
1716 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1717   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1718     Op->printAsOperand(O, SlotTracker);
1719   });
1720 }
1721 #endif
1722 
1723 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1724                                           Old2NewTy &Old2New,
1725                                           InterleavedAccessInfo &IAI) {
1726   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
1727   for (VPBlockBase *Base : RPOT) {
1728     visitBlock(Base, Old2New, IAI);
1729   }
1730 }
1731 
1732 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1733                                          InterleavedAccessInfo &IAI) {
1734   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1735     for (VPRecipeBase &VPI : *VPBB) {
1736       if (isa<VPHeaderPHIRecipe>(&VPI))
1737         continue;
1738       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1739       auto *VPInst = cast<VPInstruction>(&VPI);
1740       auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue());
1741       auto *IG = IAI.getInterleaveGroup(Inst);
1742       if (!IG)
1743         continue;
1744 
1745       auto NewIGIter = Old2New.find(IG);
1746       if (NewIGIter == Old2New.end())
1747         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1748             IG->getFactor(), IG->isReverse(), IG->getAlign());
1749 
1750       if (Inst == IG->getInsertPos())
1751         Old2New[IG]->setInsertPos(VPInst);
1752 
1753       InterleaveGroupMap[VPInst] = Old2New[IG];
1754       InterleaveGroupMap[VPInst]->insertMember(
1755           VPInst, IG->getIndex(Inst),
1756           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1757                                 : IG->getFactor()));
1758     }
1759   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1760     visitRegion(Region, Old2New, IAI);
1761   else
1762     llvm_unreachable("Unsupported kind of VPBlock.");
1763 }
1764 
1765 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1766                                                  InterleavedAccessInfo &IAI) {
1767   Old2NewTy Old2New;
1768   visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI);
1769 }
1770 
1771 void VPSlotTracker::assignSlot(const VPValue *V) {
1772   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
1773   Slots[V] = NextSlot++;
1774 }
1775 
1776 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1777 
1778   for (const auto &P : Plan.VPExternalDefs)
1779     assignSlot(P.second);
1780 
1781   assignSlot(&Plan.VectorTripCount);
1782   if (Plan.BackedgeTakenCount)
1783     assignSlot(Plan.BackedgeTakenCount);
1784 
1785   ReversePostOrderTraversal<
1786       VPBlockRecursiveTraversalWrapper<const VPBlockBase *>>
1787       RPOT(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>(
1788           Plan.getEntry()));
1789   for (const VPBasicBlock *VPBB :
1790        VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1791     for (const VPRecipeBase &Recipe : *VPBB)
1792       for (VPValue *Def : Recipe.definedValues())
1793         assignSlot(Def);
1794 }
1795 
1796 bool vputils::onlyFirstLaneUsed(VPValue *Def) {
1797   return all_of(Def->users(),
1798                 [Def](VPUser *U) { return U->onlyFirstLaneUsed(Def); });
1799 }
1800 
1801 VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr,
1802                                                 ScalarEvolution &SE) {
1803   if (auto *E = dyn_cast<SCEVConstant>(Expr))
1804     return Plan.getOrAddExternalDef(E->getValue());
1805   if (auto *E = dyn_cast<SCEVUnknown>(Expr))
1806     return Plan.getOrAddExternalDef(E->getValue());
1807 
1808   VPBasicBlock *Preheader = Plan.getEntry()->getEntryBasicBlock();
1809   VPValue *Step = new VPExpandSCEVRecipe(Expr, SE);
1810   Preheader->appendRecipe(cast<VPRecipeBase>(Step->getDef()));
1811   return Step;
1812 }
1813