LLVM 19.0.0git
VPlanTransforms.cpp
Go to the documentation of this file.
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 "VPlanAnalysis.h"
17#include "VPlanCFG.h"
18#include "VPlanDominatorTree.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
24#include "llvm/IR/Intrinsics.h"
26
27using namespace llvm;
28
29using namespace llvm::PatternMatch;
30
32 VPlanPtr &Plan,
34 GetIntOrFpInductionDescriptor,
35 ScalarEvolution &SE, const TargetLibraryInfo &TLI) {
36
38 Plan->getEntry());
39 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
40 VPRecipeBase *Term = VPBB->getTerminator();
41 auto EndIter = Term ? Term->getIterator() : VPBB->end();
42 // Introduce each ingredient into VPlan.
43 for (VPRecipeBase &Ingredient :
44 make_early_inc_range(make_range(VPBB->begin(), EndIter))) {
45
46 VPValue *VPV = Ingredient.getVPSingleValue();
47 Instruction *Inst = cast<Instruction>(VPV->getUnderlyingValue());
48
49 VPRecipeBase *NewRecipe = nullptr;
50 if (auto *VPPhi = dyn_cast<VPWidenPHIRecipe>(&Ingredient)) {
51 auto *Phi = cast<PHINode>(VPPhi->getUnderlyingValue());
52 if (const auto *II = GetIntOrFpInductionDescriptor(Phi)) {
53 VPValue *Start = Plan->getVPValueOrAddLiveIn(II->getStartValue());
54 VPValue *Step =
55 vputils::getOrCreateVPValueForSCEVExpr(*Plan, II->getStep(), SE);
56 NewRecipe = new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, *II);
57 } else {
58 Plan->addVPValue(Phi, VPPhi);
59 continue;
60 }
61 } else {
62 assert(isa<VPInstruction>(&Ingredient) &&
63 "only VPInstructions expected here");
64 assert(!isa<PHINode>(Inst) && "phis should be handled above");
65 // Create VPWidenMemoryInstructionRecipe for loads and stores.
66 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
67 NewRecipe = new VPWidenMemoryInstructionRecipe(
68 *Load, Ingredient.getOperand(0), nullptr /*Mask*/,
69 false /*Consecutive*/, false /*Reverse*/);
70 } else if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
71 NewRecipe = new VPWidenMemoryInstructionRecipe(
72 *Store, Ingredient.getOperand(1), Ingredient.getOperand(0),
73 nullptr /*Mask*/, false /*Consecutive*/, false /*Reverse*/);
74 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
75 NewRecipe = new VPWidenGEPRecipe(GEP, Ingredient.operands());
76 } else if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
77 NewRecipe = new VPWidenCallRecipe(
78 *CI, drop_end(Ingredient.operands()),
79 getVectorIntrinsicIDForCall(CI, &TLI), CI->getDebugLoc());
80 } else if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
81 NewRecipe = new VPWidenSelectRecipe(*SI, Ingredient.operands());
82 } else if (auto *CI = dyn_cast<CastInst>(Inst)) {
83 NewRecipe = new VPWidenCastRecipe(
84 CI->getOpcode(), Ingredient.getOperand(0), CI->getType(), *CI);
85 } else {
86 NewRecipe = new VPWidenRecipe(*Inst, Ingredient.operands());
87 }
88 }
89
90 NewRecipe->insertBefore(&Ingredient);
91 if (NewRecipe->getNumDefinedValues() == 1)
92 VPV->replaceAllUsesWith(NewRecipe->getVPSingleValue());
93 else
94 assert(NewRecipe->getNumDefinedValues() == 0 &&
95 "Only recpies with zero or one defined values expected");
96 Ingredient.eraseFromParent();
97 }
98 }
99}
100
101static bool sinkScalarOperands(VPlan &Plan) {
102 auto Iter = vp_depth_first_deep(Plan.getEntry());
103 bool Changed = false;
104 // First, collect the operands of all recipes in replicate blocks as seeds for
105 // sinking.
107 for (VPRegionBlock *VPR : VPBlockUtils::blocksOnly<VPRegionBlock>(Iter)) {
108 VPBasicBlock *EntryVPBB = VPR->getEntryBasicBlock();
109 if (!VPR->isReplicator() || EntryVPBB->getSuccessors().size() != 2)
110 continue;
111 VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(EntryVPBB->getSuccessors()[0]);
112 if (!VPBB || VPBB->getSingleSuccessor() != VPR->getExitingBasicBlock())
113 continue;
114 for (auto &Recipe : *VPBB) {
115 for (VPValue *Op : Recipe.operands())
116 if (auto *Def =
117 dyn_cast_or_null<VPSingleDefRecipe>(Op->getDefiningRecipe()))
118 WorkList.insert(std::make_pair(VPBB, Def));
119 }
120 }
121
122 bool ScalarVFOnly = Plan.hasScalarVFOnly();
123 // Try to sink each replicate or scalar IV steps recipe in the worklist.
124 for (unsigned I = 0; I != WorkList.size(); ++I) {
125 VPBasicBlock *SinkTo;
126 VPSingleDefRecipe *SinkCandidate;
127 std::tie(SinkTo, SinkCandidate) = WorkList[I];
128 if (SinkCandidate->getParent() == SinkTo ||
129 SinkCandidate->mayHaveSideEffects() ||
130 SinkCandidate->mayReadOrWriteMemory())
131 continue;
132 if (auto *RepR = dyn_cast<VPReplicateRecipe>(SinkCandidate)) {
133 if (!ScalarVFOnly && RepR->isUniform())
134 continue;
135 } else if (!isa<VPScalarIVStepsRecipe>(SinkCandidate))
136 continue;
137
138 bool NeedsDuplicating = false;
139 // All recipe users of the sink candidate must be in the same block SinkTo
140 // or all users outside of SinkTo must be uniform-after-vectorization (
141 // i.e., only first lane is used) . In the latter case, we need to duplicate
142 // SinkCandidate.
143 auto CanSinkWithUser = [SinkTo, &NeedsDuplicating,
144 SinkCandidate](VPUser *U) {
145 auto *UI = dyn_cast<VPRecipeBase>(U);
146 if (!UI)
147 return false;
148 if (UI->getParent() == SinkTo)
149 return true;
150 NeedsDuplicating = UI->onlyFirstLaneUsed(SinkCandidate);
151 // We only know how to duplicate VPRecipeRecipes for now.
152 return NeedsDuplicating && isa<VPReplicateRecipe>(SinkCandidate);
153 };
154 if (!all_of(SinkCandidate->users(), CanSinkWithUser))
155 continue;
156
157 if (NeedsDuplicating) {
158 if (ScalarVFOnly)
159 continue;
160 Instruction *I = cast<Instruction>(
161 cast<VPReplicateRecipe>(SinkCandidate)->getUnderlyingValue());
162 auto *Clone = new VPReplicateRecipe(I, SinkCandidate->operands(), true);
163 // TODO: add ".cloned" suffix to name of Clone's VPValue.
164
165 Clone->insertBefore(SinkCandidate);
166 SinkCandidate->replaceUsesWithIf(Clone, [SinkTo](VPUser &U, unsigned) {
167 return cast<VPRecipeBase>(&U)->getParent() != SinkTo;
168 });
169 }
170 SinkCandidate->moveBefore(*SinkTo, SinkTo->getFirstNonPhi());
171 for (VPValue *Op : SinkCandidate->operands())
172 if (auto *Def =
173 dyn_cast_or_null<VPSingleDefRecipe>(Op->getDefiningRecipe()))
174 WorkList.insert(std::make_pair(SinkTo, Def));
175 Changed = true;
176 }
177 return Changed;
178}
179
180/// If \p R is a region with a VPBranchOnMaskRecipe in the entry block, return
181/// the mask.
183 auto *EntryBB = dyn_cast<VPBasicBlock>(R->getEntry());
184 if (!EntryBB || EntryBB->size() != 1 ||
185 !isa<VPBranchOnMaskRecipe>(EntryBB->begin()))
186 return nullptr;
187
188 return cast<VPBranchOnMaskRecipe>(&*EntryBB->begin())->getOperand(0);
189}
190
191/// If \p R is a triangle region, return the 'then' block of the triangle.
193 auto *EntryBB = cast<VPBasicBlock>(R->getEntry());
194 if (EntryBB->getNumSuccessors() != 2)
195 return nullptr;
196
197 auto *Succ0 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[0]);
198 auto *Succ1 = dyn_cast<VPBasicBlock>(EntryBB->getSuccessors()[1]);
199 if (!Succ0 || !Succ1)
200 return nullptr;
201
202 if (Succ0->getNumSuccessors() + Succ1->getNumSuccessors() != 1)
203 return nullptr;
204 if (Succ0->getSingleSuccessor() == Succ1)
205 return Succ0;
206 if (Succ1->getSingleSuccessor() == Succ0)
207 return Succ1;
208 return nullptr;
209}
210
211// Merge replicate regions in their successor region, if a replicate region
212// is connected to a successor replicate region with the same predicate by a
213// single, empty VPBasicBlock.
215 SetVector<VPRegionBlock *> DeletedRegions;
216
217 // Collect replicate regions followed by an empty block, followed by another
218 // replicate region with matching masks to process front. This is to avoid
219 // iterator invalidation issues while merging regions.
221 for (VPRegionBlock *Region1 : VPBlockUtils::blocksOnly<VPRegionBlock>(
222 vp_depth_first_deep(Plan.getEntry()))) {
223 if (!Region1->isReplicator())
224 continue;
225 auto *MiddleBasicBlock =
226 dyn_cast_or_null<VPBasicBlock>(Region1->getSingleSuccessor());
227 if (!MiddleBasicBlock || !MiddleBasicBlock->empty())
228 continue;
229
230 auto *Region2 =
231 dyn_cast_or_null<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
232 if (!Region2 || !Region2->isReplicator())
233 continue;
234
235 VPValue *Mask1 = getPredicatedMask(Region1);
236 VPValue *Mask2 = getPredicatedMask(Region2);
237 if (!Mask1 || Mask1 != Mask2)
238 continue;
239
240 assert(Mask1 && Mask2 && "both region must have conditions");
241 WorkList.push_back(Region1);
242 }
243
244 // Move recipes from Region1 to its successor region, if both are triangles.
245 for (VPRegionBlock *Region1 : WorkList) {
246 if (DeletedRegions.contains(Region1))
247 continue;
248 auto *MiddleBasicBlock = cast<VPBasicBlock>(Region1->getSingleSuccessor());
249 auto *Region2 = cast<VPRegionBlock>(MiddleBasicBlock->getSingleSuccessor());
250
251 VPBasicBlock *Then1 = getPredicatedThenBlock(Region1);
252 VPBasicBlock *Then2 = getPredicatedThenBlock(Region2);
253 if (!Then1 || !Then2)
254 continue;
255
256 // Note: No fusion-preventing memory dependencies are expected in either
257 // region. Such dependencies should be rejected during earlier dependence
258 // checks, which guarantee accesses can be re-ordered for vectorization.
259 //
260 // Move recipes to the successor region.
261 for (VPRecipeBase &ToMove : make_early_inc_range(reverse(*Then1)))
262 ToMove.moveBefore(*Then2, Then2->getFirstNonPhi());
263
264 auto *Merge1 = cast<VPBasicBlock>(Then1->getSingleSuccessor());
265 auto *Merge2 = cast<VPBasicBlock>(Then2->getSingleSuccessor());
266
267 // Move VPPredInstPHIRecipes from the merge block to the successor region's
268 // merge block. Update all users inside the successor region to use the
269 // original values.
270 for (VPRecipeBase &Phi1ToMove : make_early_inc_range(reverse(*Merge1))) {
271 VPValue *PredInst1 =
272 cast<VPPredInstPHIRecipe>(&Phi1ToMove)->getOperand(0);
273 VPValue *Phi1ToMoveV = Phi1ToMove.getVPSingleValue();
274 Phi1ToMoveV->replaceUsesWithIf(PredInst1, [Then2](VPUser &U, unsigned) {
275 auto *UI = dyn_cast<VPRecipeBase>(&U);
276 return UI && UI->getParent() == Then2;
277 });
278
279 Phi1ToMove.moveBefore(*Merge2, Merge2->begin());
280 }
281
282 // Finally, remove the first region.
283 for (VPBlockBase *Pred : make_early_inc_range(Region1->getPredecessors())) {
284 VPBlockUtils::disconnectBlocks(Pred, Region1);
285 VPBlockUtils::connectBlocks(Pred, MiddleBasicBlock);
286 }
287 VPBlockUtils::disconnectBlocks(Region1, MiddleBasicBlock);
288 DeletedRegions.insert(Region1);
289 }
290
291 for (VPRegionBlock *ToDelete : DeletedRegions)
292 delete ToDelete;
293 return !DeletedRegions.empty();
294}
295
297 VPlan &Plan) {
298 Instruction *Instr = PredRecipe->getUnderlyingInstr();
299 // Build the triangular if-then region.
300 std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
301 assert(Instr->getParent() && "Predicated instruction not in any basic block");
302 auto *BlockInMask = PredRecipe->getMask();
303 auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
304 auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
305
306 // Replace predicated replicate recipe with a replicate recipe without a
307 // mask but in the replicate region.
308 auto *RecipeWithoutMask = new VPReplicateRecipe(
309 PredRecipe->getUnderlyingInstr(),
310 make_range(PredRecipe->op_begin(), std::prev(PredRecipe->op_end())),
311 PredRecipe->isUniform());
312 auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", RecipeWithoutMask);
313
314 VPPredInstPHIRecipe *PHIRecipe = nullptr;
315 if (PredRecipe->getNumUsers() != 0) {
316 PHIRecipe = new VPPredInstPHIRecipe(RecipeWithoutMask);
317 PredRecipe->replaceAllUsesWith(PHIRecipe);
318 PHIRecipe->setOperand(0, RecipeWithoutMask);
319 }
320 PredRecipe->eraseFromParent();
321 auto *Exiting = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
322 VPRegionBlock *Region = new VPRegionBlock(Entry, Exiting, RegionName, true);
323
324 // Note: first set Entry as region entry and then connect successors starting
325 // from it in order, to propagate the "parent" of each VPBasicBlock.
326 VPBlockUtils::insertTwoBlocksAfter(Pred, Exiting, Entry);
327 VPBlockUtils::connectBlocks(Pred, Exiting);
328
329 return Region;
330}
331
332static void addReplicateRegions(VPlan &Plan) {
334 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
335 vp_depth_first_deep(Plan.getEntry()))) {
336 for (VPRecipeBase &R : *VPBB)
337 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
338 if (RepR->isPredicated())
339 WorkList.push_back(RepR);
340 }
341 }
342
343 unsigned BBNum = 0;
344 for (VPReplicateRecipe *RepR : WorkList) {
345 VPBasicBlock *CurrentBlock = RepR->getParent();
346 VPBasicBlock *SplitBlock = CurrentBlock->splitAt(RepR->getIterator());
347
348 BasicBlock *OrigBB = RepR->getUnderlyingInstr()->getParent();
350 OrigBB->hasName() ? OrigBB->getName() + "." + Twine(BBNum++) : "");
351 // Record predicated instructions for above packing optimizations.
353 Region->setParent(CurrentBlock->getParent());
355 VPBlockUtils::connectBlocks(CurrentBlock, Region);
357 }
358}
359
360/// Remove redundant VPBasicBlocks by merging them into their predecessor if
361/// the predecessor has a single successor.
364 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
365 vp_depth_first_deep(Plan.getEntry()))) {
366 auto *PredVPBB =
367 dyn_cast_or_null<VPBasicBlock>(VPBB->getSinglePredecessor());
368 if (PredVPBB && PredVPBB->getNumSuccessors() == 1)
369 WorkList.push_back(VPBB);
370 }
371
372 for (VPBasicBlock *VPBB : WorkList) {
373 VPBasicBlock *PredVPBB = cast<VPBasicBlock>(VPBB->getSinglePredecessor());
374 for (VPRecipeBase &R : make_early_inc_range(*VPBB))
375 R.moveBefore(*PredVPBB, PredVPBB->end());
376 VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
377 auto *ParentRegion = cast_or_null<VPRegionBlock>(VPBB->getParent());
378 if (ParentRegion && ParentRegion->getExiting() == VPBB)
379 ParentRegion->setExiting(PredVPBB);
380 for (auto *Succ : to_vector(VPBB->successors())) {
382 VPBlockUtils::connectBlocks(PredVPBB, Succ);
383 }
384 delete VPBB;
385 }
386 return !WorkList.empty();
387}
388
390 // Convert masked VPReplicateRecipes to if-then region blocks.
392
393 bool ShouldSimplify = true;
394 while (ShouldSimplify) {
395 ShouldSimplify = sinkScalarOperands(Plan);
396 ShouldSimplify |= mergeReplicateRegionsIntoSuccessors(Plan);
397 ShouldSimplify |= mergeBlocksIntoPredecessors(Plan);
398 }
399}
400
401/// Remove redundant casts of inductions.
402///
403/// Such redundant casts are casts of induction variables that can be ignored,
404/// because we already proved that the casted phi is equal to the uncasted phi
405/// in the vectorized loop. There is no need to vectorize the cast - the same
406/// value can be used for both the phi and casts in the vector loop.
408 for (auto &Phi : Plan.getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
409 auto *IV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
410 if (!IV || IV->getTruncInst())
411 continue;
412
413 // A sequence of IR Casts has potentially been recorded for IV, which
414 // *must be bypassed* when the IV is vectorized, because the vectorized IV
415 // will produce the desired casted value. This sequence forms a def-use
416 // chain and is provided in reverse order, ending with the cast that uses
417 // the IV phi. Search for the recipe of the last cast in the chain and
418 // replace it with the original IV. Note that only the final cast is
419 // expected to have users outside the cast-chain and the dead casts left
420 // over will be cleaned up later.
421 auto &Casts = IV->getInductionDescriptor().getCastInsts();
422 VPValue *FindMyCast = IV;
423 for (Instruction *IRCast : reverse(Casts)) {
424 VPSingleDefRecipe *FoundUserCast = nullptr;
425 for (auto *U : FindMyCast->users()) {
426 auto *UserCast = dyn_cast<VPSingleDefRecipe>(U);
427 if (UserCast && UserCast->getUnderlyingValue() == IRCast) {
428 FoundUserCast = UserCast;
429 break;
430 }
431 }
432 FindMyCast = FoundUserCast;
433 }
434 FindMyCast->replaceAllUsesWith(IV);
435 }
436}
437
438/// Try to replace VPWidenCanonicalIVRecipes with a widened canonical IV
439/// recipe, if it exists.
441 VPCanonicalIVPHIRecipe *CanonicalIV = Plan.getCanonicalIV();
442 VPWidenCanonicalIVRecipe *WidenNewIV = nullptr;
443 for (VPUser *U : CanonicalIV->users()) {
444 WidenNewIV = dyn_cast<VPWidenCanonicalIVRecipe>(U);
445 if (WidenNewIV)
446 break;
447 }
448
449 if (!WidenNewIV)
450 return;
451
453 for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
454 auto *WidenOriginalIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
455
456 if (!WidenOriginalIV || !WidenOriginalIV->isCanonical() ||
457 WidenOriginalIV->getScalarType() != WidenNewIV->getScalarType())
458 continue;
459
460 // Replace WidenNewIV with WidenOriginalIV if WidenOriginalIV provides
461 // everything WidenNewIV's users need. That is, WidenOriginalIV will
462 // generate a vector phi or all users of WidenNewIV demand the first lane
463 // only.
464 if (any_of(WidenOriginalIV->users(),
465 [WidenOriginalIV](VPUser *U) {
466 return !U->usesScalars(WidenOriginalIV);
467 }) ||
468 vputils::onlyFirstLaneUsed(WidenNewIV)) {
469 WidenNewIV->replaceAllUsesWith(WidenOriginalIV);
470 WidenNewIV->eraseFromParent();
471 return;
472 }
473 }
474}
475
476static void removeDeadRecipes(VPlan &Plan) {
478 Plan.getEntry());
479
480 for (VPBasicBlock *VPBB : reverse(VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT))) {
481 // The recipes in the block are processed in reverse order, to catch chains
482 // of dead recipes.
483 for (VPRecipeBase &R : make_early_inc_range(reverse(*VPBB))) {
484 // A user keeps R alive:
485 if (any_of(R.definedValues(),
486 [](VPValue *V) { return V->getNumUsers(); }))
487 continue;
488
489 // Having side effects keeps R alive, but do remove conditional assume
490 // instructions as their conditions may be flattened.
491 auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
492 bool IsConditionalAssume =
493 RepR && RepR->isPredicated() &&
494 match(RepR->getUnderlyingInstr(), m_Intrinsic<Intrinsic::assume>());
495 if (R.mayHaveSideEffects() && !IsConditionalAssume)
496 continue;
497
498 R.eraseFromParent();
499 }
500 }
501}
502
504 ScalarEvolution &SE, Instruction *TruncI,
505 VPValue *StartV, VPValue *Step,
508 VPCanonicalIVPHIRecipe *CanonicalIV = Plan.getCanonicalIV();
509 VPSingleDefRecipe *BaseIV = CanonicalIV;
510 if (!CanonicalIV->isCanonical(ID.getKind(), StartV, Step)) {
511 BaseIV = new VPDerivedIVRecipe(ID, StartV, CanonicalIV, Step);
512 HeaderVPBB->insert(BaseIV, IP);
513 }
514
515 // Truncate base induction if needed.
517 SE.getContext());
518 Type *ResultTy = TypeInfo.inferScalarType(BaseIV);
519 if (TruncI) {
520 Type *TruncTy = TruncI->getType();
521 assert(ResultTy->getScalarSizeInBits() > TruncTy->getScalarSizeInBits() &&
522 "Not truncating.");
523 assert(ResultTy->isIntegerTy() && "Truncation requires an integer type");
524 BaseIV = new VPScalarCastRecipe(Instruction::Trunc, BaseIV, TruncTy);
525 HeaderVPBB->insert(BaseIV, IP);
526 ResultTy = TruncTy;
527 }
528
529 // Truncate step if needed.
530 Type *StepTy = TypeInfo.inferScalarType(Step);
531 if (ResultTy != StepTy) {
532 assert(StepTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits() &&
533 "Not truncating.");
534 assert(StepTy->isIntegerTy() && "Truncation requires an integer type");
535 Step = new VPScalarCastRecipe(Instruction::Trunc, Step, ResultTy);
536 auto *VecPreheader =
537 cast<VPBasicBlock>(HeaderVPBB->getSingleHierarchicalPredecessor());
538 VecPreheader->appendRecipe(Step->getDefiningRecipe());
539 }
540
541 VPScalarIVStepsRecipe *Steps = new VPScalarIVStepsRecipe(ID, BaseIV, Step);
542 HeaderVPBB->insert(Steps, IP);
543 return Steps;
544}
545
546/// If any user of a VPWidenIntOrFpInductionRecipe needs scalar values,
547/// provide them by building scalar steps off of the canonical scalar IV and
548/// update the original IV's users. This is an optional optimization to reduce
549/// the needs of vector extracts.
550static void optimizeInductions(VPlan &Plan, ScalarEvolution &SE) {
553 bool HasOnlyVectorVFs = !Plan.hasVF(ElementCount::getFixed(1));
554 VPBasicBlock::iterator InsertPt = HeaderVPBB->getFirstNonPhi();
555 for (VPRecipeBase &Phi : HeaderVPBB->phis()) {
556 auto *WideIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&Phi);
557 if (!WideIV)
558 continue;
559 if (HasOnlyVectorVFs && none_of(WideIV->users(), [WideIV](VPUser *U) {
560 return U->usesScalars(WideIV);
561 }))
562 continue;
563
564 const InductionDescriptor &ID = WideIV->getInductionDescriptor();
565 VPValue *Steps = createScalarIVSteps(Plan, ID, SE, WideIV->getTruncInst(),
566 WideIV->getStartValue(),
567 WideIV->getStepValue(), InsertPt);
568
569 // Update scalar users of IV to use Step instead.
570 if (!HasOnlyVectorVFs)
571 WideIV->replaceAllUsesWith(Steps);
572 else
573 WideIV->replaceUsesWithIf(Steps, [WideIV](VPUser &U, unsigned) {
574 return U.usesScalars(WideIV);
575 });
576 }
577}
578
579/// Remove redundant EpxandSCEVRecipes in \p Plan's entry block by replacing
580/// them with already existing recipes expanding the same SCEV expression.
583
584 for (VPRecipeBase &R :
586 auto *ExpR = dyn_cast<VPExpandSCEVRecipe>(&R);
587 if (!ExpR)
588 continue;
589
590 auto I = SCEV2VPV.insert({ExpR->getSCEV(), ExpR});
591 if (I.second)
592 continue;
593 ExpR->replaceAllUsesWith(I.first->second);
594 ExpR->eraseFromParent();
595 }
596}
597
599 VPInstruction *Not = dyn_cast<VPInstruction>(Term->getOperand(0));
600 if (!Not || Not->getOpcode() != VPInstruction::Not)
601 return false;
602
603 VPInstruction *ALM = dyn_cast<VPInstruction>(Not->getOperand(0));
604 return ALM && ALM->getOpcode() == VPInstruction::ActiveLaneMask;
605}
606
608 unsigned BestUF,
610 assert(Plan.hasVF(BestVF) && "BestVF is not available in Plan");
611 assert(Plan.hasUF(BestUF) && "BestUF is not available in Plan");
612 VPBasicBlock *ExitingVPBB =
614 auto *Term = dyn_cast<VPInstruction>(&ExitingVPBB->back());
615 // Try to simplify the branch condition if TC <= VF * UF when preparing to
616 // execute the plan for the main vector loop. We only do this if the
617 // terminator is:
618 // 1. BranchOnCount, or
619 // 2. BranchOnCond where the input is Not(ActiveLaneMask).
620 if (!Term || (Term->getOpcode() != VPInstruction::BranchOnCount &&
621 (Term->getOpcode() != VPInstruction::BranchOnCond ||
623 return;
624
625 Type *IdxTy =
627 const SCEV *TripCount = createTripCountSCEV(IdxTy, PSE);
628 ScalarEvolution &SE = *PSE.getSE();
629 const SCEV *C =
630 SE.getConstant(TripCount->getType(), BestVF.getKnownMinValue() * BestUF);
631 if (TripCount->isZero() ||
632 !SE.isKnownPredicate(CmpInst::ICMP_ULE, TripCount, C))
633 return;
634
635 LLVMContext &Ctx = SE.getContext();
636 auto *BOC = new VPInstruction(
639 Term->eraseFromParent();
640 ExitingVPBB->appendRecipe(BOC);
641 Plan.setVF(BestVF);
642 Plan.setUF(BestUF);
643 // TODO: Further simplifications are possible
644 // 1. Replace inductions with constants.
645 // 2. Replace vector loop region with VPBasicBlock.
646}
647
648#ifndef NDEBUG
650 auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
651 if (Region && Region->isReplicator()) {
652 assert(Region->getNumSuccessors() == 1 &&
653 Region->getNumPredecessors() == 1 && "Expected SESE region!");
654 assert(R->getParent()->size() == 1 &&
655 "A recipe in an original replicator region must be the only "
656 "recipe in its block");
657 return Region;
658 }
659 return nullptr;
660}
661#endif
662
663static bool properlyDominates(const VPRecipeBase *A, const VPRecipeBase *B,
664 VPDominatorTree &VPDT) {
665 if (A == B)
666 return false;
667
668 auto LocalComesBefore = [](const VPRecipeBase *A, const VPRecipeBase *B) {
669 for (auto &R : *A->getParent()) {
670 if (&R == A)
671 return true;
672 if (&R == B)
673 return false;
674 }
675 llvm_unreachable("recipe not found");
676 };
677 const VPBlockBase *ParentA = A->getParent();
678 const VPBlockBase *ParentB = B->getParent();
679 if (ParentA == ParentB)
680 return LocalComesBefore(A, B);
681
682 assert(!GetReplicateRegion(const_cast<VPRecipeBase *>(A)) &&
683 "No replicate regions expected at this point");
684 assert(!GetReplicateRegion(const_cast<VPRecipeBase *>(B)) &&
685 "No replicate regions expected at this point");
686 return VPDT.properlyDominates(ParentA, ParentB);
687}
688
689/// Sink users of \p FOR after the recipe defining the previous value \p
690/// Previous of the recurrence. \returns true if all users of \p FOR could be
691/// re-arranged as needed or false if it is not possible.
692static bool
694 VPRecipeBase *Previous,
695 VPDominatorTree &VPDT) {
696 // Collect recipes that need sinking.
699 Seen.insert(Previous);
700 auto TryToPushSinkCandidate = [&](VPRecipeBase *SinkCandidate) {
701 // The previous value must not depend on the users of the recurrence phi. In
702 // that case, FOR is not a fixed order recurrence.
703 if (SinkCandidate == Previous)
704 return false;
705
706 if (isa<VPHeaderPHIRecipe>(SinkCandidate) ||
707 !Seen.insert(SinkCandidate).second ||
708 properlyDominates(Previous, SinkCandidate, VPDT))
709 return true;
710
711 if (SinkCandidate->mayHaveSideEffects())
712 return false;
713
714 WorkList.push_back(SinkCandidate);
715 return true;
716 };
717
718 // Recursively sink users of FOR after Previous.
719 WorkList.push_back(FOR);
720 for (unsigned I = 0; I != WorkList.size(); ++I) {
721 VPRecipeBase *Current = WorkList[I];
722 assert(Current->getNumDefinedValues() == 1 &&
723 "only recipes with a single defined value expected");
724
725 for (VPUser *User : Current->getVPSingleValue()->users()) {
726 if (auto *R = dyn_cast<VPRecipeBase>(User))
727 if (!TryToPushSinkCandidate(R))
728 return false;
729 }
730 }
731
732 // Keep recipes to sink ordered by dominance so earlier instructions are
733 // processed first.
734 sort(WorkList, [&VPDT](const VPRecipeBase *A, const VPRecipeBase *B) {
735 return properlyDominates(A, B, VPDT);
736 });
737
738 for (VPRecipeBase *SinkCandidate : WorkList) {
739 if (SinkCandidate == FOR)
740 continue;
741
742 SinkCandidate->moveAfter(Previous);
743 Previous = SinkCandidate;
744 }
745 return true;
746}
747
749 VPBuilder &Builder) {
750 VPDominatorTree VPDT;
751 VPDT.recalculate(Plan);
752
754 for (VPRecipeBase &R :
756 if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
757 RecurrencePhis.push_back(FOR);
758
759 for (VPFirstOrderRecurrencePHIRecipe *FOR : RecurrencePhis) {
761 VPRecipeBase *Previous = FOR->getBackedgeValue()->getDefiningRecipe();
762 // Fixed-order recurrences do not contain cycles, so this loop is guaranteed
763 // to terminate.
764 while (auto *PrevPhi =
765 dyn_cast_or_null<VPFirstOrderRecurrencePHIRecipe>(Previous)) {
766 assert(PrevPhi->getParent() == FOR->getParent());
767 assert(SeenPhis.insert(PrevPhi).second);
768 Previous = PrevPhi->getBackedgeValue()->getDefiningRecipe();
769 }
770
771 if (!sinkRecurrenceUsersAfterPrevious(FOR, Previous, VPDT))
772 return false;
773
774 // Introduce a recipe to combine the incoming and previous values of a
775 // fixed-order recurrence.
776 VPBasicBlock *InsertBlock = Previous->getParent();
777 if (isa<VPHeaderPHIRecipe>(Previous))
778 Builder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
779 else
780 Builder.setInsertPoint(InsertBlock, std::next(Previous->getIterator()));
781
782 auto *RecurSplice = cast<VPInstruction>(
784 {FOR, FOR->getBackedgeValue()}));
785
786 FOR->replaceAllUsesWith(RecurSplice);
787 // Set the first operand of RecurSplice to FOR again, after replacing
788 // all users.
789 RecurSplice->setOperand(0, FOR);
790 }
791 return true;
792}
793
795 for (VPRecipeBase &R :
797 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
798 if (!PhiR)
799 continue;
800 const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
801 RecurKind RK = RdxDesc.getRecurrenceKind();
802 if (RK != RecurKind::Add && RK != RecurKind::Mul)
803 continue;
804
806 Worklist.insert(PhiR);
807
808 for (unsigned I = 0; I != Worklist.size(); ++I) {
809 VPValue *Cur = Worklist[I];
810 if (auto *RecWithFlags =
811 dyn_cast<VPRecipeWithIRFlags>(Cur->getDefiningRecipe())) {
812 RecWithFlags->dropPoisonGeneratingFlags();
813 }
814
815 for (VPUser *U : Cur->users()) {
816 auto *UserRecipe = dyn_cast<VPRecipeBase>(U);
817 if (!UserRecipe)
818 continue;
819 for (VPValue *V : UserRecipe->definedValues())
820 Worklist.insert(V);
821 }
822 }
823 }
824}
825
826/// Returns true is \p V is constant one.
827static bool isConstantOne(VPValue *V) {
828 if (!V->isLiveIn())
829 return false;
830 auto *C = dyn_cast<ConstantInt>(V->getLiveInIRValue());
831 return C && C->isOne();
832}
833
834/// Returns the llvm::Instruction opcode for \p R.
835static unsigned getOpcodeForRecipe(VPRecipeBase &R) {
836 if (auto *WidenR = dyn_cast<VPWidenRecipe>(&R))
837 return WidenR->getUnderlyingInstr()->getOpcode();
838 if (auto *WidenC = dyn_cast<VPWidenCastRecipe>(&R))
839 return WidenC->getOpcode();
840 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R))
841 return RepR->getUnderlyingInstr()->getOpcode();
842 if (auto *VPI = dyn_cast<VPInstruction>(&R))
843 return VPI->getOpcode();
844 return 0;
845}
846
847/// Try to simplify recipe \p R.
848static void simplifyRecipe(VPRecipeBase &R, VPTypeAnalysis &TypeInfo) {
849 // Try to remove redundant blend recipes.
850 if (auto *Blend = dyn_cast<VPBlendRecipe>(&R)) {
851 VPValue *Inc0 = Blend->getIncomingValue(0);
852 for (unsigned I = 1; I != Blend->getNumIncomingValues(); ++I)
853 if (Inc0 != Blend->getIncomingValue(I))
854 return;
855 Blend->replaceAllUsesWith(Inc0);
856 Blend->eraseFromParent();
857 return;
858 }
859
860 switch (getOpcodeForRecipe(R)) {
861 case Instruction::Mul: {
862 VPValue *A = R.getOperand(0);
863 VPValue *B = R.getOperand(1);
864 if (isConstantOne(A))
865 return R.getVPSingleValue()->replaceAllUsesWith(B);
866 if (isConstantOne(B))
867 return R.getVPSingleValue()->replaceAllUsesWith(A);
868 break;
869 }
870 case Instruction::Trunc: {
871 VPRecipeBase *Ext = R.getOperand(0)->getDefiningRecipe();
872 if (!Ext)
873 break;
874 unsigned ExtOpcode = getOpcodeForRecipe(*Ext);
875 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
876 break;
877 VPValue *A = Ext->getOperand(0);
878 VPValue *Trunc = R.getVPSingleValue();
879 Type *TruncTy = TypeInfo.inferScalarType(Trunc);
880 Type *ATy = TypeInfo.inferScalarType(A);
881 if (TruncTy == ATy) {
882 Trunc->replaceAllUsesWith(A);
883 } else {
884 // Don't replace a scalarizing recipe with a widened cast.
885 if (isa<VPReplicateRecipe>(&R))
886 break;
887 if (ATy->getScalarSizeInBits() < TruncTy->getScalarSizeInBits()) {
888 auto *VPC =
889 new VPWidenCastRecipe(Instruction::CastOps(ExtOpcode), A, TruncTy);
890 VPC->insertBefore(&R);
891 Trunc->replaceAllUsesWith(VPC);
892 } else if (ATy->getScalarSizeInBits() > TruncTy->getScalarSizeInBits()) {
893 auto *VPC = new VPWidenCastRecipe(Instruction::Trunc, A, TruncTy);
894 VPC->insertBefore(&R);
895 Trunc->replaceAllUsesWith(VPC);
896 }
897 }
898#ifndef NDEBUG
899 // Verify that the cached type info is for both A and its users is still
900 // accurate by comparing it to freshly computed types.
901 VPTypeAnalysis TypeInfo2(
902 R.getParent()->getPlan()->getCanonicalIV()->getScalarType(),
903 TypeInfo.getContext());
904 assert(TypeInfo.inferScalarType(A) == TypeInfo2.inferScalarType(A));
905 for (VPUser *U : A->users()) {
906 auto *R = dyn_cast<VPRecipeBase>(U);
907 if (!R)
908 continue;
909 for (VPValue *VPV : R->definedValues())
910 assert(TypeInfo.inferScalarType(VPV) == TypeInfo2.inferScalarType(VPV));
911 }
912#endif
913 break;
914 }
915 default:
916 break;
917 }
918}
919
920/// Try to simplify the recipes in \p Plan.
921static void simplifyRecipes(VPlan &Plan, LLVMContext &Ctx) {
923 Plan.getEntry());
924 VPTypeAnalysis TypeInfo(Plan.getCanonicalIV()->getScalarType(), Ctx);
925 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
926 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
927 simplifyRecipe(R, TypeInfo);
928 }
929 }
930}
931
933 VPlan &Plan, const MapVector<Instruction *, uint64_t> &MinBWs,
934 LLVMContext &Ctx) {
935#ifndef NDEBUG
936 // Count the processed recipes and cross check the count later with MinBWs
937 // size, to make sure all entries in MinBWs have been handled.
938 unsigned NumProcessedRecipes = 0;
939#endif
940 // Keep track of created truncates, so they can be re-used. Note that we
941 // cannot use RAUW after creating a new truncate, as this would could make
942 // other uses have different types for their operands, making them invalidly
943 // typed.
945 VPTypeAnalysis TypeInfo(Plan.getCanonicalIV()->getScalarType(), Ctx);
946 VPBasicBlock *PH = Plan.getEntry();
947 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
949 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
952 continue;
953 if (isa<VPWidenMemoryInstructionRecipe>(&R) &&
954 cast<VPWidenMemoryInstructionRecipe>(&R)->isStore())
955 continue;
956
957 VPValue *ResultVPV = R.getVPSingleValue();
958 auto *UI = cast_or_null<Instruction>(ResultVPV->getUnderlyingValue());
959 unsigned NewResSizeInBits = MinBWs.lookup(UI);
960 if (!NewResSizeInBits)
961 continue;
962
963#ifndef NDEBUG
964 NumProcessedRecipes++;
965#endif
966 // If the value wasn't vectorized, we must maintain the original scalar
967 // type. Skip those here, after incrementing NumProcessedRecipes. Also
968 // skip casts which do not need to be handled explicitly here, as
969 // redundant casts will be removed during recipe simplification.
970 if (isa<VPReplicateRecipe, VPWidenCastRecipe>(&R)) {
971#ifndef NDEBUG
972 // If any of the operands is a live-in and not used by VPWidenRecipe or
973 // VPWidenSelectRecipe, but in MinBWs, make sure it is counted as
974 // processed as well. When MinBWs is currently constructed, there is no
975 // information about whether recipes are widened or replicated and in
976 // case they are reciplicated the operands are not truncated. Counting
977 // them them here ensures we do not miss any recipes in MinBWs.
978 // TODO: Remove once the analysis is done on VPlan.
979 for (VPValue *Op : R.operands()) {
980 if (!Op->isLiveIn())
981 continue;
982 auto *UV = dyn_cast_or_null<Instruction>(Op->getUnderlyingValue());
983 if (UV && MinBWs.contains(UV) && !ProcessedTruncs.contains(Op) &&
984 all_of(Op->users(), [](VPUser *U) {
985 return !isa<VPWidenRecipe, VPWidenSelectRecipe>(U);
986 })) {
987 // Add an entry to ProcessedTruncs to avoid counting the same
988 // operand multiple times.
989 ProcessedTruncs[Op] = nullptr;
990 NumProcessedRecipes += 1;
991 }
992 }
993#endif
994 continue;
995 }
996
997 Type *OldResTy = TypeInfo.inferScalarType(ResultVPV);
998 unsigned OldResSizeInBits = OldResTy->getScalarSizeInBits();
999 assert(OldResTy->isIntegerTy() && "only integer types supported");
1000 (void)OldResSizeInBits;
1001
1002 auto *NewResTy = IntegerType::get(Ctx, NewResSizeInBits);
1003
1004 // Any wrapping introduced by shrinking this operation shouldn't be
1005 // considered undefined behavior. So, we can't unconditionally copy
1006 // arithmetic wrapping flags to VPW.
1007 if (auto *VPW = dyn_cast<VPRecipeWithIRFlags>(&R))
1008 VPW->dropPoisonGeneratingFlags();
1009
1010 if (OldResSizeInBits != NewResSizeInBits) {
1011 // Extend result to original width.
1012 auto *Ext =
1013 new VPWidenCastRecipe(Instruction::ZExt, ResultVPV, OldResTy);
1014 Ext->insertAfter(&R);
1015 ResultVPV->replaceAllUsesWith(Ext);
1016 Ext->setOperand(0, ResultVPV);
1017 assert(OldResSizeInBits > NewResSizeInBits && "Nothing to shrink?");
1018 } else
1019 assert(cast<VPWidenRecipe>(&R)->getOpcode() == Instruction::ICmp &&
1020 "Only ICmps should not need extending the result.");
1021
1022 if (isa<VPWidenMemoryInstructionRecipe>(&R)) {
1023 assert(!cast<VPWidenMemoryInstructionRecipe>(&R)->isStore() && "stores cannot be narrowed");
1024 continue;
1025 }
1026
1027 // Shrink operands by introducing truncates as needed.
1028 unsigned StartIdx = isa<VPWidenSelectRecipe>(&R) ? 1 : 0;
1029 for (unsigned Idx = StartIdx; Idx != R.getNumOperands(); ++Idx) {
1030 auto *Op = R.getOperand(Idx);
1031 unsigned OpSizeInBits =
1033 if (OpSizeInBits == NewResSizeInBits)
1034 continue;
1035 assert(OpSizeInBits > NewResSizeInBits && "nothing to truncate");
1036 auto [ProcessedIter, IterIsEmpty] =
1037 ProcessedTruncs.insert({Op, nullptr});
1038 VPWidenCastRecipe *NewOp =
1039 IterIsEmpty
1040 ? new VPWidenCastRecipe(Instruction::Trunc, Op, NewResTy)
1041 : ProcessedIter->second;
1042 R.setOperand(Idx, NewOp);
1043 if (!IterIsEmpty)
1044 continue;
1045 ProcessedIter->second = NewOp;
1046 if (!Op->isLiveIn()) {
1047 NewOp->insertBefore(&R);
1048 } else {
1049 PH->appendRecipe(NewOp);
1050#ifndef NDEBUG
1051 auto *OpInst = dyn_cast<Instruction>(Op->getLiveInIRValue());
1052 bool IsContained = MinBWs.contains(OpInst);
1053 NumProcessedRecipes += IsContained;
1054#endif
1055 }
1056 }
1057
1058 }
1059 }
1060
1061 assert(MinBWs.size() == NumProcessedRecipes &&
1062 "some entries in MinBWs haven't been processed");
1063}
1064
1068
1069 simplifyRecipes(Plan, SE.getContext());
1070 optimizeInductions(Plan, SE);
1071 removeDeadRecipes(Plan);
1072
1074
1077}
1078
1079// Add a VPActiveLaneMaskPHIRecipe and related recipes to \p Plan and replace
1080// the loop terminator with a branch-on-cond recipe with the negated
1081// active-lane-mask as operand. Note that this turns the loop into an
1082// uncountable one. Only the existing terminator is replaced, all other existing
1083// recipes/users remain unchanged, except for poison-generating flags being
1084// dropped from the canonical IV increment. Return the created
1085// VPActiveLaneMaskPHIRecipe.
1086//
1087// The function uses the following definitions:
1088//
1089// %TripCount = DataWithControlFlowWithoutRuntimeCheck ?
1090// calculate-trip-count-minus-VF (original TC) : original TC
1091// %IncrementValue = DataWithControlFlowWithoutRuntimeCheck ?
1092// CanonicalIVPhi : CanonicalIVIncrement
1093// %StartV is the canonical induction start value.
1094//
1095// The function adds the following recipes:
1096//
1097// vector.ph:
1098// %TripCount = calculate-trip-count-minus-VF (original TC)
1099// [if DataWithControlFlowWithoutRuntimeCheck]
1100// %EntryInc = canonical-iv-increment-for-part %StartV
1101// %EntryALM = active-lane-mask %EntryInc, %TripCount
1102//
1103// vector.body:
1104// ...
1105// %P = active-lane-mask-phi [ %EntryALM, %vector.ph ], [ %ALM, %vector.body ]
1106// ...
1107// %InLoopInc = canonical-iv-increment-for-part %IncrementValue
1108// %ALM = active-lane-mask %InLoopInc, TripCount
1109// %Negated = Not %ALM
1110// branch-on-cond %Negated
1111//
1114 VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
1115 VPBasicBlock *EB = TopRegion->getExitingBasicBlock();
1116 auto *CanonicalIVPHI = Plan.getCanonicalIV();
1117 VPValue *StartV = CanonicalIVPHI->getStartValue();
1118
1119 auto *CanonicalIVIncrement =
1120 cast<VPInstruction>(CanonicalIVPHI->getBackedgeValue());
1121 // TODO: Check if dropping the flags is needed if
1122 // !DataAndControlFlowWithoutRuntimeCheck.
1123 CanonicalIVIncrement->dropPoisonGeneratingFlags();
1124 DebugLoc DL = CanonicalIVIncrement->getDebugLoc();
1125 // We can't use StartV directly in the ActiveLaneMask VPInstruction, since
1126 // we have to take unrolling into account. Each part needs to start at
1127 // Part * VF
1128 auto *VecPreheader = cast<VPBasicBlock>(TopRegion->getSinglePredecessor());
1129 VPBuilder Builder(VecPreheader);
1130
1131 // Create the ActiveLaneMask instruction using the correct start values.
1132 VPValue *TC = Plan.getTripCount();
1133
1134 VPValue *TripCount, *IncrementValue;
1136 // When the loop is guarded by a runtime overflow check for the loop
1137 // induction variable increment by VF, we can increment the value before
1138 // the get.active.lane mask and use the unmodified tripcount.
1139 IncrementValue = CanonicalIVIncrement;
1140 TripCount = TC;
1141 } else {
1142 // When avoiding a runtime check, the active.lane.mask inside the loop
1143 // uses a modified trip count and the induction variable increment is
1144 // done after the active.lane.mask intrinsic is called.
1145 IncrementValue = CanonicalIVPHI;
1147 {TC}, DL);
1148 }
1149 auto *EntryIncrement = Builder.createOverflowingOp(
1150 VPInstruction::CanonicalIVIncrementForPart, {StartV}, {false, false}, DL,
1151 "index.part.next");
1152
1153 // Create the active lane mask instruction in the VPlan preheader.
1154 auto *EntryALM =
1155 Builder.createNaryOp(VPInstruction::ActiveLaneMask, {EntryIncrement, TC},
1156 DL, "active.lane.mask.entry");
1157
1158 // Now create the ActiveLaneMaskPhi recipe in the main loop using the
1159 // preheader ActiveLaneMask instruction.
1160 auto LaneMaskPhi = new VPActiveLaneMaskPHIRecipe(EntryALM, DebugLoc());
1161 LaneMaskPhi->insertAfter(CanonicalIVPHI);
1162
1163 // Create the active lane mask for the next iteration of the loop before the
1164 // original terminator.
1165 VPRecipeBase *OriginalTerminator = EB->getTerminator();
1166 Builder.setInsertPoint(OriginalTerminator);
1167 auto *InLoopIncrement =
1169 {IncrementValue}, {false, false}, DL);
1170 auto *ALM = Builder.createNaryOp(VPInstruction::ActiveLaneMask,
1171 {InLoopIncrement, TripCount}, DL,
1172 "active.lane.mask.next");
1173 LaneMaskPhi->addOperand(ALM);
1174
1175 // Replace the original terminator with BranchOnCond. We have to invert the
1176 // mask here because a true condition means jumping to the exit block.
1177 auto *NotMask = Builder.createNot(ALM, DL);
1178 Builder.createNaryOp(VPInstruction::BranchOnCond, {NotMask}, DL);
1179 OriginalTerminator->eraseFromParent();
1180 return LaneMaskPhi;
1181}
1182
1184 VPlan &Plan, bool UseActiveLaneMaskForControlFlow,
1187 UseActiveLaneMaskForControlFlow) &&
1188 "DataAndControlFlowWithoutRuntimeCheck implies "
1189 "UseActiveLaneMaskForControlFlow");
1190
1191 auto FoundWidenCanonicalIVUser =
1192 find_if(Plan.getCanonicalIV()->users(),
1193 [](VPUser *U) { return isa<VPWidenCanonicalIVRecipe>(U); });
1194 assert(FoundWidenCanonicalIVUser &&
1195 "Must have widened canonical IV when tail folding!");
1196 auto *WideCanonicalIV =
1197 cast<VPWidenCanonicalIVRecipe>(*FoundWidenCanonicalIVUser);
1198 VPSingleDefRecipe *LaneMask;
1199 if (UseActiveLaneMaskForControlFlow) {
1202 } else {
1204 {WideCanonicalIV, Plan.getTripCount()},
1205 nullptr, "active.lane.mask");
1206 LaneMask->insertAfter(WideCanonicalIV);
1207 }
1208
1209 // Walk users of WideCanonicalIV and replace all compares of the form
1210 // (ICMP_ULE, WideCanonicalIV, backedge-taken-count) with an
1211 // active-lane-mask.
1213 for (VPUser *U : SmallVector<VPUser *>(WideCanonicalIV->users())) {
1214 auto *CompareToReplace = dyn_cast<VPInstruction>(U);
1215 if (!CompareToReplace ||
1216 CompareToReplace->getOpcode() != Instruction::ICmp ||
1217 CompareToReplace->getPredicate() != CmpInst::ICMP_ULE ||
1218 CompareToReplace->getOperand(1) != BTC)
1219 continue;
1220
1221 assert(CompareToReplace->getOperand(0) == WideCanonicalIV &&
1222 "WidenCanonicalIV must be the first operand of the compare");
1223 CompareToReplace->replaceAllUsesWith(LaneMask);
1224 CompareToReplace->eraseFromParent();
1225 }
1226}
1227
1229 VPlan &Plan, function_ref<bool(BasicBlock *)> BlockNeedsPredication) {
1230 // Collect recipes in the backward slice of `Root` that may generate a poison
1231 // value that is used after vectorization.
1233 auto collectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1235 Worklist.push_back(Root);
1236
1237 // Traverse the backward slice of Root through its use-def chain.
1238 while (!Worklist.empty()) {
1239 VPRecipeBase *CurRec = Worklist.back();
1240 Worklist.pop_back();
1241
1242 if (!Visited.insert(CurRec).second)
1243 continue;
1244
1245 // Prune search if we find another recipe generating a widen memory
1246 // instruction. Widen memory instructions involved in address computation
1247 // will lead to gather/scatter instructions, which don't need to be
1248 // handled.
1249 if (isa<VPWidenMemoryInstructionRecipe>(CurRec) ||
1250 isa<VPInterleaveRecipe>(CurRec) ||
1251 isa<VPScalarIVStepsRecipe>(CurRec) ||
1252 isa<VPCanonicalIVPHIRecipe>(CurRec) ||
1253 isa<VPActiveLaneMaskPHIRecipe>(CurRec))
1254 continue;
1255
1256 // This recipe contributes to the address computation of a widen
1257 // load/store. If the underlying instruction has poison-generating flags,
1258 // drop them directly.
1259 if (auto *RecWithFlags = dyn_cast<VPRecipeWithIRFlags>(CurRec)) {
1260 RecWithFlags->dropPoisonGeneratingFlags();
1261 } else {
1262 Instruction *Instr = dyn_cast_or_null<Instruction>(
1263 CurRec->getVPSingleValue()->getUnderlyingValue());
1264 (void)Instr;
1265 assert((!Instr || !Instr->hasPoisonGeneratingFlags()) &&
1266 "found instruction with poison generating flags not covered by "
1267 "VPRecipeWithIRFlags");
1268 }
1269
1270 // Add new definitions to the worklist.
1271 for (VPValue *operand : CurRec->operands())
1272 if (VPRecipeBase *OpDef = operand->getDefiningRecipe())
1273 Worklist.push_back(OpDef);
1274 }
1275 });
1276
1277 // Traverse all the recipes in the VPlan and collect the poison-generating
1278 // recipes in the backward slice starting at the address of a VPWidenRecipe or
1279 // VPInterleaveRecipe.
1280 auto Iter = vp_depth_first_deep(Plan.getEntry());
1281 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1282 for (VPRecipeBase &Recipe : *VPBB) {
1283 if (auto *WidenRec = dyn_cast<VPWidenMemoryInstructionRecipe>(&Recipe)) {
1284 Instruction &UnderlyingInstr = WidenRec->getIngredient();
1285 VPRecipeBase *AddrDef = WidenRec->getAddr()->getDefiningRecipe();
1286 if (AddrDef && WidenRec->isConsecutive() &&
1287 BlockNeedsPredication(UnderlyingInstr.getParent()))
1288 collectPoisonGeneratingInstrsInBackwardSlice(AddrDef);
1289 } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1290 VPRecipeBase *AddrDef = InterleaveRec->getAddr()->getDefiningRecipe();
1291 if (AddrDef) {
1292 // Check if any member of the interleave group needs predication.
1293 const InterleaveGroup<Instruction> *InterGroup =
1294 InterleaveRec->getInterleaveGroup();
1295 bool NeedPredication = false;
1296 for (int I = 0, NumMembers = InterGroup->getNumMembers();
1297 I < NumMembers; ++I) {
1298 Instruction *Member = InterGroup->getMember(I);
1299 if (Member)
1300 NeedPredication |= BlockNeedsPredication(Member->getParent());
1301 }
1302
1303 if (NeedPredication)
1304 collectPoisonGeneratingInstrsInBackwardSlice(AddrDef);
1305 }
1306 }
1307 }
1308 }
1309}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool isStore(int Opcode)
ReachingDefAnalysis InstSet & ToRemove
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Hexagon Common GEP
static bool isConstantOne(const Value *Val)
isConstantOne - Return true only if val is constant int 1
Definition: IRBuilder.cpp:295
static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU, ScalarEvolution &SE)
#define I(x, y, z)
Definition: MD5.cpp:58
if(VerifyEach)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
static bool canSimplifyBranchOnCond(VPInstruction *Term)
static bool sinkScalarOperands(VPlan &Plan)
static void optimizeInductions(VPlan &Plan, ScalarEvolution &SE)
If any user of a VPWidenIntOrFpInductionRecipe needs scalar values, provide them by building scalar s...
static void removeRedundantInductionCasts(VPlan &Plan)
Remove redundant casts of inductions.
static void simplifyRecipes(VPlan &Plan, LLVMContext &Ctx)
Try to simplify the recipes in Plan.
static bool sinkRecurrenceUsersAfterPrevious(VPFirstOrderRecurrencePHIRecipe *FOR, VPRecipeBase *Previous, VPDominatorTree &VPDT)
Sink users of FOR after the recipe defining the previous value Previous of the recurrence.
static bool mergeReplicateRegionsIntoSuccessors(VPlan &Plan)
static VPActiveLaneMaskPHIRecipe * addVPLaneMaskPhiAndUpdateExitBranch(VPlan &Plan, bool DataAndControlFlowWithoutRuntimeCheck)
static void addReplicateRegions(VPlan &Plan)
static VPValue * createScalarIVSteps(VPlan &Plan, const InductionDescriptor &ID, ScalarEvolution &SE, Instruction *TruncI, VPValue *StartV, VPValue *Step, VPBasicBlock::iterator IP)
static void simplifyRecipe(VPRecipeBase &R, VPTypeAnalysis &TypeInfo)
Try to simplify recipe R.
static VPRegionBlock * GetReplicateRegion(VPRecipeBase *R)
static void removeRedundantExpandSCEVRecipes(VPlan &Plan)
Remove redundant EpxandSCEVRecipes in Plan's entry block by replacing them with already existing reci...
static bool properlyDominates(const VPRecipeBase *A, const VPRecipeBase *B, VPDominatorTree &VPDT)
static unsigned getOpcodeForRecipe(VPRecipeBase &R)
Returns the llvm::Instruction opcode for R.
static void removeDeadRecipes(VPlan &Plan)
static VPRegionBlock * createReplicateRegion(VPReplicateRecipe *PredRecipe, VPlan &Plan)
static VPBasicBlock * getPredicatedThenBlock(VPRegionBlock *R)
If R is a triangle region, return the 'then' block of the triangle.
VPValue * getPredicatedMask(VPRegionBlock *R)
If R is a region with a VPBranchOnMaskRecipe in the entry block, return the mask.
static void removeRedundantCanonicalIVs(VPlan &Plan)
Try to replace VPWidenCanonicalIVRecipes with a widened canonical IV recipe, if it exists.
This file provides utility VPlan to VPlan transformations.
static const uint32_t IV[8]
Definition: blake3_impl.h:78
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:205
This class represents a function call, abstracting a target machine's calling convention.
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:991
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:849
This class represents an Operation in the Expression.
A debug info location.
Definition: DebugLoc.h:33
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:145
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:220
Core dominator tree base class.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition: TypeSize.h:296
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:973
A struct for saving information about induction variables.
const BasicBlock * getParent() const
Definition: Instruction.h:150
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:278
The group of interleaved loads/stores sharing the same stride and close to each other.
Definition: VectorUtils.h:439
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
Definition: VectorUtils.h:509
uint32_t getNumMembers() const
Definition: VectorUtils.h:457
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:184
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
bool contains(const KeyT &Key) const
Definition: MapVector.h:163
ValueT lookup(const KeyT &Key) const
Definition: MapVector.h:110
size_type size() const
Definition: MapVector.h:60
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Definition: IVDescriptors.h:71
RecurKind getRecurrenceKind() const
This class represents an analyzed expression in the program.
bool isZero() const
Return true if the expression is a constant zero.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
const SCEV * getConstant(ConstantInt *V)
bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVMContext & getContext() const
This class represents the LLVM 'select' instruction.
A vector that has set insertion semantics.
Definition: SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:98
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:93
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
bool contains(const key_type &key) const
Check if the SetVector contains the given key.
Definition: SetVector.h:254
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:317
Provides information about what library functions are available for the current target.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
op_range operands()
Definition: User.h:242
A recipe for generating the active lane mask for the vector loop that is used to predicate the vector...
Definition: VPlan.h:2420
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition: VPlan.h:2594
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition: VPlan.h:2662
RecipeListTy::iterator iterator
Instruction iterators...
Definition: VPlan.h:2615
iterator end()
Definition: VPlan.h:2625
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition: VPlan.h:2672
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition: VPlan.cpp:208
VPBasicBlock * splitAt(iterator SplitAt)
Split current block at SplitAt by inserting a new block between the current block and its successors ...
Definition: VPlan.cpp:528
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition: VPlan.cpp:593
const VPRecipeBase & back() const
Definition: VPlan.h:2637
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition: VPlan.h:2653
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition: VPlan.h:421
VPRegionBlock * getParent()
Definition: VPlan.h:493
const VPBasicBlock * getExitingBasicBlock() const
Definition: VPlan.cpp:173
VPBlockBase * getSinglePredecessor() const
Definition: VPlan.h:534
const VPBasicBlock * getEntryBasicBlock() const
Definition: VPlan.cpp:151
VPBlockBase * getSingleHierarchicalPredecessor()
Definition: VPlan.h:580
VPBlockBase * getSingleSuccessor() const
Definition: VPlan.h:528
const VPBlocksTy & getSuccessors() const
Definition: VPlan.h:518
static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBases IfTrue and IfFalse after BlockPtr.
Definition: VPlan.h:3199
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition: VPlan.h:3227
static void connectBlocks(VPBlockBase *From, VPBlockBase *To)
Connect VPBlockBases From and To bi-directionally.
Definition: VPlan.h:3216
A recipe for generating conditional branches on the bits of a mask.
Definition: VPlan.h:2142
VPlan-based builder utility analogous to IRBuilder.
VPValue * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const Twine &Name="")
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
VPInstruction * createOverflowingOp(unsigned Opcode, std::initializer_list< VPValue * > Operands, VPRecipeWithIRFlags::WrapFlagsTy WrapFlags, DebugLoc DL={}, const Twine &Name="")
VPValue * createNot(VPValue *Operand, DebugLoc DL={}, const Twine &Name="")
void setInsertPoint(VPBasicBlock *TheBB)
This specifies that created VPInstructions should be appended to the end of the specified block.
Canonical scalar induction phi of the vector loop.
Definition: VPlan.h:2363
Type * getScalarType() const
Returns the scalar type of the induction.
Definition: VPlan.h:2392
bool isCanonical(InductionDescriptor::InductionKind Kind, VPValue *Start, VPValue *Step) const
Check if the induction described by Kind, /p Start and Step is canonical, i.e.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition: VPlanValue.h:425
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition: VPlanValue.h:398
A recipe for converting the canonical IV value to the corresponding value of an IV with different sta...
Definition: VPlan.h:2484
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition: VPlan.h:1602
This is a concrete Recipe that models a single VPlan-level instruction.
Definition: VPlan.h:1139
unsigned getOpcode() const
Definition: VPlan.h:1209
@ FirstOrderRecurrenceSplice
Definition: VPlan.h:1145
@ CanonicalIVIncrementForPart
Definition: VPlan.h:1154
@ CalculateTripCountMinusVF
Definition: VPlan.h:1152
VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when control converges back from ...
Definition: VPlan.h:2193
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition: VPlan.h:713
bool mayReadOrWriteMemory() const
Returns true if the recipe may read from or write to memory.
Definition: VPlan.h:799
bool mayHaveSideEffects() const
Returns true if the recipe may have side-effects.
VPBasicBlock * getParent()
Definition: VPlan.h:738
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
void insertAfter(VPRecipeBase *InsertPos)
Insert an unlinked Recipe into a basic block immediately after the specified Recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition: VPlan.h:2727
const VPBlockBase * getEntry() const
Definition: VPlan.h:2766
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition: VPlan.h:2071
bool isUniform() const
Definition: VPlan.h:2111
VPValue * getMask()
Return the mask of a predicated VPReplicateRecipe.
Definition: VPlan.h:2135
VPScalarCastRecipe is a recipe to create scalar cast instructions.
Definition: VPlan.h:1359
A recipe for handling phi nodes of integer and floating-point inductions, producing their scalar valu...
Definition: VPlan.h:2544
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
Definition: VPlan.h:830
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition: VPlan.h:887
An analysis for type-inference for VPValues.
Definition: VPlanAnalysis.h:36
LLVMContext & getContext()
Return the LLVMContext used by the analysis.
Definition: VPlanAnalysis.h:61
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition: VPlanValue.h:204
operand_range operands()
Definition: VPlanValue.h:279
void setOperand(unsigned I, VPValue *New)
Definition: VPlanValue.h:259
operand_iterator op_end()
Definition: VPlanValue.h:277
operand_iterator op_begin()
Definition: VPlanValue.h:275
VPValue * getOperand(unsigned N) const
Definition: VPlanValue.h:254
Value * getUnderlyingValue()
Return the underlying Value attached to this VPValue.
Definition: VPlanValue.h:78
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition: VPlan.cpp:116
void replaceAllUsesWith(VPValue *New)
Definition: VPlan.cpp:1280
unsigned getNumUsers() const
Definition: VPlanValue.h:113
Value * getLiveInIRValue()
Returns the underlying IR value, if this VPValue is defined outside the scope of VPlan.
Definition: VPlanValue.h:174
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser &U, unsigned Idx)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition: VPlan.cpp:1284
user_range users()
Definition: VPlanValue.h:134
A recipe for widening Call instructions.
Definition: VPlan.h:1398
A Recipe for widening the canonical induction variable of the vector loop.
Definition: VPlan.h:2449
const Type * getScalarType() const
Returns the scalar type of the induction.
Definition: VPlan.h:2475
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition: VPlan.h:1309
A recipe for handling GEP instructions.
Definition: VPlan.h:1471
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition: VPlan.h:1626
A Recipe for widening load/store operations.
Definition: VPlan.h:2230
VPWidenRecipe is a recipe for producing a copy of vector type its ingredient.
Definition: VPlan.h:1277
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition: VPlan.h:2828
VPBasicBlock * getEntry()
Definition: VPlan.h:2925
VPValue * getTripCount() const
The trip count of the original loop.
Definition: VPlan.h:2929
VPValue * getOrCreateBackedgeTakenCount()
The backedge taken count of the original loop.
Definition: VPlan.h:2943
VPValue * getVPValueOrAddLiveIn(Value *V)
Gets the VPValue for V or adds a new live-in (if none exists yet) for V.
Definition: VPlan.h:3008
VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition: VPlan.h:3044
bool hasVF(ElementCount VF)
Definition: VPlan.h:2967
bool hasUF(unsigned UF) const
Definition: VPlan.h:2974
void setVF(ElementCount VF)
Definition: VPlan.h:2961
bool hasScalarVFOnly() const
Definition: VPlan.h:2972
VPCanonicalIVPHIRecipe * getCanonicalIV()
Returns the canonical induction recipe of the vector loop.
Definition: VPlan.h:3052
void setUF(unsigned UF)
Definition: VPlan.h:2976
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
bool hasName() const
Definition: Value.h:261
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition: TypeSize.h:168
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition: ilist_node.h:109
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, ScalarEvolution &SE)
Get or create a VPValue that corresponds to the expansion of Expr.
Definition: VPlan.cpp:1422
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
Definition: VPlan.cpp:1412
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1731
Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
const SCEV * createTripCountSCEV(Type *IdxTy, PredicatedScalarEvolution &PSE, Loop *OrigLoop)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:665
iterator_range< df_iterator< VPBlockDeepTraversalWrapper< VPBlockBase * > > > vp_depth_first_deep(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order while traversing t...
Definition: VPlanCFG.h:226
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1738
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:428
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1656
std::unique_ptr< VPlan > VPlanPtr
Definition: VPlan.h:134
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1745
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
Definition: SmallVector.h:1312
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition: Casting.h:548
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition: STLExtras.h:336
RecurKind
These are the kinds of recurrences that we support.
Definition: IVDescriptors.h:34
@ Mul
Product of integers.
@ Add
Sum of integers.
DWARFExpression::Operation Op
BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1758
@ DataAndControlFlowWithoutRuntimeCheck
Use predicate to control both data and control flow, but modify the trip count so that a runtime over...
A recipe for handling first-order recurrence phis.
Definition: VPlan.h:1796
A recipe for widening select instructions.
Definition: VPlan.h:1437
static void createAndOptimizeReplicateRegions(VPlan &Plan)
Wrap predicated VPReplicateRecipes with a mask operand in an if-then region block and remove the mask...
static void dropPoisonGeneratingRecipes(VPlan &Plan, function_ref< bool(BasicBlock *)> BlockNeedsPredication)
Drop poison flags from recipes that may generate a poison value that is used after vectorization,...
static void optimize(VPlan &Plan, ScalarEvolution &SE)
Apply VPlan-to-VPlan optimizations to Plan, including induction recipe optimizations,...
static void clearReductionWrapFlags(VPlan &Plan)
Clear NSW/NUW flags from reduction instructions if necessary.
static void VPInstructionsToVPRecipes(VPlanPtr &Plan, function_ref< const InductionDescriptor *(PHINode *)> GetIntOrFpInductionDescriptor, ScalarEvolution &SE, const TargetLibraryInfo &TLI)
Replaces the VPInstructions in Plan with corresponding widen recipes.
static void truncateToMinimalBitwidths(VPlan &Plan, const MapVector< Instruction *, uint64_t > &MinBWs, LLVMContext &Ctx)
Insert truncates and extends for any truncated recipe.
static void addActiveLaneMask(VPlan &Plan, bool UseActiveLaneMaskForControlFlow, bool DataAndControlFlowWithoutRuntimeCheck)
Replace (ICMP_ULE, wide canonical IV, backedge-taken-count) checks with an (active-lane-mask recipe,...
static bool adjustFixedOrderRecurrences(VPlan &Plan, VPBuilder &Builder)
Sink users of fixed-order recurrences after the recipe defining their previous value.
static void optimizeForVFAndUF(VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
Optimize Plan based on BestVF and BestUF.