LLVM 24.0.0git
VPlanEVLTailFolding.cpp
Go to the documentation of this file.
1//===- VPlanEVLTailFolding.cpp - EVL tail folding 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 the VPlan-to-VPlan transforms related to explicit
11/// vector length (EVL) tail folding support.
12///
13//===----------------------------------------------------------------------===//
14
16#include "VPlan.h"
17#include "VPlanCFG.h"
18#include "VPlanHelpers.h"
19#include "VPlanPatternMatch.h"
20#include "VPlanTransforms.h"
21#include "VPlanUtils.h"
23#include "llvm/IR/Intrinsics.h"
24
25using namespace llvm;
26using namespace VPlanPatternMatch;
27
28/// From the definition of llvm.experimental.get.vector.length,
29/// VPInstruction::ExplicitVectorLength(%AVL) = %AVL when %AVL <= VF.
34 for (VPRecipeBase &R : *VPBB) {
35 VPValue *AVL;
36 if (!match(&R, m_EVL(m_VPValue(AVL))))
37 continue;
38
39 const SCEV *AVLSCEV = vputils::getSCEVExprForVPValue(AVL, PSE);
40 if (isa<SCEVCouldNotCompute>(AVLSCEV))
41 continue;
42 ScalarEvolution &SE = *PSE.getSE();
43 const SCEV *VFSCEV = SE.getElementCount(AVLSCEV->getType(), VF);
44 if (!SE.isKnownPredicate(CmpInst::ICMP_ULE, AVLSCEV, VFSCEV))
45 continue;
46
48 AVL, Type::getInt32Ty(Plan.getContext()), AVLSCEV->getType(),
49 R.getDebugLoc());
50 if (Trunc != AVL) {
51 auto *TruncR = cast<VPSingleDefRecipe>(Trunc);
52 const DataLayout &DL = Plan.getDataLayout();
53 if (VPValue *Folded =
54 vputils::tryToFoldLiveIns(*TruncR, TruncR->operands(), DL))
55 Trunc = Folded;
56 }
57 R.getVPSingleValue()->replaceAllUsesWith(Trunc);
58 return true;
59 }
60 }
61 return false;
62}
63
64template <typename Op0_t, typename Op1_t> struct RemoveMask_match {
65 Op0_t In;
67
68 RemoveMask_match(const Op0_t &In, Op1_t &Out) : In(In), Out(Out) {}
69
70 template <typename OpTy> bool match(OpTy *V) const {
71 if (m_Specific(In).match(V)) {
72 Out = nullptr;
73 return true;
74 }
75 return m_LogicalAnd(m_Specific(In), m_VPValue(Out)).match(V);
76 }
77};
78
79/// Match a specific mask \p In, or a combination of it (logical-and In, Out).
80/// Returns the remaining part \p Out if so, or nullptr otherwise.
81template <typename Op0_t, typename Op1_t>
82static inline RemoveMask_match<Op0_t, Op1_t> m_RemoveMask(const Op0_t &In,
83 Op1_t &Out) {
84 return RemoveMask_match<Op0_t, Op1_t>(In, Out);
85}
86
87static std::optional<Intrinsic::ID> getVPDivRemIntrinsic(Intrinsic::ID IntrID) {
88 switch (IntrID) {
89 case Intrinsic::masked_udiv:
90 return Intrinsic::vp_udiv;
91 case Intrinsic::masked_sdiv:
92 return Intrinsic::vp_sdiv;
93 case Intrinsic::masked_urem:
94 return Intrinsic::vp_urem;
95 case Intrinsic::masked_srem:
96 return Intrinsic::vp_srem;
97 default:
98 return std::nullopt;
99 }
100}
101
102/// Try to optimize a \p CurRecipe masked by \p HeaderMask to a corresponding
103/// EVL-based recipe without the header mask. Returns nullptr if no EVL-based
104/// recipe could be created.
105/// \p HeaderMask Header Mask.
106/// \p CurRecipe Recipe to be transform.
107/// \p EVL The explicit vector length parameter of vector-predication
108/// intrinsics.
110 VPRecipeBase &CurRecipe, VPValue &EVL) {
111 VPlan *Plan = CurRecipe.getParent()->getPlan();
112 DebugLoc DL = CurRecipe.getDebugLoc();
113 VPValue *Addr, *Mask, *EndPtr;
114
115 /// Adjust any end pointers so that they point to the end of EVL lanes not VF.
116 auto AdjustEndPtr = [&CurRecipe, &EVL](VPValue *EndPtr) {
117 auto *EVLEndPtr = cast<VPVectorEndPointerRecipe>(EndPtr)->clone();
118 EVLEndPtr->insertBefore(&CurRecipe);
119 // Cast EVL (i32) to match the VF operand's type.
120 VPValue *EVLAsVF = VPBuilder(EVLEndPtr).createScalarZExtOrTrunc(
121 &EVL, EVLEndPtr->getOperand(1)->getScalarType(), EVL.getScalarType(),
123 EVLEndPtr->setOperand(1, EVLAsVF);
124 return EVLEndPtr;
125 };
126
127 auto GetVPReverse = [&CurRecipe, &EVL, Plan,
129 if (!V)
130 return nullptr;
132 Intrinsic::experimental_vp_reverse, {V, Plan->getTrue(), &EVL},
133 V->getScalarType(), {}, {}, DL);
134 Reverse->insertBefore(&CurRecipe);
135 return Reverse;
136 };
137
138 if (match(&CurRecipe,
139 m_MaskedLoad(m_VPValue(Addr), m_RemoveMask(HeaderMask, Mask))))
140 return new VPWidenLoadEVLRecipe(cast<VPWidenLoadRecipe>(CurRecipe), Addr,
141 EVL, Mask);
142
143 if (match(&CurRecipe,
144 m_MaskedLoad(m_VPValue(EndPtr),
145 m_Reverse(m_RemoveMask(HeaderMask, Mask)))) &&
146 match(EndPtr, m_VecEndPtr(m_VPValue(), m_Specific(&Plan->getVF())))) {
147 Mask = GetVPReverse(Mask);
148 Addr = AdjustEndPtr(EndPtr);
149 auto *LoadR = new VPWidenLoadEVLRecipe(cast<VPWidenLoadRecipe>(CurRecipe),
150 Addr, EVL, Mask);
151 LoadR->insertBefore(&CurRecipe);
152 VPValue *Poison = Plan->getPoison(LoadR->getScalarType());
153 return new VPWidenIntrinsicRecipe(Intrinsic::vector_splice_left,
154 {Poison, LoadR, &EVL},
155 LoadR->getScalarType(), {}, {}, DL);
156 }
157
158 VPValue *Stride;
160 m_VPValue(Addr), m_VPValue(Stride),
161 m_RemoveMask(HeaderMask, Mask),
162 m_TruncOrSelf(m_Specific(&Plan->getVF()))))) {
163 if (!Mask)
164 Mask = Plan->getTrue();
165 auto *NewLoad = cast<VPWidenMemIntrinsicRecipe>(&CurRecipe)->clone();
166 NewLoad->setOperand(2, Mask);
167 NewLoad->setOperand(3, &EVL);
168 return NewLoad;
169 }
170
171 VPValue *StoredVal;
172 if (match(&CurRecipe, m_MaskedStore(m_VPValue(Addr), m_VPValue(StoredVal),
173 m_RemoveMask(HeaderMask, Mask))))
174 return new VPWidenStoreEVLRecipe(cast<VPWidenStoreRecipe>(CurRecipe), Addr,
175 StoredVal, EVL, Mask);
176
177 if (match(&CurRecipe,
178 m_MaskedStore(m_VPValue(EndPtr), m_VPValue(StoredVal),
179 m_Reverse(m_RemoveMask(HeaderMask, Mask)))) &&
180 match(EndPtr, m_VecEndPtr(m_VPValue(), m_Specific(&Plan->getVF())))) {
181 Mask = GetVPReverse(Mask);
182 Addr = AdjustEndPtr(EndPtr);
183 VPValue *Poison = Plan->getPoison(StoredVal->getScalarType());
184 auto *SpliceR = new VPWidenIntrinsicRecipe(
185 Intrinsic::vector_splice_right, {StoredVal, Poison, &EVL},
186 StoredVal->getScalarType(), {}, {}, DL);
187 SpliceR->insertBefore(&CurRecipe);
188 return new VPWidenStoreEVLRecipe(cast<VPWidenStoreRecipe>(CurRecipe), Addr,
189 SpliceR, EVL, Mask);
190 }
191
192 if (auto *Rdx = dyn_cast<VPReductionRecipe>(&CurRecipe))
193 if (Rdx->isConditional() &&
194 match(Rdx->getCondOp(), m_RemoveMask(HeaderMask, Mask)))
195 return new VPReductionEVLRecipe(*Rdx, EVL, Mask);
196
197 if (auto *Interleave = dyn_cast<VPInterleaveRecipe>(&CurRecipe))
198 if (Interleave->getMask() &&
199 match(Interleave->getMask(), m_RemoveMask(HeaderMask, Mask)))
200 return new VPInterleaveEVLRecipe(*Interleave, EVL, Mask);
201
202 VPValue *LHS, *RHS;
203 if (match(&CurRecipe, m_SelectLike(m_RemoveMask(HeaderMask, Mask),
205 return new VPWidenIntrinsicRecipe(
206 Intrinsic::vp_merge, {Mask ? Mask : Plan->getTrue(), LHS, RHS, &EVL},
207 LHS->getScalarType(), {}, {}, DL);
208
209 if (match(&CurRecipe, m_LastActiveLane(m_Specific(HeaderMask)))) {
210 Type *Ty = CurRecipe.getVPSingleValue()->getScalarType();
211 VPValue *ZExt =
212 VPBuilder(&CurRecipe)
213 .createScalarZExtOrTrunc(&EVL, Ty, EVL.getScalarType(), DL);
214 return new VPInstruction(
215 Instruction::Sub, {ZExt, Plan->getConstantInt(Ty, 1)},
216 VPIRFlags::getDefaultFlags(Instruction::Sub), {}, DL);
217 }
218
219 // lhs | (headermask && rhs) -> vp.merge rhs, true, lhs, evl
220 if (match(&CurRecipe,
222 m_LogicalAnd(m_Specific(HeaderMask), m_VPValue(RHS)))))
223 return new VPWidenIntrinsicRecipe(Intrinsic::vp_merge,
224 {RHS, Plan->getTrue(), LHS, &EVL},
225 LHS->getScalarType(), {}, {}, DL);
226
227 if (auto *IntrR = dyn_cast<VPWidenIntrinsicRecipe>(&CurRecipe))
228 if (auto VPID = getVPDivRemIntrinsic(IntrR->getVectorIntrinsicID()))
229 if (match(IntrR->getOperand(2), m_RemoveMask(HeaderMask, Mask)))
230 return new VPWidenIntrinsicRecipe(*VPID,
231 {IntrR->getOperand(0),
232 IntrR->getOperand(1),
233 Mask ? Mask : Plan->getTrue(), &EVL},
234 IntrR->getScalarType(), {}, {}, DL);
235
236 return nullptr;
237}
238
239/// Optimize away any EVL-based header masks to VP intrinsic based recipes.
240/// The transforms here need to preserve the original semantics.
242 // Find the EVL-based header mask if it exists: icmp ult step-vector, EVL
243 VPValue *HeaderMask = nullptr, *EVL = nullptr;
246 m_VPValue(EVL))) &&
247 match(EVL, m_EVL(m_VPValue()))) {
248 HeaderMask = R.getVPSingleValue();
249 break;
250 }
251 }
252 if (!HeaderMask)
253 return;
254
256 for (VPUser *U : vputils::collectUsersRecursively(HeaderMask)) {
258 if (auto *NewR = optimizeMaskToEVL(HeaderMask, *R, *EVL)) {
259 NewR->insertBefore(R);
260 for (auto [Old, New] :
261 zip_equal(R->definedValues(), NewR->definedValues()))
262 Old->replaceAllUsesWith(New);
263 OldRecipes.push_back(R);
264 }
265 }
266
267 // Replace remaining (HeaderMask && Mask) with vp.merge (True, Mask,
268 // False, EVL)
269 for (VPUser *U : vputils::collectUsersRecursively(HeaderMask)) {
270 VPValue *Mask;
271 if (match(U, m_LogicalAnd(m_Specific(HeaderMask), m_VPValue(Mask)))) {
272 auto *LogicalAnd = cast<VPInstruction>(U);
273 auto *Merge = new VPWidenIntrinsicRecipe(
274 Intrinsic::vp_merge, {Plan.getTrue(), Mask, Plan.getFalse(), EVL},
275 Mask->getScalarType(), {}, {}, LogicalAnd->getDebugLoc());
276 Merge->insertBefore(LogicalAnd);
277 LogicalAnd->replaceAllUsesWith(Merge);
278 OldRecipes.push_back(LogicalAnd);
279 }
280 }
281
282 // Pull out left splices from any elementwise op.
283 // binop(splice.left(poison, x, evl), live-in)
284 // -> splice.left(poison, binop(x,live-in), evl)
286 Plan,
287 [&EVL](VPValue *&X) {
289 m_Poison(), m_VPValue(X), m_Specific(EVL));
290 },
291 [&Plan, &EVL](auto *X) {
292 return new VPWidenIntrinsicRecipe(
293 Intrinsic::vector_splice_left,
294 {Plan.getPoison(X->getScalarType()), X, EVL}, X->getScalarType(),
295 {}, {}, X->getDebugLoc());
296 });
297
298 // Fold the following splice patterns:
299 // splice.right(splice.left(poison, x, evl), poison, evl) -> x
300 // vector.reverse(splice.left(poison, x, evl)) -> vp.reverse(x, true, evl)
301 // splice.right(vector.reverse(x), poison, evl) -> vp.reverse(x, true, evl)
303 auto *R = cast<VPRecipeBase>(U);
304 // Remove potentially dead left splices from the transform above.
306 R->getVPSingleValue()->getNumUsers() == 0) {
307 OldRecipes.push_back(R);
308 continue;
309 }
310
311 VPValue *X;
314 m_Poison(), m_VPValue(X), m_Specific(EVL)),
315 m_Poison(), m_Specific(EVL)))) {
316 R->getVPSingleValue()->replaceAllUsesWith(X);
317 OldRecipes.push_back(R);
318 continue;
319 }
320
321 if (!match(U,
324 m_Poison(), m_VPValue(X), m_Specific(EVL))),
327 continue;
328
329 auto *VPReverse = new VPWidenIntrinsicRecipe(
330 Intrinsic::experimental_vp_reverse, {X, Plan.getTrue(), EVL},
331 X->getScalarType(), {}, {}, R->getDebugLoc());
332 VPReverse->insertBefore(R);
333 R->getVPSingleValue()->replaceAllUsesWith(VPReverse);
334 OldRecipes.push_back(R);
335 }
336
337 for (VPRecipeBase *R : reverse(OldRecipes)) {
338 SmallVector<VPValue *> PossiblyDead(R->operands());
339 R->eraseFromParent();
340 for (VPValue *Op : PossiblyDead)
342 }
343}
344
345/// After replacing the canonical IV with a EVL-based IV, fixup recipes that use
346/// VF to use the EVL instead to avoid incorrect updates on the penultimate
347/// iteration.
348static void fixupVFUsersForEVL(VPlan &Plan, VPValue &EVL) {
349 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
350 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
351
352 // EVL is i32 but VF/VFxUF are IdxTy. Convert as needed.
353 VPValue *EVLAsIdx =
357
358 assert(all_of(Plan.getVF().users(),
359 [&Plan](VPUser *U) {
360 auto IsAllowedUser =
361 IsaPred<VPVectorEndPointerRecipe, VPScalarIVStepsRecipe,
362 VPWidenIntOrFpInductionRecipe,
363 VPWidenMemIntrinsicRecipe>;
364 if (match(U, m_Trunc(m_Specific(&Plan.getVF()))))
365 return all_of(cast<VPSingleDefRecipe>(U)->users(),
366 IsAllowedUser);
367 return IsAllowedUser(U);
368 }) &&
369 "User of VF that we can't transform to EVL.");
370 Plan.getVF().replaceUsesWithIf(EVLAsIdx, [](VPUser &U, unsigned Idx) {
372 });
373
374 assert(all_of(Plan.getVFxUF().users(),
376 m_c_Add(m_Specific(LoopRegion->getCanonicalIV()),
377 m_Specific(&Plan.getVFxUF())),
379 "Only users of VFxUF should be VPWidenPointerInductionRecipe and the "
380 "increment of the canonical induction.");
381 Plan.getVFxUF().replaceUsesWithIf(EVLAsIdx, [](VPUser &U, unsigned Idx) {
382 // Only replace uses in VPWidenPointerInductionRecipe; The increment of the
383 // canonical induction must not be updated.
385 });
386
387 // Create a scalar phi to track the previous EVL if fixed-order recurrence is
388 // contained.
389 bool ContainsFORs =
391 if (ContainsFORs) {
392 // TODO: Use VPInstruction::ExplicitVectorLength to get maximum EVL.
393 VPValue *MaxEVL = &Plan.getVF();
394 // Emit VPScalarCastRecipe in preheader if VF is not a 32 bits integer.
395 VPBuilder Builder(LoopRegion->getPreheaderVPBB());
396 MaxEVL = Builder.createScalarZExtOrTrunc(
397 MaxEVL, Type::getInt32Ty(Plan.getContext()), MaxEVL->getScalarType(),
399
400 Builder.setInsertPoint(Header, Header->getFirstNonPhi());
401 VPValue *PrevEVL = Builder.createScalarPhi(
402 {MaxEVL, &EVL}, DebugLoc::getUnknown(), "prev.evl");
403
406 for (VPRecipeBase &R : *VPBB) {
407 VPValue *V1, *V2;
408 if (!match(&R,
410 m_VPValue(V1), m_VPValue(V2))))
411 continue;
412 VPValue *Imm = Plan.getOrAddLiveIn(
415 Intrinsic::experimental_vp_splice,
416 {V1, V2, Imm, Plan.getTrue(), PrevEVL, &EVL},
417 R.getVPSingleValue()->getScalarType(), {}, {}, R.getDebugLoc());
418 VPSplice->insertBefore(&R);
419 R.getVPSingleValue()->replaceAllUsesWith(VPSplice);
420 }
421 }
422 }
423
424 VPValue *HeaderMask = LoopRegion->getHeaderMask();
425 if (!HeaderMask)
426 return;
427
428 // Ensure that any reduction that uses a select to mask off tail lanes does so
429 // in the vector loop, not the middle block, since EVL tail folding can have
430 // tail elements in the penultimate iteration.
431 assert(all_of(*Plan.getMiddleBlock(), [&Plan, HeaderMask](VPRecipeBase &R) {
432 if (match(&R, m_ComputeReductionResult(m_Select(m_Specific(HeaderMask),
433 m_VPValue(), m_VPValue()))))
434 return R.getOperand(0)->getDefiningRecipe()->getRegion() ==
435 Plan.getVectorLoopRegion();
436 return true;
437 }));
438
439 // Replace the abstract header mask with a mask equivalent to predicating by
440 // EVL: icmp ult step-vector, EVL
441 VPRecipeBase *EVLR = EVL.getDefiningRecipe();
442 VPBuilder Builder(EVLR->getParent(), std::next(EVLR->getIterator()));
443 Type *EVLType = EVL.getScalarType();
444 VPValue *EVLMask = Builder.createICmp(
446 Builder.createNaryOp(VPInstruction::StepVector, {}, EVLType), &EVL);
447 HeaderMask->replaceAllUsesWith(EVLMask);
448}
449
450/// Converts a tail folded vector loop region to step by
451/// VPInstruction::ExplicitVectorLength elements instead of VF elements each
452/// iteration.
453///
454/// - Add a VPCurrentIterationPHIRecipe and related recipes to \p Plan and
455/// replaces all uses of the canonical IV except for the canonical IV
456/// increment with a VPCurrentIterationPHIRecipe. The canonical IV is used
457/// only for loop iterations counting after this transformation.
458///
459/// - The header mask is replaced with a header mask based on the EVL.
460///
461/// - Plans with FORs have a new phi added to keep track of the EVL of the
462/// previous iteration, and VPFirstOrderRecurrencePHIRecipes are replaced with
463/// @llvm.vp.splice.
464///
465/// The function uses the following definitions:
466/// %StartV is the canonical induction start value.
467///
468/// The function adds the following recipes:
469///
470/// vector.ph:
471/// ...
472///
473/// vector.body:
474/// ...
475/// %CurrentIter = CURRENT-ITERATION-PHI [ %StartV, %vector.ph ],
476/// [ %NextIter, %vector.body ]
477/// %AVL = phi [ trip-count, %vector.ph ], [ %NextAVL, %vector.body ]
478/// %VPEVL = EXPLICIT-VECTOR-LENGTH %AVL
479/// ...
480/// %OpEVL = cast i32 %VPEVL to IVSize
481/// %NextIter = add IVSize %OpEVL, %CurrentIter
482/// %NextAVL = sub IVSize nuw %AVL, %OpEVL
483/// ...
484///
485/// If MaxSafeElements is provided, the function adds the following recipes:
486/// vector.ph:
487/// ...
488///
489/// vector.body:
490/// ...
491/// %CurrentIter = CURRENT-ITERATION-PHI [ %StartV, %vector.ph ],
492/// [ %NextIter, %vector.body ]
493/// %AVL = phi [ trip-count, %vector.ph ], [ %NextAVL, %vector.body ]
494/// %cmp = cmp ult %AVL, MaxSafeElements
495/// %SAFE_AVL = select %cmp, %AVL, MaxSafeElements
496/// %VPEVL = EXPLICIT-VECTOR-LENGTH %SAFE_AVL
497/// ...
498/// %OpEVL = cast i32 %VPEVL to IVSize
499/// %NextIter = add IVSize %OpEVL, %CurrentIter
500/// %NextAVL = sub IVSize nuw %AVL, %OpEVL
501/// ...
502///
504 VPlan &Plan, const std::optional<unsigned> &MaxSafeElements) {
505 if (Plan.hasScalarVFOnly())
506 return;
507 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
508 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
509
510 auto *CanonicalIV = LoopRegion->getCanonicalIV();
511 auto *CanIVTy = LoopRegion->getCanonicalIVType();
512 VPValue *StartV = Plan.getZero(CanIVTy);
513 auto *CanonicalIVIncrement = LoopRegion->getOrCreateCanonicalIVIncrement();
514
515 // Create the CurrentIteration recipe in the vector loop.
516 auto *CurrentIteration =
518 CurrentIteration->insertBefore(*Header, Header->begin());
519 VPBuilder Builder(Header, Header->getFirstNonPhi());
520 // Create the AVL (application vector length), starting from TC -> 0 in steps
521 // of EVL.
522 VPPhi *AVLPhi = Builder.createScalarPhi(
524 VPValue *AVL = AVLPhi;
525
526 if (MaxSafeElements) {
527 // Support for MaxSafeDist for correct loop emission.
528 VPValue *AVLSafe = Plan.getConstantInt(CanIVTy, *MaxSafeElements);
529 VPValue *Cmp = Builder.createICmp(ICmpInst::ICMP_ULT, AVL, AVLSafe);
530 AVL = Builder.createSelect(Cmp, AVL, AVLSafe, DebugLoc::getUnknown(),
531 "safe_avl");
532 }
533 auto *VPEVL = Builder.createNaryOp(VPInstruction::ExplicitVectorLength, AVL,
534 DebugLoc::getUnknown(), "evl");
535
536 Builder.setInsertPoint(CanonicalIVIncrement);
537 VPValue *OpVPEVL = VPEVL;
538
539 auto *I32Ty = Type::getInt32Ty(Plan.getContext());
540 OpVPEVL = Builder.createScalarZExtOrTrunc(
541 OpVPEVL, CanIVTy, I32Ty, CanonicalIVIncrement->getDebugLoc());
542
543 auto *NextIter = Builder.createAdd(
544 OpVPEVL, CurrentIteration, CanonicalIVIncrement->getDebugLoc(),
545 "current.iteration.next", CanonicalIVIncrement->getNoWrapFlags());
546 CurrentIteration->addBackedgeValue(NextIter);
547
548 VPValue *NextAVL =
549 Builder.createSub(AVLPhi, OpVPEVL, DebugLoc::getCompilerGenerated(),
550 "avl.next", {/*NUW=*/true, /*NSW=*/false});
551 AVLPhi->addIncoming(NextAVL);
552
553 fixupVFUsersForEVL(Plan, *VPEVL);
554 removeDeadRecipes(Plan);
555
556 // Replace all uses of the canonical IV with VPCurrentIterationPHIRecipe
557 // except for the canonical IV increment.
558 CanonicalIV->replaceUsesWithIf(CurrentIteration,
559 [CanonicalIVIncrement](VPUser &U, unsigned) {
560 return &U != CanonicalIVIncrement;
561 });
562 // TODO: support unroll factor > 1.
563 Plan.setUF(1);
564}
565
567 // Find the vector loop entry by locating VPCurrentIterationPHIRecipe.
568 // There should be only one VPCurrentIteration in the entire plan.
569 VPCurrentIterationPHIRecipe *CurrentIteration = nullptr;
570
573 for (VPRecipeBase &R : VPBB->phis())
574 if (auto *PhiR = dyn_cast<VPCurrentIterationPHIRecipe>(&R)) {
575 assert(!CurrentIteration &&
576 "Found multiple CurrentIteration. Only one expected");
577 CurrentIteration = PhiR;
578 }
579
580 // Early return if it is not variable-length stepping.
581 if (!CurrentIteration)
582 return;
583
584 VPBasicBlock *HeaderVPBB = CurrentIteration->getParent();
585 VPValue *CurrentIterationIncr = CurrentIteration->getBackedgeValue();
586
587 // Convert CurrentIteration to concrete recipe.
588 auto *ScalarR =
589 VPBuilder(CurrentIteration)
591 {CurrentIteration->getStartValue(), CurrentIterationIncr},
592 CurrentIteration->getDebugLoc(), "current.iteration.iv");
593 CurrentIteration->replaceAllUsesWith(ScalarR);
594 CurrentIteration->eraseFromParent();
595
596 // Replace CanonicalIVInc with CurrentIteration increment if it exists.
597 auto *CanonicalIV = cast<VPPhi>(&*HeaderVPBB->begin());
598 if (auto *CanIVInc = findUserOf(
599 CanonicalIV, m_c_Add(m_VPValue(), m_Specific(&Plan.getVFxUF())))) {
600 cast<VPInstruction>(CanIVInc)->replaceAllUsesWith(CurrentIterationIncr);
601 CanIVInc->eraseFromParent();
602 }
603}
604
606 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
607 if (!LoopRegion)
608 return;
609 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
610 if (Header->empty())
611 return;
612 // The EVL IV is always at the beginning.
613 auto *EVLPhi = dyn_cast<VPCurrentIterationPHIRecipe>(&Header->front());
614 if (!EVLPhi)
615 return;
616
617 // Bail if not an EVL tail folded loop.
618 VPValue *AVL;
619 if (!match(EVLPhi->getBackedgeValue(),
621 return;
622
623 // The AVL may be capped to a safe distance.
624 VPValue *SafeAVL, *UnsafeAVL;
625 if (match(AVL,
627 m_VPValue(SafeAVL)),
628 m_Deferred(UnsafeAVL), m_Deferred(SafeAVL))))
629 AVL = UnsafeAVL;
630
631 VPValue *AVLNext;
632 [[maybe_unused]] bool FoundAVLNext =
634 m_Specific(Plan.getTripCount()), m_VPValue(AVLNext)));
635 assert(FoundAVLNext && "Didn't find AVL backedge?");
636
637 VPBasicBlock *Latch = LoopRegion->getExitingBasicBlock();
638 auto *LatchBr = cast<VPInstruction>(Latch->getTerminator());
639 if (match(LatchBr, m_BranchOnCond(m_True())))
640 return;
641
642 VPValue *CanIVInc;
643 [[maybe_unused]] bool FoundIncrement = match(
644 LatchBr,
646 m_Specific(&Plan.getVectorTripCount()))));
647 assert(FoundIncrement &&
648 match(CanIVInc, m_Add(m_Specific(LoopRegion->getCanonicalIV()),
649 m_Specific(&Plan.getVFxUF()))) &&
650 "Expected BranchOnCond with ICmp comparing CanIV + VFxUF with vector "
651 "trip count");
652
653 Type *AVLTy = AVLNext->getScalarType();
654 VPBuilder Builder(LatchBr);
655 LatchBr->setOperand(
656 0, Builder.createICmp(CmpInst::ICMP_EQ, AVLNext, Plan.getZero(AVLTy)));
657}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
This file provides a LoopVectorizationPlanner class.
R600 Clause Merge
static RemoveMask_match< Op0_t, Op1_t > m_RemoveMask(const Op0_t &In, Op1_t &Out)
Match a specific mask In, or a combination of it (logical-and In, Out).
static void fixupVFUsersForEVL(VPlan &Plan, VPValue &EVL)
After replacing the canonical IV with a EVL-based IV, fixup recipes that use VF to use the EVL instea...
static std::optional< Intrinsic::ID > getVPDivRemIntrinsic(Intrinsic::ID IntrID)
static VPRecipeBase * optimizeMaskToEVL(VPValue *HeaderMask, VPRecipeBase &CurRecipe, VPValue &EVL)
Try to optimize a CurRecipe masked by HeaderMask to a corresponding EVL-based recipe without the head...
This file contains the declarations of different VPlan-related auxiliary helpers.
This file provides utility VPlan to VPlan transformations.
This file contains the declarations of the Vectorization Plan base classes:
Value * RHS
Value * LHS
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getCompilerGenerated()
Definition DebugLoc.h:154
static DebugLoc getUnknown()
Definition DebugLoc.h:153
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.
This class represents an analyzed expression in the program.
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4362
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4397
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:639
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:236
VPlan * getPlan()
Definition VPlan.cpp:211
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:216
static auto blocksAs(T &&Range)
Return an iterator range over Range with each block cast to BlockTy.
Definition VPlanUtils.h:375
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:356
VPlan-based builder utility analogous to IRBuilder.
VPValue * createScalarZExtOrTrunc(VPValue *Op, Type *ResultTy, Type *SrcTy, DebugLoc DL)
static VPBuilder getToInsertAfter(VPRecipeBase *R)
Create a VPBuilder to insert after R.
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", const VPIRFlags &Flags={}, Type *ResultTy=nullptr)
A recipe for generating the phi node tracking the current scalar iteration index.
Definition VPlan.h:4056
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:549
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2474
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2463
static VPIRFlags getDefaultFlags(unsigned Opcode)
Returns default flags for Opcode for opcodes that support it, asserts otherwise.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1224
A recipe for interleaved memory operations with vector-predication intrinsics.
Definition VPlan.h:3156
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1657
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:402
VPBasicBlock * getParent()
Definition VPlan.h:474
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:552
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A recipe to represent inloop reduction operations with vector-predication intrinsics,...
Definition VPlan.h:3326
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4587
const VPBlockBase * getEntry() const
Definition VPlan.h:4631
VPInstruction * getOrCreateCanonicalIVIncrement()
Get the canonical IV increment instruction if it exists.
Definition VPlan.cpp:864
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4707
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4699
VPBasicBlock * getPreheaderVPBB()
Returns the pre-header VPBasicBlock of the loop region.
Definition VPlan.h:4656
VPRegionValue * getHeaderMask() const
Return the header mask of the region, or null if not set.
Definition VPlan.h:4712
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:399
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:149
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:130
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1468
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:1474
user_range users()
Definition VPlanValue.h:157
A recipe for widening vector intrinsics.
Definition VPlan.h:1917
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4766
const DataLayout & getDataLayout() const
Definition VPlan.h:4973
LLVMContext & getContext() const
Definition VPlan.h:4969
VPBasicBlock * getEntry()
Definition VPlan.h:4862
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4927
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:5064
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:4967
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5092
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:4957
VPIRValue * getOrAddLiveIn(Value *V)
Gets the live-in VPIRValue for V or adds a new live-in (if none exists yet) for V.
Definition VPlan.h:5041
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5067
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1060
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4897
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:5061
bool hasScalarVFOnly() const
Definition VPlan.h:5009
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:4960
void setUF(unsigned UF)
Definition VPlan.h:5024
VPIRValue * getConstantInt(Type *Ty, uint64_t Val, bool IsSigned=false)
Return a VPIRValue wrapping a ConstantInt with the given type and value.
Definition VPlan.h:5075
self_iterator getIterator()
Definition ilist_node.h:123
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
auto m_Poison()
Match an arbitrary poison constant.
match_combine_or< CastInst_match< OpTy, ZExtInst >, OpTy > m_ZExtOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
SpecificCmpClass_match< LHS, RHS, CmpInst > m_SpecificCmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
SelectLike_match< CondTy, LTy, RTy > m_SelectLike(const CondTy &C, const LTy &TrueC, const RTy &FalseC)
Matches a value that behaves like a boolean-controlled select, i.e.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_MaskedStore(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
Matches MaskedStore Intrinsic.
auto m_MaskedLoad(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
Matches MaskedLoad Intrinsic.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
AllRecipe_commutative_match< Instruction::Or, Op0_t, Op1_t > m_c_BinaryOr(const Op0_t &Op0, const Op1_t &Op1)
VPInstruction_match< VPInstruction::StepVector > m_StepVector()
VPInstruction_match< VPInstruction::LastActiveLane, Op0_t > m_LastActiveLane(const Op0_t &Op0)
specific_intval< 1 > m_True()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VectorEndPointerRecipe_match< Op0_t, Op1_t > m_VecEndPtr(const Op0_t &Op0, const Op1_t &Op1)
VPRecipeBase * findUserOf(VPValue *V, const MatchT &P)
If V is used by a recipe matching pattern P, return it.
VPInstruction_match< VPInstruction::ExplicitVectorLength, Op0_t > m_EVL(const Op0_t &Op0)
match_bind< VPInstruction > m_VPInstruction(VPInstruction *&V)
Match a VPInstruction, capturing if we match.
VPInstruction_match< VPInstruction::BranchOnCond > m_BranchOnCond()
VPInstruction_match< VPInstruction::Reverse, Op0_t > m_Reverse(const Op0_t &Op0)
VPIRValue * tryToFoldLiveIns(VPSingleDefRecipe &R, ArrayRef< VPValue * > Operands, const DataLayout &DL)
Try to fold R using InstSimplifyFolder.
void recursivelyDeleteDeadRecipes(VPValue *V)
Recursively delete V and any of its operands that become dead.
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
void pullOutPermutations(VPlan &Plan, Match_t Perm, Builder Build)
Removes the permutation pattern Perm from any elementwise operations in the plan, by constructing a n...
Definition VPlanUtils.h:208
SmallVector< VPUser * > collectUsersRecursively(VPValue *V)
Collect all users of V, looking through recipes that define other values.
This is an optimization pass for GlobalISel generic memory operations.
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:1739
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:840
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< df_iterator< VPBlockShallowTraversalWrapper< VPBlockBase * > > > vp_depth_first_shallow(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order.
Definition VPlanCFG.h:250
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:285
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:1746
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
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:547
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
RemoveMask_match(const Op0_t &In, Op1_t &Out)
bool match(OpTy *V) const
A recipe for widening load operations with vector-predication intrinsics, using the address to load f...
Definition VPlan.h:3832
A recipe for widening store operations with vector-predication intrinsics, using the value to store,...
Definition VPlan.h:3935
static bool simplifyKnownEVL(VPlan &Plan, ElementCount VF, PredicatedScalarEvolution &PSE)
Try to simplify VPInstruction::ExplicitVectorLength recipes when the AVL is known to be <= VF,...
static void convertToVariableLengthStep(VPlan &Plan)
Transform loops with variable-length stepping after region dissolution.
static void addExplicitVectorLength(VPlan &Plan, const std::optional< unsigned > &MaxEVLSafeElements)
Add a VPCurrentIterationPHIRecipe and related recipes to Plan and replaces all uses of the canonical ...
static void optimizeEVLMasks(VPlan &Plan)
Optimize recipes which use an EVL-based header mask to VP intrinsics, for example:
static void removeDeadRecipes(VPlan &Plan)
Remove dead recipes from Plan.
static void convertEVLExitCond(VPlan &Plan)
Replaces the exit condition from (branch-on-cond eq CanonicalIVInc, VectorTripCount) to (branch-on-co...