xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlanTransforms.cpp (revision 16d19aaedf347f452c22c7254934753b19803d5d)
1 //===-- VPlanTransforms.cpp - Utility VPlan to VPlan transforms -----------===//
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 file implements a set of utility VPlan to VPlan transformations.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "VPlanTransforms.h"
15 #include "VPRecipeBuilder.h"
16 #include "VPlan.h"
17 #include "VPlanAnalysis.h"
18 #include "VPlanCFG.h"
19 #include "VPlanDominatorTree.h"
20 #include "VPlanPatternMatch.h"
21 #include "VPlanUtils.h"
22 #include "llvm/ADT/PostOrderIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/TypeSwitch.h"
26 #include "llvm/Analysis/IVDescriptors.h"
27 #include "llvm/Analysis/VectorUtils.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/PatternMatch.h"
30 
31 using namespace llvm;
32 
33 void VPlanTransforms::VPInstructionsToVPRecipes(
34     VPlanPtr &Plan,
35     function_ref<const InductionDescriptor *(PHINode *)>
36         GetIntOrFpInductionDescriptor,
37     ScalarEvolution &SE, const TargetLibraryInfo &TLI) {
38 
39   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> RPOT(
40       Plan->getVectorLoopRegion());
41   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
42     // Skip blocks outside region
43     if (!VPBB->getParent())
44       break;
45     VPRecipeBase *Term = VPBB->getTerminator();
46     auto EndIter = Term ? Term->getIterator() : VPBB->end();
47     // Introduce each ingredient into VPlan.
48     for (VPRecipeBase &Ingredient :
49          make_early_inc_range(make_range(VPBB->begin(), EndIter))) {
50 
51       VPValue *VPV = Ingredient.getVPSingleValue();
52       Instruction *Inst = cast<Instruction>(VPV->getUnderlyingValue());
53 
54       VPRecipeBase *NewRecipe = nullptr;
55       if (auto *VPPhi = dyn_cast<VPWidenPHIRecipe>(&Ingredient)) {
56         auto *Phi = cast<PHINode>(VPPhi->getUnderlyingValue());
57         const auto *II = GetIntOrFpInductionDescriptor(Phi);
58         if (!II)
59           continue;
60 
61         VPValue *Start = Plan->getOrAddLiveIn(II->getStartValue());
62         VPValue *Step =
63             vputils::getOrCreateVPValueForSCEVExpr(*Plan, II->getStep(), SE);
64         NewRecipe = new VPWidenIntOrFpInductionRecipe(
65             Phi, Start, Step, &Plan->getVF(), *II, Ingredient.getDebugLoc());
66       } else {
67         assert(isa<VPInstruction>(&Ingredient) &&
68                "only VPInstructions expected here");
69         assert(!isa<PHINode>(Inst) && "phis should be handled above");
70         // Create VPWidenMemoryRecipe for loads and stores.
71         if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
72           NewRecipe = new VPWidenLoadRecipe(
73               *Load, Ingredient.getOperand(0), nullptr /*Mask*/,
74               false /*Consecutive*/, false /*Reverse*/,
75               Ingredient.getDebugLoc());
76         } else if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
77           NewRecipe = new VPWidenStoreRecipe(
78               *Store, Ingredient.getOperand(1), Ingredient.getOperand(0),
79               nullptr /*Mask*/, false /*Consecutive*/, false /*Reverse*/,
80               Ingredient.getDebugLoc());
81         } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
82           NewRecipe = new VPWidenGEPRecipe(GEP, Ingredient.operands());
83         } else if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
84           NewRecipe = new VPWidenIntrinsicRecipe(
85               *CI, getVectorIntrinsicIDForCall(CI, &TLI),
86               {Ingredient.op_begin(), Ingredient.op_end() - 1}, CI->getType(),
87               CI->getDebugLoc());
88         } else if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
89           NewRecipe = new VPWidenSelectRecipe(*SI, Ingredient.operands());
90         } else if (auto *CI = dyn_cast<CastInst>(Inst)) {
91           NewRecipe = new VPWidenCastRecipe(
92               CI->getOpcode(), Ingredient.getOperand(0), CI->getType(), *CI);
93         } else {
94           NewRecipe = new VPWidenRecipe(*Inst, Ingredient.operands());
95         }
96       }
97 
98       NewRecipe->insertBefore(&Ingredient);
99       if (NewRecipe->getNumDefinedValues() == 1)
100         VPV->replaceAllUsesWith(NewRecipe->getVPSingleValue());
101       else
102         assert(NewRecipe->getNumDefinedValues() == 0 &&
103                "Only recpies with zero or one defined values expected");
104       Ingredient.eraseFromParent();
105     }
106   }
107 }
108 
109 static bool sinkScalarOperands(VPlan &Plan) {
110   auto Iter = vp_depth_first_deep(Plan.getEntry());
111   bool Changed = false;
112   // First, collect the operands of all recipes in replicate blocks as seeds for
113   // sinking.
114   SetVector<std::pair<VPBasicBlock *, VPSingleDefRecipe *>> WorkList;
115   for (VPRegionBlock *VPR : VPBlockUtils::blocksOnly<VPRegionBlock>(Iter)) {
116     VPBasicBlock *EntryVPBB = VPR->getEntryBasicBlock();
117     if (!VPR->isReplicator() || EntryVPBB->getSuccessors().size() != 2)
118       continue;
119     VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(EntryVPBB->getSuccessors()[0]);
120     if (!VPBB || VPBB->getSingleSuccessor() != VPR->getExitingBasicBlock())
121       continue;
122     for (auto &Recipe : *VPBB) {
123       for (VPValue *Op : Recipe.operands())
124         if (auto *Def =
125                 dyn_cast_or_null<VPSingleDefRecipe>(Op->getDefiningRecipe()))
126           WorkList.insert(std::make_pair(VPBB, Def));
127     }
128   }
129 
130   bool ScalarVFOnly = Plan.hasScalarVFOnly();
131   // Try to sink each replicate or scalar IV steps recipe in the worklist.
132   for (unsigned I = 0; I != WorkList.size(); ++I) {
133     VPBasicBlock *SinkTo;
134     VPSingleDefRecipe *SinkCandidate;
135     std::tie(SinkTo, SinkCandidate) = WorkList[I];
136     if (SinkCandidate->getParent() == SinkTo ||
137         SinkCandidate->mayHaveSideEffects() ||
138         SinkCandidate->mayReadOrWriteMemory())
139       continue;
140     if (auto *RepR = dyn_cast<VPReplicateRecipe>(SinkCandidate)) {
141       if (!ScalarVFOnly && RepR->isUniform())
142         continue;
143     } else if (!isa<VPScalarIVStepsRecipe>(SinkCandidate))
144       continue;
145 
146     bool NeedsDuplicating = false;
147     // All recipe users of the sink candidate must be in the same block SinkTo
148     // or all users outside of SinkTo must be uniform-after-vectorization (
149     // i.e., only first lane is used) . In the latter case, we need to duplicate
150     // SinkCandidate.
151     auto CanSinkWithUser = [SinkTo, &NeedsDuplicating,
152                             SinkCandidate](VPUser *U) {
153       auto *UI = cast<VPRecipeBase>(U);
154       if (UI->getParent() == SinkTo)
155         return true;
156       NeedsDuplicating = UI->onlyFirstLaneUsed(SinkCandidate);
157       // We only know how to duplicate VPRecipeRecipes for now.
158       return NeedsDuplicating && isa<VPReplicateRecipe>(SinkCandidate);
159     };
160     if (!all_of(SinkCandidate->users(), CanSinkWithUser))
161       continue;
162 
163     if (NeedsDuplicating) {
164       if (ScalarVFOnly)
165         continue;
166       Instruction *I = SinkCandidate->getUnderlyingInstr();
167       auto *Clone = new VPReplicateRecipe(I, SinkCandidate->operands(), true);
168       // TODO: add ".cloned" suffix to name of Clone's VPValue.
169 
170       Clone->insertBefore(SinkCandidate);
171       SinkCandidate->replaceUsesWithIf(Clone, [SinkTo](VPUser &U, unsigned) {
172         return cast<VPRecipeBase>(&U)->getParent() != SinkTo;
173       });
174     }
175     SinkCandidate->moveBefore(*SinkTo, SinkTo->getFirstNonPhi());
176     for (VPValue *Op : SinkCandidate->operands())
177       if (auto *Def =
178               dyn_cast_or_null<VPSingleDefRecipe>(Op->getDefiningRecipe()))
179         WorkList.insert(std::make_pair(SinkTo, Def));
180     Changed = true;
181   }
182   return Changed;
183 }
184 
185 /// If \p R is a region with a VPBranchOnMaskRecipe in the entry block, return
186 /// the mask.
187 VPValue *getPredicatedMask(VPRegionBlock *R) {
188   auto *EntryBB = dyn_cast<VPBasicBlock>(R->getEntry());
189   if (!EntryBB || EntryBB->size() != 1 ||
190       !isa<VPBranchOnMaskRecipe>(EntryBB->begin()))
191     return nullptr;
192 
193   return cast<VPBranchOnMaskRecipe>(&*EntryBB->begin())->getOperand(0);
194 }
195 
196 /// If \p R is a triangle region, return the 'then' block of the triangle.
197 static VPBasicBlock *getPredicatedThenBlock(VPRegionBlock *R) {
198   auto *EntryBB = cast<VPBasicBlock>(R->getEntry());
199   if (EntryBB->getNumSuccessors() != 2)
200     return nullptr;
201 
202   auto *Succ0 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[0]);
203   auto *Succ1 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[1]);
204   if (!Succ0 || !Succ1)
205     return nullptr;
206 
207   if (Succ0->getNumSuccessors() + Succ1->getNumSuccessors() != 1)
208     return nullptr;
209   if (Succ0->getSingleSuccessor() == Succ1)
210     return Succ0;
211   if (Succ1->getSingleSuccessor() == Succ0)
212     return Succ1;
213   return nullptr;
214 }
215 
216 // Merge replicate regions in their successor region, if a replicate region
217 // is connected to a successor replicate region with the same predicate by a
218 // single, empty VPBasicBlock.
219 static bool mergeReplicateRegionsIntoSuccessors(VPlan &Plan) {
220   SmallPtrSet<VPRegionBlock *, 4> TransformedRegions;
221 
222   // Collect replicate regions followed by an empty block, followed by another
223   // replicate region with matching masks to process front. This is to avoid
224   // iterator invalidation issues while merging regions.
225   SmallVector<VPRegionBlock *, 8> WorkList;
226   for (VPRegionBlock *Region1 : VPBlockUtils::blocksOnly<VPRegionBlock>(
227            vp_depth_first_deep(Plan.getEntry()))) {
228     if (!Region1->isReplicator())
229       continue;
230     auto *MiddleBasicBlock =
231         dyn_cast_or_null<VPBasicBlock>(Region1->getSingleSuccessor());
232     if (!MiddleBasicBlock || !MiddleBasicBlock->empty())
233       continue;
234 
235     auto *Region2 =
236         dyn_cast_or_null<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
237     if (!Region2 || !Region2->isReplicator())
238       continue;
239 
240     VPValue *Mask1 = getPredicatedMask(Region1);
241     VPValue *Mask2 = getPredicatedMask(Region2);
242     if (!Mask1 || Mask1 != Mask2)
243       continue;
244 
245     assert(Mask1 && Mask2 && "both region must have conditions");
246     WorkList.push_back(Region1);
247   }
248 
249   // Move recipes from Region1 to its successor region, if both are triangles.
250   for (VPRegionBlock *Region1 : WorkList) {
251     if (TransformedRegions.contains(Region1))
252       continue;
253     auto *MiddleBasicBlock = cast<VPBasicBlock>(Region1->getSingleSuccessor());
254     auto *Region2 = cast<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
255 
256     VPBasicBlock *Then1 = getPredicatedThenBlock(Region1);
257     VPBasicBlock *Then2 = getPredicatedThenBlock(Region2);
258     if (!Then1 || !Then2)
259       continue;
260 
261     // Note: No fusion-preventing memory dependencies are expected in either
262     // region. Such dependencies should be rejected during earlier dependence
263     // checks, which guarantee accesses can be re-ordered for vectorization.
264     //
265     // Move recipes to the successor region.
266     for (VPRecipeBase &ToMove : make_early_inc_range(reverse(*Then1)))
267       ToMove.moveBefore(*Then2, Then2->getFirstNonPhi());
268 
269     auto *Merge1 = cast<VPBasicBlock>(Then1->getSingleSuccessor());
270     auto *Merge2 = cast<VPBasicBlock>(Then2->getSingleSuccessor());
271 
272     // Move VPPredInstPHIRecipes from the merge block to the successor region's
273     // merge block. Update all users inside the successor region to use the
274     // original values.
275     for (VPRecipeBase &Phi1ToMove : make_early_inc_range(reverse(*Merge1))) {
276       VPValue *PredInst1 =
277           cast<VPPredInstPHIRecipe>(&Phi1ToMove)->getOperand(0);
278       VPValue *Phi1ToMoveV = Phi1ToMove.getVPSingleValue();
279       Phi1ToMoveV->replaceUsesWithIf(PredInst1, [Then2](VPUser &U, unsigned) {
280         return cast<VPRecipeBase>(&U)->getParent() == Then2;
281       });
282 
283       // Remove phi recipes that are unused after merging the regions.
284       if (Phi1ToMove.getVPSingleValue()->getNumUsers() == 0) {
285         Phi1ToMove.eraseFromParent();
286         continue;
287       }
288       Phi1ToMove.moveBefore(*Merge2, Merge2->begin());
289     }
290 
291     // Finally, remove the first region.
292     for (VPBlockBase *Pred : make_early_inc_range(Region1->getPredecessors())) {
293       VPBlockUtils::disconnectBlocks(Pred, Region1);
294       VPBlockUtils::connectBlocks(Pred, MiddleBasicBlock);
295     }
296     VPBlockUtils::disconnectBlocks(Region1, MiddleBasicBlock);
297     TransformedRegions.insert(Region1);
298   }
299 
300   return !TransformedRegions.empty();
301 }
302 
303 static VPRegionBlock *createReplicateRegion(VPReplicateRecipe *PredRecipe,
304                                             VPlan &Plan) {
305   Instruction *Instr = PredRecipe->getUnderlyingInstr();
306   // Build the triangular if-then region.
307   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
308   assert(Instr->getParent() && "Predicated instruction not in any basic block");
309   auto *BlockInMask = PredRecipe->getMask();
310   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
311   auto *Entry =
312       Plan.createVPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
313 
314   // Replace predicated replicate recipe with a replicate recipe without a
315   // mask but in the replicate region.
316   auto *RecipeWithoutMask = new VPReplicateRecipe(
317       PredRecipe->getUnderlyingInstr(),
318       make_range(PredRecipe->op_begin(), std::prev(PredRecipe->op_end())),
319       PredRecipe->isUniform());
320   auto *Pred =
321       Plan.createVPBasicBlock(Twine(RegionName) + ".if", RecipeWithoutMask);
322 
323   VPPredInstPHIRecipe *PHIRecipe = nullptr;
324   if (PredRecipe->getNumUsers() != 0) {
325     PHIRecipe = new VPPredInstPHIRecipe(RecipeWithoutMask,
326                                         RecipeWithoutMask->getDebugLoc());
327     PredRecipe->replaceAllUsesWith(PHIRecipe);
328     PHIRecipe->setOperand(0, RecipeWithoutMask);
329   }
330   PredRecipe->eraseFromParent();
331   auto *Exiting =
332       Plan.createVPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
333   VPRegionBlock *Region =
334       Plan.createVPRegionBlock(Entry, Exiting, RegionName, true);
335 
336   // Note: first set Entry as region entry and then connect successors starting
337   // from it in order, to propagate the "parent" of each VPBasicBlock.
338   VPBlockUtils::insertTwoBlocksAfter(Pred, Exiting, Entry);
339   VPBlockUtils::connectBlocks(Pred, Exiting);
340 
341   return Region;
342 }
343 
344 static void addReplicateRegions(VPlan &Plan) {
345   SmallVector<VPReplicateRecipe *> WorkList;
346   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
347            vp_depth_first_deep(Plan.getEntry()))) {
348     for (VPRecipeBase &R : *VPBB)
349       if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
350         if (RepR->isPredicated())
351           WorkList.push_back(RepR);
352       }
353   }
354 
355   unsigned BBNum = 0;
356   for (VPReplicateRecipe *RepR : WorkList) {
357     VPBasicBlock *CurrentBlock = RepR->getParent();
358     VPBasicBlock *SplitBlock = CurrentBlock->splitAt(RepR->getIterator());
359 
360     BasicBlock *OrigBB = RepR->getUnderlyingInstr()->getParent();
361     SplitBlock->setName(
362         OrigBB->hasName() ? OrigBB->getName() + "." + Twine(BBNum++) : "");
363     // Record predicated instructions for above packing optimizations.
364     VPBlockBase *Region = createReplicateRegion(RepR, Plan);
365     Region->setParent(CurrentBlock->getParent());
366     VPBlockUtils::insertOnEdge(CurrentBlock, SplitBlock, Region);
367   }
368 }
369 
370 /// Remove redundant VPBasicBlocks by merging them into their predecessor if
371 /// the predecessor has a single successor.
372 static bool mergeBlocksIntoPredecessors(VPlan &Plan) {
373   SmallVector<VPBasicBlock *> WorkList;
374   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
375            vp_depth_first_deep(Plan.getEntry()))) {
376     // Don't fold the blocks in the skeleton of the Plan into their single
377     // predecessors for now.
378     // TODO: Remove restriction once more of the skeleton is modeled in VPlan.
379     if (!VPBB->getParent())
380       continue;
381     auto *PredVPBB =
382         dyn_cast_or_null<VPBasicBlock>(VPBB->getSinglePredecessor());
383     if (!PredVPBB || PredVPBB->getNumSuccessors() != 1 ||
384         isa<VPIRBasicBlock>(PredVPBB))
385       continue;
386     WorkList.push_back(VPBB);
387   }
388 
389   for (VPBasicBlock *VPBB : WorkList) {
390     VPBasicBlock *PredVPBB = cast<VPBasicBlock>(VPBB->getSinglePredecessor());
391     for (VPRecipeBase &R : make_early_inc_range(*VPBB))
392       R.moveBefore(*PredVPBB, PredVPBB->end());
393     VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
394     auto *ParentRegion = cast_or_null<VPRegionBlock>(VPBB->getParent());
395     if (ParentRegion && ParentRegion->getExiting() == VPBB)
396       ParentRegion->setExiting(PredVPBB);
397     for (auto *Succ : to_vector(VPBB->successors())) {
398       VPBlockUtils::disconnectBlocks(VPBB, Succ);
399       VPBlockUtils::connectBlocks(PredVPBB, Succ);
400     }
401     // VPBB is now dead and will be cleaned up when the plan gets destroyed.
402   }
403   return !WorkList.empty();
404 }
405 
406 void VPlanTransforms::createAndOptimizeReplicateRegions(VPlan &Plan) {
407   // Convert masked VPReplicateRecipes to if-then region blocks.
408   addReplicateRegions(Plan);
409 
410   bool ShouldSimplify = true;
411   while (ShouldSimplify) {
412     ShouldSimplify = sinkScalarOperands(Plan);
413     ShouldSimplify |= mergeReplicateRegionsIntoSuccessors(Plan);
414     ShouldSimplify |= mergeBlocksIntoPredecessors(Plan);
415   }
416 }
417 
418 /// Remove redundant casts of inductions.
419 ///
420 /// Such redundant casts are casts of induction variables that can be ignored,
421 /// because we already proved that the casted phi is equal to the uncasted phi
422 /// in the vectorized loop. There is no need to vectorize the cast - the same
423 /// value can be used for both the phi and casts in the vector loop.
424 static void removeRedundantInductionCasts(VPlan &Plan) {
425   for (auto &Phi : Plan.getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
426     auto *IV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
427     if (!IV || IV->getTruncInst())
428       continue;
429 
430     // A sequence of IR Casts has potentially been recorded for IV, which
431     // *must be bypassed* when the IV is vectorized, because the vectorized IV
432     // will produce the desired casted value. This sequence forms a def-use
433     // chain and is provided in reverse order, ending with the cast that uses
434     // the IV phi. Search for the recipe of the last cast in the chain and
435     // replace it with the original IV. Note that only the final cast is
436     // expected to have users outside the cast-chain and the dead casts left
437     // over will be cleaned up later.
438     auto &Casts = IV->getInductionDescriptor().getCastInsts();
439     VPValue *FindMyCast = IV;
440     for (Instruction *IRCast : reverse(Casts)) {
441       VPSingleDefRecipe *FoundUserCast = nullptr;
442       for (auto *U : FindMyCast->users()) {
443         auto *UserCast = dyn_cast<VPSingleDefRecipe>(U);
444         if (UserCast && UserCast->getUnderlyingValue() == IRCast) {
445           FoundUserCast = UserCast;
446           break;
447         }
448       }
449       FindMyCast = FoundUserCast;
450     }
451     FindMyCast->replaceAllUsesWith(IV);
452   }
453 }
454 
455 /// Try to replace VPWidenCanonicalIVRecipes with a widened canonical IV
456 /// recipe, if it exists.
457 static void removeRedundantCanonicalIVs(VPlan &Plan) {
458   VPCanonicalIVPHIRecipe *CanonicalIV = Plan.getCanonicalIV();
459   VPWidenCanonicalIVRecipe *WidenNewIV = nullptr;
460   for (VPUser *U : CanonicalIV->users()) {
461     WidenNewIV = dyn_cast<VPWidenCanonicalIVRecipe>(U);
462     if (WidenNewIV)
463       break;
464   }
465 
466   if (!WidenNewIV)
467     return;
468 
469   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
470   for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
471     auto *WidenOriginalIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
472 
473     if (!WidenOriginalIV || !WidenOriginalIV->isCanonical())
474       continue;
475 
476     // Replace WidenNewIV with WidenOriginalIV if WidenOriginalIV provides
477     // everything WidenNewIV's users need. That is, WidenOriginalIV will
478     // generate a vector phi or all users of WidenNewIV demand the first lane
479     // only.
480     if (any_of(WidenOriginalIV->users(),
481                [WidenOriginalIV](VPUser *U) {
482                  return !U->usesScalars(WidenOriginalIV);
483                }) ||
484         vputils::onlyFirstLaneUsed(WidenNewIV)) {
485       WidenNewIV->replaceAllUsesWith(WidenOriginalIV);
486       WidenNewIV->eraseFromParent();
487       return;
488     }
489   }
490 }
491 
492 /// Returns true if \p R is dead and can be removed.
493 static bool isDeadRecipe(VPRecipeBase &R) {
494   using namespace llvm::PatternMatch;
495   // Do remove conditional assume instructions as their conditions may be
496   // flattened.
497   auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
498   bool IsConditionalAssume =
499       RepR && RepR->isPredicated() &&
500       match(RepR->getUnderlyingInstr(), m_Intrinsic<Intrinsic::assume>());
501   if (IsConditionalAssume)
502     return true;
503 
504   if (R.mayHaveSideEffects())
505     return false;
506 
507   // Recipe is dead if no user keeps the recipe alive.
508   return all_of(R.definedValues(),
509                 [](VPValue *V) { return V->getNumUsers() == 0; });
510 }
511 
512 void VPlanTransforms::removeDeadRecipes(VPlan &Plan) {
513   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> RPOT(
514       Plan.getEntry());
515 
516   for (VPBasicBlock *VPBB : reverse(VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT))) {
517     // The recipes in the block are processed in reverse order, to catch chains
518     // of dead recipes.
519     for (VPRecipeBase &R : make_early_inc_range(reverse(*VPBB))) {
520       if (isDeadRecipe(R))
521         R.eraseFromParent();
522     }
523   }
524 }
525 
526 static VPScalarIVStepsRecipe *
527 createScalarIVSteps(VPlan &Plan, InductionDescriptor::InductionKind Kind,
528                     Instruction::BinaryOps InductionOpcode,
529                     FPMathOperator *FPBinOp, Instruction *TruncI,
530                     VPValue *StartV, VPValue *Step, VPBuilder &Builder) {
531   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
532   VPCanonicalIVPHIRecipe *CanonicalIV = Plan.getCanonicalIV();
533   VPSingleDefRecipe *BaseIV = Builder.createDerivedIV(
534       Kind, FPBinOp, StartV, CanonicalIV, Step, "offset.idx");
535 
536   // Truncate base induction if needed.
537   Type *CanonicalIVType = CanonicalIV->getScalarType();
538   VPTypeAnalysis TypeInfo(CanonicalIVType);
539   Type *ResultTy = TypeInfo.inferScalarType(BaseIV);
540   if (TruncI) {
541     Type *TruncTy = TruncI->getType();
542     assert(ResultTy->getScalarSizeInBits() > TruncTy->getScalarSizeInBits() &&
543            "Not truncating.");
544     assert(ResultTy->isIntegerTy() && "Truncation requires an integer type");
545     BaseIV = Builder.createScalarCast(Instruction::Trunc, BaseIV, TruncTy);
546     ResultTy = TruncTy;
547   }
548 
549   // Truncate step if needed.
550   Type *StepTy = TypeInfo.inferScalarType(Step);
551   if (ResultTy != StepTy) {
552     assert(StepTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits() &&
553            "Not truncating.");
554     assert(StepTy->isIntegerTy() && "Truncation requires an integer type");
555     auto *VecPreheader =
556         cast<VPBasicBlock>(HeaderVPBB->getSingleHierarchicalPredecessor());
557     VPBuilder::InsertPointGuard Guard(Builder);
558     Builder.setInsertPoint(VecPreheader);
559     Step = Builder.createScalarCast(Instruction::Trunc, Step, ResultTy);
560   }
561   return Builder.createScalarIVSteps(InductionOpcode, FPBinOp, BaseIV, Step);
562 }
563 
564 /// Legalize VPWidenPointerInductionRecipe, by replacing it with a PtrAdd
565 /// (IndStart, ScalarIVSteps (0, Step)) if only its scalar values are used, as
566 /// VPWidenPointerInductionRecipe will generate vectors only. If some users
567 /// require vectors while other require scalars, the scalar uses need to extract
568 /// the scalars from the generated vectors (Note that this is different to how
569 /// int/fp inductions are handled). Also optimize VPWidenIntOrFpInductionRecipe,
570 /// if any of its users needs scalar values, by providing them scalar steps
571 /// built on the canonical scalar IV and update the original IV's users. This is
572 /// an optional optimization to reduce the needs of vector extracts.
573 static void legalizeAndOptimizeInductions(VPlan &Plan) {
574   SmallVector<VPRecipeBase *> ToRemove;
575   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
576   bool HasOnlyVectorVFs = !Plan.hasVF(ElementCount::getFixed(1));
577   VPBuilder Builder(HeaderVPBB, HeaderVPBB->getFirstNonPhi());
578   for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
579     // Replace wide pointer inductions which have only their scalars used by
580     // PtrAdd(IndStart, ScalarIVSteps (0, Step)).
581     if (auto *PtrIV = dyn_cast<VPWidenPointerInductionRecipe>(&Phi)) {
582       if (!PtrIV->onlyScalarsGenerated(Plan.hasScalableVF()))
583         continue;
584 
585       const InductionDescriptor &ID = PtrIV->getInductionDescriptor();
586       VPValue *StartV =
587           Plan.getOrAddLiveIn(ConstantInt::get(ID.getStep()->getType(), 0));
588       VPValue *StepV = PtrIV->getOperand(1);
589       VPScalarIVStepsRecipe *Steps = createScalarIVSteps(
590           Plan, InductionDescriptor::IK_IntInduction, Instruction::Add, nullptr,
591           nullptr, StartV, StepV, Builder);
592 
593       VPValue *PtrAdd = Builder.createPtrAdd(PtrIV->getStartValue(), Steps,
594                                              PtrIV->getDebugLoc(), "next.gep");
595 
596       PtrIV->replaceAllUsesWith(PtrAdd);
597       continue;
598     }
599 
600     // Replace widened induction with scalar steps for users that only use
601     // scalars.
602     auto *WideIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
603     if (!WideIV)
604       continue;
605     if (HasOnlyVectorVFs && none_of(WideIV->users(), [WideIV](VPUser *U) {
606           return U->usesScalars(WideIV);
607         }))
608       continue;
609 
610     const InductionDescriptor &ID = WideIV->getInductionDescriptor();
611     VPScalarIVStepsRecipe *Steps = createScalarIVSteps(
612         Plan, ID.getKind(), ID.getInductionOpcode(),
613         dyn_cast_or_null<FPMathOperator>(ID.getInductionBinOp()),
614         WideIV->getTruncInst(), WideIV->getStartValue(), WideIV->getStepValue(),
615         Builder);
616 
617     // Update scalar users of IV to use Step instead.
618     if (!HasOnlyVectorVFs)
619       WideIV->replaceAllUsesWith(Steps);
620     else
621       WideIV->replaceUsesWithIf(Steps, [WideIV](VPUser &U, unsigned) {
622         return U.usesScalars(WideIV);
623       });
624   }
625 }
626 
627 /// Remove redundant EpxandSCEVRecipes in \p Plan's entry block by replacing
628 /// them with already existing recipes expanding the same SCEV expression.
629 static void removeRedundantExpandSCEVRecipes(VPlan &Plan) {
630   DenseMap<const SCEV *, VPValue *> SCEV2VPV;
631 
632   for (VPRecipeBase &R :
633        make_early_inc_range(*Plan.getEntry()->getEntryBasicBlock())) {
634     auto *ExpR = dyn_cast<VPExpandSCEVRecipe>(&R);
635     if (!ExpR)
636       continue;
637 
638     auto I = SCEV2VPV.insert({ExpR->getSCEV(), ExpR});
639     if (I.second)
640       continue;
641     ExpR->replaceAllUsesWith(I.first->second);
642     ExpR->eraseFromParent();
643   }
644 }
645 
646 static void recursivelyDeleteDeadRecipes(VPValue *V) {
647   SmallVector<VPValue *> WorkList;
648   SmallPtrSet<VPValue *, 8> Seen;
649   WorkList.push_back(V);
650 
651   while (!WorkList.empty()) {
652     VPValue *Cur = WorkList.pop_back_val();
653     if (!Seen.insert(Cur).second)
654       continue;
655     VPRecipeBase *R = Cur->getDefiningRecipe();
656     if (!R)
657       continue;
658     if (!isDeadRecipe(*R))
659       continue;
660     WorkList.append(R->op_begin(), R->op_end());
661     R->eraseFromParent();
662   }
663 }
664 
665 void VPlanTransforms::optimizeForVFAndUF(VPlan &Plan, ElementCount BestVF,
666                                          unsigned BestUF,
667                                          PredicatedScalarEvolution &PSE) {
668   assert(Plan.hasVF(BestVF) && "BestVF is not available in Plan");
669   assert(Plan.hasUF(BestUF) && "BestUF is not available in Plan");
670   VPBasicBlock *ExitingVPBB =
671       Plan.getVectorLoopRegion()->getExitingBasicBlock();
672   auto *Term = &ExitingVPBB->back();
673   // Try to simplify the branch condition if TC <= VF * UF when preparing to
674   // execute the plan for the main vector loop. We only do this if the
675   // terminator is:
676   //  1. BranchOnCount, or
677   //  2. BranchOnCond where the input is Not(ActiveLaneMask).
678   using namespace llvm::VPlanPatternMatch;
679   if (!match(Term, m_BranchOnCount(m_VPValue(), m_VPValue())) &&
680       !match(Term,
681              m_BranchOnCond(m_Not(m_ActiveLaneMask(m_VPValue(), m_VPValue())))))
682     return;
683 
684   ScalarEvolution &SE = *PSE.getSE();
685   const SCEV *TripCount =
686       vputils::getSCEVExprForVPValue(Plan.getTripCount(), SE);
687   assert(!isa<SCEVCouldNotCompute>(TripCount) &&
688          "Trip count SCEV must be computable");
689   ElementCount NumElements = BestVF.multiplyCoefficientBy(BestUF);
690   const SCEV *C = SE.getElementCount(TripCount->getType(), NumElements);
691   if (TripCount->isZero() ||
692       !SE.isKnownPredicate(CmpInst::ICMP_ULE, TripCount, C))
693     return;
694 
695   LLVMContext &Ctx = SE.getContext();
696   auto *BOC = new VPInstruction(
697       VPInstruction::BranchOnCond,
698       {Plan.getOrAddLiveIn(ConstantInt::getTrue(Ctx))}, Term->getDebugLoc());
699 
700   SmallVector<VPValue *> PossiblyDead(Term->operands());
701   Term->eraseFromParent();
702   for (VPValue *Op : PossiblyDead)
703     recursivelyDeleteDeadRecipes(Op);
704   ExitingVPBB->appendRecipe(BOC);
705   Plan.setVF(BestVF);
706   Plan.setUF(BestUF);
707   // TODO: Further simplifications are possible
708   //      1. Replace inductions with constants.
709   //      2. Replace vector loop region with VPBasicBlock.
710 }
711 
712 /// Sink users of \p FOR after the recipe defining the previous value \p
713 /// Previous of the recurrence. \returns true if all users of \p FOR could be
714 /// re-arranged as needed or false if it is not possible.
715 static bool
716 sinkRecurrenceUsersAfterPrevious(VPFirstOrderRecurrencePHIRecipe *FOR,
717                                  VPRecipeBase *Previous,
718                                  VPDominatorTree &VPDT) {
719   // Collect recipes that need sinking.
720   SmallVector<VPRecipeBase *> WorkList;
721   SmallPtrSet<VPRecipeBase *, 8> Seen;
722   Seen.insert(Previous);
723   auto TryToPushSinkCandidate = [&](VPRecipeBase *SinkCandidate) {
724     // The previous value must not depend on the users of the recurrence phi. In
725     // that case, FOR is not a fixed order recurrence.
726     if (SinkCandidate == Previous)
727       return false;
728 
729     if (isa<VPHeaderPHIRecipe>(SinkCandidate) ||
730         !Seen.insert(SinkCandidate).second ||
731         VPDT.properlyDominates(Previous, SinkCandidate))
732       return true;
733 
734     if (SinkCandidate->mayHaveSideEffects())
735       return false;
736 
737     WorkList.push_back(SinkCandidate);
738     return true;
739   };
740 
741   // Recursively sink users of FOR after Previous.
742   WorkList.push_back(FOR);
743   for (unsigned I = 0; I != WorkList.size(); ++I) {
744     VPRecipeBase *Current = WorkList[I];
745     assert(Current->getNumDefinedValues() == 1 &&
746            "only recipes with a single defined value expected");
747 
748     for (VPUser *User : Current->getVPSingleValue()->users()) {
749       if (!TryToPushSinkCandidate(cast<VPRecipeBase>(User)))
750         return false;
751     }
752   }
753 
754   // Keep recipes to sink ordered by dominance so earlier instructions are
755   // processed first.
756   sort(WorkList, [&VPDT](const VPRecipeBase *A, const VPRecipeBase *B) {
757     return VPDT.properlyDominates(A, B);
758   });
759 
760   for (VPRecipeBase *SinkCandidate : WorkList) {
761     if (SinkCandidate == FOR)
762       continue;
763 
764     SinkCandidate->moveAfter(Previous);
765     Previous = SinkCandidate;
766   }
767   return true;
768 }
769 
770 /// Try to hoist \p Previous and its operands before all users of \p FOR.
771 static bool hoistPreviousBeforeFORUsers(VPFirstOrderRecurrencePHIRecipe *FOR,
772                                         VPRecipeBase *Previous,
773                                         VPDominatorTree &VPDT) {
774   if (Previous->mayHaveSideEffects() || Previous->mayReadFromMemory())
775     return false;
776 
777   // Collect recipes that need hoisting.
778   SmallVector<VPRecipeBase *> HoistCandidates;
779   SmallPtrSet<VPRecipeBase *, 8> Visited;
780   VPRecipeBase *HoistPoint = nullptr;
781   // Find the closest hoist point by looking at all users of FOR and selecting
782   // the recipe dominating all other users.
783   for (VPUser *U : FOR->users()) {
784     auto *R = cast<VPRecipeBase>(U);
785     if (!HoistPoint || VPDT.properlyDominates(R, HoistPoint))
786       HoistPoint = R;
787   }
788   assert(all_of(FOR->users(),
789                 [&VPDT, HoistPoint](VPUser *U) {
790                   auto *R = cast<VPRecipeBase>(U);
791                   return HoistPoint == R ||
792                          VPDT.properlyDominates(HoistPoint, R);
793                 }) &&
794          "HoistPoint must dominate all users of FOR");
795 
796   auto NeedsHoisting = [HoistPoint, &VPDT,
797                         &Visited](VPValue *HoistCandidateV) -> VPRecipeBase * {
798     VPRecipeBase *HoistCandidate = HoistCandidateV->getDefiningRecipe();
799     if (!HoistCandidate)
800       return nullptr;
801     VPRegionBlock *EnclosingLoopRegion =
802         HoistCandidate->getParent()->getEnclosingLoopRegion();
803     assert((!HoistCandidate->getParent()->getParent() ||
804             HoistCandidate->getParent()->getParent() == EnclosingLoopRegion) &&
805            "CFG in VPlan should still be flat, without replicate regions");
806     // Hoist candidate was already visited, no need to hoist.
807     if (!Visited.insert(HoistCandidate).second)
808       return nullptr;
809 
810     // Candidate is outside loop region or a header phi, dominates FOR users w/o
811     // hoisting.
812     if (!EnclosingLoopRegion || isa<VPHeaderPHIRecipe>(HoistCandidate))
813       return nullptr;
814 
815     // If we reached a recipe that dominates HoistPoint, we don't need to
816     // hoist the recipe.
817     if (VPDT.properlyDominates(HoistCandidate, HoistPoint))
818       return nullptr;
819     return HoistCandidate;
820   };
821   auto CanHoist = [&](VPRecipeBase *HoistCandidate) {
822     // Avoid hoisting candidates with side-effects, as we do not yet analyze
823     // associated dependencies.
824     return !HoistCandidate->mayHaveSideEffects();
825   };
826 
827   if (!NeedsHoisting(Previous->getVPSingleValue()))
828     return true;
829 
830   // Recursively try to hoist Previous and its operands before all users of FOR.
831   HoistCandidates.push_back(Previous);
832 
833   for (unsigned I = 0; I != HoistCandidates.size(); ++I) {
834     VPRecipeBase *Current = HoistCandidates[I];
835     assert(Current->getNumDefinedValues() == 1 &&
836            "only recipes with a single defined value expected");
837     if (!CanHoist(Current))
838       return false;
839 
840     for (VPValue *Op : Current->operands()) {
841       // If we reach FOR, it means the original Previous depends on some other
842       // recurrence that in turn depends on FOR. If that is the case, we would
843       // also need to hoist recipes involving the other FOR, which may break
844       // dependencies.
845       if (Op == FOR)
846         return false;
847 
848       if (auto *R = NeedsHoisting(Op))
849         HoistCandidates.push_back(R);
850     }
851   }
852 
853   // Order recipes to hoist by dominance so earlier instructions are processed
854   // first.
855   sort(HoistCandidates, [&VPDT](const VPRecipeBase *A, const VPRecipeBase *B) {
856     return VPDT.properlyDominates(A, B);
857   });
858 
859   for (VPRecipeBase *HoistCandidate : HoistCandidates) {
860     HoistCandidate->moveBefore(*HoistPoint->getParent(),
861                                HoistPoint->getIterator());
862   }
863 
864   return true;
865 }
866 
867 bool VPlanTransforms::adjustFixedOrderRecurrences(VPlan &Plan,
868                                                   VPBuilder &LoopBuilder) {
869   VPDominatorTree VPDT;
870   VPDT.recalculate(Plan);
871 
872   SmallVector<VPFirstOrderRecurrencePHIRecipe *> RecurrencePhis;
873   for (VPRecipeBase &R :
874        Plan.getVectorLoopRegion()->getEntry()->getEntryBasicBlock()->phis())
875     if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
876       RecurrencePhis.push_back(FOR);
877 
878   for (VPFirstOrderRecurrencePHIRecipe *FOR : RecurrencePhis) {
879     SmallPtrSet<VPFirstOrderRecurrencePHIRecipe *, 4> SeenPhis;
880     VPRecipeBase *Previous = FOR->getBackedgeValue()->getDefiningRecipe();
881     // Fixed-order recurrences do not contain cycles, so this loop is guaranteed
882     // to terminate.
883     while (auto *PrevPhi =
884                dyn_cast_or_null<VPFirstOrderRecurrencePHIRecipe>(Previous)) {
885       assert(PrevPhi->getParent() == FOR->getParent());
886       assert(SeenPhis.insert(PrevPhi).second);
887       Previous = PrevPhi->getBackedgeValue()->getDefiningRecipe();
888     }
889 
890     if (!sinkRecurrenceUsersAfterPrevious(FOR, Previous, VPDT) &&
891         !hoistPreviousBeforeFORUsers(FOR, Previous, VPDT))
892       return false;
893 
894     // Introduce a recipe to combine the incoming and previous values of a
895     // fixed-order recurrence.
896     VPBasicBlock *InsertBlock = Previous->getParent();
897     if (isa<VPHeaderPHIRecipe>(Previous))
898       LoopBuilder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
899     else
900       LoopBuilder.setInsertPoint(InsertBlock,
901                                  std::next(Previous->getIterator()));
902 
903     auto *RecurSplice = cast<VPInstruction>(
904         LoopBuilder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
905                                  {FOR, FOR->getBackedgeValue()}));
906 
907     FOR->replaceAllUsesWith(RecurSplice);
908     // Set the first operand of RecurSplice to FOR again, after replacing
909     // all users.
910     RecurSplice->setOperand(0, FOR);
911   }
912   return true;
913 }
914 
915 static SmallVector<VPUser *> collectUsersRecursively(VPValue *V) {
916   SetVector<VPUser *> Users(V->user_begin(), V->user_end());
917   for (unsigned I = 0; I != Users.size(); ++I) {
918     VPRecipeBase *Cur = cast<VPRecipeBase>(Users[I]);
919     if (isa<VPHeaderPHIRecipe>(Cur))
920       continue;
921     for (VPValue *V : Cur->definedValues())
922       Users.insert(V->user_begin(), V->user_end());
923   }
924   return Users.takeVector();
925 }
926 
927 void VPlanTransforms::clearReductionWrapFlags(VPlan &Plan) {
928   for (VPRecipeBase &R :
929        Plan.getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
930     auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
931     if (!PhiR)
932       continue;
933     const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
934     RecurKind RK = RdxDesc.getRecurrenceKind();
935     if (RK != RecurKind::Add && RK != RecurKind::Mul)
936       continue;
937 
938     for (VPUser *U : collectUsersRecursively(PhiR))
939       if (auto *RecWithFlags = dyn_cast<VPRecipeWithIRFlags>(U)) {
940         RecWithFlags->dropPoisonGeneratingFlags();
941       }
942   }
943 }
944 
945 /// Try to simplify recipe \p R.
946 static void simplifyRecipe(VPRecipeBase &R, VPTypeAnalysis &TypeInfo) {
947   using namespace llvm::VPlanPatternMatch;
948 
949   if (auto *Blend = dyn_cast<VPBlendRecipe>(&R)) {
950     // Try to remove redundant blend recipes.
951     SmallPtrSet<VPValue *, 4> UniqueValues;
952     if (Blend->isNormalized() || !match(Blend->getMask(0), m_False()))
953       UniqueValues.insert(Blend->getIncomingValue(0));
954     for (unsigned I = 1; I != Blend->getNumIncomingValues(); ++I)
955       if (!match(Blend->getMask(I), m_False()))
956         UniqueValues.insert(Blend->getIncomingValue(I));
957 
958     if (UniqueValues.size() == 1) {
959       Blend->replaceAllUsesWith(*UniqueValues.begin());
960       Blend->eraseFromParent();
961       return;
962     }
963 
964     if (Blend->isNormalized())
965       return;
966 
967     // Normalize the blend so its first incoming value is used as the initial
968     // value with the others blended into it.
969 
970     unsigned StartIndex = 0;
971     for (unsigned I = 0; I != Blend->getNumIncomingValues(); ++I) {
972       // If a value's mask is used only by the blend then is can be deadcoded.
973       // TODO: Find the most expensive mask that can be deadcoded, or a mask
974       // that's used by multiple blends where it can be removed from them all.
975       VPValue *Mask = Blend->getMask(I);
976       if (Mask->getNumUsers() == 1 && !match(Mask, m_False())) {
977         StartIndex = I;
978         break;
979       }
980     }
981 
982     SmallVector<VPValue *, 4> OperandsWithMask;
983     OperandsWithMask.push_back(Blend->getIncomingValue(StartIndex));
984 
985     for (unsigned I = 0; I != Blend->getNumIncomingValues(); ++I) {
986       if (I == StartIndex)
987         continue;
988       OperandsWithMask.push_back(Blend->getIncomingValue(I));
989       OperandsWithMask.push_back(Blend->getMask(I));
990     }
991 
992     auto *NewBlend = new VPBlendRecipe(
993         cast<PHINode>(Blend->getUnderlyingValue()), OperandsWithMask);
994     NewBlend->insertBefore(&R);
995 
996     VPValue *DeadMask = Blend->getMask(StartIndex);
997     Blend->replaceAllUsesWith(NewBlend);
998     Blend->eraseFromParent();
999     recursivelyDeleteDeadRecipes(DeadMask);
1000     return;
1001   }
1002 
1003   VPValue *A;
1004   if (match(&R, m_Trunc(m_ZExtOrSExt(m_VPValue(A))))) {
1005     VPValue *Trunc = R.getVPSingleValue();
1006     Type *TruncTy = TypeInfo.inferScalarType(Trunc);
1007     Type *ATy = TypeInfo.inferScalarType(A);
1008     if (TruncTy == ATy) {
1009       Trunc->replaceAllUsesWith(A);
1010     } else {
1011       // Don't replace a scalarizing recipe with a widened cast.
1012       if (isa<VPReplicateRecipe>(&R))
1013         return;
1014       if (ATy->getScalarSizeInBits() < TruncTy->getScalarSizeInBits()) {
1015 
1016         unsigned ExtOpcode = match(R.getOperand(0), m_SExt(m_VPValue()))
1017                                  ? Instruction::SExt
1018                                  : Instruction::ZExt;
1019         auto *VPC =
1020             new VPWidenCastRecipe(Instruction::CastOps(ExtOpcode), A, TruncTy);
1021         if (auto *UnderlyingExt = R.getOperand(0)->getUnderlyingValue()) {
1022           // UnderlyingExt has distinct return type, used to retain legacy cost.
1023           VPC->setUnderlyingValue(UnderlyingExt);
1024         }
1025         VPC->insertBefore(&R);
1026         Trunc->replaceAllUsesWith(VPC);
1027       } else if (ATy->getScalarSizeInBits() > TruncTy->getScalarSizeInBits()) {
1028         auto *VPC = new VPWidenCastRecipe(Instruction::Trunc, A, TruncTy);
1029         VPC->insertBefore(&R);
1030         Trunc->replaceAllUsesWith(VPC);
1031       }
1032     }
1033 #ifndef NDEBUG
1034     // Verify that the cached type info is for both A and its users is still
1035     // accurate by comparing it to freshly computed types.
1036     VPTypeAnalysis TypeInfo2(
1037         R.getParent()->getPlan()->getCanonicalIV()->getScalarType());
1038     assert(TypeInfo.inferScalarType(A) == TypeInfo2.inferScalarType(A));
1039     for (VPUser *U : A->users()) {
1040       auto *R = cast<VPRecipeBase>(U);
1041       for (VPValue *VPV : R->definedValues())
1042         assert(TypeInfo.inferScalarType(VPV) == TypeInfo2.inferScalarType(VPV));
1043     }
1044 #endif
1045   }
1046 
1047   // Simplify (X && Y) || (X && !Y) -> X.
1048   // TODO: Split up into simpler, modular combines: (X && Y) || (X && Z) into X
1049   // && (Y || Z) and (X || !X) into true. This requires queuing newly created
1050   // recipes to be visited during simplification.
1051   VPValue *X, *Y, *X1, *Y1;
1052   if (match(&R,
1053             m_c_BinaryOr(m_LogicalAnd(m_VPValue(X), m_VPValue(Y)),
1054                          m_LogicalAnd(m_VPValue(X1), m_Not(m_VPValue(Y1))))) &&
1055       X == X1 && Y == Y1) {
1056     R.getVPSingleValue()->replaceAllUsesWith(X);
1057     R.eraseFromParent();
1058     return;
1059   }
1060 
1061   if (match(&R, m_c_Mul(m_VPValue(A), m_SpecificInt(1))))
1062     return R.getVPSingleValue()->replaceAllUsesWith(A);
1063 
1064   if (match(&R, m_Not(m_Not(m_VPValue(A)))))
1065     return R.getVPSingleValue()->replaceAllUsesWith(A);
1066 
1067   // Remove redundant DerviedIVs, that is 0 + A * 1 -> A and 0 + 0 * x -> 0.
1068   if ((match(&R,
1069              m_DerivedIV(m_SpecificInt(0), m_VPValue(A), m_SpecificInt(1))) ||
1070        match(&R,
1071              m_DerivedIV(m_SpecificInt(0), m_SpecificInt(0), m_VPValue()))) &&
1072       TypeInfo.inferScalarType(R.getOperand(1)) ==
1073           TypeInfo.inferScalarType(R.getVPSingleValue()))
1074     return R.getVPSingleValue()->replaceAllUsesWith(R.getOperand(1));
1075 }
1076 
1077 /// Move loop-invariant recipes out of the vector loop region in \p Plan.
1078 static void licm(VPlan &Plan) {
1079   VPBasicBlock *Preheader = Plan.getVectorPreheader();
1080 
1081   // Return true if we do not know how to (mechanically) hoist a given recipe
1082   // out of a loop region. Does not address legality concerns such as aliasing
1083   // or speculation safety.
1084   auto CannotHoistRecipe = [](VPRecipeBase &R) {
1085     // Allocas cannot be hoisted.
1086     auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
1087     return RepR && RepR->getOpcode() == Instruction::Alloca;
1088   };
1089 
1090   // Hoist any loop invariant recipes from the vector loop region to the
1091   // preheader. Preform a shallow traversal of the vector loop region, to
1092   // exclude recipes in replicate regions.
1093   VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
1094   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
1095            vp_depth_first_shallow(LoopRegion->getEntry()))) {
1096     for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
1097       if (CannotHoistRecipe(R))
1098         continue;
1099       // TODO: Relax checks in the future, e.g. we could also hoist reads, if
1100       // their memory location is not modified in the vector loop.
1101       if (R.mayHaveSideEffects() || R.mayReadFromMemory() || R.isPhi() ||
1102           any_of(R.operands(), [](VPValue *Op) {
1103             return !Op->isDefinedOutsideLoopRegions();
1104           }))
1105         continue;
1106       R.moveBefore(*Preheader, Preheader->end());
1107     }
1108   }
1109 }
1110 
1111 /// Try to simplify the recipes in \p Plan.
1112 static void simplifyRecipes(VPlan &Plan) {
1113   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> RPOT(
1114       Plan.getEntry());
1115   Type *CanonicalIVType = Plan.getCanonicalIV()->getScalarType();
1116   VPTypeAnalysis TypeInfo(CanonicalIVType);
1117   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
1118     for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
1119       simplifyRecipe(R, TypeInfo);
1120     }
1121   }
1122 }
1123 
1124 void VPlanTransforms::truncateToMinimalBitwidths(
1125     VPlan &Plan, const MapVector<Instruction *, uint64_t> &MinBWs) {
1126 #ifndef NDEBUG
1127   // Count the processed recipes and cross check the count later with MinBWs
1128   // size, to make sure all entries in MinBWs have been handled.
1129   unsigned NumProcessedRecipes = 0;
1130 #endif
1131   // Keep track of created truncates, so they can be re-used. Note that we
1132   // cannot use RAUW after creating a new truncate, as this would could make
1133   // other uses have different types for their operands, making them invalidly
1134   // typed.
1135   DenseMap<VPValue *, VPWidenCastRecipe *> ProcessedTruncs;
1136   Type *CanonicalIVType = Plan.getCanonicalIV()->getScalarType();
1137   VPTypeAnalysis TypeInfo(CanonicalIVType);
1138   VPBasicBlock *PH = Plan.getVectorPreheader();
1139   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
1140            vp_depth_first_deep(Plan.getVectorLoopRegion()))) {
1141     for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
1142       if (!isa<VPWidenRecipe, VPWidenCastRecipe, VPReplicateRecipe,
1143                VPWidenSelectRecipe, VPWidenLoadRecipe>(&R))
1144         continue;
1145 
1146       VPValue *ResultVPV = R.getVPSingleValue();
1147       auto *UI = cast_or_null<Instruction>(ResultVPV->getUnderlyingValue());
1148       unsigned NewResSizeInBits = MinBWs.lookup(UI);
1149       if (!NewResSizeInBits)
1150         continue;
1151 
1152 #ifndef NDEBUG
1153       NumProcessedRecipes++;
1154 #endif
1155       // If the value wasn't vectorized, we must maintain the original scalar
1156       // type. Skip those here, after incrementing NumProcessedRecipes. Also
1157       // skip casts which do not need to be handled explicitly here, as
1158       // redundant casts will be removed during recipe simplification.
1159       if (isa<VPReplicateRecipe, VPWidenCastRecipe>(&R)) {
1160 #ifndef NDEBUG
1161         // If any of the operands is a live-in and not used by VPWidenRecipe or
1162         // VPWidenSelectRecipe, but in MinBWs, make sure it is counted as
1163         // processed as well. When MinBWs is currently constructed, there is no
1164         // information about whether recipes are widened or replicated and in
1165         // case they are reciplicated the operands are not truncated. Counting
1166         // them them here ensures we do not miss any recipes in MinBWs.
1167         // TODO: Remove once the analysis is done on VPlan.
1168         for (VPValue *Op : R.operands()) {
1169           if (!Op->isLiveIn())
1170             continue;
1171           auto *UV = dyn_cast_or_null<Instruction>(Op->getUnderlyingValue());
1172           if (UV && MinBWs.contains(UV) && !ProcessedTruncs.contains(Op) &&
1173               none_of(Op->users(),
1174                       IsaPred<VPWidenRecipe, VPWidenSelectRecipe>)) {
1175             // Add an entry to ProcessedTruncs to avoid counting the same
1176             // operand multiple times.
1177             ProcessedTruncs[Op] = nullptr;
1178             NumProcessedRecipes += 1;
1179           }
1180         }
1181 #endif
1182         continue;
1183       }
1184 
1185       Type *OldResTy = TypeInfo.inferScalarType(ResultVPV);
1186       unsigned OldResSizeInBits = OldResTy->getScalarSizeInBits();
1187       assert(OldResTy->isIntegerTy() && "only integer types supported");
1188       (void)OldResSizeInBits;
1189 
1190       LLVMContext &Ctx = CanonicalIVType->getContext();
1191       auto *NewResTy = IntegerType::get(Ctx, NewResSizeInBits);
1192 
1193       // Any wrapping introduced by shrinking this operation shouldn't be
1194       // considered undefined behavior. So, we can't unconditionally copy
1195       // arithmetic wrapping flags to VPW.
1196       if (auto *VPW = dyn_cast<VPRecipeWithIRFlags>(&R))
1197         VPW->dropPoisonGeneratingFlags();
1198 
1199       using namespace llvm::VPlanPatternMatch;
1200       if (OldResSizeInBits != NewResSizeInBits &&
1201           !match(&R, m_Binary<Instruction::ICmp>(m_VPValue(), m_VPValue()))) {
1202         // Extend result to original width.
1203         auto *Ext =
1204             new VPWidenCastRecipe(Instruction::ZExt, ResultVPV, OldResTy);
1205         Ext->insertAfter(&R);
1206         ResultVPV->replaceAllUsesWith(Ext);
1207         Ext->setOperand(0, ResultVPV);
1208         assert(OldResSizeInBits > NewResSizeInBits && "Nothing to shrink?");
1209       } else {
1210         assert(
1211             match(&R, m_Binary<Instruction::ICmp>(m_VPValue(), m_VPValue())) &&
1212             "Only ICmps should not need extending the result.");
1213       }
1214 
1215       assert(!isa<VPWidenStoreRecipe>(&R) && "stores cannot be narrowed");
1216       if (isa<VPWidenLoadRecipe>(&R))
1217         continue;
1218 
1219       // Shrink operands by introducing truncates as needed.
1220       unsigned StartIdx = isa<VPWidenSelectRecipe>(&R) ? 1 : 0;
1221       for (unsigned Idx = StartIdx; Idx != R.getNumOperands(); ++Idx) {
1222         auto *Op = R.getOperand(Idx);
1223         unsigned OpSizeInBits =
1224             TypeInfo.inferScalarType(Op)->getScalarSizeInBits();
1225         if (OpSizeInBits == NewResSizeInBits)
1226           continue;
1227         assert(OpSizeInBits > NewResSizeInBits && "nothing to truncate");
1228         auto [ProcessedIter, IterIsEmpty] =
1229             ProcessedTruncs.insert({Op, nullptr});
1230         VPWidenCastRecipe *NewOp =
1231             IterIsEmpty
1232                 ? new VPWidenCastRecipe(Instruction::Trunc, Op, NewResTy)
1233                 : ProcessedIter->second;
1234         R.setOperand(Idx, NewOp);
1235         if (!IterIsEmpty)
1236           continue;
1237         ProcessedIter->second = NewOp;
1238         if (!Op->isLiveIn()) {
1239           NewOp->insertBefore(&R);
1240         } else {
1241           PH->appendRecipe(NewOp);
1242 #ifndef NDEBUG
1243           auto *OpInst = dyn_cast<Instruction>(Op->getLiveInIRValue());
1244           bool IsContained = MinBWs.contains(OpInst);
1245           NumProcessedRecipes += IsContained;
1246 #endif
1247         }
1248       }
1249 
1250     }
1251   }
1252 
1253   assert(MinBWs.size() == NumProcessedRecipes &&
1254          "some entries in MinBWs haven't been processed");
1255 }
1256 
1257 void VPlanTransforms::optimize(VPlan &Plan) {
1258   removeRedundantCanonicalIVs(Plan);
1259   removeRedundantInductionCasts(Plan);
1260 
1261   simplifyRecipes(Plan);
1262   legalizeAndOptimizeInductions(Plan);
1263   removeRedundantExpandSCEVRecipes(Plan);
1264   simplifyRecipes(Plan);
1265   removeDeadRecipes(Plan);
1266 
1267   createAndOptimizeReplicateRegions(Plan);
1268   mergeBlocksIntoPredecessors(Plan);
1269   licm(Plan);
1270 }
1271 
1272 // Add a VPActiveLaneMaskPHIRecipe and related recipes to \p Plan and replace
1273 // the loop terminator with a branch-on-cond recipe with the negated
1274 // active-lane-mask as operand. Note that this turns the loop into an
1275 // uncountable one. Only the existing terminator is replaced, all other existing
1276 // recipes/users remain unchanged, except for poison-generating flags being
1277 // dropped from the canonical IV increment. Return the created
1278 // VPActiveLaneMaskPHIRecipe.
1279 //
1280 // The function uses the following definitions:
1281 //
1282 //  %TripCount = DataWithControlFlowWithoutRuntimeCheck ?
1283 //    calculate-trip-count-minus-VF (original TC) : original TC
1284 //  %IncrementValue = DataWithControlFlowWithoutRuntimeCheck ?
1285 //     CanonicalIVPhi : CanonicalIVIncrement
1286 //  %StartV is the canonical induction start value.
1287 //
1288 // The function adds the following recipes:
1289 //
1290 // vector.ph:
1291 //   %TripCount = calculate-trip-count-minus-VF (original TC)
1292 //       [if DataWithControlFlowWithoutRuntimeCheck]
1293 //   %EntryInc = canonical-iv-increment-for-part %StartV
1294 //   %EntryALM = active-lane-mask %EntryInc, %TripCount
1295 //
1296 // vector.body:
1297 //   ...
1298 //   %P = active-lane-mask-phi [ %EntryALM, %vector.ph ], [ %ALM, %vector.body ]
1299 //   ...
1300 //   %InLoopInc = canonical-iv-increment-for-part %IncrementValue
1301 //   %ALM = active-lane-mask %InLoopInc, TripCount
1302 //   %Negated = Not %ALM
1303 //   branch-on-cond %Negated
1304 //
1305 static VPActiveLaneMaskPHIRecipe *addVPLaneMaskPhiAndUpdateExitBranch(
1306     VPlan &Plan, bool DataAndControlFlowWithoutRuntimeCheck) {
1307   VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
1308   VPBasicBlock *EB = TopRegion->getExitingBasicBlock();
1309   auto *CanonicalIVPHI = Plan.getCanonicalIV();
1310   VPValue *StartV = CanonicalIVPHI->getStartValue();
1311 
1312   auto *CanonicalIVIncrement =
1313       cast<VPInstruction>(CanonicalIVPHI->getBackedgeValue());
1314   // TODO: Check if dropping the flags is needed if
1315   // !DataAndControlFlowWithoutRuntimeCheck.
1316   CanonicalIVIncrement->dropPoisonGeneratingFlags();
1317   DebugLoc DL = CanonicalIVIncrement->getDebugLoc();
1318   // We can't use StartV directly in the ActiveLaneMask VPInstruction, since
1319   // we have to take unrolling into account. Each part needs to start at
1320   //   Part * VF
1321   auto *VecPreheader = Plan.getVectorPreheader();
1322   VPBuilder Builder(VecPreheader);
1323 
1324   // Create the ActiveLaneMask instruction using the correct start values.
1325   VPValue *TC = Plan.getTripCount();
1326 
1327   VPValue *TripCount, *IncrementValue;
1328   if (!DataAndControlFlowWithoutRuntimeCheck) {
1329     // When the loop is guarded by a runtime overflow check for the loop
1330     // induction variable increment by VF, we can increment the value before
1331     // the get.active.lane mask and use the unmodified tripcount.
1332     IncrementValue = CanonicalIVIncrement;
1333     TripCount = TC;
1334   } else {
1335     // When avoiding a runtime check, the active.lane.mask inside the loop
1336     // uses a modified trip count and the induction variable increment is
1337     // done after the active.lane.mask intrinsic is called.
1338     IncrementValue = CanonicalIVPHI;
1339     TripCount = Builder.createNaryOp(VPInstruction::CalculateTripCountMinusVF,
1340                                      {TC}, DL);
1341   }
1342   auto *EntryIncrement = Builder.createOverflowingOp(
1343       VPInstruction::CanonicalIVIncrementForPart, {StartV}, {false, false}, DL,
1344       "index.part.next");
1345 
1346   // Create the active lane mask instruction in the VPlan preheader.
1347   auto *EntryALM =
1348       Builder.createNaryOp(VPInstruction::ActiveLaneMask, {EntryIncrement, TC},
1349                            DL, "active.lane.mask.entry");
1350 
1351   // Now create the ActiveLaneMaskPhi recipe in the main loop using the
1352   // preheader ActiveLaneMask instruction.
1353   auto *LaneMaskPhi = new VPActiveLaneMaskPHIRecipe(EntryALM, DebugLoc());
1354   LaneMaskPhi->insertAfter(CanonicalIVPHI);
1355 
1356   // Create the active lane mask for the next iteration of the loop before the
1357   // original terminator.
1358   VPRecipeBase *OriginalTerminator = EB->getTerminator();
1359   Builder.setInsertPoint(OriginalTerminator);
1360   auto *InLoopIncrement =
1361       Builder.createOverflowingOp(VPInstruction::CanonicalIVIncrementForPart,
1362                                   {IncrementValue}, {false, false}, DL);
1363   auto *ALM = Builder.createNaryOp(VPInstruction::ActiveLaneMask,
1364                                    {InLoopIncrement, TripCount}, DL,
1365                                    "active.lane.mask.next");
1366   LaneMaskPhi->addOperand(ALM);
1367 
1368   // Replace the original terminator with BranchOnCond. We have to invert the
1369   // mask here because a true condition means jumping to the exit block.
1370   auto *NotMask = Builder.createNot(ALM, DL);
1371   Builder.createNaryOp(VPInstruction::BranchOnCond, {NotMask}, DL);
1372   OriginalTerminator->eraseFromParent();
1373   return LaneMaskPhi;
1374 }
1375 
1376 /// Collect all VPValues representing a header mask through the (ICMP_ULE,
1377 /// WideCanonicalIV, backedge-taken-count) pattern.
1378 /// TODO: Introduce explicit recipe for header-mask instead of searching
1379 /// for the header-mask pattern manually.
1380 static SmallVector<VPValue *> collectAllHeaderMasks(VPlan &Plan) {
1381   SmallVector<VPValue *> WideCanonicalIVs;
1382   auto *FoundWidenCanonicalIVUser =
1383       find_if(Plan.getCanonicalIV()->users(),
1384               [](VPUser *U) { return isa<VPWidenCanonicalIVRecipe>(U); });
1385   assert(count_if(Plan.getCanonicalIV()->users(),
1386                   [](VPUser *U) { return isa<VPWidenCanonicalIVRecipe>(U); }) <=
1387              1 &&
1388          "Must have at most one VPWideCanonicalIVRecipe");
1389   if (FoundWidenCanonicalIVUser != Plan.getCanonicalIV()->users().end()) {
1390     auto *WideCanonicalIV =
1391         cast<VPWidenCanonicalIVRecipe>(*FoundWidenCanonicalIVUser);
1392     WideCanonicalIVs.push_back(WideCanonicalIV);
1393   }
1394 
1395   // Also include VPWidenIntOrFpInductionRecipes that represent a widened
1396   // version of the canonical induction.
1397   VPBasicBlock *HeaderVPBB = Plan.getVectorLoopRegion()->getEntryBasicBlock();
1398   for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
1399     auto *WidenOriginalIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
1400     if (WidenOriginalIV && WidenOriginalIV->isCanonical())
1401       WideCanonicalIVs.push_back(WidenOriginalIV);
1402   }
1403 
1404   // Walk users of wide canonical IVs and collect to all compares of the form
1405   // (ICMP_ULE, WideCanonicalIV, backedge-taken-count).
1406   SmallVector<VPValue *> HeaderMasks;
1407   for (auto *Wide : WideCanonicalIVs) {
1408     for (VPUser *U : SmallVector<VPUser *>(Wide->users())) {
1409       auto *HeaderMask = dyn_cast<VPInstruction>(U);
1410       if (!HeaderMask || !vputils::isHeaderMask(HeaderMask, Plan))
1411         continue;
1412 
1413       assert(HeaderMask->getOperand(0) == Wide &&
1414              "WidenCanonicalIV must be the first operand of the compare");
1415       HeaderMasks.push_back(HeaderMask);
1416     }
1417   }
1418   return HeaderMasks;
1419 }
1420 
1421 void VPlanTransforms::addActiveLaneMask(
1422     VPlan &Plan, bool UseActiveLaneMaskForControlFlow,
1423     bool DataAndControlFlowWithoutRuntimeCheck) {
1424   assert((!DataAndControlFlowWithoutRuntimeCheck ||
1425           UseActiveLaneMaskForControlFlow) &&
1426          "DataAndControlFlowWithoutRuntimeCheck implies "
1427          "UseActiveLaneMaskForControlFlow");
1428 
1429   auto *FoundWidenCanonicalIVUser =
1430       find_if(Plan.getCanonicalIV()->users(),
1431               [](VPUser *U) { return isa<VPWidenCanonicalIVRecipe>(U); });
1432   assert(FoundWidenCanonicalIVUser &&
1433          "Must have widened canonical IV when tail folding!");
1434   auto *WideCanonicalIV =
1435       cast<VPWidenCanonicalIVRecipe>(*FoundWidenCanonicalIVUser);
1436   VPSingleDefRecipe *LaneMask;
1437   if (UseActiveLaneMaskForControlFlow) {
1438     LaneMask = addVPLaneMaskPhiAndUpdateExitBranch(
1439         Plan, DataAndControlFlowWithoutRuntimeCheck);
1440   } else {
1441     VPBuilder B = VPBuilder::getToInsertAfter(WideCanonicalIV);
1442     LaneMask = B.createNaryOp(VPInstruction::ActiveLaneMask,
1443                               {WideCanonicalIV, Plan.getTripCount()}, nullptr,
1444                               "active.lane.mask");
1445   }
1446 
1447   // Walk users of WideCanonicalIV and replace all compares of the form
1448   // (ICMP_ULE, WideCanonicalIV, backedge-taken-count) with an
1449   // active-lane-mask.
1450   for (VPValue *HeaderMask : collectAllHeaderMasks(Plan))
1451     HeaderMask->replaceAllUsesWith(LaneMask);
1452 }
1453 
1454 /// Try to convert \p CurRecipe to a corresponding EVL-based recipe. Returns
1455 /// nullptr if no EVL-based recipe could be created.
1456 /// \p HeaderMask  Header Mask.
1457 /// \p CurRecipe   Recipe to be transform.
1458 /// \p TypeInfo    VPlan-based type analysis.
1459 /// \p AllOneMask  The vector mask parameter of vector-predication intrinsics.
1460 /// \p EVL         The explicit vector length parameter of vector-predication
1461 /// intrinsics.
1462 static VPRecipeBase *createEVLRecipe(VPValue *HeaderMask,
1463                                      VPRecipeBase &CurRecipe,
1464                                      VPTypeAnalysis &TypeInfo,
1465                                      VPValue &AllOneMask, VPValue &EVL) {
1466   using namespace llvm::VPlanPatternMatch;
1467   auto GetNewMask = [&](VPValue *OrigMask) -> VPValue * {
1468     assert(OrigMask && "Unmasked recipe when folding tail");
1469     return HeaderMask == OrigMask ? nullptr : OrigMask;
1470   };
1471 
1472   return TypeSwitch<VPRecipeBase *, VPRecipeBase *>(&CurRecipe)
1473       .Case<VPWidenLoadRecipe>([&](VPWidenLoadRecipe *L) {
1474         VPValue *NewMask = GetNewMask(L->getMask());
1475         return new VPWidenLoadEVLRecipe(*L, EVL, NewMask);
1476       })
1477       .Case<VPWidenStoreRecipe>([&](VPWidenStoreRecipe *S) {
1478         VPValue *NewMask = GetNewMask(S->getMask());
1479         return new VPWidenStoreEVLRecipe(*S, EVL, NewMask);
1480       })
1481       .Case<VPWidenRecipe>([&](VPWidenRecipe *W) -> VPRecipeBase * {
1482         unsigned Opcode = W->getOpcode();
1483         if (!Instruction::isBinaryOp(Opcode) && !Instruction::isUnaryOp(Opcode))
1484           return nullptr;
1485         return new VPWidenEVLRecipe(*W, EVL);
1486       })
1487       .Case<VPReductionRecipe>([&](VPReductionRecipe *Red) {
1488         VPValue *NewMask = GetNewMask(Red->getCondOp());
1489         return new VPReductionEVLRecipe(*Red, EVL, NewMask);
1490       })
1491       .Case<VPWidenIntrinsicRecipe, VPWidenCastRecipe>(
1492           [&](auto *CR) -> VPRecipeBase * {
1493             Intrinsic::ID VPID;
1494             if (auto *CallR = dyn_cast<VPWidenIntrinsicRecipe>(CR)) {
1495               VPID =
1496                   VPIntrinsic::getForIntrinsic(CallR->getVectorIntrinsicID());
1497             } else {
1498               auto *CastR = cast<VPWidenCastRecipe>(CR);
1499               VPID = VPIntrinsic::getForOpcode(CastR->getOpcode());
1500             }
1501             assert(VPID != Intrinsic::not_intrinsic && "Expected VP intrinsic");
1502             assert(VPIntrinsic::getMaskParamPos(VPID) &&
1503                    VPIntrinsic::getVectorLengthParamPos(VPID) &&
1504                    "Expected VP intrinsic");
1505 
1506             SmallVector<VPValue *> Ops(CR->operands());
1507             Ops.push_back(&AllOneMask);
1508             Ops.push_back(&EVL);
1509             return new VPWidenIntrinsicRecipe(
1510                 VPID, Ops, TypeInfo.inferScalarType(CR), CR->getDebugLoc());
1511           })
1512       .Case<VPWidenSelectRecipe>([&](VPWidenSelectRecipe *Sel) {
1513         SmallVector<VPValue *> Ops(Sel->operands());
1514         Ops.push_back(&EVL);
1515         return new VPWidenIntrinsicRecipe(Intrinsic::vp_select, Ops,
1516                                           TypeInfo.inferScalarType(Sel),
1517                                           Sel->getDebugLoc());
1518       })
1519       .Case<VPInstruction>([&](VPInstruction *VPI) -> VPRecipeBase * {
1520         VPValue *LHS, *RHS;
1521         // Transform select with a header mask condition
1522         //   select(header_mask, LHS, RHS)
1523         // into vector predication merge.
1524         //   vp.merge(all-true, LHS, RHS, EVL)
1525         if (!match(VPI, m_Select(m_Specific(HeaderMask), m_VPValue(LHS),
1526                                  m_VPValue(RHS))))
1527           return nullptr;
1528         // Use all true as the condition because this transformation is
1529         // limited to selects whose condition is a header mask.
1530         return new VPWidenIntrinsicRecipe(
1531             Intrinsic::vp_merge, {&AllOneMask, LHS, RHS, &EVL},
1532             TypeInfo.inferScalarType(LHS), VPI->getDebugLoc());
1533       })
1534       .Default([&](VPRecipeBase *R) { return nullptr; });
1535 }
1536 
1537 /// Replace recipes with their EVL variants.
1538 static void transformRecipestoEVLRecipes(VPlan &Plan, VPValue &EVL) {
1539   Type *CanonicalIVType = Plan.getCanonicalIV()->getScalarType();
1540   VPTypeAnalysis TypeInfo(CanonicalIVType);
1541   LLVMContext &Ctx = CanonicalIVType->getContext();
1542   VPValue *AllOneMask = Plan.getOrAddLiveIn(ConstantInt::getTrue(Ctx));
1543 
1544   for (VPUser *U : Plan.getVF().users()) {
1545     if (auto *R = dyn_cast<VPReverseVectorPointerRecipe>(U))
1546       R->setOperand(1, &EVL);
1547   }
1548 
1549   SmallVector<VPRecipeBase *> ToErase;
1550 
1551   for (VPValue *HeaderMask : collectAllHeaderMasks(Plan)) {
1552     for (VPUser *U : collectUsersRecursively(HeaderMask)) {
1553       auto *CurRecipe = cast<VPRecipeBase>(U);
1554       VPRecipeBase *EVLRecipe =
1555           createEVLRecipe(HeaderMask, *CurRecipe, TypeInfo, *AllOneMask, EVL);
1556       if (!EVLRecipe)
1557         continue;
1558 
1559       [[maybe_unused]] unsigned NumDefVal = EVLRecipe->getNumDefinedValues();
1560       assert(NumDefVal == CurRecipe->getNumDefinedValues() &&
1561              "New recipe must define the same number of values as the "
1562              "original.");
1563       assert(
1564           NumDefVal <= 1 &&
1565           "Only supports recipes with a single definition or without users.");
1566       EVLRecipe->insertBefore(CurRecipe);
1567       if (isa<VPSingleDefRecipe, VPWidenLoadEVLRecipe>(EVLRecipe)) {
1568         VPValue *CurVPV = CurRecipe->getVPSingleValue();
1569         CurVPV->replaceAllUsesWith(EVLRecipe->getVPSingleValue());
1570       }
1571       // Defer erasing recipes till the end so that we don't invalidate the
1572       // VPTypeAnalysis cache.
1573       ToErase.push_back(CurRecipe);
1574     }
1575   }
1576 
1577   for (VPRecipeBase *R : reverse(ToErase)) {
1578     SmallVector<VPValue *> PossiblyDead(R->operands());
1579     R->eraseFromParent();
1580     for (VPValue *Op : PossiblyDead)
1581       recursivelyDeleteDeadRecipes(Op);
1582   }
1583 }
1584 
1585 /// Add a VPEVLBasedIVPHIRecipe and related recipes to \p Plan and
1586 /// replaces all uses except the canonical IV increment of
1587 /// VPCanonicalIVPHIRecipe with a VPEVLBasedIVPHIRecipe. VPCanonicalIVPHIRecipe
1588 /// is used only for loop iterations counting after this transformation.
1589 ///
1590 /// The function uses the following definitions:
1591 ///  %StartV is the canonical induction start value.
1592 ///
1593 /// The function adds the following recipes:
1594 ///
1595 /// vector.ph:
1596 /// ...
1597 ///
1598 /// vector.body:
1599 /// ...
1600 /// %EVLPhi = EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI [ %StartV, %vector.ph ],
1601 ///                                               [ %NextEVLIV, %vector.body ]
1602 /// %AVL = sub original TC, %EVLPhi
1603 /// %VPEVL = EXPLICIT-VECTOR-LENGTH %AVL
1604 /// ...
1605 /// %NextEVLIV = add IVSize (cast i32 %VPEVVL to IVSize), %EVLPhi
1606 /// ...
1607 ///
1608 /// If MaxSafeElements is provided, the function adds the following recipes:
1609 /// vector.ph:
1610 /// ...
1611 ///
1612 /// vector.body:
1613 /// ...
1614 /// %EVLPhi = EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI [ %StartV, %vector.ph ],
1615 ///                                               [ %NextEVLIV, %vector.body ]
1616 /// %AVL = sub original TC, %EVLPhi
1617 /// %cmp = cmp ult %AVL, MaxSafeElements
1618 /// %SAFE_AVL = select %cmp, %AVL, MaxSafeElements
1619 /// %VPEVL = EXPLICIT-VECTOR-LENGTH %SAFE_AVL
1620 /// ...
1621 /// %NextEVLIV = add IVSize (cast i32 %VPEVL to IVSize), %EVLPhi
1622 /// ...
1623 ///
1624 bool VPlanTransforms::tryAddExplicitVectorLength(
1625     VPlan &Plan, const std::optional<unsigned> &MaxSafeElements) {
1626   VPBasicBlock *Header = Plan.getVectorLoopRegion()->getEntryBasicBlock();
1627   // The transform updates all users of inductions to work based on EVL, instead
1628   // of the VF directly. At the moment, widened inductions cannot be updated, so
1629   // bail out if the plan contains any.
1630   bool ContainsWidenInductions = any_of(
1631       Header->phis(),
1632       IsaPred<VPWidenIntOrFpInductionRecipe, VPWidenPointerInductionRecipe>);
1633   if (ContainsWidenInductions)
1634     return false;
1635 
1636   auto *CanonicalIVPHI = Plan.getCanonicalIV();
1637   VPValue *StartV = CanonicalIVPHI->getStartValue();
1638 
1639   // Create the ExplicitVectorLengthPhi recipe in the main loop.
1640   auto *EVLPhi = new VPEVLBasedIVPHIRecipe(StartV, DebugLoc());
1641   EVLPhi->insertAfter(CanonicalIVPHI);
1642   VPBuilder Builder(Header, Header->getFirstNonPhi());
1643   // Compute original TC - IV as the AVL (application vector length).
1644   VPValue *AVL = Builder.createNaryOp(
1645       Instruction::Sub, {Plan.getTripCount(), EVLPhi}, DebugLoc(), "avl");
1646   if (MaxSafeElements) {
1647     // Support for MaxSafeDist for correct loop emission.
1648     VPValue *AVLSafe = Plan.getOrAddLiveIn(
1649         ConstantInt::get(CanonicalIVPHI->getScalarType(), *MaxSafeElements));
1650     VPValue *Cmp = Builder.createICmp(ICmpInst::ICMP_ULT, AVL, AVLSafe);
1651     AVL = Builder.createSelect(Cmp, AVL, AVLSafe, DebugLoc(), "safe_avl");
1652   }
1653   auto *VPEVL = Builder.createNaryOp(VPInstruction::ExplicitVectorLength, AVL,
1654                                      DebugLoc());
1655 
1656   auto *CanonicalIVIncrement =
1657       cast<VPInstruction>(CanonicalIVPHI->getBackedgeValue());
1658   VPSingleDefRecipe *OpVPEVL = VPEVL;
1659   if (unsigned IVSize = CanonicalIVPHI->getScalarType()->getScalarSizeInBits();
1660       IVSize != 32) {
1661     OpVPEVL = new VPScalarCastRecipe(IVSize < 32 ? Instruction::Trunc
1662                                                  : Instruction::ZExt,
1663                                      OpVPEVL, CanonicalIVPHI->getScalarType());
1664     OpVPEVL->insertBefore(CanonicalIVIncrement);
1665   }
1666   auto *NextEVLIV =
1667       new VPInstruction(Instruction::Add, {OpVPEVL, EVLPhi},
1668                         {CanonicalIVIncrement->hasNoUnsignedWrap(),
1669                          CanonicalIVIncrement->hasNoSignedWrap()},
1670                         CanonicalIVIncrement->getDebugLoc(), "index.evl.next");
1671   NextEVLIV->insertBefore(CanonicalIVIncrement);
1672   EVLPhi->addOperand(NextEVLIV);
1673 
1674   transformRecipestoEVLRecipes(Plan, *VPEVL);
1675 
1676   // Replace all uses of VPCanonicalIVPHIRecipe by
1677   // VPEVLBasedIVPHIRecipe except for the canonical IV increment.
1678   CanonicalIVPHI->replaceAllUsesWith(EVLPhi);
1679   CanonicalIVIncrement->setOperand(0, CanonicalIVPHI);
1680   // TODO: support unroll factor > 1.
1681   Plan.setUF(1);
1682   return true;
1683 }
1684 
1685 void VPlanTransforms::dropPoisonGeneratingRecipes(
1686     VPlan &Plan, function_ref<bool(BasicBlock *)> BlockNeedsPredication) {
1687   // Collect recipes in the backward slice of `Root` that may generate a poison
1688   // value that is used after vectorization.
1689   SmallPtrSet<VPRecipeBase *, 16> Visited;
1690   auto CollectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1691     SmallVector<VPRecipeBase *, 16> Worklist;
1692     Worklist.push_back(Root);
1693 
1694     // Traverse the backward slice of Root through its use-def chain.
1695     while (!Worklist.empty()) {
1696       VPRecipeBase *CurRec = Worklist.pop_back_val();
1697 
1698       if (!Visited.insert(CurRec).second)
1699         continue;
1700 
1701       // Prune search if we find another recipe generating a widen memory
1702       // instruction. Widen memory instructions involved in address computation
1703       // will lead to gather/scatter instructions, which don't need to be
1704       // handled.
1705       if (isa<VPWidenMemoryRecipe, VPInterleaveRecipe, VPScalarIVStepsRecipe,
1706               VPHeaderPHIRecipe>(CurRec))
1707         continue;
1708 
1709       // This recipe contributes to the address computation of a widen
1710       // load/store. If the underlying instruction has poison-generating flags,
1711       // drop them directly.
1712       if (auto *RecWithFlags = dyn_cast<VPRecipeWithIRFlags>(CurRec)) {
1713         VPValue *A, *B;
1714         using namespace llvm::VPlanPatternMatch;
1715         // Dropping disjoint from an OR may yield incorrect results, as some
1716         // analysis may have converted it to an Add implicitly (e.g. SCEV used
1717         // for dependence analysis). Instead, replace it with an equivalent Add.
1718         // This is possible as all users of the disjoint OR only access lanes
1719         // where the operands are disjoint or poison otherwise.
1720         if (match(RecWithFlags, m_BinaryOr(m_VPValue(A), m_VPValue(B))) &&
1721             RecWithFlags->isDisjoint()) {
1722           VPBuilder Builder(RecWithFlags);
1723           VPInstruction *New = Builder.createOverflowingOp(
1724               Instruction::Add, {A, B}, {false, false},
1725               RecWithFlags->getDebugLoc());
1726           New->setUnderlyingValue(RecWithFlags->getUnderlyingValue());
1727           RecWithFlags->replaceAllUsesWith(New);
1728           RecWithFlags->eraseFromParent();
1729           CurRec = New;
1730         } else
1731           RecWithFlags->dropPoisonGeneratingFlags();
1732       } else {
1733         Instruction *Instr = dyn_cast_or_null<Instruction>(
1734             CurRec->getVPSingleValue()->getUnderlyingValue());
1735         (void)Instr;
1736         assert((!Instr || !Instr->hasPoisonGeneratingFlags()) &&
1737                "found instruction with poison generating flags not covered by "
1738                "VPRecipeWithIRFlags");
1739       }
1740 
1741       // Add new definitions to the worklist.
1742       for (VPValue *Operand : CurRec->operands())
1743         if (VPRecipeBase *OpDef = Operand->getDefiningRecipe())
1744           Worklist.push_back(OpDef);
1745     }
1746   });
1747 
1748   // Traverse all the recipes in the VPlan and collect the poison-generating
1749   // recipes in the backward slice starting at the address of a VPWidenRecipe or
1750   // VPInterleaveRecipe.
1751   auto Iter = vp_depth_first_deep(Plan.getEntry());
1752   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1753     for (VPRecipeBase &Recipe : *VPBB) {
1754       if (auto *WidenRec = dyn_cast<VPWidenMemoryRecipe>(&Recipe)) {
1755         Instruction &UnderlyingInstr = WidenRec->getIngredient();
1756         VPRecipeBase *AddrDef = WidenRec->getAddr()->getDefiningRecipe();
1757         if (AddrDef && WidenRec->isConsecutive() &&
1758             BlockNeedsPredication(UnderlyingInstr.getParent()))
1759           CollectPoisonGeneratingInstrsInBackwardSlice(AddrDef);
1760       } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1761         VPRecipeBase *AddrDef = InterleaveRec->getAddr()->getDefiningRecipe();
1762         if (AddrDef) {
1763           // Check if any member of the interleave group needs predication.
1764           const InterleaveGroup<Instruction> *InterGroup =
1765               InterleaveRec->getInterleaveGroup();
1766           bool NeedPredication = false;
1767           for (int I = 0, NumMembers = InterGroup->getNumMembers();
1768                I < NumMembers; ++I) {
1769             Instruction *Member = InterGroup->getMember(I);
1770             if (Member)
1771               NeedPredication |= BlockNeedsPredication(Member->getParent());
1772           }
1773 
1774           if (NeedPredication)
1775             CollectPoisonGeneratingInstrsInBackwardSlice(AddrDef);
1776         }
1777       }
1778     }
1779   }
1780 }
1781 
1782 void VPlanTransforms::createInterleaveGroups(
1783     VPlan &Plan,
1784     const SmallPtrSetImpl<const InterleaveGroup<Instruction> *>
1785         &InterleaveGroups,
1786     VPRecipeBuilder &RecipeBuilder, bool ScalarEpilogueAllowed) {
1787   if (InterleaveGroups.empty())
1788     return;
1789 
1790   // Interleave memory: for each Interleave Group we marked earlier as relevant
1791   // for this VPlan, replace the Recipes widening its memory instructions with a
1792   // single VPInterleaveRecipe at its insertion point.
1793   VPDominatorTree VPDT;
1794   VPDT.recalculate(Plan);
1795   for (const auto *IG : InterleaveGroups) {
1796     SmallVector<VPValue *, 4> StoredValues;
1797     for (unsigned i = 0; i < IG->getFactor(); ++i)
1798       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
1799         auto *StoreR = cast<VPWidenStoreRecipe>(RecipeBuilder.getRecipe(SI));
1800         StoredValues.push_back(StoreR->getStoredValue());
1801       }
1802 
1803     bool NeedsMaskForGaps =
1804         IG->requiresScalarEpilogue() && !ScalarEpilogueAllowed;
1805 
1806     Instruction *IRInsertPos = IG->getInsertPos();
1807     auto *InsertPos =
1808         cast<VPWidenMemoryRecipe>(RecipeBuilder.getRecipe(IRInsertPos));
1809 
1810     // Get or create the start address for the interleave group.
1811     auto *Start =
1812         cast<VPWidenMemoryRecipe>(RecipeBuilder.getRecipe(IG->getMember(0)));
1813     VPValue *Addr = Start->getAddr();
1814     VPRecipeBase *AddrDef = Addr->getDefiningRecipe();
1815     if (AddrDef && !VPDT.properlyDominates(AddrDef, InsertPos)) {
1816       // TODO: Hoist Addr's defining recipe (and any operands as needed) to
1817       // InsertPos or sink loads above zero members to join it.
1818       bool InBounds = false;
1819       if (auto *Gep = dyn_cast<GetElementPtrInst>(
1820               getLoadStorePointerOperand(IRInsertPos)->stripPointerCasts()))
1821         InBounds = Gep->isInBounds();
1822 
1823       // We cannot re-use the address of member zero because it does not
1824       // dominate the insert position. Instead, use the address of the insert
1825       // position and create a PtrAdd adjusting it to the address of member
1826       // zero.
1827       assert(IG->getIndex(IRInsertPos) != 0 &&
1828              "index of insert position shouldn't be zero");
1829       auto &DL = IRInsertPos->getDataLayout();
1830       APInt Offset(32,
1831                    DL.getTypeAllocSize(getLoadStoreType(IRInsertPos)) *
1832                        IG->getIndex(IRInsertPos),
1833                    /*IsSigned=*/true);
1834       VPValue *OffsetVPV = Plan.getOrAddLiveIn(
1835           ConstantInt::get(IRInsertPos->getParent()->getContext(), -Offset));
1836       VPBuilder B(InsertPos);
1837       Addr = InBounds ? B.createInBoundsPtrAdd(InsertPos->getAddr(), OffsetVPV)
1838                       : B.createPtrAdd(InsertPos->getAddr(), OffsetVPV);
1839     }
1840     auto *VPIG = new VPInterleaveRecipe(IG, Addr, StoredValues,
1841                                         InsertPos->getMask(), NeedsMaskForGaps);
1842     VPIG->insertBefore(InsertPos);
1843 
1844     unsigned J = 0;
1845     for (unsigned i = 0; i < IG->getFactor(); ++i)
1846       if (Instruction *Member = IG->getMember(i)) {
1847         VPRecipeBase *MemberR = RecipeBuilder.getRecipe(Member);
1848         if (!Member->getType()->isVoidTy()) {
1849           VPValue *OriginalV = MemberR->getVPSingleValue();
1850           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
1851           J++;
1852         }
1853         MemberR->eraseFromParent();
1854       }
1855   }
1856 }
1857 
1858 void VPlanTransforms::convertToConcreteRecipes(VPlan &Plan) {
1859   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
1860            vp_depth_first_deep(Plan.getEntry()))) {
1861     for (VPRecipeBase &R : make_early_inc_range(VPBB->phis())) {
1862       if (!isa<VPCanonicalIVPHIRecipe, VPEVLBasedIVPHIRecipe>(&R))
1863         continue;
1864       auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
1865       StringRef Name =
1866           isa<VPCanonicalIVPHIRecipe>(PhiR) ? "index" : "evl.based.iv";
1867       auto *ScalarR =
1868           new VPScalarPHIRecipe(PhiR->getStartValue(), PhiR->getBackedgeValue(),
1869                                 PhiR->getDebugLoc(), Name);
1870       ScalarR->insertBefore(PhiR);
1871       PhiR->replaceAllUsesWith(ScalarR);
1872       PhiR->eraseFromParent();
1873     }
1874   }
1875 }
1876 
1877 void VPlanTransforms::handleUncountableEarlyExit(
1878     VPlan &Plan, ScalarEvolution &SE, Loop *OrigLoop,
1879     BasicBlock *UncountableExitingBlock, VPRecipeBuilder &RecipeBuilder) {
1880   VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
1881   auto *LatchVPBB = cast<VPBasicBlock>(LoopRegion->getExiting());
1882   VPBuilder Builder(LatchVPBB->getTerminator());
1883   auto *MiddleVPBB = Plan.getMiddleBlock();
1884   VPValue *IsEarlyExitTaken = nullptr;
1885 
1886   // Process the uncountable exiting block. Update IsEarlyExitTaken, which
1887   // tracks if the uncountable early exit has been taken. Also split the middle
1888   // block and have it conditionally branch to the early exit block if
1889   // EarlyExitTaken.
1890   auto *EarlyExitingBranch =
1891       cast<BranchInst>(UncountableExitingBlock->getTerminator());
1892   BasicBlock *TrueSucc = EarlyExitingBranch->getSuccessor(0);
1893   BasicBlock *FalseSucc = EarlyExitingBranch->getSuccessor(1);
1894 
1895   // The early exit block may or may not be the same as the "countable" exit
1896   // block. Creates a new VPIRBB for the early exit block in case it is distinct
1897   // from the countable exit block.
1898   // TODO: Introduce both exit blocks during VPlan skeleton construction.
1899   VPIRBasicBlock *VPEarlyExitBlock;
1900   if (OrigLoop->getUniqueExitBlock()) {
1901     VPEarlyExitBlock = cast<VPIRBasicBlock>(MiddleVPBB->getSuccessors()[0]);
1902   } else {
1903     VPEarlyExitBlock = Plan.createVPIRBasicBlock(
1904         !OrigLoop->contains(TrueSucc) ? TrueSucc : FalseSucc);
1905   }
1906 
1907   VPValue *EarlyExitNotTakenCond = RecipeBuilder.getBlockInMask(
1908       OrigLoop->contains(TrueSucc) ? TrueSucc : FalseSucc);
1909   auto *EarlyExitTakenCond = Builder.createNot(EarlyExitNotTakenCond);
1910   IsEarlyExitTaken =
1911       Builder.createNaryOp(VPInstruction::AnyOf, {EarlyExitTakenCond});
1912 
1913   VPBasicBlock *NewMiddle = Plan.createVPBasicBlock("middle.split");
1914   VPBlockUtils::insertOnEdge(LoopRegion, MiddleVPBB, NewMiddle);
1915   VPBlockUtils::connectBlocks(NewMiddle, VPEarlyExitBlock);
1916   NewMiddle->swapSuccessors();
1917 
1918   VPBuilder MiddleBuilder(NewMiddle);
1919   MiddleBuilder.createNaryOp(VPInstruction::BranchOnCond, {IsEarlyExitTaken});
1920 
1921   // Replace the condition controlling the non-early exit from the vector loop
1922   // with one exiting if either the original condition of the vector latch is
1923   // true or the early exit has been taken.
1924   auto *LatchExitingBranch = cast<VPInstruction>(LatchVPBB->getTerminator());
1925   assert(LatchExitingBranch->getOpcode() == VPInstruction::BranchOnCount &&
1926          "Unexpected terminator");
1927   auto *IsLatchExitTaken =
1928       Builder.createICmp(CmpInst::ICMP_EQ, LatchExitingBranch->getOperand(0),
1929                          LatchExitingBranch->getOperand(1));
1930   auto *AnyExitTaken = Builder.createNaryOp(
1931       Instruction::Or, {IsEarlyExitTaken, IsLatchExitTaken});
1932   Builder.createNaryOp(VPInstruction::BranchOnCond, AnyExitTaken);
1933   LatchExitingBranch->eraseFromParent();
1934 }
1935