xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision 946831ea2d7717a56383e284426527bc6de3808d)
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/LoopInfo.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/CFG.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/Instruction.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/IR/Value.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.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 "llvm/Transforms/Utils/LoopVersioning.h"
42 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
43 #include <cassert>
44 #include <string>
45 #include <vector>
46 
47 using namespace llvm;
48 extern cl::opt<bool> EnableVPlanNativePath;
49 
50 #define DEBUG_TYPE "vplan"
51 
52 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
53 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
54   const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
55   VPSlotTracker SlotTracker(
56       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
57   V.print(OS, SlotTracker);
58   return OS;
59 }
60 #endif
61 
62 Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder,
63                                 const ElementCount &VF) const {
64   switch (LaneKind) {
65   case VPLane::Kind::ScalableLast:
66     // Lane = RuntimeVF - VF.getKnownMinValue() + Lane
67     return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF),
68                              Builder.getInt32(VF.getKnownMinValue() - Lane));
69   case VPLane::Kind::First:
70     return Builder.getInt32(Lane);
71   }
72   llvm_unreachable("Unknown lane kind");
73 }
74 
75 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)
76     : SubclassID(SC), UnderlyingVal(UV), Def(Def) {
77   if (Def)
78     Def->addDefinedValue(this);
79 }
80 
81 VPValue::~VPValue() {
82   assert(Users.empty() && "trying to delete a VPValue with remaining users");
83   if (Def)
84     Def->removeDefinedValue(this);
85 }
86 
87 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
88 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
89   if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def))
90     R->print(OS, "", SlotTracker);
91   else
92     printAsOperand(OS, SlotTracker);
93 }
94 
95 void VPValue::dump() const {
96   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def);
97   VPSlotTracker SlotTracker(
98       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
99   print(dbgs(), SlotTracker);
100   dbgs() << "\n";
101 }
102 
103 void VPDef::dump() const {
104   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this);
105   VPSlotTracker SlotTracker(
106       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
107   print(dbgs(), "", SlotTracker);
108   dbgs() << "\n";
109 }
110 #endif
111 
112 VPRecipeBase *VPValue::getDefiningRecipe() {
113   return cast_or_null<VPRecipeBase>(Def);
114 }
115 
116 const VPRecipeBase *VPValue::getDefiningRecipe() const {
117   return cast_or_null<VPRecipeBase>(Def);
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::getExitingBasicBlock() const {
169   const VPBlockBase *Block = this;
170   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
171     Block = Region->getExiting();
172   return cast<VPBasicBlock>(Block);
173 }
174 
175 VPBasicBlock *VPBlockBase::getExitingBasicBlock() {
176   VPBlockBase *Block = this;
177   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
178     Block = Region->getExiting();
179   return cast<VPBasicBlock>(Block);
180 }
181 
182 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
183   if (!Successors.empty() || !Parent)
184     return this;
185   assert(Parent->getExiting() == this &&
186          "Block w/o successors not the exiting block 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(depth_first(Entry));
200 
201   for (VPBlockBase *Block : Blocks)
202     delete Block;
203 }
204 
205 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
206   iterator It = begin();
207   while (It != end() && It->isPhi())
208     It++;
209   return It;
210 }
211 
212 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) {
213   if (!Def->hasDefiningRecipe())
214     return Def->getLiveInIRValue();
215 
216   if (hasScalarValue(Def, Instance)) {
217     return Data
218         .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)];
219   }
220 
221   assert(hasVectorValue(Def, Instance.Part));
222   auto *VecPart = Data.PerPartOutput[Def][Instance.Part];
223   if (!VecPart->getType()->isVectorTy()) {
224     assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar");
225     return VecPart;
226   }
227   // TODO: Cache created scalar values.
228   Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF);
229   auto *Extract = Builder.CreateExtractElement(VecPart, Lane);
230   // set(Def, Extract, Instance);
231   return Extract;
232 }
233 BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) {
234   VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion();
235   return VPBB2IRBB[LoopRegion->getPreheaderVPBB()];
236 }
237 
238 void VPTransformState::addNewMetadata(Instruction *To,
239                                       const Instruction *Orig) {
240   // If the loop was versioned with memchecks, add the corresponding no-alias
241   // metadata.
242   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
243     LVer->annotateInstWithNoAlias(To, Orig);
244 }
245 
246 void VPTransformState::addMetadata(Instruction *To, Instruction *From) {
247   propagateMetadata(To, From);
248   addNewMetadata(To, From);
249 }
250 
251 void VPTransformState::addMetadata(ArrayRef<Value *> To, Instruction *From) {
252   for (Value *V : To) {
253     if (Instruction *I = dyn_cast<Instruction>(V))
254       addMetadata(I, From);
255   }
256 }
257 
258 void VPTransformState::setDebugLocFromInst(const Value *V) {
259   const Instruction *Inst = dyn_cast<Instruction>(V);
260   if (!Inst) {
261     Builder.SetCurrentDebugLocation(DebugLoc());
262     return;
263   }
264 
265   const DILocation *DIL = Inst->getDebugLoc();
266   // When a FSDiscriminator is enabled, we don't need to add the multiply
267   // factors to the discriminators.
268   if (DIL && Inst->getFunction()->shouldEmitDebugInfoForProfiling() &&
269       !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
270     // FIXME: For scalable vectors, assume vscale=1.
271     auto NewDIL =
272         DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
273     if (NewDIL)
274       Builder.SetCurrentDebugLocation(*NewDIL);
275     else
276       LLVM_DEBUG(dbgs() << "Failed to create new discriminator: "
277                         << DIL->getFilename() << " Line: " << DIL->getLine());
278   } else
279     Builder.SetCurrentDebugLocation(DIL);
280 }
281 
282 BasicBlock *
283 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
284   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
285   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
286   BasicBlock *PrevBB = CFG.PrevBB;
287   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
288                                          PrevBB->getParent(), CFG.ExitBB);
289   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
290 
291   // Hook up the new basic block to its predecessors.
292   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
293     VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();
294     auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();
295     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
296 
297     assert(PredBB && "Predecessor basic-block not found building successor.");
298     auto *PredBBTerminator = PredBB->getTerminator();
299     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
300 
301     auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator);
302     if (isa<UnreachableInst>(PredBBTerminator)) {
303       assert(PredVPSuccessors.size() == 1 &&
304              "Predecessor ending w/o branch must have single successor.");
305       DebugLoc DL = PredBBTerminator->getDebugLoc();
306       PredBBTerminator->eraseFromParent();
307       auto *Br = BranchInst::Create(NewBB, PredBB);
308       Br->setDebugLoc(DL);
309     } else if (TermBr && !TermBr->isConditional()) {
310       TermBr->setSuccessor(0, NewBB);
311     } else {
312       // Set each forward successor here when it is created, excluding
313       // backedges. A backward successor is set when the branch is created.
314       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
315       assert(!TermBr->getSuccessor(idx) &&
316              "Trying to reset an existing successor block.");
317       TermBr->setSuccessor(idx, NewBB);
318     }
319   }
320   return NewBB;
321 }
322 
323 void VPBasicBlock::execute(VPTransformState *State) {
324   bool Replica = State->Instance && !State->Instance->isFirstIteration();
325   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
326   VPBlockBase *SingleHPred = nullptr;
327   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
328 
329   auto IsLoopRegion = [](VPBlockBase *BB) {
330     auto *R = dyn_cast<VPRegionBlock>(BB);
331     return R && !R->isReplicator();
332   };
333 
334   // 1. Create an IR basic block, or reuse the last one or ExitBB if possible.
335   if (getPlan()->getVectorLoopRegion()->getSingleSuccessor() == this) {
336     // ExitBB can be re-used for the exit block of the Plan.
337     NewBB = State->CFG.ExitBB;
338     State->CFG.PrevBB = NewBB;
339 
340     // Update the branch instruction in the predecessor to branch to ExitBB.
341     VPBlockBase *PredVPB = getSingleHierarchicalPredecessor();
342     VPBasicBlock *ExitingVPBB = PredVPB->getExitingBasicBlock();
343     assert(PredVPB->getSingleSuccessor() == this &&
344            "predecessor must have the current block as only successor");
345     BasicBlock *ExitingBB = State->CFG.VPBB2IRBB[ExitingVPBB];
346     // The Exit block of a loop is always set to be successor 0 of the Exiting
347     // block.
348     cast<BranchInst>(ExitingBB->getTerminator())->setSuccessor(0, NewBB);
349   } else if (PrevVPBB && /* A */
350              !((SingleHPred = getSingleHierarchicalPredecessor()) &&
351                SingleHPred->getExitingBasicBlock() == PrevVPBB &&
352                PrevVPBB->getSingleHierarchicalSuccessor() &&
353                (SingleHPred->getParent() == getEnclosingLoopRegion() &&
354                 !IsLoopRegion(SingleHPred))) &&         /* B */
355              !(Replica && getPredecessors().empty())) { /* C */
356     // The last IR basic block is reused, as an optimization, in three cases:
357     // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null;
358     // B. when the current VPBB has a single (hierarchical) predecessor which
359     //    is PrevVPBB and the latter has a single (hierarchical) successor which
360     //    both are in the same non-replicator region; and
361     // C. when the current VPBB is an entry of a region replica - where PrevVPBB
362     //    is the exiting VPBB of this region from a previous instance, or the
363     //    predecessor of this region.
364 
365     NewBB = createEmptyBasicBlock(State->CFG);
366     State->Builder.SetInsertPoint(NewBB);
367     // Temporarily terminate with unreachable until CFG is rewired.
368     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
369     // Register NewBB in its loop. In innermost loops its the same for all
370     // BB's.
371     if (State->CurrentVectorLoop)
372       State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI);
373     State->Builder.SetInsertPoint(Terminator);
374     State->CFG.PrevBB = NewBB;
375   }
376 
377   // 2. Fill the IR basic block with IR instructions.
378   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
379                     << " in BB:" << NewBB->getName() << '\n');
380 
381   State->CFG.VPBB2IRBB[this] = NewBB;
382   State->CFG.PrevVPBB = this;
383 
384   for (VPRecipeBase &Recipe : Recipes)
385     Recipe.execute(*State);
386 
387   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
388 }
389 
390 void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
391   for (VPRecipeBase &R : Recipes) {
392     for (auto *Def : R.definedValues())
393       Def->replaceAllUsesWith(NewValue);
394 
395     for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
396       R.setOperand(I, NewValue);
397   }
398 }
399 
400 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) {
401   assert((SplitAt == end() || SplitAt->getParent() == this) &&
402          "can only split at a position in the same block");
403 
404   SmallVector<VPBlockBase *, 2> Succs(successors());
405   // First, disconnect the current block from its successors.
406   for (VPBlockBase *Succ : Succs)
407     VPBlockUtils::disconnectBlocks(this, Succ);
408 
409   // Create new empty block after the block to split.
410   auto *SplitBlock = new VPBasicBlock(getName() + ".split");
411   VPBlockUtils::insertBlockAfter(SplitBlock, this);
412 
413   // Add successors for block to split to new block.
414   for (VPBlockBase *Succ : Succs)
415     VPBlockUtils::connectBlocks(SplitBlock, Succ);
416 
417   // Finally, move the recipes starting at SplitAt to new block.
418   for (VPRecipeBase &ToMove :
419        make_early_inc_range(make_range(SplitAt, this->end())))
420     ToMove.moveBefore(*SplitBlock, SplitBlock->end());
421 
422   return SplitBlock;
423 }
424 
425 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() {
426   VPRegionBlock *P = getParent();
427   if (P && P->isReplicator()) {
428     P = P->getParent();
429     assert(!cast<VPRegionBlock>(P)->isReplicator() &&
430            "unexpected nested replicate regions");
431   }
432   return P;
433 }
434 
435 static bool hasConditionalTerminator(const VPBasicBlock *VPBB) {
436   if (VPBB->empty()) {
437     assert(
438         VPBB->getNumSuccessors() < 2 &&
439         "block with multiple successors doesn't have a recipe as terminator");
440     return false;
441   }
442 
443   const VPRecipeBase *R = &VPBB->back();
444   auto *VPI = dyn_cast<VPInstruction>(R);
445   bool IsCondBranch =
446       isa<VPBranchOnMaskRecipe>(R) ||
447       (VPI && (VPI->getOpcode() == VPInstruction::BranchOnCond ||
448                VPI->getOpcode() == VPInstruction::BranchOnCount));
449   (void)IsCondBranch;
450 
451   if (VPBB->getNumSuccessors() >= 2 || VPBB->isExiting()) {
452     assert(IsCondBranch && "block with multiple successors not terminated by "
453                            "conditional branch recipe");
454 
455     return true;
456   }
457 
458   assert(
459       !IsCondBranch &&
460       "block with 0 or 1 successors terminated by conditional branch recipe");
461   return false;
462 }
463 
464 VPRecipeBase *VPBasicBlock::getTerminator() {
465   if (hasConditionalTerminator(this))
466     return &back();
467   return nullptr;
468 }
469 
470 const VPRecipeBase *VPBasicBlock::getTerminator() const {
471   if (hasConditionalTerminator(this))
472     return &back();
473   return nullptr;
474 }
475 
476 bool VPBasicBlock::isExiting() const {
477   return getParent()->getExitingBasicBlock() == this;
478 }
479 
480 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
481 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {
482   if (getSuccessors().empty()) {
483     O << Indent << "No successors\n";
484   } else {
485     O << Indent << "Successor(s): ";
486     ListSeparator LS;
487     for (auto *Succ : getSuccessors())
488       O << LS << Succ->getName();
489     O << '\n';
490   }
491 }
492 
493 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
494                          VPSlotTracker &SlotTracker) const {
495   O << Indent << getName() << ":\n";
496 
497   auto RecipeIndent = Indent + "  ";
498   for (const VPRecipeBase &Recipe : *this) {
499     Recipe.print(O, RecipeIndent, SlotTracker);
500     O << '\n';
501   }
502 
503   printSuccessors(O, Indent);
504 }
505 #endif
506 
507 void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
508   for (VPBlockBase *Block : depth_first(Entry))
509     // Drop all references in VPBasicBlocks and replace all uses with
510     // DummyValue.
511     Block->dropAllReferences(NewValue);
512 }
513 
514 void VPRegionBlock::execute(VPTransformState *State) {
515   ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry);
516 
517   if (!isReplicator()) {
518     // Create and register the new vector loop.
519     Loop *PrevLoop = State->CurrentVectorLoop;
520     State->CurrentVectorLoop = State->LI->AllocateLoop();
521     BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()];
522     Loop *ParentLoop = State->LI->getLoopFor(VectorPH);
523 
524     // Insert the new loop into the loop nest and register the new basic blocks
525     // before calling any utilities such as SCEV that require valid LoopInfo.
526     if (ParentLoop)
527       ParentLoop->addChildLoop(State->CurrentVectorLoop);
528     else
529       State->LI->addTopLevelLoop(State->CurrentVectorLoop);
530 
531     // Visit the VPBlocks connected to "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     State->CurrentVectorLoop = PrevLoop;
538     return;
539   }
540 
541   assert(!State->Instance && "Replicating a Region with non-null instance.");
542 
543   // Enter replicating mode.
544   State->Instance = VPIteration(0, 0);
545 
546   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
547     State->Instance->Part = Part;
548     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
549     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
550          ++Lane) {
551       State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);
552       // Visit the VPBlocks connected to \p this, starting from it.
553       for (VPBlockBase *Block : RPOT) {
554         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
555         Block->execute(State);
556       }
557     }
558   }
559 
560   // Exit replicating mode.
561   State->Instance.reset();
562 }
563 
564 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
565 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent,
566                           VPSlotTracker &SlotTracker) const {
567   O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
568   auto NewIndent = Indent + "  ";
569   for (auto *BlockBase : depth_first(Entry)) {
570     O << '\n';
571     BlockBase->print(O, NewIndent, SlotTracker);
572   }
573   O << Indent << "}\n";
574 
575   printSuccessors(O, Indent);
576 }
577 #endif
578 
579 VPActiveLaneMaskPHIRecipe *VPlan::getActiveLaneMaskPhi() {
580   VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
581   for (VPRecipeBase &R : Header->phis()) {
582     if (isa<VPActiveLaneMaskPHIRecipe>(&R))
583       return cast<VPActiveLaneMaskPHIRecipe>(&R);
584   }
585   return nullptr;
586 }
587 
588 static bool canSimplifyBranchOnCond(VPInstruction *Term) {
589   VPInstruction *Not = dyn_cast<VPInstruction>(Term->getOperand(0));
590   if (!Not || Not->getOpcode() != VPInstruction::Not)
591     return false;
592 
593   VPInstruction *ALM = dyn_cast<VPInstruction>(Not->getOperand(0));
594   return ALM && ALM->getOpcode() == VPInstruction::ActiveLaneMask;
595 }
596 
597 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,
598                              Value *CanonicalIVStartValue,
599                              VPTransformState &State,
600                              bool IsEpilogueVectorization) {
601 
602   VPBasicBlock *ExitingVPBB = getVectorLoopRegion()->getExitingBasicBlock();
603   auto *Term = dyn_cast<VPInstruction>(&ExitingVPBB->back());
604   // Try to simplify the branch condition if TC <= VF * UF when preparing to
605   // execute the plan for the main vector loop. We only do this if the
606   // terminator is:
607   //  1. BranchOnCount, or
608   //  2. BranchOnCond where the input is Not(ActiveLaneMask).
609   if (!IsEpilogueVectorization && Term && isa<ConstantInt>(TripCountV) &&
610       (Term->getOpcode() == VPInstruction::BranchOnCount ||
611        (Term->getOpcode() == VPInstruction::BranchOnCond &&
612         canSimplifyBranchOnCond(Term)))) {
613     ConstantInt *C = cast<ConstantInt>(TripCountV);
614     uint64_t TCVal = C->getZExtValue();
615     if (TCVal && TCVal <= State.VF.getKnownMinValue() * State.UF) {
616       auto *BOC =
617           new VPInstruction(VPInstruction::BranchOnCond,
618                             {getOrAddExternalDef(State.Builder.getTrue())});
619       Term->eraseFromParent();
620       ExitingVPBB->appendRecipe(BOC);
621       // TODO: Further simplifications are possible
622       //      1. Replace inductions with constants.
623       //      2. Replace vector loop region with VPBasicBlock.
624     }
625   }
626 
627   // Check if the trip count is needed, and if so build it.
628   if (TripCount && TripCount->getNumUsers()) {
629     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
630       State.set(TripCount, TripCountV, Part);
631   }
632 
633   // Check if the backedge taken count is needed, and if so build it.
634   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
635     IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
636     auto *TCMO = Builder.CreateSub(TripCountV,
637                                    ConstantInt::get(TripCountV->getType(), 1),
638                                    "trip.count.minus.1");
639     auto VF = State.VF;
640     Value *VTCMO =
641         VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
642     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
643       State.set(BackedgeTakenCount, VTCMO, Part);
644   }
645 
646   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
647     State.set(&VectorTripCount, VectorTripCountV, Part);
648 
649   // When vectorizing the epilogue loop, the canonical induction start value
650   // needs to be changed from zero to the value after the main vector loop.
651   // FIXME: Improve modeling for canonical IV start values in the epilogue loop.
652   if (CanonicalIVStartValue) {
653     VPValue *VPV = getOrAddExternalDef(CanonicalIVStartValue);
654     auto *IV = getCanonicalIV();
655     assert(all_of(IV->users(),
656                   [](const VPUser *U) {
657                     if (isa<VPScalarIVStepsRecipe>(U) ||
658                         isa<VPDerivedIVRecipe>(U))
659                       return true;
660                     auto *VPI = cast<VPInstruction>(U);
661                     return VPI->getOpcode() ==
662                                VPInstruction::CanonicalIVIncrement ||
663                            VPI->getOpcode() ==
664                                VPInstruction::CanonicalIVIncrementNUW;
665                   }) &&
666            "the canonical IV should only be used by its increments or "
667            "ScalarIVSteps when "
668            "resetting the start value");
669     IV->setOperand(0, VPV);
670   }
671 }
672 
673 /// Generate the code inside the preheader and body of the vectorized loop.
674 /// Assumes a single pre-header basic-block was created for this. Introduce
675 /// additional basic-blocks as needed, and fill them all.
676 void VPlan::execute(VPTransformState *State) {
677   // Set the reverse mapping from VPValues to Values for code generation.
678   for (auto &Entry : Value2VPValue)
679     State->VPValue2Value[Entry.second] = Entry.first;
680 
681   // Initialize CFG state.
682   State->CFG.PrevVPBB = nullptr;
683   State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();
684   BasicBlock *VectorPreHeader = State->CFG.PrevBB;
685   State->Builder.SetInsertPoint(VectorPreHeader->getTerminator());
686 
687   // Generate code in the loop pre-header and body.
688   for (VPBlockBase *Block : depth_first(Entry))
689     Block->execute(State);
690 
691   VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock();
692   BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB];
693 
694   // Fix the latch value of canonical, reduction and first-order recurrences
695   // phis in the vector loop.
696   VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
697   for (VPRecipeBase &R : Header->phis()) {
698     // Skip phi-like recipes that generate their backedege values themselves.
699     if (isa<VPWidenPHIRecipe>(&R))
700       continue;
701 
702     if (isa<VPWidenPointerInductionRecipe>(&R) ||
703         isa<VPWidenIntOrFpInductionRecipe>(&R)) {
704       PHINode *Phi = nullptr;
705       if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {
706         Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));
707       } else {
708         auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);
709         // TODO: Split off the case that all users of a pointer phi are scalar
710         // from the VPWidenPointerInductionRecipe.
711         if (WidenPhi->onlyScalarsGenerated(State->VF))
712           continue;
713 
714         auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));
715         Phi = cast<PHINode>(GEP->getPointerOperand());
716       }
717 
718       Phi->setIncomingBlock(1, VectorLatchBB);
719 
720       // Move the last step to the end of the latch block. This ensures
721       // consistent placement of all induction updates.
722       Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));
723       Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());
724       continue;
725     }
726 
727     auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
728     // For  canonical IV, first-order recurrences and in-order reduction phis,
729     // only a single part is generated, which provides the last part from the
730     // previous iteration. For non-ordered reductions all UF parts are
731     // generated.
732     bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) ||
733                             isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) ||
734                             (isa<VPReductionPHIRecipe>(PhiR) &&
735                              cast<VPReductionPHIRecipe>(PhiR)->isOrdered());
736     unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
737 
738     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
739       Value *Phi = State->get(PhiR, Part);
740       Value *Val = State->get(PhiR->getBackedgeValue(),
741                               SinglePartNeeded ? State->UF - 1 : Part);
742       cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
743     }
744   }
745 
746   // We do not attempt to preserve DT for outer loop vectorization currently.
747   if (!EnableVPlanNativePath) {
748     BasicBlock *VectorHeaderBB = State->CFG.VPBB2IRBB[Header];
749     State->DT->addNewBlock(VectorHeaderBB, VectorPreHeader);
750     updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB,
751                         State->CFG.ExitBB);
752   }
753 }
754 
755 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
756 LLVM_DUMP_METHOD
757 void VPlan::print(raw_ostream &O) const {
758   VPSlotTracker SlotTracker(this);
759 
760   O << "VPlan '" << Name << "' {";
761 
762   if (VectorTripCount.getNumUsers() > 0) {
763     O << "\nLive-in ";
764     VectorTripCount.printAsOperand(O, SlotTracker);
765     O << " = vector-trip-count\n";
766   }
767 
768   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
769     O << "\nLive-in ";
770     BackedgeTakenCount->printAsOperand(O, SlotTracker);
771     O << " = backedge-taken count\n";
772   }
773 
774   for (const VPBlockBase *Block : depth_first(getEntry())) {
775     O << '\n';
776     Block->print(O, "", SlotTracker);
777   }
778 
779   if (!LiveOuts.empty())
780     O << "\n";
781   for (const auto &KV : LiveOuts) {
782     O << "Live-out ";
783     KV.second->getPhi()->printAsOperand(O);
784     O << " = ";
785     KV.second->getOperand(0)->printAsOperand(O, SlotTracker);
786     O << "\n";
787   }
788 
789   O << "}\n";
790 }
791 
792 LLVM_DUMP_METHOD
793 void VPlan::printDOT(raw_ostream &O) const {
794   VPlanPrinter Printer(O, *this);
795   Printer.dump();
796 }
797 
798 LLVM_DUMP_METHOD
799 void VPlan::dump() const { print(dbgs()); }
800 #endif
801 
802 void VPlan::addLiveOut(PHINode *PN, VPValue *V) {
803   assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists");
804   LiveOuts.insert({PN, new VPLiveOut(PN, V)});
805 }
806 
807 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB,
808                                 BasicBlock *LoopLatchBB,
809                                 BasicBlock *LoopExitBB) {
810   // The vector body may be more than a single basic-block by this point.
811   // Update the dominator tree information inside the vector body by propagating
812   // it from header to latch, expecting only triangular control-flow, if any.
813   BasicBlock *PostDomSucc = nullptr;
814   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
815     // Get the list of successors of this block.
816     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
817     assert(Succs.size() <= 2 &&
818            "Basic block in vector loop has more than 2 successors.");
819     PostDomSucc = Succs[0];
820     if (Succs.size() == 1) {
821       assert(PostDomSucc->getSinglePredecessor() &&
822              "PostDom successor has more than one predecessor.");
823       DT->addNewBlock(PostDomSucc, BB);
824       continue;
825     }
826     BasicBlock *InterimSucc = Succs[1];
827     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
828       PostDomSucc = Succs[1];
829       InterimSucc = Succs[0];
830     }
831     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
832            "One successor of a basic block does not lead to the other.");
833     assert(InterimSucc->getSinglePredecessor() &&
834            "Interim successor has more than one predecessor.");
835     assert(PostDomSucc->hasNPredecessors(2) &&
836            "PostDom successor has more than two predecessors.");
837     DT->addNewBlock(InterimSucc, BB);
838     DT->addNewBlock(PostDomSucc, BB);
839   }
840   // Latch block is a new dominator for the loop exit.
841   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
842   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
843 }
844 
845 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
846 
847 Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
848   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
849          Twine(getOrCreateBID(Block));
850 }
851 
852 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
853   const std::string &Name = Block->getName();
854   if (!Name.empty())
855     return Name;
856   return "VPB" + Twine(getOrCreateBID(Block));
857 }
858 
859 void VPlanPrinter::dump() {
860   Depth = 1;
861   bumpIndent(0);
862   OS << "digraph VPlan {\n";
863   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
864   if (!Plan.getName().empty())
865     OS << "\\n" << DOT::EscapeString(Plan.getName());
866   if (Plan.BackedgeTakenCount) {
867     OS << ", where:\\n";
868     Plan.BackedgeTakenCount->print(OS, SlotTracker);
869     OS << " := BackedgeTakenCount";
870   }
871   OS << "\"]\n";
872   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
873   OS << "edge [fontname=Courier, fontsize=30]\n";
874   OS << "compound=true\n";
875 
876   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
877     dumpBlock(Block);
878 
879   OS << "}\n";
880 }
881 
882 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
883   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
884     dumpBasicBlock(BasicBlock);
885   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
886     dumpRegion(Region);
887   else
888     llvm_unreachable("Unsupported kind of VPBlock.");
889 }
890 
891 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
892                             bool Hidden, const Twine &Label) {
893   // Due to "dot" we print an edge between two regions as an edge between the
894   // exiting basic block and the entry basic of the respective regions.
895   const VPBlockBase *Tail = From->getExitingBasicBlock();
896   const VPBlockBase *Head = To->getEntryBasicBlock();
897   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
898   OS << " [ label=\"" << Label << '\"';
899   if (Tail != From)
900     OS << " ltail=" << getUID(From);
901   if (Head != To)
902     OS << " lhead=" << getUID(To);
903   if (Hidden)
904     OS << "; splines=none";
905   OS << "]\n";
906 }
907 
908 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
909   auto &Successors = Block->getSuccessors();
910   if (Successors.size() == 1)
911     drawEdge(Block, Successors.front(), false, "");
912   else if (Successors.size() == 2) {
913     drawEdge(Block, Successors.front(), false, "T");
914     drawEdge(Block, Successors.back(), false, "F");
915   } else {
916     unsigned SuccessorNumber = 0;
917     for (auto *Successor : Successors)
918       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
919   }
920 }
921 
922 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
923   // Implement dot-formatted dump by performing plain-text dump into the
924   // temporary storage followed by some post-processing.
925   OS << Indent << getUID(BasicBlock) << " [label =\n";
926   bumpIndent(1);
927   std::string Str;
928   raw_string_ostream SS(Str);
929   // Use no indentation as we need to wrap the lines into quotes ourselves.
930   BasicBlock->print(SS, "", SlotTracker);
931 
932   // We need to process each line of the output separately, so split
933   // single-string plain-text dump.
934   SmallVector<StringRef, 0> Lines;
935   StringRef(Str).rtrim('\n').split(Lines, "\n");
936 
937   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
938     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
939   };
940 
941   // Don't need the "+" after the last line.
942   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
943     EmitLine(Line, " +\n");
944   EmitLine(Lines.back(), "\n");
945 
946   bumpIndent(-1);
947   OS << Indent << "]\n";
948 
949   dumpEdges(BasicBlock);
950 }
951 
952 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
953   OS << Indent << "subgraph " << getUID(Region) << " {\n";
954   bumpIndent(1);
955   OS << Indent << "fontname=Courier\n"
956      << Indent << "label=\""
957      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
958      << DOT::EscapeString(Region->getName()) << "\"\n";
959   // Dump the blocks of the region.
960   assert(Region->getEntry() && "Region contains no inner blocks.");
961   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
962     dumpBlock(Block);
963   bumpIndent(-1);
964   OS << Indent << "}\n";
965   dumpEdges(Region);
966 }
967 
968 void VPlanIngredient::print(raw_ostream &O) const {
969   if (auto *Inst = dyn_cast<Instruction>(V)) {
970     if (!Inst->getType()->isVoidTy()) {
971       Inst->printAsOperand(O, false);
972       O << " = ";
973     }
974     O << Inst->getOpcodeName() << " ";
975     unsigned E = Inst->getNumOperands();
976     if (E > 0) {
977       Inst->getOperand(0)->printAsOperand(O, false);
978       for (unsigned I = 1; I < E; ++I)
979         Inst->getOperand(I)->printAsOperand(O << ", ", false);
980     }
981   } else // !Inst
982     V->printAsOperand(O, false);
983 }
984 
985 #endif
986 
987 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
988 
989 void VPValue::replaceAllUsesWith(VPValue *New) {
990   for (unsigned J = 0; J < getNumUsers();) {
991     VPUser *User = Users[J];
992     unsigned NumUsers = getNumUsers();
993     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
994       if (User->getOperand(I) == this)
995         User->setOperand(I, New);
996     // If a user got removed after updating the current user, the next user to
997     // update will be moved to the current position, so we only need to
998     // increment the index if the number of users did not change.
999     if (NumUsers == getNumUsers())
1000       J++;
1001   }
1002 }
1003 
1004 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1005 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1006   if (const Value *UV = getUnderlyingValue()) {
1007     OS << "ir<";
1008     UV->printAsOperand(OS, false);
1009     OS << ">";
1010     return;
1011   }
1012 
1013   unsigned Slot = Tracker.getSlot(this);
1014   if (Slot == unsigned(-1))
1015     OS << "<badref>";
1016   else
1017     OS << "vp<%" << Tracker.getSlot(this) << ">";
1018 }
1019 
1020 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1021   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1022     Op->printAsOperand(O, SlotTracker);
1023   });
1024 }
1025 #endif
1026 
1027 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1028                                           Old2NewTy &Old2New,
1029                                           InterleavedAccessInfo &IAI) {
1030   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
1031   for (VPBlockBase *Base : RPOT) {
1032     visitBlock(Base, Old2New, IAI);
1033   }
1034 }
1035 
1036 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1037                                          InterleavedAccessInfo &IAI) {
1038   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1039     for (VPRecipeBase &VPI : *VPBB) {
1040       if (isa<VPHeaderPHIRecipe>(&VPI))
1041         continue;
1042       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1043       auto *VPInst = cast<VPInstruction>(&VPI);
1044 
1045       auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue());
1046       if (!Inst)
1047         continue;
1048       auto *IG = IAI.getInterleaveGroup(Inst);
1049       if (!IG)
1050         continue;
1051 
1052       auto NewIGIter = Old2New.find(IG);
1053       if (NewIGIter == Old2New.end())
1054         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1055             IG->getFactor(), IG->isReverse(), IG->getAlign());
1056 
1057       if (Inst == IG->getInsertPos())
1058         Old2New[IG]->setInsertPos(VPInst);
1059 
1060       InterleaveGroupMap[VPInst] = Old2New[IG];
1061       InterleaveGroupMap[VPInst]->insertMember(
1062           VPInst, IG->getIndex(Inst),
1063           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1064                                 : IG->getFactor()));
1065     }
1066   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1067     visitRegion(Region, Old2New, IAI);
1068   else
1069     llvm_unreachable("Unsupported kind of VPBlock.");
1070 }
1071 
1072 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1073                                                  InterleavedAccessInfo &IAI) {
1074   Old2NewTy Old2New;
1075   visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI);
1076 }
1077 
1078 void VPSlotTracker::assignSlot(const VPValue *V) {
1079   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
1080   Slots[V] = NextSlot++;
1081 }
1082 
1083 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1084 
1085   for (const auto &P : Plan.VPExternalDefs)
1086     assignSlot(P.second);
1087 
1088   assignSlot(&Plan.VectorTripCount);
1089   if (Plan.BackedgeTakenCount)
1090     assignSlot(Plan.BackedgeTakenCount);
1091 
1092   ReversePostOrderTraversal<
1093       VPBlockRecursiveTraversalWrapper<const VPBlockBase *>>
1094       RPOT(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>(
1095           Plan.getEntry()));
1096   for (const VPBasicBlock *VPBB :
1097        VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1098     for (const VPRecipeBase &Recipe : *VPBB)
1099       for (VPValue *Def : Recipe.definedValues())
1100         assignSlot(Def);
1101 }
1102 
1103 bool vputils::onlyFirstLaneUsed(VPValue *Def) {
1104   return all_of(Def->users(),
1105                 [Def](VPUser *U) { return U->onlyFirstLaneUsed(Def); });
1106 }
1107 
1108 VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr,
1109                                                 ScalarEvolution &SE) {
1110   if (auto *E = dyn_cast<SCEVConstant>(Expr))
1111     return Plan.getOrAddExternalDef(E->getValue());
1112   if (auto *E = dyn_cast<SCEVUnknown>(Expr))
1113     return Plan.getOrAddExternalDef(E->getValue());
1114 
1115   VPBasicBlock *Preheader = Plan.getEntry()->getEntryBasicBlock();
1116   VPExpandSCEVRecipe *Step = new VPExpandSCEVRecipe(Expr, SE);
1117   Preheader->appendRecipe(Step);
1118   return Step;
1119 }
1120