LLVM 24.0.0git
VPlanUtils.cpp
Go to the documentation of this file.
1//===- VPlanUtils.cpp - VPlan-related utilities ---------------------------===//
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#include "VPlanUtils.h"
11#include "VPlanAnalysis.h"
12#include "VPlanCFG.h"
13#include "VPlanDominatorTree.h"
14#include "VPlanPatternMatch.h"
15#include "llvm/ADT/SetVector.h"
16#include "llvm/ADT/TypeSwitch.h"
22#include "llvm/IR/Dominators.h"
24
25using namespace llvm;
26using namespace llvm::VPlanPatternMatch;
27using namespace llvm::SCEVPatternMatch;
28
30 return all_of(Def->users(),
31 [Def](const VPUser *U) { return U->usesFirstLaneOnly(Def); });
32}
33
35 return all_of(Def->users(),
36 [Def](const VPUser *U) { return U->usesFirstPartOnly(Def); });
37}
38
40 return all_of(Def->users(),
41 [Def](const VPUser *U) { return U->usesScalars(Def); });
42}
43
45 if (auto *E = dyn_cast<SCEVConstant>(Expr))
46 return Plan.getOrAddLiveIn(E->getValue());
47 // Skip SCEV expansion if Expr is a SCEVUnknown wrapping a non-instruction
48 // value. Otherwise the value may be defined in a loop and using it directly
49 // will break LCSSA form. The SCEV expansion takes care of preserving LCSSA
50 // form.
51 auto *U = dyn_cast<SCEVUnknown>(Expr);
52 if (U && !isa<Instruction>(U->getValue()))
53 return Plan.getOrAddLiveIn(U->getValue());
54 auto *Expanded = new VPExpandSCEVRecipe(Expr);
55 VPBasicBlock *EntryVPBB = Plan.getEntry();
56 auto Iter = EntryVPBB->getFirstNonPhi();
57 while (Iter != EntryVPBB->end() && isa<VPIRInstruction>(*Iter))
58 ++Iter;
59 EntryVPBB->insert(Expanded, Iter);
60 return Expanded;
61}
62
63/// Returns true if \p V being poison is guaranteed to trigger UB because it
64/// propagates to the address of a memory recipe.
65static bool poisonGuaranteesUB(const VPValue *V) {
68
69 auto PropagatesPoisonFromRecipeOp = [](const VPRecipeBase *R) {
71 return false;
72 unsigned Opcode = vputils::getOpcode(R->getVPSingleValue());
73 return Instruction::isCast(Opcode) || Opcode == Instruction::GetElementPtr;
74 };
75
76 Worklist.push_back(V);
77
78 while (!Worklist.empty()) {
79 const VPValue *Current = Worklist.pop_back_val();
80 if (!Visited.insert(Current).second)
81 continue;
82
83 for (VPUser *U : Current->users()) {
84 // Check if Current is used as an address operand for load/store.
85 auto *R = cast<VPRecipeBase>(U);
86 if (auto *MemR = dyn_cast<VPWidenMemoryRecipe>(R)) {
87 if (MemR->getAddr() == Current)
88 return true;
89 continue;
90 }
91 if (auto *Rep = dyn_cast<VPReplicateRecipe>(U)) {
92 unsigned Opcode = Rep->getOpcode();
93 if ((Opcode == Instruction::Load && Rep->getOperand(0) == Current) ||
94 (Opcode == Instruction::Store && Rep->getOperand(1) == Current))
95 return true;
96 }
97
98 // Check if poison propagates through this recipe to any of its users.
99 for (const VPValue *Op : R->operands()) {
100 if (Op == Current && PropagatesPoisonFromRecipeOp(R)) {
101 Worklist.push_back(R->getVPSingleValue());
102 break;
103 }
104 }
105 }
106 }
107
108 return false;
109}
110
112 // Like IR stripPointerCasts, look through GEPs with all-zero indices and
113 // casts to find a root GEP VPInstruction.
114 while (auto *PtrVPI = dyn_cast<VPInstruction>(Ptr)) {
115 unsigned Opcode = PtrVPI->getOpcode();
116 if (Opcode == Instruction::GetElementPtr) {
117 if (!all_of(drop_begin(PtrVPI->operands()), match_fn(m_ZeroInt())))
118 return PtrVPI->getGEPNoWrapFlags();
119 Ptr = PtrVPI->getOperand(0);
120 continue;
121 }
122 if (Opcode != Instruction::BitCast && Opcode != Instruction::AddrSpaceCast)
123 break;
124 Ptr = PtrVPI->getOperand(0);
125 }
126 return GEPNoWrapFlags::none();
127}
128
131 const Loop *L) {
132 ScalarEvolution &SE = *PSE.getSE();
133 if (auto *RV = dyn_cast<VPRegionValue>(V)) {
134 assert(RV == RV->getDefiningRegion()->getCanonicalIV() &&
135 "RegionValue must be canonical IV");
136 if (!L)
137 return SE.getCouldNotCompute();
138 return SE.getAddRecExpr(SE.getZero(RV->getType()), SE.getOne(RV->getType()),
140 }
141
143 Value *LiveIn = V->getUnderlyingValue();
144 if (LiveIn && SE.isSCEVable(LiveIn->getType()))
145 return SE.getSCEV(LiveIn);
146 return SE.getCouldNotCompute();
147 }
148
149 // Helper to create SCEVs for binary and unary operations.
150 auto CreateSCEV = [&](ArrayRef<VPValue *> Ops,
151 function_ref<const SCEV *(ArrayRef<SCEVUse>)> CreateFn)
152 -> const SCEV * {
154 for (VPValue *Op : Ops) {
155 const SCEV *S = getSCEVExprForVPValue(Op, PSE, L);
157 return SE.getCouldNotCompute();
158 SCEVOps.push_back(S);
159 }
160 return PSE.getPredicatedSCEV(CreateFn(SCEVOps));
161 };
162
163 VPValue *LHSVal, *RHSVal;
164 if (match(V, m_Add(m_VPValue(LHSVal), m_VPValue(RHSVal))))
165 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
166 return SE.getAddExpr(Ops[0], Ops[1], SCEV::FlagAnyWrap, 0);
167 });
168 if (match(V, m_BinaryOr(m_VPValue(LHSVal), m_VPValue(RHSVal))))
169 if (cast<VPRecipeWithIRFlags>(V->getDefiningRecipe())->isDisjoint())
170 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
171 return SE.getAddExpr(Ops[0], Ops[1], SCEV::FlagAnyWrap, 0);
172 });
173 if (match(V, m_Sub(m_VPValue(LHSVal), m_VPValue(RHSVal))))
174 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
175 return SE.getMinusSCEV(Ops[0], Ops[1], SCEV::FlagAnyWrap, 0);
176 });
177 if (match(V, m_Not(m_VPValue(LHSVal)))) {
178 // not X = xor X, -1 = -1 - X
179 return CreateSCEV({LHSVal}, [&](ArrayRef<SCEVUse> Ops) {
180 return SE.getMinusSCEV(SE.getMinusOne(Ops[0]->getType()), Ops[0]);
181 });
182 }
183 if (match(V, m_Mul(m_VPValue(LHSVal), m_VPValue(RHSVal))))
184 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
185 return SE.getMulExpr(Ops[0], Ops[1], SCEV::FlagAnyWrap, 0);
186 });
187 // Handle shl by constant: x << c is equivalent to x * (1 << c). A shift
188 // amount >= the bit width produces poison; do not rewrite it, as
189 // getPowerOfTwo requires the power to be in range.
190 uint64_t ShiftAmt;
191 if (match(V, m_Shl(m_VPValue(LHSVal), m_ConstantInt(ShiftAmt))) &&
192 ShiftAmt < LHSVal->getScalarType()->getScalarSizeInBits())
193 return CreateSCEV(LHSVal, [&](ArrayRef<SCEVUse> Ops) {
194 return SE.getMulExpr(Ops[0],
195 SE.getPowerOfTwo(Ops[0]->getType(), ShiftAmt));
196 });
197 if (match(V, m_LShr(m_VPValue(LHSVal), m_ConstantInt(ShiftAmt)))) {
198 Type *Ty = V->getScalarType();
199 if (ShiftAmt < SE.getTypeSizeInBits(Ty))
200 return CreateSCEV(LHSVal, [&](ArrayRef<SCEVUse> Ops) {
201 return SE.getUDivExpr(Ops[0], SE.getPowerOfTwo(Ty, ShiftAmt));
202 });
203 }
204 if (match(V, m_UDiv(m_VPValue(LHSVal), m_VPValue(RHSVal))))
205 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
206 return SE.getUDivExpr(Ops[0], Ops[1]);
207 });
208 if (match(V, m_URem(m_VPValue(LHSVal), m_VPValue(RHSVal))))
209 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
210 return SE.getURemExpr(Ops[0], Ops[1]);
211 });
212 // A SRem with non-negative operands is equivalent to an URem.
213 if (match(V, m_SRem(m_VPValue(LHSVal), m_VPValue(RHSVal)))) {
214 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
215 if (!SE.isKnownNonNegative(Ops[0]) || !SE.isKnownNonNegative(Ops[1]))
216 return SE.getCouldNotCompute();
217 return SE.getURemExpr(Ops[0], Ops[1]);
218 });
219 }
220 // Handle AND with constant mask: x & (2^n - 1) can be represented as x % 2^n.
221 const APInt *Mask;
222 if (match(V, m_c_BinaryAnd(m_VPValue(LHSVal), m_APInt(Mask))) &&
223 (*Mask + 1).isPowerOf2())
224 return CreateSCEV({LHSVal}, [&](ArrayRef<SCEVUse> Ops) {
225 return SE.getURemExpr(Ops[0], SE.getConstant(*Mask + 1));
226 });
227 if (match(V, m_Trunc(m_VPValue(LHSVal)))) {
228 Type *DestTy = V->getScalarType();
229 return CreateSCEV({LHSVal}, [&](ArrayRef<SCEVUse> Ops) {
230 return SE.getTruncateExpr(Ops[0], DestTy);
231 });
232 }
233 if (match(V, m_ZExt(m_VPValue(LHSVal)))) {
234 Type *DestTy = V->getScalarType();
235 return CreateSCEV({LHSVal}, [&](ArrayRef<SCEVUse> Ops) {
236 return SE.getZeroExtendExpr(Ops[0], DestTy);
237 });
238 }
239 if (match(V, m_SExt(m_VPValue(LHSVal)))) {
240 Type *DestTy = V->getScalarType();
241
242 // Mirror SCEV's createSCEV handling for sext(sub nsw): push sign extension
243 // onto the operands before computing the subtraction.
244 VPValue *SubLHS, *SubRHS;
245 auto *SubR = dyn_cast<VPRecipeWithIRFlags>(LHSVal);
246 if (match(LHSVal, m_Sub(m_VPValue(SubLHS), m_VPValue(SubRHS))) && SubR &&
247 SubR->hasNoSignedWrap() && poisonGuaranteesUB(LHSVal)) {
248 const SCEV *V1 = getSCEVExprForVPValue(SubLHS, PSE, L);
249 const SCEV *V2 = getSCEVExprForVPValue(SubRHS, PSE, L);
251 return SE.getMinusSCEV(SE.getSignExtendExpr(V1, DestTy),
252 SE.getSignExtendExpr(V2, DestTy), SCEV::FlagNSW);
253 }
254
255 return CreateSCEV({LHSVal}, [&](ArrayRef<SCEVUse> Ops) {
256 return SE.getSignExtendExpr(Ops[0], DestTy);
257 });
258 }
259 if (match(V,
261 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
262 return SE.getUMaxExpr(Ops[0], Ops[1]);
263 });
264 if (match(V,
266 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
267 return SE.getSMaxExpr(Ops[0], Ops[1]);
268 });
269 if (match(V,
271 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
272 return SE.getUMinExpr(Ops[0], Ops[1]);
273 });
274 if (match(V,
276 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
277 return SE.getSMinExpr(Ops[0], Ops[1]);
278 });
280 return CreateSCEV({LHSVal}, [&](ArrayRef<SCEVUse> Ops) {
281 // is_int_min_poison is local to this intrinsic: poison on INT_MIN is
282 // not proof that the input is never INT_MIN, nor that poison reaches
283 // UB. Do not translate it to SCEV's global IsNSW flag.
284 return SE.getAbsExpr(Ops[0], /*IsNSW=*/false);
285 });
286
288 Type *SourceElementType;
289 if (match(V, m_GetElementPtr(SourceElementType, Ops))) {
290 return CreateSCEV(Ops, [&](ArrayRef<SCEVUse> Ops) {
291 return SE.getGEPExpr(Ops.front(), Ops.drop_front(), SourceElementType);
292 });
293 }
294
295 // TODO: Support constructing SCEVs for more recipes as needed.
296 const VPRecipeBase *DefR = V->getDefiningRecipe();
297 const SCEV *Expr =
299 .Case([](const VPExpandSCEVRecipe *R) { return R->getSCEV(); })
300 .Case([&SE, &PSE, L](const VPWidenIntOrFpInductionRecipe *R) {
301 const SCEV *Step = getSCEVExprForVPValue(R->getStepValue(), PSE, L);
302 if (!L || isa<SCEVCouldNotCompute>(Step))
303 return SE.getCouldNotCompute();
304 const SCEV *Start =
305 getSCEVExprForVPValue(R->getStartValue(), PSE, L);
306 const SCEV *AddRec =
307 SE.getAddRecExpr(Start, Step, L, SCEV::FlagAnyWrap);
308 if (R->getTruncInst())
309 return SE.getTruncateExpr(AddRec, R->getScalarType());
310 return AddRec;
311 })
312 .Case([&SE, &PSE, L](const VPWidenPointerInductionRecipe *R) {
313 const SCEV *Start =
314 getSCEVExprForVPValue(R->getStartValue(), PSE, L);
315 if (!L || isa<SCEVCouldNotCompute>(Start))
316 return SE.getCouldNotCompute();
317 const SCEV *Step = getSCEVExprForVPValue(R->getStepValue(), PSE, L);
318 if (isa<SCEVCouldNotCompute>(Step))
319 return SE.getCouldNotCompute();
320 return SE.getAddRecExpr(Start, Step, L, SCEV::FlagAnyWrap);
321 })
322 .Case([&SE, &PSE, L](const VPDerivedIVRecipe *R) {
323 const SCEV *Start = getSCEVExprForVPValue(R->getOperand(0), PSE, L);
324 const SCEV *IV = getSCEVExprForVPValue(R->getOperand(1), PSE, L);
325 const SCEV *Scale = getSCEVExprForVPValue(R->getOperand(2), PSE, L);
326 if (any_of(ArrayRef({Start, IV, Scale}),
328 return SE.getCouldNotCompute();
329
330 return SE.getAddExpr(
331 SE.getTruncateOrSignExtend(Start, IV->getType()),
332 SE.getMulExpr(
333 IV, SE.getTruncateOrSignExtend(Scale, IV->getType())));
334 })
335 .Case([&SE, &PSE, L](const VPScalarIVStepsRecipe *R) {
336 const SCEV *IV = getSCEVExprForVPValue(R->getOperand(0), PSE, L);
337 const SCEV *Step = getSCEVExprForVPValue(R->getOperand(1), PSE, L);
339 return SE.getCouldNotCompute();
340 return SE.getTruncateOrSignExtend(IV, Step->getType());
341 })
342 .Default(
343 [&SE](const VPRecipeBase *) { return SE.getCouldNotCompute(); });
344
345 return PSE.getPredicatedSCEV(Expr);
346}
347
349 const Loop *L) {
350 // If address is an SCEVAddExpr, we require that all operands must be either
351 // be invariant or a (possibly sign-extend) affine AddRec.
352 if (auto *PtrAdd = dyn_cast<SCEVAddExpr>(Addr)) {
353 return all_of(PtrAdd->operands(), [&SE, L](const SCEV *Op) {
354 return SE.isLoopInvariant(Op, L) ||
355 match(Op, m_scev_SExt(m_scev_AffineAddRec(m_SCEV(), m_SCEV()))) ||
356 match(Op, m_scev_AffineAddRec(m_SCEV(), m_SCEV()));
357 });
358 }
359
360 // Otherwise, check if address is loop invariant or an affine add recurrence.
361 return SE.isLoopInvariant(Addr, L) ||
363}
364
365unsigned vputils::getOpcode(const VPValue *V) {
369 [](auto *I) { return I->getOpcode(); })
370 .Case<VPVectorPointerRecipe, VPPredInstPHIRecipe, VPScalarIVStepsRecipe>(
371 [](auto *I) {
372 // For recipes that do not directly map to LLVM IR instructions,
373 // assign opcodes after the last VPInstruction opcode (which is also
374 // after the last IR Instruction opcode), based on the VPRecipeID.
375 return VPInstruction::OpsEnd + 1 + I->getVPRecipeID();
376 })
377 .Default([](auto *) { return 0; });
378}
379
380std::optional<std::pair<bool, unsigned>>
383 return std::make_pair(true, IID);
384 if (unsigned Opcode = vputils::getOpcode(V))
385 return std::make_pair(false, Opcode);
386 return {};
387}
388
389/// Returns true if \p Opcode preserves uniformity, i.e., if all operands are
390/// uniform, the result will also be uniform.
391static bool preservesUniformity(unsigned Opcode) {
392 if (Instruction::isBinaryOp(Opcode) || Instruction::isCast(Opcode))
393 return true;
394 switch (Opcode) {
395 case Instruction::Freeze:
396 case Instruction::GetElementPtr:
397 case Instruction::ICmp:
398 case Instruction::FCmp:
399 case Instruction::Select:
404 return true;
405 default:
406 return false;
407 }
408}
409
411 // TODO: Handle more opcodes and recipes.
413 return false;
414 unsigned Opcode = getOpcode(V);
415 return Instruction::isUnaryOp(Opcode) || Instruction::isBinaryOp(Opcode);
416}
417
419 // Live-in, symbolic and canonical-IV region values are single-scalar.
420 if (auto *RV = dyn_cast<VPRegionValue>(VPV))
421 return RV == RV->getDefiningRegion()->getCanonicalIV();
423 return true;
424
425 if (auto *Rep = dyn_cast<VPReplicateRecipe>(VPV)) {
426 const VPRegionBlock *RegionOfR = Rep->getRegion();
427 // Don't consider recipes in replicate regions as uniform yet; their first
428 // lane cannot be accessed when executing the replicate region for other
429 // lanes.
430 if (RegionOfR && RegionOfR->isReplicator())
431 return false;
432 return Rep->isSingleScalar() || (preservesUniformity(Rep->getOpcode()) &&
433 all_of(Rep->operands(), isSingleScalar));
434 }
437 if (auto *WidenR = dyn_cast<VPWidenRecipe>(VPV)) {
438 return preservesUniformity(WidenR->getOpcode()) &&
439 all_of(WidenR->operands(), isSingleScalar);
440 }
441 if (auto *VPI = dyn_cast<VPInstruction>(VPV))
442 return VPI->isSingleScalar() || VPI->isVectorToScalar() ||
443 (preservesUniformity(VPI->getOpcode()) &&
444 all_of(VPI->operands(), isSingleScalar));
445 if (auto *RR = dyn_cast<VPReductionRecipe>(VPV))
446 return !RR->isPartialReduction();
448 VPV))
449 return true;
450 if (auto *Expr = dyn_cast<VPExpressionRecipe>(VPV))
451 return Expr->isVectorToScalar();
452
453 // VPExpandSCEVRecipes must be placed in the entry and are always uniform.
454 return isa<VPExpandSCEVRecipe>(VPV);
455}
456
458 // Live-ins, symbolic and canonical-IV region values are uniform.
459 if (auto *RV = dyn_cast<VPRegionValue>(V))
460 return RV == RV->getDefiningRegion()->getCanonicalIV();
462 return true;
463
464 const VPRecipeBase *R = V->getDefiningRecipe();
465 const VPBasicBlock *VPBB = R ? R->getParent() : nullptr;
466 const VPlan *Plan = VPBB ? VPBB->getPlan() : nullptr;
467 if (VPBB &&
468 (VPBB == Plan->getVectorPreheader() || VPBB == Plan->getEntry())) {
469 if (match(R,
472 return false;
473 return all_of(R->operands(), isUniformAcrossVFsAndUFs);
474 }
475
477 .Case([](const VPDerivedIVRecipe *R) { return true; })
478 .Case([](const VPReplicateRecipe *R) {
479 // Be conservative about side-effects, except for the
480 // known-side-effecting assumes and stores, which we know will be
481 // uniform.
482 return R->isSingleScalar() &&
483 (!R->mayHaveSideEffects() ||
484 isa<AssumeInst, StoreInst>(R->getUnderlyingInstr())) &&
485 all_of(R->operands(), isUniformAcrossVFsAndUFs);
486 })
487 .Case([](const VPWidenRecipe *R) {
488 return preservesUniformity(R->getOpcode()) &&
489 all_of(R->operands(), isUniformAcrossVFsAndUFs);
490 })
491 .Case([](const VPPhi *) {
492 // Bail out on VPPhi, as we can end up in infinite cycles.
493 return false;
494 })
495 .Case([](const VPInstruction *VPI) {
496 return (VPI->isSingleScalar() || VPI->isVectorToScalar() ||
499 })
500 .Case([](const VPWidenCastRecipe *R) {
501 // A cast is uniform according to its operand.
502 return isUniformAcrossVFsAndUFs(R->getOperand(0));
503 })
504 .Default([](const VPRecipeBase *) { // A value is considered non-uniform
505 // unless proven otherwise.
506 return false;
507 });
508}
509
511 if (auto *RepR = dyn_cast<VPReplicateRecipe>(R))
512 return RepR->doesGeneratePerAllLanes();
513 if (auto *VPI = dyn_cast<VPInstruction>(R))
514 return VPI->doesGeneratePerAllLanes();
515 if (auto *SIVSteps = dyn_cast<VPScalarIVStepsRecipe>(R))
516 return SIVSteps->doesGeneratePerAllLanes();
517 return false;
518}
519
521 auto DepthFirst = vp_depth_first_shallow(Plan.getEntry());
522 auto I = find_if(DepthFirst, [&VPDT](VPBlockBase *VPB) {
523 return VPBlockUtils::isHeader(VPB, VPDT);
524 });
525 return I == DepthFirst.end() ? nullptr : cast<VPBasicBlock>(*I);
526}
527
529 if (!R)
530 return 1;
531 if (auto *RR = dyn_cast<VPReductionPHIRecipe>(R))
532 return RR->getVFScaleFactor();
533 if (auto *RR = dyn_cast<VPReductionRecipe>(R))
534 return RR->getVFScaleFactor();
535 if (auto *ER = dyn_cast<VPExpressionRecipe>(R))
536 return ER->getVFScaleFactor();
537 assert(
540 "getting scaling factor of reduction-start-vector not implemented yet");
541 return 1;
542}
543
544bool vputils::cannotHoistOrSinkRecipe(const VPRecipeBase &R, bool Sinking) {
545 // Assumes don't alias anything or throw; as long as they're guaranteed to
546 // execute, they're safe to hoist. They should however not be sunk, as it
547 // would destroy information.
549 return Sinking;
550 if (R.mayHaveSideEffects() || R.mayReadFromMemory() || R.isPhi())
551 return true;
552 // Allocas cannot be hoisted.
553 auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
554 return RepR && RepR->getOpcode() == Instruction::Alloca;
555}
556
559 VPBasicBlock *LastBB) {
560 assert(FirstBB->getParent() == LastBB->getParent() &&
561 "FirstBB and LastBB from different regions");
562#ifndef NDEBUG
563 bool InSingleSuccChain = false;
564 for (VPBlockBase *Succ = FirstBB; Succ; Succ = Succ->getSingleSuccessor())
565 InSingleSuccChain |= (Succ == LastBB);
566 assert(InSingleSuccChain &&
567 "LastBB unreachable from FirstBB in single-successor chain");
568#endif
569 auto Blocks = to_vector(
571 auto *LastIt = find(Blocks, LastBB);
572 assert(LastIt != Blocks.end() &&
573 "LastBB unreachable from FirstBB in depth-first traversal");
574 Blocks.erase(std::next(LastIt), Blocks.end());
575 return Blocks;
576}
577
579 for (VPRecipeBase &R : *Plan.getVectorPreheader())
581 return cast<VPInstruction>(&R);
582 return nullptr;
583}
584
586vputils::getEarlyExits(const VPlan &Plan, const VPBlockBase *MiddleVPBB) {
588 for (VPIRBasicBlock *ExitVPBB : Plan.getExitBlocks())
589 for (VPBlockBase *Pred : ExitVPBB->getPredecessors())
590 if (Pred != MiddleVPBB)
591 Exits.emplace_back(cast<VPBasicBlock>(Pred), ExitVPBB);
592 return Exits;
593}
594
597 Instruction::BinaryOps InductionOpcode, FPMathOperator *FPBinOp,
598 Instruction *TruncI, VPIRValue *StartV, VPValue *Step, DebugLoc DL,
599 VPBuilder &Builder, const VPIRFlags::WrapFlagsTy &Flags) {
600 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
601 VPBasicBlock *HeaderVPBB = LoopRegion->getEntryBasicBlock();
602 VPValue *CanonicalIV = LoopRegion->getCanonicalIV();
603 VPSingleDefRecipe *BaseIV =
604 Builder.createDerivedIV(Kind, FPBinOp, StartV, CanonicalIV, Step, Flags);
605
606 // Truncate base induction if needed.
607 Type *ResultTy = BaseIV->getScalarType();
608 if (TruncI) {
609 Type *TruncTy = TruncI->getType();
610 assert(ResultTy->getScalarSizeInBits() > TruncTy->getScalarSizeInBits() &&
611 "Not truncating.");
612 assert(ResultTy->isIntegerTy() && "Truncation requires an integer type");
613 BaseIV = Builder.createScalarCast(Instruction::Trunc, BaseIV, TruncTy, DL);
614 ResultTy = TruncTy;
615 }
616
617 // Truncate step if needed.
618 Type *StepTy = Step->getScalarType();
619 if (ResultTy != StepTy) {
620 assert(StepTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits() &&
621 "Not truncating.");
622 assert(StepTy->isIntegerTy() && "Truncation requires an integer type");
623 auto *VecPreheader =
625 VPBuilder::InsertPointGuard Guard(Builder);
626 Builder.setInsertPoint(VecPreheader);
627 Step = Builder.createScalarCast(Instruction::Trunc, Step, ResultTy, DL);
628 }
629 return Builder.createScalarIVSteps(InductionOpcode, FPBinOp, BaseIV, Step,
630 &Plan.getVF(), DL);
631}
632
633VPValue *
635 VPlan &Plan, VPBuilder &Builder) {
636 const InductionDescriptor &ID = PtrIV->getInductionDescriptor();
637 VPIRValue *StartV = Plan.getZero(ID.getStep()->getType());
638 VPValue *StepV = PtrIV->getOperand(1);
640 Plan, InductionDescriptor::IK_IntInduction, Instruction::Add, nullptr,
641 nullptr, StartV, StepV, PtrIV->getDebugLoc(), Builder);
642
643 return Builder.createPtrAdd(PtrIV->getStartValue(), Steps,
644 PtrIV->getDebugLoc(), "next.gep");
645}
646
648 const VPDominatorTree &VPDT) {
649 auto *VPBB = dyn_cast<VPBasicBlock>(VPB);
650 if (!VPBB)
651 return false;
652
653 // If VPBB is in a region R, VPBB is a loop header if R is a loop region with
654 // VPBB as its entry, i.e., free of predecessors.
655 if (auto *R = VPBB->getParent())
656 return !R->isReplicator() && !VPBB->hasPredecessors();
657
658 // A header dominates its second predecessor (the latch), with the other
659 // predecessor being the preheader
660 return VPB->getPredecessors().size() == 2 &&
661 VPDT.dominates(VPB, VPB->getPredecessors()[1]);
662}
663
665 const VPDominatorTree &VPDT) {
666 // A latch has a header as its last successor, with its other successors
667 // leaving the loop. A preheader OTOH has a header as its first (and only)
668 // successor.
669 return VPB->getNumSuccessors() >= 2 &&
671}
672
673std::pair<VPBasicBlock *, VPBasicBlock *>
676 Plan.getEntry()->getNumSuccessors() == 1
677 ? Plan.getEntry()->getSingleSuccessor()
678 : Plan.getEntry()->getSuccessors()[1]->getSingleSuccessor());
679 assert(Header->getNumPredecessors() == 2 &&
680 "Header must have exactly 2 predecessors");
681 auto *Latch = cast<VPBasicBlock>(Header->getPredecessors()[1]);
682 return {Header, Latch};
683}
684
688
689std::optional<MemoryLocation>
691 auto *M = dyn_cast<VPIRMetadata>(&R);
692 if (!M)
693 return std::nullopt;
695 // Populate noalias metadata from VPIRMetadata.
696 if (MDNode *NoAliasMD = M->getMetadata(LLVMContext::MD_noalias))
697 Loc.AATags.NoAlias = NoAliasMD;
698 if (MDNode *AliasScopeMD = M->getMetadata(LLVMContext::MD_alias_scope))
699 Loc.AATags.Scope = AliasScopeMD;
700 return Loc;
701}
702
704 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
705 VPRegionValue *CanIV = LoopRegion->getCanonicalIV();
706 assert(CanIV && "Expected loop region to have a canonical IV");
707
708 VPSymbolicValue &VFxUF = Plan.getVFxUF();
709
710 // Check if \p Step matches the expected increment step, accounting for
711 // materialization of VFxUF and UF.
712 auto IsIncrementStep = [&](VPValue *Step) -> bool {
713 if (!VFxUF.isMaterialized())
714 return Step == &VFxUF;
715
716 VPSymbolicValue &UF = Plan.getUF();
717 if (!UF.isMaterialized())
718 return Step == &UF ||
719 match(Step, m_c_Mul(m_Specific(&Plan.getUF()), m_VScale()));
720
721 // Alias masking: step is number of active lanes of a dependence mask.
722 if (match(Step, m_ZExtOrTruncOrSelf(
724 return true;
725
726 unsigned ConcreteUF = Plan.getConcreteUF();
727 // Fixed VF: step is just the concrete UF.
728 if (match(Step, m_SpecificInt(ConcreteUF)))
729 return true;
730
731 // Scalable VF: step involves VScale.
732 if (ConcreteUF == 1)
733 return match(Step, m_VScale());
734 if (match(Step, m_c_Mul(m_SpecificInt(ConcreteUF), m_VScale())))
735 return true;
736 // mul(VScale, ConcreteUF) may have been simplified to
737 // shl(VScale, log2(ConcreteUF)) when ConcreteUF is a power of 2.
738 return isPowerOf2_32(ConcreteUF) &&
739 match(Step, m_Shl(m_VScale(), m_SpecificInt(Log2_32(ConcreteUF))));
740 };
741
742 VPInstruction *Increment = nullptr;
743 for (VPUser *U : CanIV->users()) {
744 VPValue *Step;
745 if (isa<VPInstruction>(U) &&
746 match(U, m_c_Add(m_Specific(CanIV), m_VPValue(Step))) &&
747 IsIncrementStep(Step)) {
748 assert(!Increment && "There must be a unique increment");
750 }
751 }
752
753 assert((!VFxUF.isMaterialized() || Increment) &&
754 "After materializing VFxUF, an increment must exist");
755 assert((!Increment ||
756 LoopRegion->hasCanonicalIVNUW() == Increment->hasNoUnsignedWrap()) &&
757 "NUW flag in region and increment must match");
758 return Increment;
759}
760
761/// Find the ComputeReductionResult recipe for \p PhiR, looking through selects
762/// inserted for predicated reductions or tail folding.
764 VPValue *BackedgeVal = PhiR->getBackedgeValue();
765 if (auto *Res =
767 return Res;
768
769 // Look through selects inserted for tail folding or predicated reductions.
770 VPRecipeBase *SelR =
771 findUserOf(BackedgeVal, m_Select(m_VPValue(), m_VPValue(), m_VPValue()));
772 if (!SelR)
773 return nullptr;
776}
777
780 SmallVector<const VPValue *> WorkList = {V};
781
782 while (!WorkList.empty()) {
783 const VPValue *Cur = WorkList.pop_back_val();
784 if (!Seen.insert(Cur).second)
785 continue;
786
787 auto *Blend = dyn_cast<VPBlendRecipe>(Cur);
788 // Skip blends that use V only through a compare by checking if any incoming
789 // value was already visited.
790 if (Blend && none_of(seq<unsigned>(0, Blend->getNumIncomingValues()),
791 [&](unsigned I) {
792 return Seen.contains(Blend->getIncomingValue(I));
793 }))
794 continue;
795
796 for (VPUser *U : Cur->users()) {
797 if (auto *InterleaveR = dyn_cast<VPInterleaveBase>(U))
798 if (InterleaveR->getAddr() == Cur)
799 return true;
800 // Cur is used as the pointer of a (possibly masked) load (operand 0) or
801 // store (operand 1).
804 m_Specific(Cur)))))
805 return true;
807 if (MemR->getAddr() == Cur && MemR->isConsecutive())
808 return true;
809 }
810 }
811
812 // The legacy cost model only supports scalarization loads/stores with phi
813 // addresses, if the phi is directly used as load/store address. Don't
814 // traverse further for Blends.
815 if (Blend)
816 continue;
817
818 // Only traverse further through users that also define a value (and can
819 // thus have their own users walked). Skip when Cur is only used as mask ,
820 // as well as loads: a loaded value does not depend on the load's operand.
821 for (VPUser *U : Cur->users()) {
822 auto *VPI = dyn_cast<VPInstruction>(U);
823 if (VPI && VPI->getMask() == Cur &&
824 none_of(VPI->operandsWithoutMask(), equal_to(Cur)))
825 continue;
827 continue;
828 if (auto *SDR = dyn_cast<VPSingleDefRecipe>(U))
829 WorkList.push_back(SDR);
830 }
831 }
832 return false;
833}
834
835/// Try to find a loop-invariant IR value for \p S in the plan's entry block
836/// that can be reused. Returns the corresponding live-in VPValue, or nullptr
837/// if no reusable IR value is found.
838VPValue *VPSCEVExpander::tryToReuseIRValue(const SCEV *S) {
840 return nullptr;
841 VPlan &Plan = Builder.getPlan();
842 BasicBlock *PH = cast<VPIRBasicBlock>(Plan.getEntry())->getIRBasicBlock();
843 for (Value *V : SE.getSCEVValues(S)) {
844 // Only reuse instructions in the plan's entry block, or, when a
845 // DominatorTree is available, any instruction that dominates it.
846 // Instructions in sibling branches may not dominate the entry block.
847 auto *I = dyn_cast<Instruction>(V);
848 if (!I)
849 return Plan.getOrAddLiveIn(V);
850 if (!SE.DT.dominates(I->getParent(), PH))
851 continue;
852 SmallVector<Instruction *> DropPoisonGeneratingInsts;
853 if (!SE.canReuseInstruction(S, I, DropPoisonGeneratingInsts))
854 continue;
855 for (Instruction *DropI : DropPoisonGeneratingInsts)
857 return Plan.getOrAddLiveIn(V);
858 }
859 return nullptr;
860}
861
863 if (VPValue *V = tryToReuseIRValue(S))
864 return V;
865
866 switch (S->getSCEVType()) {
867 case scConstant:
868 return Builder.getPlan().getOrAddLiveIn(cast<SCEVConstant>(S)->getValue());
869 case scUnknown:
870 return Builder.getPlan().getOrAddLiveIn(cast<SCEVUnknown>(S)->getValue());
871 case scVScale:
872 return Builder.createVScale(S->getType(), DL);
873 case scAddExpr: {
874 auto *AddE = cast<SCEVAddExpr>(S);
875 VPIRFlags::WrapFlagsTy WrapFlags(AddE->hasNoUnsignedWrap(),
876 AddE->hasNoSignedWrap());
877
878 // Expand pointer SCEVAddExpr as a ptradd of the pointer base and the
879 // integer offset, matching SCEVExpander.
880 if (S->getType()->isPointerTy()) {
881 VPValue *Base = expand(SE.getPointerBase(S));
882 VPValue *Offset = expand(SE.removePointerBase(S));
883 GEPNoWrapFlags GEPFlags = WrapFlags.HasNUW
886 return Builder.createNoWrapPtrAdd(Base, Offset, GEPFlags, DL);
887 }
888
889 // Non-constant-negative add operands are expanded negated and subtracted
890 // from the running result below, instead of being negated and added.
891 auto UseSubtract = [](const SCEV *Op) {
892 return Op->isNonConstantNegative();
893 };
894 // Iterate in reverse so that constants are emitted last, and move the
895 // subtracted operands last, matching SCEVExpander's LoopCompare, so that
896 // they don't start the running result.
897 SmallVector<const SCEV *, 2> SCEVOps(reverse(AddE->operands()));
898 stable_sort(SCEVOps, [&](const SCEV *L, const SCEV *R) {
899 return !UseSubtract(L) && UseSubtract(R);
900 });
902 for (const SCEV *Op : SCEVOps) {
903 // The first operand starts the result, so it is never subtracted.
904 bool Negate = !Ops.empty() && UseSubtract(Op);
905 Ops.push_back(expand(Negate ? SE.getNegativeSCEV(Op) : Op));
906 }
907 VPValue *Result = Ops.front();
908 for (auto [Op, OpV] : drop_begin(zip_equal(SCEVOps, Ops))) {
909 if (UseSubtract(Op)) {
910 // Result + (-Op) == Result - Op, which saves the multiply for the
911 // negation. NSW only transfers if negating Op cannot overflow, see
912 // ScalarEvolution::getMinusSCEV.
913 bool HasNSW =
914 WrapFlags.HasNSW && !SE.getSignedRangeMin(Op).isMinSignedValue();
915 Result = Builder.createOverflowingOp(Instruction::Sub, {Result, OpV},
916 {/*HasNUW=*/false, HasNSW}, DL);
917 continue;
918 }
919 Result = Builder.createOverflowingOp(Instruction::Add, {Result, OpV},
920 WrapFlags, DL);
921 }
922 return Result;
923 }
924 case scMulExpr: {
925 auto *MulE = cast<SCEVMulExpr>(S);
926 VPIRFlags::WrapFlagsTy WrapFlags(MulE->hasNoUnsignedWrap(),
927 MulE->hasNoSignedWrap());
929 for (const SCEV *Op : reverse(MulE->operands()))
930 Ops.push_back(expand(Op));
931 VPValue *Result = Ops.front();
932 for (VPValue *OpV : drop_begin(Ops)) {
933 Result = Builder.createOverflowingOp(Instruction::Mul, {Result, OpV},
934 WrapFlags, DL);
935 }
936 return Result;
937 }
938 case scUDivExpr: {
939 auto *UDiv = cast<SCEVUDivExpr>(S);
940 VPValue *LHS = expand(UDiv->getLHS());
941 const SCEV *RHSExpr = UDiv->getRHS();
942 VPValue *RHS = expand(RHSExpr);
943 if (SafeUDivMode) {
944 // Make sure the UDiv's divisor is guaranteed to not be zero/poison, to
945 // avoid UB.
946 Type *Ty = UDiv->getType();
947 bool GuaranteedNotPoison =
949 if (!GuaranteedNotPoison)
950 RHS = Builder.createScalarFreeze(RHS, DL);
951 if (!SE.isKnownNonZero(RHSExpr) || !GuaranteedNotPoison)
952 RHS = Builder.createScalarIntrinsic(
953 Intrinsic::umax, {RHS, Builder.getPlan().getConstantInt(Ty, 1)}, Ty,
954 DL);
955 }
956 return Builder.createNaryOp(Instruction::UDiv, {LHS, RHS},
957 VPIRFlags::getDefaultFlags(Instruction::UDiv),
958 DL);
959 }
960 case scTruncate:
961 case scZeroExtend:
962 case scSignExtend:
963 case scPtrToAddr: {
964 auto *Cast = cast<SCEVCastExpr>(S);
965 VPValue *Op = expand(Cast->getOperand());
967 switch (S->getSCEVType()) {
968 case scTruncate:
969 Opcode = Instruction::Trunc;
970 break;
971 case scZeroExtend:
972 Opcode = Instruction::ZExt;
973 break;
974 case scSignExtend:
975 Opcode = Instruction::SExt;
976 break;
977 case scPtrToAddr:
978 Opcode = Instruction::PtrToAddr;
979 break;
980 default:
981 llvm_unreachable("Unhandled cast SCEV");
982 }
983
984 // When expanding ptrtoaddr, first check if there's an existing ptrtoint we
985 // can reuse.
986 if (Opcode == Instruction::PtrToAddr) {
987 VPlan &Plan = Builder.getPlan();
988 BasicBlock *PH = cast<VPIRBasicBlock>(Plan.getEntry())->getIRBasicBlock();
989 if (auto *IRV = dyn_cast<VPIRValue>(Op)) {
991 IRV->getValue(), S->getType(), PH->getDataLayout(),
992 [&](const CastInst *CI) {
993 return SE.DT.dominates(CI->getParent(), PH);
994 }))
995 return Plan.getOrAddLiveIn(CI);
996 }
997 }
998
999 return Builder.createScalarCast(Opcode, Op, S->getType(), DL);
1000 }
1001 case scUMaxExpr:
1002 case scSMaxExpr:
1003 case scUMinExpr:
1004 case scSMinExpr:
1005 case scSequentialUMinExpr: {
1006 auto *MinMax = cast<SCEVNAryExpr>(S);
1007 Intrinsic::ID IntrinsicID;
1008 switch (S->getSCEVType()) {
1009 case scUMaxExpr:
1010 IntrinsicID = Intrinsic::umax;
1011 break;
1012 case scSMaxExpr:
1013 IntrinsicID = Intrinsic::smax;
1014 break;
1015 case scUMinExpr:
1017 IntrinsicID = Intrinsic::umin;
1018 break;
1019 case scSMinExpr:
1020 IntrinsicID = Intrinsic::smin;
1021 break;
1022 default:
1023 llvm_unreachable("Unexpected min/max SCEV type");
1024 }
1025 // Chain operands in reverse order matching SCEVExpander's expansion of
1026 // min/max expressions. In SafeUDivMode freeze expansion results of operands
1027 // other than the first for sequential UMins, to avoid short-circuiting
1028 // divide-by-0/poison.
1029 bool IsSequential = S->getSCEVType() == scSequentialUMinExpr;
1030 Type *ResultTy = MinMax->getType();
1031 bool PrevSafeMode = SafeUDivMode;
1033 for (const SCEV *SCEVOp : reverse(MinMax->operands())) {
1034 bool MayShortCircuit =
1035 IsSequential && Ops.size() != MinMax->getNumOperands() - 1;
1036 SafeUDivMode = MayShortCircuit || PrevSafeMode;
1037 VPValue *OpV = expand(SCEVOp);
1038 SafeUDivMode = PrevSafeMode;
1039 if (MayShortCircuit)
1040 OpV = Builder.createScalarFreeze(OpV, DL);
1041 Ops.push_back(OpV);
1042 }
1043 VPValue *Result = Ops.front();
1044 for (VPValue *Op : drop_begin(Ops))
1045 Result = Builder.createScalarIntrinsic(IntrinsicID, {Result, Op},
1046 ResultTy, DL);
1047 return Result;
1048 }
1049 case scAddRecExpr: {
1050 [[maybe_unused]] BasicBlock *PH =
1051 cast<VPIRBasicBlock>(Builder.getPlan().getEntry())->getIRBasicBlock();
1052 assert(
1053 SE.DT.dominates(cast<SCEVAddRecExpr>(S)->getLoop()->getHeader(), PH) &&
1054 "can only expand AddRecs for loops outside VPlan's scope");
1055 // AddRecs outside VPlan's scope must be expanded via VPExpandSCEV.
1056 return vputils::getOrCreateVPValueForSCEVExpr(Builder.getPlan(), S);
1057 }
1058 case scCouldNotCompute:
1059 llvm_unreachable("Attempt to expand a SCEVCouldNotCompute");
1060 }
1061 llvm_unreachable("Unknown SCEV kind!");
1062}
1063
1065 // Do remove conditional assume instructions as their conditions may be
1066 // flattened.
1067 auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
1068 bool IsConditionalAssume = RepR && RepR->isPredicated() &&
1070 if (IsConditionalAssume)
1071 return true;
1072
1073 if (R.mayHaveSideEffects())
1074 return false;
1075
1076 // Forbid removing trip-count expressions.
1077 if (isa<VPExpandSCEVRecipe>(R) &&
1078 R.getVPSingleValue() == R.getParent()->getPlan()->getTripCount())
1079 return false;
1080
1081 // Recipe is dead if no user keeps the recipe alive.
1082 return all_of(R.definedValues(), [](VPValue *V) { return V->user_empty(); });
1083}
1084
1086 SmallVector<VPValue *> WorkList;
1088 WorkList.push_back(V);
1089
1090 while (!WorkList.empty()) {
1091 VPValue *Cur = WorkList.pop_back_val();
1092 if (!Seen.insert(Cur).second)
1093 continue;
1094 VPRecipeBase *R = Cur->getDefiningRecipe();
1095 if (!R)
1096 continue;
1097 if (!isDeadRecipe(*R))
1098 continue;
1099 append_range(WorkList, R->operands());
1100 R->eraseFromParent();
1101 }
1102}
1103
1106 for (unsigned I = 0; I != Users.size(); ++I) {
1108 for (VPValue *V : Cur->definedValues())
1109 Users.insert_range(V->users());
1110 }
1111 return Users.takeVector();
1112}
1113
1116 const DataLayout &DL) {
1117 auto OpcodeOrIID = getOpcodeOrIntrinsicID(&R);
1118 if (!OpcodeOrIID)
1119 return nullptr;
1120
1122 for (VPValue *Op : Operands) {
1123 VPValue *Candidate = Op;
1124 match(Op, m_Broadcast(m_VPValue(Candidate)));
1125 if (!match(Candidate, m_LiveIn()))
1126 return nullptr;
1127 Value *V = Candidate->getUnderlyingValue();
1128 if (!V)
1129 return nullptr;
1130 Ops.push_back(V);
1131 }
1132
1133 VPlan &Plan = *R.getParent()->getPlan();
1134 auto FoldToIRValue = [&]() -> Value * {
1135 InstSimplifyFolder Folder(DL);
1136 if (OpcodeOrIID->first) {
1137 // VPInstructions store the called intrinsic as last operand.
1138 if (isa<VPInstruction>(R))
1139 Ops.pop_back();
1140
1141 auto *RFlags = dyn_cast<VPRecipeWithIRFlags>(&R);
1142 return Folder.FoldIntrinsic(OpcodeOrIID->second, Ops, R.getScalarType(),
1143 RFlags ? RFlags->getFastMathFlagsOrNone()
1144 : FastMathFlags());
1145 }
1146 unsigned Opcode = OpcodeOrIID->second;
1147 if (Instruction::isBinaryOp(Opcode))
1148 return Folder.FoldBinOp(static_cast<Instruction::BinaryOps>(Opcode),
1149 Ops[0], Ops[1]);
1150 if (Instruction::isCast(Opcode))
1151 return Folder.FoldCast(static_cast<Instruction::CastOps>(Opcode), Ops[0],
1152 R.getVPSingleValue()->getScalarType());
1153 switch (Opcode) {
1154 case VPInstruction::Not:
1155 return Folder.FoldBinOp(Instruction::BinaryOps::Xor, Ops[0],
1157 case Instruction::Select:
1158 return Folder.FoldSelect(Ops[0], Ops[1], Ops[2]);
1159 case Instruction::ICmp:
1160 case Instruction::FCmp:
1161 return Folder.FoldCmp(cast<VPRecipeWithIRFlags>(R).getPredicate(), Ops[0],
1162 Ops[1]);
1163 case Instruction::GetElementPtr: {
1164 auto &RFlags = cast<VPRecipeWithIRFlags>(R);
1165 auto *GEP = cast<GetElementPtrInst>(RFlags.getUnderlyingInstr());
1166 return Folder.FoldGEP(GEP->getSourceElementType(), Ops[0],
1167 drop_begin(Ops), RFlags.getGEPNoWrapFlags());
1168 }
1171 return Folder.FoldGEP(IntegerType::getInt8Ty(Plan.getContext()), Ops[0],
1172 Ops[1],
1173 cast<VPRecipeWithIRFlags>(R).getGEPNoWrapFlags());
1174 // An extract of a live-in is an extract of a broadcast, so return the
1175 // broadcasted element.
1176 case Instruction::ExtractElement:
1177 assert(!Ops[0]->getType()->isVectorTy() && "Live-ins should be scalar");
1178 return Ops[0];
1179 }
1180 return nullptr;
1181 };
1182
1183 if (Value *V = FoldToIRValue())
1184 return Plan.getOrAddLiveIn(V);
1185 return nullptr;
1186}
1187
1189 VPlan &Plan, function_ref<VPValue *(VPValue *Op)> MatchPerm,
1192 vp_depth_first_deep(Plan.getEntry()))) {
1193 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
1194 auto *Def = dyn_cast<VPSingleDefRecipe>(&R);
1195 if (!Def || !isElementwise(Def))
1196 continue;
1197
1198 // At least one of the ops must be a permutation.
1199 if (none_of(Def->operands(), MatchPerm))
1200 continue;
1201
1202 // All operands must be a single-use permutation or a live in (splat).
1203 if (!all_of(Def->operands(), [&MatchPerm](VPValue *Op) {
1204 return (Op->hasOneUse() && MatchPerm(Op)) || match(Op, m_LiveIn());
1205 }))
1206 continue;
1207
1208 // Remove the inner permutations.
1209 for (unsigned I = 0, E = Def->getNumOperands(); I != E; ++I)
1210 if (VPValue *X = MatchPerm(Def->getOperand(I)))
1211 Def->setOperand(I, X);
1212
1213 VPSingleDefRecipe *Res = BuildPerm(Def);
1214 Res->insertAfter(Def);
1215 Def->replaceUsesWithIf(
1216 Res, [&Res](VPUser &U, unsigned _) { return &U != Res; });
1217 }
1218 }
1219}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
Hexagon Common GEP
#define _
iv Induction Variable Users
Definition IVUsers.cpp:48
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file provides a LoopVectorizationPlanner class.
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
SI Fold Operands
This file implements a set that has insertion order iteration characteristics.
static unsigned getScalarSizeInBits(Type *Ty)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file implements the TypeSwitch template, which mimics a switch() statement whose cases are type ...
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
static bool preservesUniformity(unsigned Opcode)
Returns true if Opcode preserves uniformity, i.e., if all operands are uniform, the result will also ...
static bool poisonGuaranteesUB(const VPValue *V)
Returns true if V being poison is guaranteed to trigger UB because it propagates to the address of a ...
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
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
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags none()
A struct for saving information about induction variables.
InductionKind
This enum represents the kinds of inductions that we support.
@ IK_IntInduction
Integer induction variable. Step = C.
InstSimplifyFolder - Use InstructionSimplify to fold operations to existing values.
bool isCast() const
bool isBinaryOp() const
bool isUnaryOp() const
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1069
Representation for a specific memory location.
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.
LLVM_ABI const SCEV * getPredicatedSCEV(const SCEV *Expr)
Returns the rewritten SCEV for Expr in the context of the current SCEV predicate.
static LLVM_ABI void dropPoisonGeneratingAnnotationsAndReinfer(ScalarEvolution &SE, Instruction *I)
Drop poison-generating flags from I, then try re-infer via SCEV.
static LLVM_ABI CastInst * findReusableCastForPtrToAddr(Value *PtrOp, Type *Ty, const DataLayout &DL, function_ref< bool(const CastInst *)> Dominates)
Find an existing cast among PtrOp's users that computes the same value as a ptrtoaddr of PtrOp to Ty ...
This class represents an analyzed expression in the program.
static constexpr auto FlagAnyWrap
static constexpr auto FlagNSW
Type * getType() const
Return the LLVM type of this SCEV expression.
SCEVTypes getSCEVType() const
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI const SCEV * getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI const SCEV * getURemExpr(SCEVUse LHS, SCEVUse RHS)
Represents an unsigned remainder expression based on unsigned division.
LLVM_ABI const SCEV * getSMinExpr(SCEVUse LHS, SCEVUse RHS)
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
static LLVM_ABI bool isGuaranteedNotToBePoison(const SCEV *Op)
Returns true if Op is guaranteed to not be poison.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI const SCEV * getTruncateExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI const SCEV * getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI const SCEV * getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
const SCEV * getPowerOfTwo(Type *Ty, unsigned Power)
Return a SCEV for the constant Power of two.
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI const SCEV * getSMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
LLVM_ABI const SCEV * getGEPExpr(GEPOperator *GEP, ArrayRef< SCEVUse > IndexExprs)
Returns an expression for a GEP.
LLVM_ABI const SCEV * getUMinExpr(SCEVUse LHS, SCEVUse RHS, bool Sequential=false)
LLVM_ABI const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
A vector that has set insertion semantics.
Definition SetVector.h:57
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class implements a switch-like dispatch statement for a value of 'T' using dyn_cast functionalit...
Definition TypeSwitch.h:89
TypeSwitch< T, ResultT > & Case(CallableT &&caseFn)
Add a case on the given type.
Definition TypeSwitch.h:98
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4400
iterator end()
Definition VPlan.h:4437
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:266
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4466
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:93
VPRegionBlock * getParent()
Definition VPlan.h:191
size_t getNumSuccessors() const
Definition VPlan.h:242
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:227
VPlan * getPlan()
Definition VPlan.cpp:211
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:216
VPBlockBase * getSingleHierarchicalPredecessor()
Definition VPlan.h:278
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:232
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:216
static bool isLatch(const VPBlockBase *VPB, const VPDominatorTree &VPDT)
Returns true if VPB is a loop latch, using isHeader().
static VPBasicBlock * getPlainCFGMiddleBlock(const VPlan &Plan)
Returns the middle block of Plan in plain CFG form (before regions are formed).
static bool isHeader(const VPBlockBase *VPB, const VPDominatorTree &VPDT)
Returns true if VPB is a loop header, based on regions or VPDT in their absence.
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:387
static std::pair< VPBasicBlock *, VPBasicBlock * > getPlainCFGHeaderAndLatch(const VPlan &Plan)
Returns the header and latch of the outermost loop of Plan in plain CFG form (before regions are form...
static SmallVector< VPBasicBlock * > blocksInSingleSuccessorChainBetween(VPBasicBlock *FirstBB, VPBasicBlock *LastBB)
Returns the blocks between FirstBB and LastBB, where FirstBB to LastBB forms a single-sucessor chain.
RAII object that stores the current insertion point and restores it when the object is destroyed.
VPlan-based builder utility analogous to IRBuilder.
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:573
A recipe for converting Current into Start + Current * Step.
Definition VPlan.h:4194
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
Recipe to expand a SCEV expression.
Definition VPlan.h:4026
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2498
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4553
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
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1332
unsigned getOpcode() const
Definition VPlan.h:1429
bool isVectorToScalar() const
Returns true if this VPInstruction produces a scalar value from a vector, e.g.
bool isSingleScalar() const
Returns true if the recipe produces a single scalar value.
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:410
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:560
void insertAfter(VPRecipeBase *InsertPos)
Insert an unlinked Recipe into a basic block immediately after the specified Recipe.
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:354
A recipe for handling reduction phis.
Definition VPlan.h:2870
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4625
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4701
bool hasCanonicalIVNUW() const
Indicates if NUW is set for the canonical IV increment, for loop regions.
Definition VPlan.h:4789
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4745
VPValues are defined by a VPRegionBlock, like the canonical IV.
Definition VPlanValue.h:252
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3405
VPValue * expand(const SCEV *S)
Expand S into recipes and live-ins using the builder.
A recipe for handling phi nodes of integer and floating-point inductions, producing their scalar valu...
Definition VPlan.h:4255
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:618
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:217
bool isMaterialized() const
Returns true if this value has been materialized.
Definition VPlanValue.h:235
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:401
operand_range operands()
Definition VPlanValue.h:474
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:442
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
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
user_range users()
Definition VPlanValue.h:157
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1894
A recipe for handling GEP instructions.
Definition VPlan.h:2221
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2573
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2596
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2625
A recipe for widened phis.
Definition VPlan.h:2757
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1828
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4812
LLVMContext & getContext() const
Definition VPlan.h:5022
VPBasicBlock * getEntry()
Definition VPlan.h:4908
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5020
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:4974
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
unsigned getConcreteUF() const
Returns the concrete UF of the plan, after unrolling.
Definition VPlan.h:5072
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:4913
VPSymbolicValue & getUF()
Returns the UF of the vector loop region.
Definition VPlan.h:5017
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:4964
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:5013
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
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)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
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.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_VScale()
Matches a call to llvm.vscale().
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
auto m_ZExtOrTruncOrSelf(const OpTy &Op)
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))
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
bool match(const SCEV *S, const Pattern &P)
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
AllRecipe_commutative_match< Instruction::And, Op0_t, Op1_t > m_c_BinaryAnd(const Op0_t &Op0, const Op1_t &Op1)
Match a binary AND operation.
AllRecipe_match< Instruction::Or, Op0_t, Op1_t > m_BinaryOr(const Op0_t &Op0, const Op1_t &Op1)
Match a binary OR operation.
AllRecipe_match< Opcode, Op0_t, Op1_t > m_Binary(const Op0_t &Op0, const Op1_t &Op1)
AllRecipe_match< Opcode, Op0_t > m_Unary(const Op0_t &Op0)
auto m_GetElementPtr(const Op0_t &Op0, const Op1_t &Op1)
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::ExtractVectorForPart, Op0_t, Op1_t > m_ExtractVectorForPart(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::Broadcast, Op0_t > m_Broadcast(const Op0_t &Op0)
match_bind< VPInstruction > m_VPInstruction(VPInstruction *&V)
Match a VPInstruction, capturing if we match.
void pullOutPermutationsImpl(VPlan &Plan, function_ref< VPValue *(VPValue *Op)> Perm, function_ref< VPSingleDefRecipe *(VPSingleDefRecipe *X)> Build)
Template-independent implementation for pullOutPermutations.
bool isSingleScalar(const VPValue *VPV)
Returns true if VPV is a single scalar, either because it produces the same value for all lanes or on...
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr)
Get or create a VPValue that corresponds to the expansion of Expr.
bool cannotHoistOrSinkRecipe(const VPRecipeBase &R, bool Sinking=false)
Return true if we do not know how to (mechanically) hoist or sink R.
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
VPBasicBlock * getFirstLoopHeader(VPlan &Plan, VPDominatorTree &VPDT)
Returns the header block of the first, top-level loop, or null if none exist.
bool isAddressSCEVForCost(const SCEV *Addr, ScalarEvolution &SE, const Loop *L)
Returns true if Addr is an address SCEV that can be passed to TTI::getAddressComputationCost,...
bool onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used.
Intrinsic::ID getIntrinsicID(const Ty *R)
Return the intrinsic ID underlying a call.
Definition VPlanUtils.h:85
VPInstruction * findComputeReductionResult(VPReductionPHIRecipe *PhiR)
Find the ComputeReductionResult recipe for PhiR, looking through selects inserted for predicated redu...
VPInstruction * findCanonicalIVIncrement(VPlan &Plan)
Find the canonical IV increment of Plan's vector loop region.
std::optional< MemoryLocation > getMemoryLocation(const VPRecipeBase &R)
Return a MemoryLocation for R with noalias metadata populated from R, if the recipe is supported and ...
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
VPIRValue * tryToFoldLiveIns(VPSingleDefRecipe &R, ArrayRef< VPValue * > Operands, const DataLayout &DL)
Try to fold R using InstSimplifyFolder.
SmallVector< std::pair< VPBasicBlock *, VPIRBasicBlock * > > getEarlyExits(const VPlan &Plan, const VPBlockBase *MiddleVPBB)
Returns the (early exiting block, exit block) pairs of Plan, i.e.
VPValue * findIncomingAliasMask(const VPlan &Plan)
Finds the incoming alias-mask within the vector preheader.
void recursivelyDeleteDeadRecipes(VPValue *V)
Recursively delete V and any of its operands that become dead.
bool doesGeneratePerAllLanes(const VPRecipeBase *R)
Returns true if R produces scalar values for all VF lanes.
bool isDeadRecipe(VPRecipeBase &R)
Returns true if R is dead, i.e.
bool isElementwise(const VPValue *V)
Return true if V is elementwise, i.e. none of the lanes are permuted.
bool onlyScalarValuesUsed(const VPValue *Def)
Returns true if only scalar values of Def are used by all users.
bool isUniformAcrossVFsAndUFs(const VPValue *V)
Checks if V is uniform across all VF lanes and UF parts.
bool isUsedByLoadStoreAddress(const VPValue *V)
Returns true if V is used as part of the address of another load or store.
std::optional< std::pair< bool, unsigned > > getOpcodeOrIntrinsicID(const VPValue *V)
Get the instruction opcode or intrinsic ID for the recipe defining V.
VPValue * scalarizeVPWidenPointerInduction(VPWidenPointerInductionRecipe *PtrIV, VPlan &Plan, VPBuilder &Builder)
Scalarize a VPWidenPointerInductionRecipe by replacing it with a PtrAdd (IndStart,...
GEPNoWrapFlags getGEPFlagsForPtr(VPValue *Ptr)
Returns the GEP nowrap flags for Ptr, looking through pointer casts mirroring Value::stripPointerCast...
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
unsigned getVFScaleFactor(VPRecipeBase *R)
Get the VF scaling factor applied to the recipe's output, if the recipe has one.
SmallVector< VPUser * > collectUsersRecursively(VPValue *V)
Collect all users of V, looking through recipes that define other values.
VPScalarIVStepsRecipe * createScalarIVSteps(VPlan &Plan, InductionDescriptor::InductionKind Kind, Instruction::BinaryOps InductionOpcode, FPMathOperator *FPBinOp, Instruction *TruncI, VPIRValue *StartV, VPValue *Step, DebugLoc DL, VPBuilder &Builder, const VPIRFlags::WrapFlagsTy &Flags={})
Create a scalar-iv-steps recipe over Plan's canonical IV for an induction of Kind with InductionOpcod...
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Offset
Definition DWP.cpp:578
void stable_sort(R &&Range)
Definition STLExtras.h:2116
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
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
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
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:633
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
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2173
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
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
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:1753
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...
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
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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:1772
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
@ Default
The result value is uniform if and only if all operands are uniform.
Definition Uniformity.h:20
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
A VPValue representing a live-in from the input IR or a constant.
Definition VPlanValue.h:279