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"
22#include "llvm/ADT/SetVector.h"
24#include "llvm/IR/Intrinsics.h"
25
26using namespace llvm;
27using namespace VPlanPatternMatch;
28
29/// From the definition of llvm.experimental.get.vector.length,
30/// VPInstruction::ExplicitVectorLength(%AVL) = %AVL when %AVL <= VF.
35 for (VPRecipeBase &R : *VPBB) {
36 VPValue *AVL;
37 if (!match(&R, m_EVL(m_VPValue(AVL))))
38 continue;
39
40 const SCEV *AVLSCEV = vputils::getSCEVExprForVPValue(AVL, PSE);
41 if (isa<SCEVCouldNotCompute>(AVLSCEV))
42 continue;
43 ScalarEvolution &SE = *PSE.getSE();
44 const SCEV *VFSCEV = SE.getElementCount(AVLSCEV->getType(), VF);
45 if (!SE.isKnownPredicate(CmpInst::ICMP_ULE, AVLSCEV, VFSCEV))
46 continue;
47
49 AVL, Type::getInt32Ty(Plan.getContext()), 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(),
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 if (match(&CurRecipe,
160 m_VPValue(), m_VPValue(), m_RemoveMask(HeaderMask, Mask),
161 m_TruncOrSelf(m_Specific(&Plan->getVF()))))) {
162 auto *NewLoad = cast<VPWidenMemIntrinsicRecipe>(&CurRecipe)->clone();
163 NewLoad->setOperand(2, Mask ? Mask : Plan->getTrue());
164 NewLoad->setOperand(3, &EVL);
165 return NewLoad;
166 }
167
168 VPValue *StoredVal;
169 if (match(&CurRecipe, m_MaskedStore(m_VPValue(Addr), m_VPValue(StoredVal),
170 m_RemoveMask(HeaderMask, Mask))))
171 return new VPWidenStoreEVLRecipe(cast<VPWidenStoreRecipe>(CurRecipe), Addr,
172 StoredVal, EVL, Mask);
173
174 if (match(&CurRecipe,
175 m_MaskedStore(m_VPValue(EndPtr), m_VPValue(StoredVal),
176 m_Reverse(m_RemoveMask(HeaderMask, Mask)))) &&
177 match(EndPtr, m_VecEndPtr(m_VPValue(), m_Specific(&Plan->getVF())))) {
178 Mask = GetVPReverse(Mask);
179 Addr = AdjustEndPtr(EndPtr);
180 VPValue *Poison = Plan->getPoison(StoredVal->getScalarType());
181 auto *SpliceR = new VPWidenIntrinsicRecipe(
182 Intrinsic::vector_splice_right, {StoredVal, Poison, &EVL},
183 StoredVal->getScalarType(), {}, {}, DL);
184 SpliceR->insertBefore(&CurRecipe);
185 return new VPWidenStoreEVLRecipe(cast<VPWidenStoreRecipe>(CurRecipe), Addr,
186 SpliceR, EVL, Mask);
187 }
188
191 m_RemoveMask(HeaderMask, Mask),
192 m_TruncOrSelf(m_Specific(&Plan->getVF()))))) {
193 auto *NewStore = cast<VPWidenMemIntrinsicRecipe>(&CurRecipe)->clone();
194 NewStore->setOperand(3, Mask ? Mask : Plan->getTrue());
195 NewStore->setOperand(4, &EVL);
196 return NewStore;
197 }
198
199 if (auto *Rdx = dyn_cast<VPReductionRecipe>(&CurRecipe))
200 if (Rdx->isConditional() &&
201 match(Rdx->getCondOp(), m_RemoveMask(HeaderMask, Mask)))
202 return new VPReductionEVLRecipe(*Rdx, EVL, Mask);
203
204 if (auto *Interleave = dyn_cast<VPInterleaveRecipe>(&CurRecipe))
205 if (Interleave->getMask() &&
206 match(Interleave->getMask(), m_RemoveMask(HeaderMask, Mask)))
207 return new VPInterleaveEVLRecipe(*Interleave, EVL, Mask);
208
209 VPValue *LHS, *RHS;
210 if (match(&CurRecipe, m_SelectLike(m_RemoveMask(HeaderMask, Mask),
212 return new VPWidenIntrinsicRecipe(
213 Intrinsic::vp_merge, {Mask ? Mask : Plan->getTrue(), LHS, RHS, &EVL},
214 LHS->getScalarType(), {}, {}, DL);
215
216 if (match(&CurRecipe, m_LastActiveLane(m_Specific(HeaderMask)))) {
217 Type *Ty = CurRecipe.getVPSingleValue()->getScalarType();
218 VPValue *ZExt = VPBuilder(&CurRecipe).createScalarZExtOrTrunc(&EVL, Ty, DL);
219 return new VPInstruction(
220 Instruction::Sub, {ZExt, Plan->getConstantInt(Ty, 1)},
221 VPIRFlags::getDefaultFlags(Instruction::Sub), {}, DL);
222 }
223
224 // lhs | (headermask && rhs) -> vp.merge rhs, true, lhs, evl
225 if (match(&CurRecipe,
227 m_LogicalAnd(m_Specific(HeaderMask), m_VPValue(RHS)))))
228 return new VPWidenIntrinsicRecipe(Intrinsic::vp_merge,
229 {RHS, Plan->getTrue(), LHS, &EVL},
230 LHS->getScalarType(), {}, {}, DL);
231
232 if (auto *IntrR = dyn_cast<VPWidenIntrinsicRecipe>(&CurRecipe))
233 if (auto VPID = getVPDivRemIntrinsic(IntrR->getVectorIntrinsicID()))
234 if (match(IntrR->getOperand(2), m_RemoveMask(HeaderMask, Mask)))
235 return new VPWidenIntrinsicRecipe(*VPID,
236 {IntrR->getOperand(0),
237 IntrR->getOperand(1),
238 Mask ? Mask : Plan->getTrue(), &EVL},
239 IntrR->getScalarType(), {}, {}, DL);
240
241 return nullptr;
242}
243
244// Decompose the expression recipe and transform each contained recipe into
245// an EVL recipe.
246static bool
248 VPValue &EVL,
249 SmallVector<VPRecipeBase *> &OldRecipes) {
250
251 auto *Expr = dyn_cast<VPExpressionRecipe>(&CurRecipe);
252 if (!Expr)
253 return false;
254
255 // Decompose first and construct with EVL recipes later.
256 SmallVector<VPSingleDefRecipe *> ExpressionRecipes(Expr->decompose());
257 SmallSetVector<VPSingleDefRecipe *, 4> UniqueExpressionRecipes(
258 from_range, ExpressionRecipes);
259
260 // Convert recipes to EVL recipes.
261 for (auto *R : UniqueExpressionRecipes)
262 if (auto *EVLR = cast_if_present<VPSingleDefRecipe>(
263 optimizeMaskToEVL(HeaderMask, *R, EVL))) {
264 EVLR->insertBefore(R);
265 R->replaceAllUsesWith(EVLR);
266 OldRecipes.push_back(R);
267 replace(ExpressionRecipes, R, EVLR);
268 }
269
270 auto *NewExpr =
271 new VPExpressionRecipe(Expr->getExpressionType(), ExpressionRecipes);
272 ExpressionRecipes.back()->replaceAllUsesWith(NewExpr);
273 NewExpr->insertBefore(Expr);
274 OldRecipes.push_back(Expr);
275 return true;
276}
277
278/// Optimize away any EVL-based header masks to VP intrinsic based recipes.
279/// The transforms here need to preserve the original semantics.
281 // Find the EVL-based header mask if it exists: icmp ult step-vector, EVL
282 VPValue *HeaderMask = nullptr, *EVL = nullptr;
285 m_VPValue(EVL))) &&
286 match(EVL, m_EVL(m_VPValue()))) {
287 HeaderMask = R.getVPSingleValue();
288 break;
289 }
290 }
291 if (!HeaderMask)
292 return;
293
295 for (VPUser *U : vputils::collectUsersRecursively(HeaderMask)) {
297 // Transform recipes contained by an expression recipe into EVL recipes.
298 if (optimizeExpressionRecipeToEVL(HeaderMask, *R, *EVL, OldRecipes))
299 continue;
300 if (auto *NewR = optimizeMaskToEVL(HeaderMask, *R, *EVL)) {
301 NewR->insertBefore(R);
302 for (auto [Old, New] :
303 zip_equal(R->definedValues(), NewR->definedValues()))
304 Old->replaceAllUsesWith(New);
305 OldRecipes.push_back(R);
306 }
307 }
308
309 // Replace remaining (HeaderMask && Mask) with vp.merge (True, Mask,
310 // False, EVL)
311 for (VPUser *U : vputils::collectUsersRecursively(HeaderMask)) {
312 VPValue *Mask;
313 if (match(U, m_LogicalAnd(m_Specific(HeaderMask), m_VPValue(Mask)))) {
314 auto *LogicalAnd = cast<VPInstruction>(U);
315 auto *Merge = new VPWidenIntrinsicRecipe(
316 Intrinsic::vp_merge, {Plan.getTrue(), Mask, Plan.getFalse(), EVL},
317 Mask->getScalarType(), {}, {}, LogicalAnd->getDebugLoc());
318 Merge->insertBefore(LogicalAnd);
319 LogicalAnd->replaceAllUsesWith(Merge);
320 OldRecipes.push_back(LogicalAnd);
321 }
322 }
323
324 // Pull out left splices from any elementwise op.
325 // binop(splice.left(poison, x, evl), live-in)
326 // -> splice.left(poison, binop(x,live-in), evl)
328 Plan,
329 [&EVL](VPValue *&X) {
331 m_Poison(), m_VPValue(X), m_Specific(EVL));
332 },
333 [&Plan, &EVL](auto *X) {
334 return new VPWidenIntrinsicRecipe(
335 Intrinsic::vector_splice_left,
336 {Plan.getPoison(X->getScalarType()), X, EVL}, X->getScalarType(),
337 {}, {}, X->getDebugLoc());
338 });
339
340 // Fold the following splice patterns:
341 // splice.right(splice.left(poison, x, evl), poison, evl) -> x
342 // vector.reverse(splice.left(poison, x, evl)) -> vp.reverse(x, true, evl)
343 // splice.right(vector.reverse(x), poison, evl) -> vp.reverse(x, true, evl)
345 auto *R = cast<VPRecipeBase>(U);
346 // Remove potentially dead left splices from the transform above.
348 R->getVPSingleValue()->getNumUsers() == 0) {
349 OldRecipes.push_back(R);
350 continue;
351 }
352
353 VPValue *X;
356 m_Poison(), m_VPValue(X), m_Specific(EVL)),
357 m_Poison(), m_Specific(EVL)))) {
358 R->getVPSingleValue()->replaceAllUsesWith(X);
359 OldRecipes.push_back(R);
360 continue;
361 }
362
363 if (!match(U,
366 m_Poison(), m_VPValue(X), m_Specific(EVL))),
369 continue;
370
371 auto *VPReverse = new VPWidenIntrinsicRecipe(
372 Intrinsic::experimental_vp_reverse, {X, Plan.getTrue(), EVL},
373 X->getScalarType(), {}, {}, R->getDebugLoc());
374 VPReverse->insertBefore(R);
375 R->getVPSingleValue()->replaceAllUsesWith(VPReverse);
376 OldRecipes.push_back(R);
377 }
378
379 for (VPRecipeBase *R : reverse(OldRecipes)) {
380 SmallVector<VPValue *> PossiblyDead(R->operands());
381 R->eraseFromParent();
382 for (VPValue *Op : PossiblyDead)
384 }
385}
386
387/// After replacing the canonical IV with a EVL-based IV, fixup recipes that use
388/// VF to use the EVL instead to avoid incorrect updates on the penultimate
389/// iteration.
390static void fixupVFUsersForEVL(VPlan &Plan, VPValue &EVL) {
391 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
392 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
393
394 // EVL is i32 but VF/VFxUF are IdxTy. Convert as needed.
395 VPValue *EVLAsIdx =
399
400 assert(all_of(Plan.getVF().users(),
401 [&Plan](VPUser *U) {
402 auto IsAllowedUser =
403 IsaPred<VPVectorEndPointerRecipe, VPScalarIVStepsRecipe,
404 VPWidenIntOrFpInductionRecipe,
405 VPWidenMemIntrinsicRecipe>;
406 if (match(U, m_Trunc(m_Specific(&Plan.getVF()))))
407 return all_of(cast<VPSingleDefRecipe>(U)->users(),
408 IsAllowedUser);
409 return IsAllowedUser(U);
410 }) &&
411 "User of VF that we can't transform to EVL.");
412 Plan.getVF().replaceUsesWithIf(EVLAsIdx, [](VPUser &U, unsigned Idx) {
414 });
415
416 assert(all_of(Plan.getVFxUF().users(),
418 m_c_Add(m_Specific(LoopRegion->getCanonicalIV()),
419 m_Specific(&Plan.getVFxUF())),
421 "Only users of VFxUF should be VPWidenPointerInductionRecipe and the "
422 "increment of the canonical induction.");
423 Plan.getVFxUF().replaceUsesWithIf(EVLAsIdx, [](VPUser &U, unsigned Idx) {
424 // Only replace uses in VPWidenPointerInductionRecipe; The increment of the
425 // canonical induction must not be updated.
427 });
428
429 // Create a scalar phi to track the previous EVL if fixed-order recurrence is
430 // contained.
431 bool ContainsFORs =
433 if (ContainsFORs) {
434 // TODO: Use VPInstruction::ExplicitVectorLength to get maximum EVL.
435 VPValue *MaxEVL = &Plan.getVF();
436 // Emit VPScalarCastRecipe in preheader if VF is not a 32 bits integer.
437 VPBuilder Builder(LoopRegion->getPreheaderVPBB());
438 MaxEVL = Builder.createScalarZExtOrTrunc(
440
441 Builder.setInsertPoint(Header, Header->getFirstNonPhi());
442 VPValue *PrevEVL = Builder.createScalarPhi(
443 {MaxEVL, &EVL}, DebugLoc::getUnknown(), "prev.evl");
444
447 for (VPRecipeBase &R : *VPBB) {
448 VPValue *V1, *V2;
449 if (!match(&R,
451 m_VPValue(V1), m_VPValue(V2))))
452 continue;
453 VPValue *Imm = Plan.getOrAddLiveIn(
456 Intrinsic::experimental_vp_splice,
457 {V1, V2, Imm, Plan.getTrue(), PrevEVL, &EVL},
458 R.getVPSingleValue()->getScalarType(), {}, {}, R.getDebugLoc());
459 VPSplice->insertBefore(&R);
460 R.getVPSingleValue()->replaceAllUsesWith(VPSplice);
461 }
462 }
463 }
464
465 VPValue *HeaderMask = LoopRegion->getHeaderMask();
466 if (!HeaderMask)
467 return;
468
469 // Ensure that any reduction that uses a select to mask off tail lanes does so
470 // in the vector loop, not the middle block, since EVL tail folding can have
471 // tail elements in the penultimate iteration.
472 assert(all_of(*Plan.getMiddleBlock(), [&Plan, HeaderMask](VPRecipeBase &R) {
473 if (match(&R, m_ComputeReductionResult(m_Select(m_Specific(HeaderMask),
474 m_VPValue(), m_VPValue()))))
475 return R.getOperand(0)->getDefiningRecipe()->getRegion() ==
476 Plan.getVectorLoopRegion();
477 return true;
478 }));
479
480 // Replace the abstract header mask with a mask equivalent to predicating by
481 // EVL: icmp ult step-vector, EVL
482 VPRecipeBase *EVLR = EVL.getDefiningRecipe();
483 VPBuilder Builder(EVLR->getParent(), std::next(EVLR->getIterator()));
484 Type *EVLType = EVL.getScalarType();
485 VPValue *EVLMask = Builder.createICmp(
487 Builder.createNaryOp(VPInstruction::StepVector, {}, EVLType), &EVL);
488 HeaderMask->replaceAllUsesWith(EVLMask);
489}
490
491/// Converts a tail folded vector loop region to step by
492/// VPInstruction::ExplicitVectorLength elements instead of VF elements each
493/// iteration.
494///
495/// - Add a VPCurrentIterationPHIRecipe and related recipes to \p Plan and
496/// replaces all uses of the canonical IV except for the canonical IV
497/// increment with a VPCurrentIterationPHIRecipe. The canonical IV is used
498/// only for loop iterations counting after this transformation.
499///
500/// - The header mask is replaced with a header mask based on the EVL.
501///
502/// - Plans with FORs have a new phi added to keep track of the EVL of the
503/// previous iteration, and VPFirstOrderRecurrencePHIRecipes are replaced with
504/// @llvm.vp.splice.
505///
506/// The function uses the following definitions:
507/// %StartV is the canonical induction start value.
508///
509/// The function adds the following recipes:
510///
511/// vector.ph:
512/// ...
513///
514/// vector.body:
515/// ...
516/// %CurrentIter = CURRENT-ITERATION-PHI [ %StartV, %vector.ph ],
517/// [ %NextIter, %vector.body ]
518/// %AVL = phi [ trip-count, %vector.ph ], [ %NextAVL, %vector.body ]
519/// %VPEVL = EXPLICIT-VECTOR-LENGTH %AVL
520/// ...
521/// %OpEVL = cast i32 %VPEVL to IVSize
522/// %NextIter = add IVSize %OpEVL, %CurrentIter
523/// %NextAVL = sub IVSize nuw %AVL, %OpEVL
524/// ...
525///
526/// If MaxSafeElements is provided, the function adds the following recipes:
527/// vector.ph:
528/// ...
529///
530/// vector.body:
531/// ...
532/// %CurrentIter = CURRENT-ITERATION-PHI [ %StartV, %vector.ph ],
533/// [ %NextIter, %vector.body ]
534/// %AVL = phi [ trip-count, %vector.ph ], [ %NextAVL, %vector.body ]
535/// %cmp = cmp ult %AVL, MaxSafeElements
536/// %SAFE_AVL = select %cmp, %AVL, MaxSafeElements
537/// %VPEVL = EXPLICIT-VECTOR-LENGTH %SAFE_AVL
538/// ...
539/// %OpEVL = cast i32 %VPEVL to IVSize
540/// %NextIter = add IVSize %OpEVL, %CurrentIter
541/// %NextAVL = sub IVSize nuw %AVL, %OpEVL
542/// ...
543///
545 VPlan &Plan, const std::optional<unsigned> &MaxSafeElements) {
546 if (Plan.hasScalarVFOnly())
547 return;
548 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
549 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
550
551 auto *CanonicalIV = LoopRegion->getCanonicalIV();
552 auto *CanIVTy = LoopRegion->getCanonicalIVType();
553 VPValue *StartV = Plan.getZero(CanIVTy);
554 auto *CanonicalIVIncrement = LoopRegion->getOrCreateCanonicalIVIncrement();
555
556 // Create the CurrentIteration recipe in the vector loop.
557 auto *CurrentIteration =
559 CurrentIteration->insertBefore(*Header, Header->begin());
560 VPBuilder Builder(Header, Header->getFirstNonPhi());
561 // Create the AVL (application vector length), starting from TC -> 0 in steps
562 // of EVL.
563 VPPhi *AVLPhi = Builder.createScalarPhi(
565 VPValue *AVL = AVLPhi;
566
567 if (MaxSafeElements) {
568 // Support for MaxSafeDist for correct loop emission.
569 VPValue *AVLSafe = Plan.getConstantInt(CanIVTy, *MaxSafeElements);
570 VPValue *Cmp = Builder.createICmp(ICmpInst::ICMP_ULT, AVL, AVLSafe);
571 AVL = Builder.createSelect(Cmp, AVL, AVLSafe, DebugLoc::getUnknown(),
572 "safe_avl");
573 }
574 auto *VPEVL = Builder.createNaryOp(VPInstruction::ExplicitVectorLength, AVL,
575 DebugLoc::getUnknown(), "evl");
576
577 Builder.setInsertPoint(CanonicalIVIncrement);
578 VPValue *OpVPEVL = VPEVL;
579
580 OpVPEVL = Builder.createScalarZExtOrTrunc(
581 OpVPEVL, CanIVTy, CanonicalIVIncrement->getDebugLoc());
582
583 auto *NextIter = Builder.createAdd(
584 OpVPEVL, CurrentIteration, CanonicalIVIncrement->getDebugLoc(),
585 "current.iteration.next", CanonicalIVIncrement->getNoWrapFlags());
586 CurrentIteration->addBackedgeValue(NextIter);
587
588 VPValue *NextAVL =
589 Builder.createSub(AVLPhi, OpVPEVL, DebugLoc::getCompilerGenerated(),
590 "avl.next", {/*NUW=*/true, /*NSW=*/false});
591 AVLPhi->addIncoming(NextAVL);
592
593 fixupVFUsersForEVL(Plan, *VPEVL);
594 removeDeadRecipes(Plan);
595
596 // Replace all uses of the canonical IV with VPCurrentIterationPHIRecipe
597 // except for the canonical IV increment.
598 CanonicalIV->replaceUsesWithIf(CurrentIteration,
599 [CanonicalIVIncrement](VPUser &U, unsigned) {
600 return &U != CanonicalIVIncrement;
601 });
602 // TODO: support unroll factor > 1.
603 Plan.setUF(1);
604}
605
607 // Find the vector loop entry by locating VPCurrentIterationPHIRecipe.
608 // There should be only one VPCurrentIteration in the entire plan.
609 VPCurrentIterationPHIRecipe *CurrentIteration = nullptr;
610
613 for (VPRecipeBase &R : VPBB->phis())
614 if (auto *PhiR = dyn_cast<VPCurrentIterationPHIRecipe>(&R)) {
615 assert(!CurrentIteration &&
616 "Found multiple CurrentIteration. Only one expected");
617 CurrentIteration = PhiR;
618 }
619
620 // Early return if it is not variable-length stepping.
621 if (!CurrentIteration)
622 return;
623
624 VPBasicBlock *HeaderVPBB = CurrentIteration->getParent();
625 VPValue *CurrentIterationIncr = CurrentIteration->getBackedgeValue();
626
627 // Convert CurrentIteration to concrete recipe.
628 auto *ScalarR =
629 VPBuilder(CurrentIteration)
631 {CurrentIteration->getStartValue(), CurrentIterationIncr},
632 CurrentIteration->getDebugLoc(), "current.iteration.iv");
633 CurrentIteration->replaceAllUsesWith(ScalarR);
634 CurrentIteration->eraseFromParent();
635
636 // Replace CanonicalIVInc with CurrentIteration increment if it exists.
637 auto *CanonicalIV = cast<VPPhi>(&*HeaderVPBB->begin());
638 if (auto *CanIVInc = findUserOf(
639 CanonicalIV, m_c_Add(m_VPValue(), m_Specific(&Plan.getVFxUF())))) {
640 cast<VPInstruction>(CanIVInc)->replaceAllUsesWith(CurrentIterationIncr);
641 CanIVInc->eraseFromParent();
642 }
643}
644
646 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
647 if (!LoopRegion)
648 return;
649 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
650 if (Header->empty())
651 return;
652 // The EVL IV is always at the beginning.
653 auto *EVLPhi = dyn_cast<VPCurrentIterationPHIRecipe>(&Header->front());
654 if (!EVLPhi)
655 return;
656
657 // Bail if not an EVL tail folded loop.
658 VPValue *AVL;
659 if (!match(EVLPhi->getBackedgeValue(),
661 return;
662
663 // The AVL may be capped to a safe distance.
664 VPValue *SafeAVL, *UnsafeAVL;
665 if (match(AVL,
667 m_VPValue(SafeAVL)),
668 m_Deferred(UnsafeAVL), m_Deferred(SafeAVL))))
669 AVL = UnsafeAVL;
670
671 VPValue *AVLNext;
672 [[maybe_unused]] bool FoundAVLNext =
674 m_Specific(Plan.getTripCount()), m_VPValue(AVLNext)));
675 assert(FoundAVLNext && "Didn't find AVL backedge?");
676
677 VPBasicBlock *Latch = LoopRegion->getExitingBasicBlock();
678 auto *LatchBr = cast<VPInstruction>(Latch->getTerminator());
679 if (match(LatchBr, m_BranchOnCond(m_True())))
680 return;
681
682 VPValue *CanIVInc;
683 [[maybe_unused]] bool FoundIncrement = match(
684 LatchBr,
686 m_Specific(&Plan.getVectorTripCount()))));
687 assert(FoundIncrement &&
688 match(CanIVInc, m_Add(m_Specific(LoopRegion->getCanonicalIV()),
689 m_Specific(&Plan.getVFxUF()))) &&
690 "Expected BranchOnCond with ICmp comparing CanIV + VFxUF with vector "
691 "trip count");
692
693 Type *AVLTy = AVLNext->getScalarType();
694 VPBuilder Builder(LatchBr);
695 LatchBr->setOperand(
696 0, Builder.createICmp(CmpInst::ICMP_EQ, AVLNext, Plan.getZero(AVLTy)));
697}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
This file provides a LoopVectorizationPlanner class.
R600 Clause Merge
This file implements a set that has insertion order iteration characteristics.
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 bool optimizeExpressionRecipeToEVL(VPValue *HeaderMask, VPRecipeBase &CurRecipe, VPValue &EVL, SmallVector< VPRecipeBase * > &OldRecipes)
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.
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,...
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
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:4400
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4435
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:663
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:405
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:387
VPlan-based builder utility analogous to IRBuilder.
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", std::optional< VPIRFlags > Flags=std::nullopt, Type *ResultTy=nullptr)
Create a phi with IncomingValues, using the default flags for the result type, unless Flags is set.
VPValue * createScalarZExtOrTrunc(VPValue *Op, Type *ResultTy, DebugLoc DL)
static VPBuilder getToInsertAfter(VPRecipeBase *R)
Create a VPBuilder to insert after R.
A recipe for generating the phi node tracking the current scalar iteration index.
Definition VPlan.h:4093
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:551
A recipe to combine multiple recipes into a single 'expression' recipe, which should be considered a ...
Definition VPlan.h:3558
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2498
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2487
static VPIRFlags getDefaultFlags(unsigned Opcode, Type *ResultTy=nullptr)
Returns default flags for Opcode and scalar ResultTy for opcodes that support it, asserts otherwise.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1235
A recipe for interleaved memory operations with vector-predication intrinsics.
Definition VPlan.h:3189
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1676
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:410
VPBasicBlock * getParent()
Definition VPlan.h:482
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:560
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:3359
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4625
const VPBlockBase * getEntry() const
Definition VPlan.h:4669
VPInstruction * getOrCreateCanonicalIVIncrement()
Get the canonical IV increment instruction if it exists.
Definition VPlan.cpp:898
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4753
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4745
VPBasicBlock * getPreheaderVPBB()
Returns the pre-header VPBasicBlock of the loop region.
Definition VPlan.h:4694
VPRegionValue * getHeaderMask() const
Return the header mask of the region, or null if not set.
Definition VPlan.h:4758
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:401
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:1495
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:1501
user_range users()
Definition VPlanValue.h:157
A recipe for widening vector intrinsics.
Definition VPlan.h:1941
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4812
const DataLayout & getDataLayout() const
Definition VPlan.h:5026
LLVMContext & getContext() const
Definition VPlan.h:5022
VPBasicBlock * getEntry()
Definition VPlan.h:4908
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4980
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:5117
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5020
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5145
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:5010
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:5094
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5120
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1080
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4950
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:5114
bool hasScalarVFOnly() const
Definition VPlan.h:5062
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:5013
void setUF(unsigned UF)
Definition VPlan.h:5077
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:5128
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:236
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.
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
Definition Casting.h:683
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
constexpr from_range_t from_range
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
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1910
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:3869
A recipe for widening store operations with vector-predication intrinsics, using the value to store,...
Definition VPlan.h:3972
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...