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"
25#include "llvm/IR/Dominators.h"
28
29using namespace llvm;
30using namespace llvm::VPlanPatternMatch;
31using namespace llvm::SCEVPatternMatch;
32
34 if (isa<VPBlendRecipe>(U))
35 return true;
36 auto *VPI = dyn_cast<VPInstruction>(U);
37 if (!VPI)
38 return false;
39 unsigned Opcode = VPI->getOpcode();
40 switch (Opcode) {
41 case Instruction::ExtractValue:
42 case Instruction::FCmp:
43 case Instruction::ICmp:
44 case Instruction::Select:
45 case Instruction::Freeze:
47 // TODO: Cover additional opcodes.
48 return true;
50 return Op != VPI->getOperand(0);
51 default:
52 return Instruction::isBinaryOp(Opcode) || Instruction::isCast(Opcode);
53 }
54}
55
58 Worklist.insert(Def);
59 for (unsigned I = 0; I != Worklist.size(); ++I) {
60 const VPValue *Cur = Worklist[I];
61 for (const VPUser *U : Cur->users()) {
62 if (propagatesFirstLaneUse(U, Cur))
64 else if (!U->usesFirstLaneOnly(Cur))
65 return false;
66 }
67 }
68 return true;
69}
70
72 return all_of(Def->users(),
73 [](const VPUser *U) { return U->usesFirstPartOnly(); });
74}
75
77 return all_of(Def->users(),
78 [Def](const VPUser *U) { return U->usesScalars(Def); });
79}
80
82 return all_of(Def->users(), [Def](VPUser *U) {
83 uint64_t Lane;
84 return U->usesScalars(Def) ||
85 match(U, m_ExtractElement(m_Specific(Def), m_ConstantInt(Lane)));
86 });
87}
88
90 bool ExpandInIR) {
91 if (auto *E = dyn_cast<SCEVConstant>(Expr))
92 return Plan.getOrAddLiveIn(E->getValue());
93 // Skip SCEV expansion if Expr is a SCEVUnknown wrapping a non-instruction
94 // value. Otherwise the value may be defined in a loop and using it directly
95 // will break LCSSA form. The SCEV expansion takes care of preserving LCSSA
96 // form.
97 auto *U = dyn_cast<SCEVUnknown>(Expr);
98 if (U && !isa<Instruction>(U->getValue()))
99 return Plan.getOrAddLiveIn(U->getValue());
100 auto *Expanded = new VPExpandSCEVRecipe(Expr, ExpandInIR);
101 VPBasicBlock *EntryVPBB = Plan.getEntry();
102 auto Iter = EntryVPBB->getFirstNonPhi();
103 while (Iter != EntryVPBB->end() && isa<VPIRInstruction>(*Iter))
104 ++Iter;
105 Expanded->insertBefore(Iter);
106 return Expanded;
107}
108
109/// Returns true if \p V being poison is guaranteed to trigger UB because it
110/// propagates to the address of a memory recipe.
111static bool poisonGuaranteesUB(const VPValue *V) {
114
115 auto PropagatesPoisonFromRecipeOp = [](const VPRecipeBase *R) {
117 return false;
118 unsigned Opcode = vputils::getOpcode(R->getVPSingleValue());
119 return Instruction::isCast(Opcode) || Opcode == Instruction::GetElementPtr;
120 };
121
122 Worklist.push_back(V);
123
124 while (!Worklist.empty()) {
125 const VPValue *Current = Worklist.pop_back_val();
126 if (!Visited.insert(Current).second)
127 continue;
128
129 for (VPUser *U : Current->users()) {
130 // Check if Current is used as an address operand for load/store.
131 auto *R = cast<VPRecipeBase>(U);
132 if (auto *MemR = dyn_cast<VPWidenMemoryRecipe>(R)) {
133 if (MemR->getAddr() == Current)
134 return true;
135 continue;
136 }
137 if (auto *Rep = dyn_cast<VPReplicateRecipe>(U)) {
138 unsigned Opcode = Rep->getOpcode();
139 if ((Opcode == Instruction::Load && Rep->getOperand(0) == Current) ||
140 (Opcode == Instruction::Store && Rep->getOperand(1) == Current))
141 return true;
142 }
143
144 // Check if poison propagates through this recipe to any of its users.
145 for (const VPValue *Op : R->operands()) {
146 if (Op == Current && PropagatesPoisonFromRecipeOp(R)) {
147 Worklist.push_back(R->getVPSingleValue());
148 break;
149 }
150 }
151 }
152 }
153
154 return false;
155}
156
158 // Like IR stripPointerCasts, look through GEPs with all-zero indices and
159 // casts to find a root GEP VPInstruction.
160 while (auto *PtrVPI = dyn_cast<VPInstruction>(Ptr)) {
161 unsigned Opcode = PtrVPI->getOpcode();
162 if (Opcode == Instruction::GetElementPtr) {
163 if (!all_of(drop_begin(PtrVPI->operands()), match_fn(m_ZeroInt())))
164 return PtrVPI->getGEPNoWrapFlags();
165 Ptr = PtrVPI->getOperand(0);
166 continue;
167 }
168 if (Opcode != Instruction::BitCast && Opcode != Instruction::AddrSpaceCast)
169 break;
170 Ptr = PtrVPI->getOperand(0);
171 }
172 return GEPNoWrapFlags::none();
173}
174
177 const Loop *L) {
178 ScalarEvolution &SE = *PSE.getSE();
179 if (auto *RV = dyn_cast<VPRegionValue>(V)) {
180 assert(RV == RV->getDefiningRegion()->getCanonicalIV() &&
181 "RegionValue must be canonical IV");
182 if (!L)
183 return SE.getCouldNotCompute();
184 return SE.getAddRecExpr(SE.getZero(RV->getType()), SE.getOne(RV->getType()),
185 L, SCEV::FlagNone);
186 }
187
189 Value *LiveIn = V->getUnderlyingValue();
190 if (LiveIn && SE.isSCEVable(LiveIn->getType()))
191 return SE.getSCEV(LiveIn);
192 return SE.getCouldNotCompute();
193 }
194
195 // Helper to create SCEVs for binary and unary operations.
196 auto CreateSCEV = [&](ArrayRef<VPValue *> Ops,
197 function_ref<const SCEV *(ArrayRef<SCEVUse>)> CreateFn)
198 -> const SCEV * {
200 for (VPValue *Op : Ops) {
201 const SCEV *S = getSCEVExprForVPValue(Op, PSE, L);
203 return SE.getCouldNotCompute();
204 SCEVOps.push_back(S);
205 }
206 return PSE.getPredicatedSCEV(CreateFn(SCEVOps));
207 };
208
209 VPValue *LHSVal, *RHSVal;
210 if (match(V, m_Add(m_VPValue(LHSVal), m_VPValue(RHSVal))))
211 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
212 return SE.getAddExpr(Ops[0], Ops[1], SCEV::FlagNone, 0);
213 });
214 if (match(V, m_BinaryOr(m_VPValue(LHSVal), m_VPValue(RHSVal))))
215 if (cast<VPRecipeWithIRFlags>(V->getDefiningRecipe())->isDisjoint())
216 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
217 return SE.getAddExpr(Ops[0], Ops[1], SCEV::FlagNone, 0);
218 });
219 if (match(V, m_Sub(m_VPValue(LHSVal), m_VPValue(RHSVal))))
220 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
221 return SE.getMinusSCEV(Ops[0], Ops[1], SCEV::FlagNone, 0);
222 });
223 if (match(V, m_Not(m_VPValue(LHSVal)))) {
224 // not X = xor X, -1 = -1 - X
225 return CreateSCEV({LHSVal}, [&](ArrayRef<SCEVUse> Ops) {
226 return SE.getMinusSCEV(SE.getMinusOne(Ops[0]->getType()), Ops[0]);
227 });
228 }
229 if (match(V, m_Mul(m_VPValue(LHSVal), m_VPValue(RHSVal))))
230 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
231 return SE.getMulExpr(Ops[0], Ops[1], SCEV::FlagNone, 0);
232 });
233 // Handle shl by constant: x << c is equivalent to x * (1 << c). A shift
234 // amount >= the bit width produces poison; do not rewrite it, as
235 // getPowerOfTwo requires the power to be in range.
236 uint64_t ShiftAmt;
237 if (match(V, m_Shl(m_VPValue(LHSVal), m_ConstantInt(ShiftAmt))) &&
238 ShiftAmt < LHSVal->getScalarType()->getScalarSizeInBits())
239 return CreateSCEV(LHSVal, [&](ArrayRef<SCEVUse> Ops) {
240 return SE.getMulExpr(Ops[0],
241 SE.getPowerOfTwo(Ops[0]->getType(), ShiftAmt));
242 });
243 if (match(V, m_LShr(m_VPValue(LHSVal), m_ConstantInt(ShiftAmt)))) {
244 Type *Ty = V->getScalarType();
245 if (ShiftAmt < SE.getTypeSizeInBits(Ty))
246 return CreateSCEV(LHSVal, [&](ArrayRef<SCEVUse> Ops) {
247 return SE.getUDivExpr(Ops[0], SE.getPowerOfTwo(Ty, ShiftAmt));
248 });
249 }
250 if (match(V, m_UDiv(m_VPValue(LHSVal), m_VPValue(RHSVal))))
251 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
252 return SE.getUDivExpr(Ops[0], Ops[1]);
253 });
254 if (match(V, m_URem(m_VPValue(LHSVal), m_VPValue(RHSVal))))
255 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
256 return SE.getURemExpr(Ops[0], Ops[1]);
257 });
258 // A SDiv with non-negative operands is equivalent to an UDiv.
259 if (match(V, m_SDiv(m_VPValue(LHSVal), m_VPValue(RHSVal)))) {
260 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
261 if (!SE.isKnownNonNegative(Ops[0]) || !SE.isKnownNonNegative(Ops[1]))
262 return SE.getCouldNotCompute();
263 return SE.getUDivExpr(Ops[0], Ops[1]);
264 });
265 }
266 // A SRem with non-negative operands is equivalent to an URem.
267 if (match(V, m_SRem(m_VPValue(LHSVal), m_VPValue(RHSVal)))) {
268 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
269 if (!SE.isKnownNonNegative(Ops[0]) || !SE.isKnownNonNegative(Ops[1]))
270 return SE.getCouldNotCompute();
271 return SE.getURemExpr(Ops[0], Ops[1]);
272 });
273 }
274 // Handle AND with constant mask: x & (2^n - 1) can be represented as x % 2^n.
275 const APInt *Mask;
276 if (match(V, m_c_BinaryAnd(m_VPValue(LHSVal), m_APInt(Mask))) &&
277 (*Mask + 1).isPowerOf2())
278 return CreateSCEV({LHSVal}, [&](ArrayRef<SCEVUse> Ops) {
279 return SE.getURemExpr(Ops[0], SE.getConstant(*Mask + 1));
280 });
281 // SCEV models ptrtoaddr, but not ptrtoint, mirroring createSCEV.
282 if (match(V, m_PtrToAddr(m_VPValue(LHSVal))))
283 return CreateSCEV({LHSVal}, [&](ArrayRef<SCEVUse> Ops) {
284 return SE.getPtrToAddrExpr(Ops[0]);
285 });
286 if (match(V, m_Trunc(m_VPValue(LHSVal)))) {
287 Type *DestTy = V->getScalarType();
288 return CreateSCEV({LHSVal}, [&](ArrayRef<SCEVUse> Ops) {
289 return SE.getTruncateExpr(Ops[0], DestTy);
290 });
291 }
292 if (match(V, m_ZExt(m_VPValue(LHSVal)))) {
293 Type *DestTy = V->getScalarType();
294 return CreateSCEV({LHSVal}, [&](ArrayRef<SCEVUse> Ops) {
295 return SE.getZeroExtendExpr(Ops[0], DestTy);
296 });
297 }
298 if (match(V, m_SExt(m_VPValue(LHSVal)))) {
299 Type *DestTy = V->getScalarType();
300
301 // Mirror SCEV's createSCEV handling for sext(sub nsw): push sign extension
302 // onto the operands before computing the subtraction.
303 VPValue *SubLHS, *SubRHS;
304 auto *SubR = dyn_cast<VPRecipeWithIRFlags>(LHSVal);
305 if (match(LHSVal, m_Sub(m_VPValue(SubLHS), m_VPValue(SubRHS))) && SubR &&
306 SubR->hasNoSignedWrap() && poisonGuaranteesUB(LHSVal)) {
307 const SCEV *V1 = getSCEVExprForVPValue(SubLHS, PSE, L);
308 const SCEV *V2 = getSCEVExprForVPValue(SubRHS, PSE, L);
310 return SE.getMinusSCEV(SE.getSignExtendExpr(V1, DestTy),
311 SE.getSignExtendExpr(V2, DestTy), SCEV::FlagNSW);
312 }
313
314 return CreateSCEV({LHSVal}, [&](ArrayRef<SCEVUse> Ops) {
315 return SE.getSignExtendExpr(Ops[0], DestTy);
316 });
317 }
318 if (match(V,
320 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
321 return SE.getUMaxExpr(Ops[0], Ops[1]);
322 });
323 if (match(V,
325 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
326 return SE.getSMaxExpr(Ops[0], Ops[1]);
327 });
328 if (match(V,
330 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
331 return SE.getUMinExpr(Ops[0], Ops[1]);
332 });
333 if (match(V,
335 return CreateSCEV({LHSVal, RHSVal}, [&](ArrayRef<SCEVUse> Ops) {
336 return SE.getSMinExpr(Ops[0], Ops[1]);
337 });
339 return CreateSCEV({LHSVal}, [&](ArrayRef<SCEVUse> Ops) {
340 // is_int_min_poison is local to this intrinsic: poison on INT_MIN is
341 // not proof that the input is never INT_MIN, nor that poison reaches
342 // UB. Do not translate it to SCEV's global IsNSW flag.
343 return SE.getAbsExpr(Ops[0], /*IsNSW=*/false);
344 });
345
347 Type *SourceElementType;
348 if (match(V, m_GetElementPtr(SourceElementType, Ops))) {
349 return CreateSCEV(Ops, [&](ArrayRef<SCEVUse> Ops) {
350 return SE.getGEPExpr(Ops.front(), Ops.drop_front(), SourceElementType);
351 });
352 }
353
354 // TODO: Support constructing SCEVs for more recipes as needed.
355 const VPRecipeBase *DefR = V->getDefiningRecipe();
356 const SCEV *Expr =
358 .Case([](const VPExpandSCEVRecipe *R) { return R->getSCEV(); })
359 .Case([&SE, &PSE, L](const VPWidenIntOrFpInductionRecipe *R) {
360 const SCEV *Step = getSCEVExprForVPValue(R->getStepValue(), PSE, L);
361 if (!L || isa<SCEVCouldNotCompute>(Step))
362 return SE.getCouldNotCompute();
363 const SCEV *Start =
364 getSCEVExprForVPValue(R->getStartValue(), PSE, L);
365 const SCEV *AddRec =
366 SE.getAddRecExpr(Start, Step, L, SCEV::FlagNone);
367 if (R->isTruncated())
368 return SE.getTruncateExpr(AddRec, R->getScalarType());
369 return AddRec;
370 })
371 .Case([&SE, &PSE,
372 L](const VPWidenPointerInductionRecipe *R) -> const SCEV * {
373 const SCEV *Start =
374 getSCEVExprForVPValue(R->getStartValue(), PSE, L);
375 if (!L || isa<SCEVCouldNotCompute>(Start))
376 return SE.getCouldNotCompute();
377 const SCEV *Step = getSCEVExprForVPValue(R->getStepValue(), PSE, L);
378 if (isa<SCEVCouldNotCompute>(Step))
379 return SE.getCouldNotCompute();
380 return SE.getAddRecExpr(Start, Step, L, SCEV::FlagNone);
381 })
382 .Case([&SE, &PSE, L](const VPDerivedIVRecipe *R) -> const SCEV * {
383 const SCEV *Start =
384 getSCEVExprForVPValue(R->getStartValue(), PSE, L);
385 const SCEV *Index = getSCEVExprForVPValue(R->getIndex(), PSE, L);
386 const SCEV *Step = getSCEVExprForVPValue(R->getStepValue(), PSE, L);
387 if (any_of(ArrayRef({Start, Index, Step}),
389 return SE.getCouldNotCompute();
390
391 // Convert Index to the step type, matching expandVPDerivedIV.
392 Index = SE.getTruncateOrZeroExtend(Index, Step->getType());
393 return SE.getAddExpr(Start, SE.getMulExpr(Index, Step));
394 })
395 .Case([&SE, &PSE, L](const VPScalarIVStepsRecipe *R) {
396 // A start index, set for parts and lanes other than the first,
397 // adds StartIndex * Step, which is not modeled.
398 const SCEV *IV = getSCEVExprForVPValue(R->getOperand(0), PSE, L);
399 if (isa<SCEVCouldNotCompute>(IV) || R->getStartIndex())
400 return SE.getCouldNotCompute();
401 return IV;
402 })
403 .Default(
404 [&SE](const VPRecipeBase *) { return SE.getCouldNotCompute(); });
405
406 return PSE.getPredicatedSCEV(Expr);
407}
408
409std::optional<int64_t>
411 PredicatedScalarEvolution &PSE, const Loop *L) {
412 if (hasIrregularType(AccessTy, L->getHeader()->getDataLayout()))
413 return {};
414 const SCEV *AddrSCEV = getSCEVExprForVPValue(Addr, PSE, L);
415 auto *AddRec = dyn_cast<SCEVAddRecExpr>(AddrSCEV);
416 if (!AddRec)
417 return {};
418
419 return getStrideFromAddRec(AddRec, L, AccessTy, /*Ptr=*/nullptr, PSE);
420}
421
423 const Loop *L) {
424 // If address is an SCEVAddExpr, we require that all operands must be either
425 // be invariant or a (possibly sign-extend) affine AddRec.
426 if (auto *PtrAdd = dyn_cast<SCEVAddExpr>(Addr)) {
427 return all_of(PtrAdd->operands(), [&SE, L](const SCEV *Op) {
428 return SE.isLoopInvariant(Op, L) ||
429 match(Op, m_scev_SExt(m_scev_AffineAddRec(m_SCEV(), m_SCEV()))) ||
430 match(Op, m_scev_AffineAddRec(m_SCEV(), m_SCEV()));
431 });
432 }
433
434 // Otherwise, check if address is loop invariant or an affine add recurrence.
435 return SE.isLoopInvariant(Addr, L) ||
437}
438
439unsigned vputils::getOpcode(const VPValue *V) {
443 VPWidenLoadEVLRecipe>([](auto *I) { return I->getOpcode(); })
446 // For recipes that do not directly map to LLVM IR instructions,
447 // assign opcodes after the last VPInstruction opcode (which is also
448 // after the last IR Instruction opcode), based on the VPRecipeID.
449 return VPInstruction::OpsEnd + 1 + I->getVPRecipeID();
450 })
451 .Default([](auto *) { return 0; });
452}
453
454std::optional<std::pair<bool, unsigned>>
457 return std::make_pair(true, IID);
458 if (unsigned Opcode = vputils::getOpcode(V))
459 return std::make_pair(false, Opcode);
460 return {};
461}
462
463/// Returns true if \p Opcode preserves uniformity, i.e., if all operands are
464/// uniform, the result will also be uniform.
465static bool preservesUniformity(unsigned Opcode) {
466 if (Instruction::isBinaryOp(Opcode) || Instruction::isCast(Opcode))
467 return true;
468 switch (Opcode) {
469 case Instruction::Freeze:
470 case Instruction::GetElementPtr:
471 case Instruction::ICmp:
472 case Instruction::FCmp:
473 case Instruction::Select:
478 return true;
479 default:
480 return false;
481 }
482}
483
485 // TODO: Handle more opcodes and recipes.
487 return false;
488 unsigned Opcode = getOpcode(V);
489 return Instruction::isUnaryOp(Opcode) || Instruction::isBinaryOp(Opcode);
490}
491
493 // Live-in, symbolic and canonical-IV region values are single-scalar.
494 if (auto *RV = dyn_cast<VPRegionValue>(VPV))
495 return RV == RV->getDefiningRegion()->getCanonicalIV();
497 return true;
498
499 if (auto *Rep = dyn_cast<VPReplicateRecipe>(VPV)) {
500 const VPRegionBlock *RegionOfR = Rep->getRegion();
501 // Don't consider recipes in replicate regions as uniform yet; their first
502 // lane cannot be accessed when executing the replicate region for other
503 // lanes.
504 if (RegionOfR && RegionOfR->isReplicator())
505 return false;
506 return Rep->isSingleScalar() || (preservesUniformity(Rep->getOpcode()) &&
507 all_of(Rep->operands(), isSingleScalar));
508 }
511 if (auto *WidenR = dyn_cast<VPWidenRecipe>(VPV)) {
512 return preservesUniformity(WidenR->getOpcode()) &&
513 all_of(WidenR->operands(), isSingleScalar);
514 }
515 if (auto *VPI = dyn_cast<VPInstruction>(VPV))
516 return VPI->doesGenerateSingleScalar() || VPI->isVectorToScalar() ||
517 (preservesUniformity(VPI->getOpcode()) &&
518 all_of(VPI->operands(), isSingleScalar));
519 if (auto *RR = dyn_cast<VPReductionRecipe>(VPV))
520 return !RR->isPartialReduction();
523 return true;
524 if (auto *Expr = dyn_cast<VPExpressionRecipe>(VPV))
525 return Expr->isVectorToScalar();
526
527 // VPExpandSCEVRecipes must be placed in the entry and are always uniform.
528 return isa<VPExpandSCEVRecipe>(VPV);
529}
530
532 const VPValue *V,
533 function_ref<void(VPUser::const_operand_range)> AddToWorklist) {
534 // Live-ins, symbolic and canonical-IV region values are uniform.
535 if (auto *RV = dyn_cast<VPRegionValue>(V))
536 return RV == RV->getDefiningRegion()->getCanonicalIV();
538 return true;
539
540 const VPRecipeBase *R = V->getDefiningRecipe();
541 const VPBasicBlock *VPBB = R ? R->getParent() : nullptr;
542 const VPlan *Plan = VPBB ? VPBB->getPlan() : nullptr;
543 if (VPBB &&
544 (VPBB == Plan->getVectorPreheader() || VPBB == Plan->getEntry())) {
545 if (match(R,
548 return false;
549 AddToWorklist(R->operands());
550 return true;
551 }
552
554 .Case([](const VPDerivedIVRecipe *) { return true; })
555 .Case([&](const VPReplicateRecipe *R) {
556 // Be conservative about side-effects, except for the
557 // known-side-effecting assumes and stores, which we know will be
558 // uniform. Each alloca creates a distinct allocation, so allocas are
559 // never uniform.
560 if (!R->isSingleScalar() || R->getOpcode() == Instruction::Alloca ||
561 (R->mayHaveSideEffects() &&
562 !isa<AssumeInst, StoreInst>(R->getUnderlyingInstr())))
563 return false;
564 AddToWorklist(R->operands());
565 return true;
566 })
567 .Case([&](const VPWidenRecipe *R) {
568 if (!preservesUniformity(R->getOpcode()))
569 return false;
570 AddToWorklist(R->operands());
571 return true;
572 })
573 .Case([](const VPPhi *) {
574 // Bail out on VPPhi, as we can end up in infinite cycles.
575 return false;
576 })
577 .Case([&](const VPInstruction *VPI) {
578 if (!VPI->doesGenerateSingleScalar() && !VPI->isVectorToScalar() &&
580 return false;
581 AddToWorklist(VPI->operands());
582 return true;
583 })
584 .Case([&](const VPWidenCastRecipe *R) {
585 // A cast is uniform according to its operand.
586 AddToWorklist(R->operands());
587 return true;
588 })
589 .Default([](const VPRecipeBase *) {
590 // A value is considered non-uniform unless proven otherwise.
591 return false;
592 });
593}
594
597 Worklist.insert(V);
598
599 auto AddToWorklist = [&Worklist](VPUser::const_operand_range Operands) {
600 Worklist.insert_range(Operands);
601 };
602
603 // All dependency checks are conjunctive, so each value needs checking once.
604 for (unsigned I = 0; I != Worklist.size(); ++I) {
605 if (!isUniformAcrossVFsAndUFsImpl(Worklist[I], AddToWorklist))
606 return false;
607 }
608 return true;
609}
610
612 if (auto *RepR = dyn_cast<VPReplicateRecipe>(R))
613 return RepR->doesGeneratePerAllLanes();
614 if (auto *VPI = dyn_cast<VPInstruction>(R))
615 return VPI->doesGeneratePerAllLanes();
616 if (auto *SIVSteps = dyn_cast<VPScalarIVStepsRecipe>(R))
617 return SIVSteps->doesGeneratePerAllLanes();
618 return false;
619}
620
622 auto DepthFirst = vp_depth_first_shallow(Plan.getEntry());
623 auto I = find_if(DepthFirst, [&VPDT](VPBlockBase *VPB) {
624 return VPBlockUtils::isHeader(VPB, VPDT);
625 });
626 return I == DepthFirst.end() ? nullptr : cast<VPBasicBlock>(*I);
627}
628
630 if (!R)
631 return 1;
632 if (auto *RR = dyn_cast<VPReductionPHIRecipe>(R))
633 return RR->getVFScaleFactor();
634 if (auto *RR = dyn_cast<VPReductionRecipe>(R))
635 return RR->getVFScaleFactor();
636 if (auto *ER = dyn_cast<VPExpressionRecipe>(R))
637 return ER->getVFScaleFactor();
638 assert(
641 "getting scaling factor of reduction-start-vector not implemented yet");
642 return 1;
643}
644
645bool vputils::cannotHoistOrSinkRecipe(const VPRecipeBase &R, bool Sinking) {
646 // Assumes don't alias anything or throw; as long as they're guaranteed to
647 // execute, they're safe to hoist. They should however not be sunk, as it
648 // would destroy information.
650 return Sinking;
651 if (R.mayHaveSideEffects() || R.mayReadFromMemory() || R.isPhi())
652 return true;
653 // Allocas cannot be hoisted.
654 auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
655 return RepR && RepR->getOpcode() == Instruction::Alloca;
656}
657
660 VPBasicBlock *LastBB) {
661 assert(FirstBB->getParent() == LastBB->getParent() &&
662 "FirstBB and LastBB from different regions");
663#ifndef NDEBUG
664 bool InSingleSuccChain = false;
665 for (VPBlockBase *Succ = FirstBB; Succ; Succ = Succ->getSingleSuccessor())
666 InSingleSuccChain |= (Succ == LastBB);
667 assert(InSingleSuccChain &&
668 "LastBB unreachable from FirstBB in single-successor chain");
669#endif
670 auto Blocks = to_vector(
672 auto *LastIt = find(Blocks, LastBB);
673 assert(LastIt != Blocks.end() &&
674 "LastBB unreachable from FirstBB in depth-first traversal");
675 Blocks.erase(std::next(LastIt), Blocks.end());
676 return Blocks;
677}
678
680 for (VPRecipeBase &R : *Plan.getVectorPreheader())
682 return cast<VPInstruction>(&R);
683 return nullptr;
684}
685
687vputils::getEarlyExits(const VPlan &Plan, const VPBlockBase *MiddleVPBB) {
689 for (VPIRBasicBlock *ExitVPBB : Plan.getExitBlocks())
690 for (VPBlockBase *Pred : ExitVPBB->getPredecessors())
691 if (Pred != MiddleVPBB)
692 Exits.emplace_back(cast<VPBasicBlock>(Pred), ExitVPBB);
693 return Exits;
694}
695
698 Instruction::BinaryOps InductionOpcode, FPMathOperator *FPBinOp,
699 Type *ResultTy, VPValue *StartV, VPValue *Step, DebugLoc DL,
700 VPBuilder &Builder, const VPIRFlags::WrapFlagsTy &Flags) {
701 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
702 VPBasicBlock *HeaderVPBB = LoopRegion->getEntryBasicBlock();
703 VPValue *CanonicalIV = LoopRegion->getCanonicalIV();
704 VPValue *BaseIV =
705 Builder.createDerivedIV(Kind, FPBinOp, StartV, CanonicalIV, Step, Flags);
706
707 // Truncate BaseIV and Step to ResultTy.
708 if (ResultTy->isIntegerTy()) {
709 [[maybe_unused]] Type *BaseIVTy = BaseIV->getScalarType();
710 assert(BaseIVTy->isIntegerTy() && "Integral BaseIV type expected");
711 assert(BaseIVTy->getPrimitiveSizeInBits() >=
712 ResultTy->getPrimitiveSizeInBits() &&
713 "BaseIV's type must be at least as large as ResultTy");
714 BaseIV = Builder.createScalarZExtOrTrunc(BaseIV, ResultTy, DL);
715 [[maybe_unused]] Type *StepTy = Step->getScalarType();
716 assert(StepTy->isIntegerTy() && "Integral Step type expected");
717 assert(StepTy->getPrimitiveSizeInBits() >=
718 ResultTy->getPrimitiveSizeInBits() &&
719 "Step's type must be at least as large as ResultTy");
720 auto *VecPreheader =
722 VPBuilder::InsertPointGuard Guard(Builder);
723 Builder.setInsertPoint(VecPreheader);
724 Step = Builder.createScalarZExtOrTrunc(Step, ResultTy, DL);
725 }
726 return Builder.createScalarIVSteps(InductionOpcode, FPBinOp, BaseIV, Step,
727 &Plan.getVF(), DL);
728}
729
730VPValue *
732 VPlan &Plan, VPBuilder &Builder) {
733 VPValue *StepV = PtrIV->getStepValue();
734 VPIRValue *StartV = Plan.getZero(StepV->getScalarType());
736 Plan, InductionDescriptor::IK_IntInduction, Instruction::Add, nullptr,
737 StartV->getScalarType(), StartV, StepV, PtrIV->getDebugLoc(), Builder);
738
739 return Builder.createPtrAdd(PtrIV->getStartValue(), Steps,
740 PtrIV->getDebugLoc(), "next.gep");
741}
742
744 const VPDominatorTree &VPDT) {
745 auto *VPBB = dyn_cast<VPBasicBlock>(VPB);
746 if (!VPBB)
747 return false;
748
749 // If VPBB is in a region R, VPBB is a loop header if R is a loop region with
750 // VPBB as its entry, i.e., free of predecessors.
751 if (auto *R = VPBB->getParent())
752 return !R->isReplicator() && !VPBB->hasPredecessors();
753
754 // A header dominates its second predecessor (the latch), with the other
755 // predecessor being the preheader
756 return VPB->getPredecessors().size() == 2 &&
757 VPDT.dominates(VPB, VPB->getPredecessors()[1]);
758}
759
761 const VPDominatorTree &VPDT) {
762 // A latch has a header as its last successor, with its other successors
763 // leaving the loop. A preheader OTOH has a header as its first (and only)
764 // successor.
765 return VPB->getNumSuccessors() >= 2 &&
767}
768
769std::pair<VPBasicBlock *, VPBasicBlock *>
772 Plan.getEntry()->getNumSuccessors() == 1
773 ? Plan.getEntry()->getSingleSuccessor()
774 : Plan.getEntry()->getSuccessors()[1]->getSingleSuccessor());
775 assert(Header->getNumPredecessors() == 2 &&
776 "Header must have exactly 2 predecessors");
777 auto *Latch = cast<VPBasicBlock>(Header->getPredecessors()[1]);
778 return {Header, Latch};
779}
780
784
786 const VPPhi *PhiR) {
787 if (ID.getKind() == InductionDescriptor::IK_FpInduction)
788 return ID.getInductionBinOp()->getFastMathFlags();
789
790 // The flags only bound the induction values if the increment directly
791 // updates PhiR.
792 VPValue *Inc = PhiR->getOperand(1);
793 if (match(Inc, m_c_Add(m_Specific(PhiR), m_VPValue())))
794 return cast<VPInstruction>(Inc)->getNoWrapFlagsOrNone();
795
796 if (match(Inc, m_Sub(m_Specific(PhiR), m_VPValue()))) {
797 // The step of a sub induction is negated, so NUW cannot be preserved. NSW
798 // can, if the step is not the signed minimum.
799 std::optional<APInt> Step = ID.getConstStepValue();
800 bool NSW = cast<VPInstruction>(Inc)->getNoWrapFlagsOrNone().HasNSW &&
801 Step && !Step->isMinSignedValue();
802 return VPIRFlags::WrapFlagsTy(/*NUW*/ false, NSW);
803 }
804
805 return VPIRFlags::WrapFlagsTy(false, false);
806}
807
808std::optional<MemoryLocation>
810 auto *M = dyn_cast<VPIRMetadata>(&R);
811 if (!M)
812 return std::nullopt;
814 // Populate noalias metadata from VPIRMetadata.
815 if (MDNode *NoAliasMD = M->getMetadata(LLVMContext::MD_noalias))
816 Loc.AATags.NoAlias = NoAliasMD;
817 if (MDNode *AliasScopeMD = M->getMetadata(LLVMContext::MD_alias_scope))
818 Loc.AATags.Scope = AliasScopeMD;
819 return Loc;
820}
821
823 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
824 VPRegionValue *CanIV = LoopRegion->getCanonicalIV();
825 assert(CanIV && "Expected loop region to have a canonical IV");
826
827 VPSymbolicValue &VFxUF = Plan.getVFxUF();
828
829 // Check if \p Step matches the expected increment step, accounting for
830 // materialization of VFxUF and UF.
831 auto IsIncrementStep = [&](VPValue *Step) -> bool {
832 if (!VFxUF.isMaterialized())
833 return Step == &VFxUF;
834
835 VPSymbolicValue &UF = Plan.getUF();
836 if (!UF.isMaterialized())
837 return Step == &UF ||
838 match(Step, m_c_Mul(m_Specific(&Plan.getUF()), m_VScale()));
839
840 // Alias masking: step is number of active lanes of a dependence mask.
841 if (match(Step, m_ZExtOrTruncOrSelf(
843 return true;
844
845 unsigned ConcreteUF = Plan.getConcreteUF();
846 // Fixed VF: step is just the concrete UF.
847 if (match(Step, m_SpecificInt(ConcreteUF)))
848 return true;
849
850 // Scalable VF: step involves VScale.
851 if (ConcreteUF == 1)
852 return match(Step, m_VScale());
853 if (match(Step, m_c_Mul(m_SpecificInt(ConcreteUF), m_VScale())))
854 return true;
855 // mul(VScale, ConcreteUF) may have been simplified to
856 // shl(VScale, log2(ConcreteUF)) when ConcreteUF is a power of 2.
857 return isPowerOf2_32(ConcreteUF) &&
858 match(Step, m_Shl(m_VScale(), m_SpecificInt(Log2_32(ConcreteUF))));
859 };
860
861 VPInstruction *Increment = nullptr;
862 for (VPUser *U : CanIV->users()) {
863 VPValue *Step;
864 if (isa<VPInstruction>(U) &&
865 match(U, m_c_Add(m_Specific(CanIV), m_VPValue(Step))) &&
866 IsIncrementStep(Step)) {
867 assert(!Increment && "There must be a unique increment");
869 }
870 }
871
872 assert((!VFxUF.isMaterialized() || Increment) &&
873 "After materializing VFxUF, an increment must exist");
874 assert((!Increment ||
875 LoopRegion->hasCanonicalIVNUW() == Increment->hasNoUnsignedWrap()) &&
876 "NUW flag in region and increment must match");
877 return Increment;
878}
879
880/// Find the ComputeReductionResult recipe for \p PhiR, looking through selects
881/// inserted for predicated reductions or tail folding.
883 VPValue *BackedgeVal = PhiR->getBackedgeValue();
884 if (auto *Res =
886 return Res;
887
888 // Look through selects inserted for tail folding or predicated reductions.
890 BackedgeVal, m_Select(m_VPValue(), m_VPValue(), m_VPValue()));
891 if (!SelR)
892 return nullptr;
894}
895
898 SmallVector<const VPValue *> WorkList = {V};
899
900 while (!WorkList.empty()) {
901 const VPValue *Cur = WorkList.pop_back_val();
902 if (!Seen.insert(Cur).second)
903 continue;
904
905 for (VPUser *U : Cur->users()) {
906 if (auto *InterleaveR = dyn_cast<VPInterleaveBase>(U))
907 if (InterleaveR->getAddr() == Cur)
908 return true;
909 // Cur is used as the pointer of a (possibly masked) load (operand 0) or
910 // store (operand 1).
913 m_Specific(Cur)))))
914 return true;
916 if (MemR->getAddr() == Cur && MemR->isConsecutive())
917 return true;
918 }
919 }
920
921 // The legacy cost model only supports scalarization loads/stores with phi
922 // addresses, if the phi is directly used as load/store address. Don't
923 // traverse further for Blends and first-order recurrence splices.
924 if (isa<VPBlendRecipe>(Cur) ||
925 match(Cur,
927 continue;
928
929 // Only traverse further through users that also define a value (and can
930 // thus have their own users walked). Skip users using Cur only as mask,
931 // including blends, as well as loads: a loaded value does not depend on
932 // the load's operand.
933 for (VPUser *U : Cur->users()) {
934 auto *VPI = dyn_cast<VPInstruction>(U);
935 if (VPI && VPI->getMask() == Cur &&
936 none_of(VPI->operandsWithoutMask(), equal_to(Cur)))
937 continue;
938 auto *Blend = dyn_cast<VPBlendRecipe>(U);
939 if (Blend && none_of(seq(Blend->getNumIncomingValues()), [&](unsigned I) {
940 return Blend->getIncomingValue(I) == Cur;
941 }))
942 continue;
944 continue;
945 if (auto *SDR = dyn_cast<VPSingleDefRecipe>(U))
946 WorkList.push_back(SDR);
947 }
948 }
949 return false;
950}
951
952/// Try to find a loop-invariant IR value for \p S in the plan's entry block
953/// that can be reused. Returns the corresponding live-in VPValue, an in-IR
954/// VPExpandSCEVRecipe if reuse requires dropping flags, or nullptr if no
955/// reusable IR value is found.
956VPValue *VPSCEVExpander::tryToReuseIRValue(const SCEV *S) {
958 return nullptr;
959 VPlan &Plan = Builder.getPlan();
960 BasicBlock *PH = cast<VPIRBasicBlock>(Plan.getEntry())->getIRBasicBlock();
961 bool ReuseNeedsDrop = false;
962 for (Value *V : SE.getSCEVValues(S)) {
963 // Only reuse instructions in the plan's entry block, or, when a
964 // DominatorTree is available, any instruction that dominates it.
965 // Instructions in sibling branches may not dominate the entry block.
966 auto *I = dyn_cast<Instruction>(V);
967 if (!I)
968 return Plan.getOrAddLiveIn(V);
969 if (!SE.DT.dominates(I->getParent(), PH))
970 continue;
971 Loop *IL = SE.LI.getLoopFor(I->getParent());
972 if (IL && !IL->contains(PH))
973 continue;
974 SmallVector<Instruction *> DropPoisonGeneratingInsts;
975 if (!SE.canReuseInstruction(S, I, DropPoisonGeneratingInsts))
976 continue;
977 if (DropPoisonGeneratingInsts.empty())
978 return Plan.getOrAddLiveIn(V);
979 ReuseNeedsDrop = true;
980 }
981 // Leave dropping flags to SCEVExpander, as the plan may be discarded.
982 if (ReuseNeedsDrop)
983 return vputils::getOrCreateVPValueForSCEVExpr(Plan, S, /*ExpandInIR=*/true);
984 return nullptr;
985}
986
987bool VPSCEVExpander::canExpandInIR(const SCEV *S) {
988 return HoistOutOf && SE.isLoopInvariant(S, HoistOutOf) &&
989 SE.isGuaranteedNotToCauseUB(S);
990}
991
992/// Returns the sums of the operands of \p S invariant in \p L and of the
993/// remaining operands, if there are at least 2 invariant and 1 variant
994/// operands.
995static std::pair<const SCEV *, const SCEV *>
997 if (!L)
998 return {nullptr, nullptr};
999 SmallVector<SCEVUse> InvOps, VarOps;
1000 for (SCEVUse Op : S->operands())
1001 (SE.isLoopInvariant(Op, L) ? InvOps : VarOps).push_back(Op);
1002 if (InvOps.size() < 2 || VarOps.empty())
1003 return {nullptr, nullptr};
1004 return {SE.getAddExpr(InvOps), SE.getAddExpr(VarOps)};
1005}
1006
1007VPValue *VPSCEVExpander::expandAsPtrAdd(const SCEVNAryExpr *S) {
1008 const SCEV *Base = SE.getPointerBase(S);
1009 const SCEV *Offset = SE.removePointerBase(S);
1010 // If the pointer is invariant in HoistOutOf, use the sum of all invariant
1011 // operands as base, so it is hoisted whole.
1012 if (auto *AddE = dyn_cast<SCEVAddExpr>(S)) {
1013 auto [InvS, VarS] = splitInvariantSum(AddE, HoistOutOf, SE);
1014 if (InvS && InvS->getType()->isPointerTy() && canExpandInIR(InvS))
1015 std::tie(Base, Offset) = std::tie(InvS, VarS);
1016 }
1017 GEPNoWrapFlags GEPFlags = S->hasNoUnsignedWrap()
1019 : GEPNoWrapFlags::none();
1020 VPValue *BaseV = expand(Base);
1021 VPValue *OffsetV = expand(Offset);
1022 return Builder.createNoWrapPtrAdd(BaseV, OffsetV, GEPFlags, DL);
1023}
1024
1025VPValue *VPSCEVExpander::expandAddOps(ArrayRef<const SCEV *> Operands,
1026 VPIRFlags::WrapFlagsTy WrapFlags) {
1027 // Non-constant-negative add operands are expanded negated and subtracted
1028 // from the running result below, instead of being negated and added.
1029 auto UseSubtract = [](const SCEV *Op) { return Op->isNonConstantNegative(); };
1030 // Move the subtracted operands last, matching SCEVExpander's LoopCompare, so
1031 // that they don't start the running result.
1033 stable_sort(SCEVOps, [&](const SCEV *L, const SCEV *R) {
1034 return !UseSubtract(L) && UseSubtract(R);
1035 });
1037 for (const SCEV *Op : SCEVOps) {
1038 // The first operand starts the result, so it is never subtracted.
1039 bool Negate = !Ops.empty() && UseSubtract(Op);
1040 Ops.push_back(expand(Negate ? SE.getNegativeSCEV(Op) : Op));
1041 }
1042 VPValue *Result = Ops.front();
1043 for (auto [Op, OpV] : drop_begin(zip_equal(SCEVOps, Ops))) {
1044 if (UseSubtract(Op)) {
1045 // Result + (-Op) == Result - Op, which saves the multiply for the
1046 // negation. NSW only transfers if negating Op cannot overflow, see
1047 // ScalarEvolution::getMinusSCEV.
1048 bool HasNSW =
1049 WrapFlags.HasNSW && !SE.getSignedRangeMin(Op).isMinSignedValue();
1050 Result = Builder.createOverflowingOp(Instruction::Sub, {Result, OpV},
1051 {/*HasNUW=*/false, HasNSW}, DL);
1052 continue;
1053 }
1054 Result = Builder.createOverflowingOp(Instruction::Add, {Result, OpV},
1055 WrapFlags, DL);
1056 }
1057 return Result;
1058}
1059
1060#ifndef NDEBUG
1061/// Returns true if \p V dominates the insert point of \p Builder.
1062static bool dominatesInsertPoint(const VPValue *V, const VPBuilder &Builder) {
1063 const VPRecipeBase *R = V->getDefiningRecipe();
1064 if (!R)
1065 return true;
1066 VPDominatorTree VPDT(Builder.getPlan());
1067 if (VPRecipeBase *InsertPt = Builder.getRecipeAtInsertPoint())
1068 return VPDT.properlyDominates(R, InsertPt);
1069 return VPDT.dominates(R->getParent(), Builder.getInsertBlock());
1070}
1071#endif
1072
1075 if (VPValue *V = InsertedExpressions.lookup(Key)) {
1076 assert(dominatesInsertPoint(V, Builder) &&
1077 "reused expansion must dominate the insert point");
1078 return V;
1079 }
1080 VPValue *V = expandImpl(S);
1081 InsertedExpressions[Key] = V;
1082 return V;
1083}
1084
1085VPValue *VPSCEVExpander::expandImpl(const SCEV *S) {
1086 if (VPValue *V = tryToReuseIRValue(S))
1087 return V;
1088
1089 if (canExpandInIR(S))
1090 return vputils::getOrCreateVPValueForSCEVExpr(Builder.getPlan(), S,
1091 /*ExpandInIR=*/true);
1092
1093 switch (S->getSCEVType()) {
1094 case scConstant:
1095 return Builder.getPlan().getOrAddLiveIn(cast<SCEVConstant>(S)->getValue());
1096 case scUnknown:
1097 return Builder.getPlan().getOrAddLiveIn(cast<SCEVUnknown>(S)->getValue());
1098 case scVScale:
1099 return Builder.createVScale(S->getType(), DL);
1100 case scAddExpr: {
1101 auto *AddE = cast<SCEVAddExpr>(S);
1102 VPIRFlags::WrapFlagsTy WrapFlags(AddE->hasNoUnsignedWrap(),
1103 AddE->hasNoSignedWrap());
1104
1105 // Expand pointer SCEVAddExpr as a ptradd of the pointer base and the
1106 // integer offset, matching SCEVExpander.
1107 if (S->getType()->isPointerTy())
1108 return expandAsPtrAdd(AddE);
1109
1110 // Iterate in reverse so that constants are emitted last.
1111 SmallVector<const SCEV *, 2> SCEVOps(reverse(AddE->operands()));
1112 // Sum the invariant operands separately, so the sum can be hoisted.
1113 auto [InvS, VarS] = splitInvariantSum(AddE, HoistOutOf, SE);
1114 if (InvS && canExpandInIR(InvS))
1115 SCEVOps = {InvS, VarS};
1116 return expandAddOps(SCEVOps, WrapFlags);
1117 }
1118 case scMulExpr: {
1119 auto *MulE = cast<SCEVMulExpr>(S);
1120 VPIRFlags::WrapFlagsTy WrapFlags(MulE->hasNoUnsignedWrap(),
1121 MulE->hasNoSignedWrap());
1123 for (const SCEV *Op : reverse(MulE->operands()))
1124 Ops.push_back(expand(Op));
1125 VPValue *Result = Ops.front();
1126 for (VPValue *OpV : drop_begin(Ops)) {
1127 Result = Builder.createOverflowingOp(Instruction::Mul, {Result, OpV},
1128 WrapFlags, DL);
1129 }
1130 return Result;
1131 }
1132 case scUDivExpr: {
1133 auto *UDiv = cast<SCEVUDivExpr>(S);
1134 VPValue *LHS = expand(UDiv->getLHS());
1135 const SCEV *RHSExpr = UDiv->getRHS();
1136 VPValue *RHS = expand(RHSExpr);
1137 if (SafeUDivMode) {
1138 // Make sure the UDiv's divisor is guaranteed to not be zero/poison, to
1139 // avoid UB.
1140 Type *Ty = UDiv->getType();
1141 bool GuaranteedNotPoison =
1143 if (!GuaranteedNotPoison)
1144 RHS = Builder.createFreeze(RHS, DL);
1145 if (!SE.isKnownNonZero(RHSExpr) || !GuaranteedNotPoison)
1146 RHS = Builder.createScalarIntrinsic(
1147 Intrinsic::umax, {RHS, Builder.getPlan().getConstantInt(Ty, 1)}, Ty,
1148 DL);
1149 }
1150 return Builder.createNaryOp(Instruction::UDiv, {LHS, RHS},
1151 VPIRFlags::getDefaultFlags(Instruction::UDiv),
1152 DL);
1153 }
1154 case scTruncate:
1155 case scZeroExtend:
1156 case scSignExtend:
1157 case scPtrToAddr: {
1158 auto *Cast = cast<SCEVCastExpr>(S);
1159 VPValue *Op = expand(Cast->getOperand());
1160 Instruction::CastOps Opcode;
1161 switch (S->getSCEVType()) {
1162 case scTruncate:
1163 Opcode = Instruction::Trunc;
1164 break;
1165 case scZeroExtend:
1166 Opcode = Instruction::ZExt;
1167 break;
1168 case scSignExtend:
1169 Opcode = Instruction::SExt;
1170 break;
1171 case scPtrToAddr:
1172 Opcode = Instruction::PtrToAddr;
1173 break;
1174 default:
1175 llvm_unreachable("Unhandled cast SCEV");
1176 }
1177
1178 // For ptrtoaddr of an IR value, reuse an existing cast dominating the
1179 // entry if there is one. Otherwise leave it to SCEVExpander, which places
1180 // the cast right after the IR value's definition, so all users can share
1181 // it.
1182 if (Opcode == Instruction::PtrToAddr) {
1183 VPlan &Plan = Builder.getPlan();
1184 BasicBlock *PH = cast<VPIRBasicBlock>(Plan.getEntry())->getIRBasicBlock();
1185 if (auto *IRV = dyn_cast<VPIRValue>(Op)) {
1187 IRV->getValue(), S->getType(), PH->getDataLayout(),
1188 [&](const CastInst *CI) {
1189 return SE.DT.dominates(CI->getParent(), PH);
1190 }))
1191 return Plan.getOrAddLiveIn(CI);
1193 }
1194 }
1195
1196 std::optional<VPIRFlags> Flags;
1197 if (Opcode == Instruction::ZExt)
1198 Flags =
1199 VPIRFlags::NonNegFlagsTy(SE.isKnownNonNegative(Cast->getOperand()));
1200
1201 return Builder.createScalarCast(Opcode, Op, S->getType(), DL, Flags);
1202 }
1203 case scUMaxExpr:
1204 case scSMaxExpr:
1205 case scUMinExpr:
1206 case scSMinExpr:
1207 case scSequentialUMinExpr: {
1208 auto *MinMax = cast<SCEVNAryExpr>(S);
1209 Intrinsic::ID IntrinsicID;
1210 switch (S->getSCEVType()) {
1211 case scUMaxExpr:
1212 IntrinsicID = Intrinsic::umax;
1213 break;
1214 case scSMaxExpr:
1215 IntrinsicID = Intrinsic::smax;
1216 break;
1217 case scUMinExpr:
1219 IntrinsicID = Intrinsic::umin;
1220 break;
1221 case scSMinExpr:
1222 IntrinsicID = Intrinsic::smin;
1223 break;
1224 default:
1225 llvm_unreachable("Unexpected min/max SCEV type");
1226 }
1227 // Chain operands in reverse order matching SCEVExpander's expansion of
1228 // min/max expressions. In SafeUDivMode freeze expansion results of operands
1229 // other than the first for sequential UMins, to avoid short-circuiting
1230 // divide-by-0/poison.
1231 bool IsSequential = S->getSCEVType() == scSequentialUMinExpr;
1232 Type *ResultTy = MinMax->getType();
1233 bool PrevSafeMode = SafeUDivMode;
1235 for (const SCEV *SCEVOp : reverse(MinMax->operands())) {
1236 bool MayShortCircuit =
1237 IsSequential && Ops.size() != MinMax->getNumOperands() - 1;
1238 SafeUDivMode = MayShortCircuit || PrevSafeMode;
1239 VPValue *OpV = expand(SCEVOp);
1240 SafeUDivMode = PrevSafeMode;
1241 if (MayShortCircuit)
1242 OpV = Builder.createFreeze(OpV, DL);
1243 Ops.push_back(OpV);
1244 }
1245 VPValue *Result = Ops.front();
1246 for (VPValue *Op : drop_begin(Ops)) {
1247 if (!ResultTy->isPointerTy()) {
1248 Result = Builder.createScalarIntrinsic(IntrinsicID, {Result, Op},
1249 ResultTy, DL);
1250 continue;
1251 }
1252 // The min/max intrinsics don't support pointer operands, so expand
1253 // pointer-typed min/max as cmp + select, matching SCEVExpander.
1254 VPValue *Cmp = Builder.createICmp(
1255 MinMaxIntrinsic::getPredicate(IntrinsicID), Result, Op, DL);
1256 Result = Builder.createSelect(Cmp, Result, Op, DL);
1257 Function &F = *Builder.getPlan().getIRFunction();
1258 if (MDNode *MD =
1260 cast<VPInstruction>(Result)->setMetadata(LLVMContext::MD_prof, MD);
1261 }
1262 return Result;
1263 }
1264 case scAddRecExpr: {
1265 auto *AR = cast<SCEVAddRecExpr>(S);
1266 VPlan &Plan = Builder.getPlan();
1267 BasicBlock *PH = cast<VPIRBasicBlock>(Plan.getEntry())->getIRBasicBlock();
1268 assert(SE.DT.dominates(AR->getLoop()->getHeader(), PH) &&
1269 "can only expand AddRecs for loops outside VPlan's scope");
1270
1271 Type *Ty = AR->getType();
1272 if (auto [LCSSAPhi, Diff] = SCEVExpander::findReusableLCSSAPhi(SE, AR, PH);
1273 LCSSAPhi) {
1274 VPValue *DiffV = expand(Diff);
1275 VPValue *BaseV = Plan.getOrAddLiveIn(LCSSAPhi);
1276 if (LCSSAPhi->getType()->isPointerTy()) {
1277 if (Ty->isPointerTy())
1278 return Builder.createPtrAdd(BaseV, DiffV, DL);
1279 BaseV = Builder.createScalarCast(Instruction::PtrToAddr, BaseV, Ty, DL);
1280 }
1281 return Builder.createAdd(BaseV, DiffV, DL);
1282 }
1283
1284 // Mirror SCEVExpander::visitAddRecExpr, but only expand the canonical IV
1285 // {0,+,1} and non-affine AddRecs to IR (which will be created outside the
1286 // scope of VPlan). The AddRec is then scaled and offset using
1287 // VPInstructions.
1288 const Loop *L = AR->getLoop();
1289 auto m_scev_CanonicalIV = // NOLINT
1291 if (!AR->isAffine() || match(AR, m_scev_CanonicalIV))
1293
1294 const SCEV *Step = AR->getStepRecurrence(SE);
1295 // {0,+,F} --> {0,+,1} * F
1296 if (AR->getStart()->isZero()) {
1297 const SCEV *CanIV =
1298 SE.getAddRecExpr(SE.getZero(Ty), SE.getOne(Ty), L, SCEV::FlagNone);
1299 return Builder.createOverflowingOp(
1300 Instruction::Mul, {expand(CanIV), expand(Step)},
1301 {SE.willNotOverflow(Instruction::Mul, /*Signed=*/false, CanIV, Step),
1302 SE.willNotOverflow(Instruction::Mul, /*Signed=*/true, CanIV, Step)},
1303 DL);
1304 }
1305
1306 // {X,+,F} --> X + {0,+,F}
1307 if (Ty->isPointerTy())
1308 return expandAsPtrAdd(AR);
1309 VPValue *Start = expand(AR->getStart());
1310 VPValue *Rest = expand(SE.getAddRecExpr(SE.getZero(Ty), Step, L,
1311 AR->getNoWrapFlags(SCEV::FlagNW)));
1312 return Builder.createAdd(Start, Rest, DL, "",
1313 {AR->hasNoUnsignedWrap(), false});
1314 }
1315 case scCouldNotCompute:
1316 llvm_unreachable("Attempt to expand a SCEVCouldNotCompute");
1317 }
1318 llvm_unreachable("Unknown SCEV kind!");
1319}
1320
1322 // Do remove conditional assume instructions as their conditions may be
1323 // flattened.
1324 auto *RepR = dyn_cast<VPReplicateRecipe>(&R);
1325 bool IsConditionalAssume = RepR && RepR->isPredicated() &&
1327 if (IsConditionalAssume)
1328 return true;
1329
1330 if (R.mayHaveSideEffects())
1331 return false;
1332
1333 // Forbid removing trip-count expressions.
1334 if (isa<VPExpandSCEVRecipe>(R) &&
1335 R.getVPSingleValue() == R.getParent()->getPlan()->getTripCount())
1336 return false;
1337
1338 // Recipe is dead if no user keeps the recipe alive.
1339 return all_of(R.definedValues(), [](VPValue *V) { return V->user_empty(); });
1340}
1341
1343 SmallVector<VPValue *> WorkList;
1345 WorkList.push_back(V);
1346
1347 while (!WorkList.empty()) {
1348 VPValue *Cur = WorkList.pop_back_val();
1349 if (!Seen.insert(Cur).second)
1350 continue;
1351 VPRecipeBase *R = Cur->getDefiningRecipe();
1352 if (!R)
1353 continue;
1354 if (!isDeadRecipe(*R))
1355 continue;
1356 append_range(WorkList, R->operands());
1357 R->eraseFromParent();
1358 }
1359}
1360
1363 for (unsigned I = 0; I != Users.size(); ++I) {
1365 for (VPValue *V : Cur->definedValues())
1366 Users.insert_range(V->users());
1367 }
1368 return Users.takeVector();
1369}
1370
1371/// Returns \p Num / \p Denom as a BranchProbability, clamped so a ratio that is
1372/// neither zero nor one does not round to zero or one. BlockFrequencyInfo also
1373/// keeps a zero-weight edge distinguishable from an unreachable one.
1375 uint64_t Denom) {
1377 if (Num == 0 || Num == Denom)
1378 return P;
1379 return BranchProbability::getRaw(std::clamp(
1380 P.getNumerator(), 1u, BranchProbability::getDenominator() - 1));
1381}
1382
1388
1389/// Returns the probability of each successor edge of \p VPBB, computed via
1390/// BranchProbabilityInfo::getEdgeProbabilitiesFromWeights from the branch
1391/// weights recorded on its terminator, or std::nullopt if not available.
1392static std::optional<SmallVector<BranchProbability>>
1394 // With a single successor the edge is always taken and needs no weights.
1395 if (VPBB->getSingleSuccessor())
1397
1398 SmallVector<uint32_t> Weights;
1400 if (!Term || !extractBranchWeights(Term->getBranchWeights(), Weights) ||
1401 Weights.size() != VPBB->getNumSuccessors())
1402 return std::nullopt;
1404}
1405
1408 using BFIBase = BlockFrequencyInfoImplBase;
1409 assert(!Blocks.empty() && "expected at least the header block");
1410 // Distribute the header's frequency using BFI. Nodes for blocks are numbered
1411 // in reverse post-order. Edges leaving Blocks, i.e. a plain CFG's edges to
1412 // the middle block or to an exit block, exit to a node outside the loop.
1413 BFIBase BFI;
1414 BFIBase::BlockNode Header(0), Outside(Blocks.size());
1415 BFIBase::LoopData &Loop = BFI.Loops.emplace_back(nullptr, Header);
1417 for (auto [Idx, VPBB] : enumerate(Blocks)) {
1418 Nodes[VPBB] = BFIBase::BlockNode(Idx);
1419 BFI.Working.emplace_back(BFIBase::BlockNode(Idx)).Loop = &Loop;
1420 }
1421 BFI.Working.emplace_back(Outside);
1422 BFI.Working[Header.Index].getMass() = BFIBase::BlockMass::getFull();
1423
1424 // Keep track nodes reached via an edge without branch weighs or with
1425 // estimated ones
1426 SmallVector<bool> IsUnknown(Blocks.size()), IsEstimated(Blocks.size());
1427 for (auto [Idx, VPBB] : enumerate(Blocks)) {
1428 BFIBase::BlockNode Node(Idx);
1429 auto Probs = getSuccessorProbabilities(VPBB);
1430 auto *Term = dyn_cast_if_present<VPInstruction>(VPBB->getTerminator());
1431 bool TermIsEstimated = Term && Term->hasEstimatedBranchWeights();
1432 BFIBase::Distribution Dist;
1433 for (auto [SuccIdx, Succ] : enumerate(VPBB->getSuccessors())) {
1434 BFIBase::BlockNode SuccNode = Nodes.lookup_or(Succ, Outside);
1435 if (SuccNode != Header && SuccNode != Outside) {
1436 IsUnknown[SuccNode.Index] |= IsUnknown[Idx] || !Probs;
1437 IsEstimated[SuccNode.Index] |= IsEstimated[Idx] || TermIsEstimated;
1438 }
1439 if (Probs)
1440 BFI.addToDist(Dist, &Loop, Node, SuccNode,
1441 getWeightFromBranchProb((*Probs)[SuccIdx]));
1442 }
1443 if (Probs)
1444 BFI.distributeMass(Node, &Loop, Dist);
1445 }
1446
1447 // Round frequencies up to at least 1, so all edges are reached with a
1448 // non-zero frequency, to distinguish rarely executed blocks from unreachable
1449 // ones. blocks distinguishable from unreachable ones.
1451 Frequencies;
1452 for (auto [Idx, VPBB] : enumerate(Blocks)) {
1453 std::optional<VPExecutionFrequency> &Freq = Frequencies[VPBB];
1454 if (IsUnknown[Idx])
1455 continue;
1456 uint64_t Mass = BFI.Working[Idx].getMass().getMass();
1457 Freq.emplace(BlockFrequency(std::max<uint64_t>(Mass, 1)), IsEstimated[Idx]);
1458 }
1459 return Frequencies;
1460}
1461
1464 const DataLayout &DL) {
1465 auto OpcodeOrIID = getOpcodeOrIntrinsicID(&R);
1466 if (!OpcodeOrIID)
1467 return nullptr;
1468
1470 for (VPValue *Op : Operands) {
1471 VPValue *Candidate = Op;
1472 match(Op, m_Broadcast(m_VPValue(Candidate)));
1473 if (!match(Candidate, m_LiveIn()))
1474 return nullptr;
1475 Value *V = Candidate->getUnderlyingValue();
1476 if (!V)
1477 return nullptr;
1478 Ops.push_back(V);
1479 }
1480
1481 VPlan &Plan = *R.getParent()->getPlan();
1482 auto FoldToIRValue = [&]() -> Value * {
1483 InstSimplifyFolder Folder(DL);
1484 if (OpcodeOrIID->first) {
1485 // VPInstructions store the called intrinsic as last operand.
1486 if (isa<VPInstruction>(R))
1487 Ops.pop_back();
1488
1489 auto *RFlags = dyn_cast<VPRecipeWithIRFlags>(&R);
1490 return Folder.FoldIntrinsic(OpcodeOrIID->second, Ops, R.getScalarType(),
1491 RFlags ? RFlags->getFastMathFlagsOrNone()
1492 : FastMathFlags());
1493 }
1494 unsigned Opcode = OpcodeOrIID->second;
1495 if (Instruction::isBinaryOp(Opcode))
1496 return Folder.FoldBinOp(static_cast<Instruction::BinaryOps>(Opcode),
1497 Ops[0], Ops[1]);
1498 if (Instruction::isCast(Opcode))
1499 return Folder.FoldCast(static_cast<Instruction::CastOps>(Opcode), Ops[0],
1500 R.getVPSingleValue()->getScalarType());
1501 switch (Opcode) {
1502 case VPInstruction::Not:
1503 return Folder.FoldBinOp(Instruction::BinaryOps::Xor, Ops[0],
1505 case Instruction::Select:
1506 return Folder.FoldSelect(Ops[0], Ops[1], Ops[2]);
1507 case Instruction::ICmp:
1508 case Instruction::FCmp:
1509 return Folder.FoldCmp(cast<VPRecipeWithIRFlags>(R).getPredicate(), Ops[0],
1510 Ops[1]);
1511 case Instruction::GetElementPtr: {
1512 auto &RFlags = cast<VPRecipeWithIRFlags>(R);
1513 auto *GEP = cast<GetElementPtrInst>(RFlags.getUnderlyingInstr());
1514 return Folder.FoldGEP(DL, GEP->getSourceElementType(), Ops[0],
1515 drop_begin(Ops), RFlags.getGEPNoWrapFlags());
1516 }
1519 return Folder.FoldGEP(DL, IntegerType::getInt8Ty(Plan.getContext()),
1520 Ops[0], Ops[1],
1521 cast<VPRecipeWithIRFlags>(R).getGEPNoWrapFlags());
1522 // An extract of a live-in is an extract of a broadcast, so return the
1523 // broadcasted element.
1524 case Instruction::ExtractElement:
1525 assert(!Ops[0]->getType()->isVectorTy() && "Live-ins should be scalar");
1526 return Ops[0];
1529 uint64_t Multiplier = 1;
1530 if (Opcode == VPInstruction::WideActiveLaneMask) {
1531 // Optimizing WideALM can only happen after the Plan is unrolled.
1532 if (!Plan.isUnrolled())
1533 return nullptr;
1534
1535 Multiplier = cast<ConstantInt>(Ops[2])->getZExtValue();
1536
1537 // TODO: We can't fold if any users require a wide value.
1538 if (Multiplier != 1 &&
1539 !all_of(R.users(), match_fn(m_ExtractVectorForPart())))
1540 return nullptr;
1541
1542 Ops.pop_back();
1543 }
1544
1545 // We rely on the fact that different VPlans are created for the
1546 // fixed-vector and scalable-vector cases.
1547 ElementCount MaxVF =
1549 Multiplier;
1550
1551 Type *I1Ty = IntegerType::getInt1Ty(Plan.getContext());
1552 if (auto *C = dyn_cast_if_present<Constant>(Folder.FoldIntrinsic(
1553 Intrinsic::get_active_lane_mask, Ops,
1554 VectorType::get(I1Ty, MaxVF), {}, Plan.getIRFunction()))) {
1555 // We cannot handle vector constants that are not all-true or all-false,
1556 // because they would not be collapsable to a scalar constant, that
1557 // would be necessary for live-in simplification.
1558 if (C->isOneValue())
1559 return ConstantInt::getTrue(I1Ty);
1560 if (C->isNullValue())
1561 return ConstantInt::getFalse(I1Ty);
1562 }
1563 }
1564 }
1565 return nullptr;
1566 };
1567
1568 if (Value *V = FoldToIRValue())
1569 return Plan.getOrAddLiveIn(V);
1570 return nullptr;
1571}
1572
1574 VPlan &Plan, function_ref<VPValue *(VPValue *Op)> MatchPerm,
1577 vp_depth_first_deep(Plan.getEntry()))) {
1578 for (VPSingleDefRecipe &Def :
1580 if (!isElementwise(&Def))
1581 continue;
1582
1583 // At least one of the ops must be a permutation.
1584 if (none_of(Def.operands(), MatchPerm))
1585 continue;
1586
1587 // All operands must be a single-use permutation or a live in (splat).
1588 if (!all_of(Def.operands(), [&MatchPerm](VPValue *Op) {
1589 return (Op->hasOneUse() && MatchPerm(Op)) || match(Op, m_LiveIn());
1590 }))
1591 continue;
1592
1593 // Remove the inner permutations.
1594 for (unsigned I = 0, E = Def.getNumOperands(); I != E; ++I)
1595 if (VPValue *X = MatchPerm(Def.getOperand(I)))
1596 Def.setOperand(I, X);
1597
1598 VPSingleDefRecipe *Res = BuildPerm(&Def);
1599 Res->insertAfter(&Def);
1600 Def.replaceUsesWithIf(Res, not_equal_to(Res));
1601 }
1602 }
1603}
1604
1605// Implements the algorithm described in "Simple and Efficient Construction of
1606// Static Single Assignment Form" by Braun et al.
1609 assert(!Defs.empty() && "Defs shouldn't be empty");
1610 assert(
1612 "VPBB isn't reachable from entry");
1613 if (VPValue *Def = Defs.lookup(VPBB))
1614 return Def;
1615 // If the entry block is reached and there's still no def, then Defs is
1616 // missing a definition that covers this path.
1617 assert(VPBB->getNumPredecessors() && "Not all paths have def");
1618
1619 if (VPBlockBase *Pred = VPBB->getSinglePredecessor())
1620 return reconstructSSA(cast<VPBasicBlock>(Pred), Defs);
1621
1622 // Multiple predecessors, create a join.
1623 Type *Ty = Defs.begin()->second->getScalarType();
1624 VPPhi *Phi = VPBuilder(VPBB->getFirstNonPhi())
1625 .createScalarPhi({}, DebugLoc::getUnknown(), "", {}, Ty);
1626 Defs[VPBB] = Phi;
1627 for (auto *Pred : VPBB->predecessors())
1628 Phi->addIncoming(reconstructSSA(cast<VPBasicBlock>(Pred), Defs));
1629
1630 // Fold away trivial phis.
1631 // TODO: Remove phi users which have become trivial too.
1632 if (all_equal(Phi->incoming_values())) {
1633 VPValue *Common = Phi->getIncomingValue(0);
1634 Phi->replaceAllUsesWith(Common);
1635 for (auto &[_, V] : Defs)
1636 if (V == Phi)
1637 V = Common;
1638 Defs[VPBB] = Common;
1639 Phi->eraseFromParent();
1640 return Common;
1641 }
1642
1643 return Phi;
1644}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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 F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
#define P(N)
This file contains the declarations for profiling metadata utility functions.
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 dominatesInsertPoint(const VPValue *V, const VPBuilder &Builder)
Returns true if V dominates the insert point of Builder.
static BranchProbability getBranchProbabilityKeepingPartial(uint64_t Num, uint64_t Denom)
Returns Num / Denom as a BranchProbability, clamped so a ratio that is neither zero nor one does not ...
static std::optional< SmallVector< BranchProbability > > getSuccessorProbabilities(const VPBasicBlock *VPBB)
Returns the probability of each successor edge of VPBB, computed via BranchProbabilityInfo::getEdgePr...
static std::pair< const SCEV *, const SCEV * > splitInvariantSum(const SCEVAddExpr *S, const Loop *L, ScalarEvolution &SE)
Returns the sums of the operands of S invariant in L and of the remaining operands,...
static bool isUniformAcrossVFsAndUFsImpl(const VPValue *V, function_ref< void(VPUser::const_operand_range)> AddToWorklist)
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 ...
Value * RHS
Value * LHS
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
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
LLVM Basic Block Representation.
Definition BasicBlock.h:61
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
Base class for BlockFrequencyInfoImpl.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
static LLVM_ABI SmallVector< BranchProbability > getEdgeProbabilitiesFromWeights(ArrayRef< uint32_t > Weights)
Returns the probabilities of edges with branch weights Weights.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
static constexpr BranchProbability getOne()
static uint32_t getDenominator()
static constexpr BranchProbability getRaw(uint32_t N)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
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:63
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getUnknown()
Definition DebugLoc.h:153
bool empty() const
Definition DenseMap.h:716
ValueT lookup_or(const_arg_type_t< KeyT > Val, U &&Default) const
Definition DenseMap.h:803
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
iterator begin()
Definition DenseMap.h:682
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_FpInduction
Floating point induction variable.
@ 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
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1087
Representation for a specific memory location.
ICmpInst::Predicate getPredicate() const
Returns the comparison predicate underlying the intrinsic.
PointerIntPair - This class implements a pair of a pointer and small integer.
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.
This node represents an addition of some number of SCEVs.
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 ...
static LLVM_ABI std::pair< PHINode *, const SCEV * > findReusableLCSSAPhi(ScalarEvolution &SE, SCEVUseT< const SCEVAddRecExpr * > S, const BasicBlock *InsertBB)
Find a phi in the exit block of S's loop, which must dominate InsertBB, such that S can be expanded i...
This node is a base class providing common functionality for n'ary operators.
ArrayRef< SCEVUse > operands() const
This class represents an analyzed expression in the program.
static constexpr auto FlagNSW
Type * getType() const
Return the LLVM type of this SCEV expression.
static constexpr auto FlagNone
SCEVTypes getSCEVType() const
static constexpr auto FlagNW
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 * 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 const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
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.
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 SCEVUse getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEVFlagsPair Flags)
Get an add recurrence expression for the specified loop.
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 SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
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 SCEVUse getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, 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 SCEVUse getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getPtrToAddrExpr(const SCEV *Op)
LLVM_ABI const SCEV * getSMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
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)
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void insert_range(Range &&R)
Definition SetVector.h:182
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
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.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
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:277
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4509
iterator end()
Definition VPlan.h:4550
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:225
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:603
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:79
VPRegionBlock * getParent()
Definition VPlan.h:177
iterator_range< VPBlockBase ** > predecessors()
Definition VPlan.h:210
size_t getNumSuccessors() const
Definition VPlan.h:227
size_t getNumPredecessors() const
Definition VPlan.h:228
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:212
VPlan * getPlan()
Definition VPlan.h:181
VPBlockBase * getSinglePredecessor() const
Definition VPlan.h:223
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:180
VPBlockBase * getSingleHierarchicalPredecessor()
Definition VPlan.h:253
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:217
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:201
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:460
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.
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.
A recipe for handling scalar conditional induction PHIs.
Definition VPlan.h:2971
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:567
A recipe for converting Current into Start + Current * Step.
Definition VPlan.h:4280
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
LLVM_ABI_FOR_TEST bool properlyDominates(const VPRecipeBase *A, const VPRecipeBase *B) const
Recipe to expand a SCEV expression.
Definition VPlan.h:4104
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2513
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2502
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4668
Class to record and manage LLVM IR flags.
Definition VPlan.h:667
static LLVM_ABI_FOR_TEST 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:1310
bool doesGenerateSingleScalar() const
Returns true if the recipe produces a single scalar value.
Definition VPlan.h:1596
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1410
unsigned getOpcode() const
Definition VPlan.h:1518
bool isVectorToScalar() const
Returns true if this VPInstruction produces a scalar value from a vector, e.g.
VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when control converges back from ...
Definition VPlan.h:3787
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:386
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:531
void insertAfter(VPRecipeBase *InsertPos)
Insert an unlinked Recipe into a basic block immediately after the specified Recipe.
A recipe for handling reduction phis.
Definition VPlan.h:2864
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4740
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4816
bool hasCanonicalIVNUW() const
Indicates if NUW is set for the canonical IV increment, for loop regions.
Definition VPlan.h:4904
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4860
VPValues are defined by a VPRegionBlock, like the canonical IV.
Definition VPlanValue.h:247
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3458
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:4341
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:589
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:212
bool isMaterialized() const
Returns true if this value has been materialized.
Definition VPlanValue.h:230
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:396
operand_range operands()
Definition VPlanValue.h:472
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:437
iterator_range< const_operand_iterator > const_operand_range
Definition VPlanValue.h:466
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:139
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:120
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
user_range users()
Definition VPlanValue.h:157
A recipe to compute a pointer to the last element of each part of a widened memory access for widened...
Definition VPlan.h:2307
A recipe to compute the pointers for widened memory accesses of SourceElementTy, with the Stride expr...
Definition VPlan.h:2387
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1889
A recipe for handling GEP instructions.
Definition VPlan.h:2247
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2571
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2617
A recipe for widened phis.
Definition VPlan.h:2751
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1822
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4927
LLVMContext & getContext() const
Definition VPlan.h:5124
VPBasicBlock * getEntry()
Definition VPlan.h:5019
iterator_range< SmallSetVector< ElementCount, 2 >::iterator > vectorFactors() const
Returns an iterator range over all VFs of the plan.
Definition VPlan.h:5157
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5122
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:5085
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:5200
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5226
bool isUnrolled() const
Returns true if the VPlan already has been unrolled, i.e.
Definition VPlan.h:5191
Function * getIRFunction() const
Definition VPlan.h:5132
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1058
unsigned getConcreteUF() const
Returns the concrete UF of the plan, after unrolling.
Definition VPlan.h:5178
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:5024
VPSymbolicValue & getUF()
Returns the UF of the vector loop region.
Definition VPlan.h:5119
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:5075
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:5115
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:217
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.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
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.
CastOperator_match< OpTy, Instruction::PtrToAddr > m_PtrToAddr(const OpTy &Op)
Matches PtrToAddr.
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::SDiv > m_SDiv(const LHS &L, const RHS &R)
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.
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
specificloop_ty m_SpecificLoop(const Loop *L)
cst_pred_ty< is_zero > m_scev_Zero()
Match an integer 0.
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.
RecipeTy * findSingleUser(VPValue *V, const MatchT &P)
Return the sole user of V matching pattern P, casting it to RecipeTy, or nullptr.
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::Broadcast, Op0_t > m_Broadcast(const Op0_t &Op0)
match_bind< VPInstruction > m_VPInstruction(VPInstruction *&V)
Match a VPInstruction, capturing if we match.
VPInstruction_match< VPInstruction::ExtractVectorForPart, Op_t... > m_ExtractVectorForPart(const Op_t &...Op)
void pullOutPermutationsImpl(VPlan &Plan, function_ref< VPValue *(VPValue *Op)> Perm, function_ref< VPSingleDefRecipe *(VPSingleDefRecipe *X)> Build)
Template-independent implementation for pullOutPermutations.
BranchProbability getExecutionProbability(BlockFrequency Freq)
Returns Freq as a BranchProbability, relative to the full mass.
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...
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...
std::optional< int64_t > getConstantStride(VPValue *Addr, Type *AccessTy, PredicatedScalarEvolution &PSE, const Loop *L)
If the pointer operand Addr of a memory access is an affine AddRec w.r.t.
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,...
LLVM_ABI_FOR_TEST VPValue * reconstructSSA(VPBasicBlock *VPBB, DenseMap< VPBasicBlock *, VPValue * > &Defs)
Insert phis to reconstruct SSA for a single value starting from VPBB.
bool onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used by all users.
Intrinsic::ID getIntrinsicID(const Ty *R)
Return the intrinsic ID underlying a call.
Definition VPlanUtils.h:103
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 by all users.
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.
DenseMap< const VPBasicBlock *, std::optional< VPExecutionFrequency > > computeExecutionFrequencies(ArrayRef< VPBasicBlock * > Blocks)
Computes for each block in Blocks, which must be in reverse post-order, the frequency with which it e...
VPScalarIVStepsRecipe * createScalarIVSteps(VPlan &Plan, InductionDescriptor::InductionKind Kind, Instruction::BinaryOps InductionOpcode, FPMathOperator *FPBinOp, Type *ResultTy, VPValue *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...
bool propagatesFirstLaneUse(const VPUser *U, const VPValue *Op)
Returns true if checking whether U uses the first lane of Op requires recursively checking Op's users...
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.
VPIRFlags getFlagsForInduction(const InductionDescriptor &ID, const VPPhi *PhiR)
Extracts and returns NoWrap flags from PhiR and fast-math flags from ID.
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 onlyScalarValuesOrLanesUsed(const VPValue *Def)
Returns true if only scalar values of Def are used by all users, either directly or by extracting a c...
bool onlyScalarValuesUsed(const VPValue *Def)
Returns true if only scalar values of Def are used by all users.
LLVM_ABI_FOR_TEST bool isUniformAcrossVFsAndUFs(const VPValue *V)
Checks if V is uniform across all VF lanes and UF parts.
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, bool ExpandInIR=false)
Get or create a VPValue that corresponds to the expansion of Expr.
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...
LLVM_ABI_FOR_TEST 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.
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:316
@ Offset
Definition DWP.cpp:577
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
Definition STLExtras.h:2196
void stable_sort(R &&Range)
Definition STLExtras.h:2132
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:1781
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:1755
uint32_t getWeightFromBranchProb(const BranchProbability Prob)
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:856
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
VPBuilderBase<> VPBuilder
Definition VPlan.h:65
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
SCEVUseT< const SCEV * > SCEVUse
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
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:649
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:286
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:2189
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
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:1762
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:408
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
bool hasIrregularType(Type *Ty, const DataLayout &DL)
A helper function that returns true if the given type is irregular.
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:1769
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...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
LLVM_ABI MDNode * getExplicitlyUnknownBranchWeightsIfProfiled(Function &F, StringRef PassName)
Returns a metadata node containing unknown branch weights if the function has an entry count,...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2104
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
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:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
LLVM_ABI std::optional< int64_t > getStrideFromAddRec(const SCEVAddRecExpr *AR, const Loop *Lp, Type *AccessTy, Value *Ptr, PredicatedScalarEvolution &PSE)
If AR is an affine AddRec for Lp with a constant step, return the step in units of AccessTy's allocat...
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
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:274
A recipe for widening load operations with vector-predication intrinsics, using the address to load f...
Definition VPlan.h:3942
A recipe for widening load operations, using the address to load from and an optional mask.
Definition VPlan.h:3887