159#define LV_NAME "loop-vectorize"
160#define DEBUG_TYPE LV_NAME
170 "llvm.loop.vectorize.followup_vectorized";
172 "llvm.loop.vectorize.followup_epilogue";
175STATISTIC(LoopsVectorized,
"Number of loops vectorized");
176STATISTIC(LoopsAnalyzed,
"Number of loops analyzed for vectorization");
177STATISTIC(LoopsEpilogueVectorized,
"Number of epilogues vectorized");
181 cl::desc(
"Enable vectorization of epilogue loops."));
185 cl::desc(
"When epilogue vectorization is enabled, and a value greater than "
186 "1 is specified, forces the given VF for all applicable epilogue "
190 "epilogue-vectorization-minimum-VF",
cl::Hidden,
191 cl::desc(
"Only loops with vectorization factor equal to or larger than "
192 "the specified value are considered for epilogue vectorization."));
198 cl::desc(
"Loops with a constant trip count that is smaller than this "
199 "value are vectorized only if no scalar iteration overheads "
204 cl::desc(
"The maximum allowed number of runtime memory checks"));
220 "prefer-predicate-over-epilogue",
223 cl::desc(
"Tail-folding and predication preferences over creating a scalar "
227 "Don't tail-predicate loops, create scalar epilogue"),
229 "predicate-else-scalar-epilogue",
230 "prefer tail-folding, create scalar epilogue if tail "
233 "predicate-dont-vectorize",
234 "prefers tail-folding, don't attempt vectorization if "
235 "tail-folding fails.")));
238 "force-tail-folding-style",
cl::desc(
"Force the tail folding style"),
241 clEnumValN(TailFoldingStyle::None,
"none",
"Disable tail folding"),
243 TailFoldingStyle::Data,
"data",
244 "Create lane mask for data only, using active.lane.mask intrinsic"),
245 clEnumValN(TailFoldingStyle::DataWithoutLaneMask,
246 "data-without-lane-mask",
247 "Create lane mask with compare/stepvector"),
248 clEnumValN(TailFoldingStyle::DataAndControlFlow,
"data-and-control",
249 "Create lane mask using active.lane.mask intrinsic, and use "
250 "it for both data and control flow"),
251 clEnumValN(TailFoldingStyle::DataAndControlFlowWithoutRuntimeCheck,
252 "data-and-control-without-rt-check",
253 "Similar to data-and-control, but remove the runtime check"),
254 clEnumValN(TailFoldingStyle::DataWithEVL,
"data-with-evl",
255 "Use predicated EVL instructions for tail folding. If EVL "
256 "is unsupported, fallback to data-without-lane-mask.")));
260 cl::desc(
"Maximize bandwidth when selecting vectorization factor which "
261 "will be determined by the smallest type in loop."));
265 cl::desc(
"Enable vectorization on interleaved memory accesses in a loop"));
271 cl::desc(
"Enable vectorization on masked interleaved memory accesses in a loop"));
275 cl::desc(
"A flag that overrides the target's number of scalar registers."));
279 cl::desc(
"A flag that overrides the target's number of vector registers."));
283 cl::desc(
"A flag that overrides the target's max interleave factor for "
288 cl::desc(
"A flag that overrides the target's max interleave factor for "
289 "vectorized loops."));
293 cl::desc(
"A flag that overrides the target's expected cost for "
294 "an instruction to a single constant value. Mostly "
295 "useful for getting consistent testing."));
300 "Pretend that scalable vectors are supported, even if the target does "
301 "not support them. This flag should only be used for testing."));
306 "The cost of a loop that is considered 'small' by the interleaver."));
310 cl::desc(
"Enable the use of the block frequency analysis to access PGO "
311 "heuristics minimizing code growth in cold regions and being more "
312 "aggressive in hot regions."));
318 "Enable runtime interleaving until load/store ports are saturated"));
323 cl::desc(
"Max number of stores to be predicated behind an if."));
327 cl::desc(
"Count the induction variable only once when interleaving"));
331 cl::desc(
"Enable if predication of stores during vectorization."));
335 cl::desc(
"The maximum interleave count to use when interleaving a scalar "
336 "reduction in a nested loop."));
341 cl::desc(
"Prefer in-loop vector reductions, "
342 "overriding the targets preference."));
346 cl::desc(
"Enable the vectorisation of loops with in-order (strict) "
352 "Prefer predicating a reduction operation over an after loop select."));
357 cl::desc(
"Enable VPlan-native vectorization path with "
358 "support for outer loop vectorization."));
362#ifdef EXPENSIVE_CHECKS
368 cl::desc(
"Verfiy VPlans after VPlan transforms."));
378 "Build VPlan for every supported loop nest in the function and bail "
379 "out right after the build (stress test the VPlan H-CFG construction "
380 "in the VPlan-native vectorization path)."));
384 cl::desc(
"Enable loop interleaving in Loop vectorization passes"));
387 cl::desc(
"Run the Loop vectorization passes"));
390 "force-widen-divrem-via-safe-divisor",
cl::Hidden,
392 "Override cost based safe divisor widening for div/rem instructions"));
395 "vectorizer-maximize-bandwidth-for-vector-calls",
cl::init(
true),
397 cl::desc(
"Try wider VFs if they enable the use of vector variants"));
402 "Enable vectorization of early exit loops with uncountable exits."));
421 return DL.getTypeAllocSizeInBits(Ty) !=
DL.getTypeSizeInBits(Ty);
430static std::optional<unsigned>
432 bool CanUseConstantMax =
true) {
442 if (!CanUseConstantMax)
454class GeneratedRTChecks;
550 "Trying to access AdditionalBypassBlock but it has not been set");
585 Value *MainVectorTripCount);
719 "A high UF for the epilogue loop is likely not beneficial.");
741 EPI.MainLoopVF,
EPI.MainLoopVF,
EPI.MainLoopUF, LVL,
836 if (
I->getDebugLoc() != Empty)
837 return I->getDebugLoc();
839 for (
Use &
Op :
I->operands()) {
841 if (OpInst->getDebugLoc() != Empty)
842 return OpInst->getDebugLoc();
845 return I->getDebugLoc();
854 dbgs() <<
"LV: " << Prefix << DebugMsg;
876 if (
I &&
I->getDebugLoc())
877 DL =
I->getDebugLoc();
895 return B.CreateElementCount(Ty, VF);
906 <<
"loop not vectorized: " << OREMsg);
929 "Vectorizing: ", TheLoop->
isInnermost() ?
"innermost loop" :
"outer loop",
935 <<
"vectorized " << LoopType <<
"loop (vectorization width: "
937 <<
", interleaved count: " <<
ore::NV(
"InterleaveCount", IC) <<
")";
994 initializeVScaleForTuning();
1086 "Profitable to scalarize relevant only for VF > 1.");
1089 "cost-model should not be used for outer loops (in VPlan-native path)");
1091 auto Scalars = InstsToScalarize.find(VF);
1092 assert(Scalars != InstsToScalarize.end() &&
1093 "VF not yet analyzed for scalarization profitability");
1094 return Scalars->second.contains(
I);
1101 "cost-model should not be used for outer loops (in VPlan-native path)");
1105 if (isa<PseudoProbeInst>(
I))
1111 auto UniformsPerVF = Uniforms.find(VF);
1112 assert(UniformsPerVF != Uniforms.end() &&
1113 "VF not yet analyzed for uniformity");
1114 return UniformsPerVF->second.count(
I);
1121 "cost-model should not be used for outer loops (in VPlan-native path)");
1125 auto ScalarsPerVF = Scalars.find(VF);
1126 assert(ScalarsPerVF != Scalars.end() &&
1127 "Scalar values are not calculated for VF");
1128 return ScalarsPerVF->second.count(
I);
1134 return VF.
isVector() && MinBWs.contains(
I) &&
1156 WideningDecisions[std::make_pair(
I, VF)] = std::make_pair(W,
Cost);
1178 WideningDecisions[std::make_pair(
I, VF)] =
1179 std::make_pair(W, InsertPosCost);
1181 WideningDecisions[std::make_pair(
I, VF)] =
1182 std::make_pair(W, OtherMemberCost);
1194 "cost-model should not be used for outer loops (in VPlan-native path)");
1196 std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(
I, VF);
1197 auto Itr = WideningDecisions.
find(InstOnVF);
1198 if (Itr == WideningDecisions.
end())
1200 return Itr->second.first;
1207 std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(
I, VF);
1209 "The cost is not calculated");
1210 return WideningDecisions[InstOnVF].second;
1223 std::optional<unsigned> MaskPos,
1226 CallWideningDecisions[std::make_pair(CI, VF)] = {Kind, Variant, IID,
1233 return CallWideningDecisions.
at(std::make_pair(CI, VF));
1241 auto *Trunc = dyn_cast<TruncInst>(
I);
1254 Value *
Op = Trunc->getOperand(0);
1274 if (VF.
isScalar() || Uniforms.contains(VF))
1277 collectLoopUniforms(VF);
1279 collectLoopScalars(VF);
1299 bool LI = isa<LoadInst>(V);
1300 bool SI = isa<StoreInst>(V);
1315 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1316 return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1327 return ScalarCost < SafeDivisorCost;
1351 std::pair<InstructionCost, InstructionCost>
1379 LLVM_DEBUG(
dbgs() <<
"LV: Loop does not require scalar epilogue\n");
1386 LLVM_DEBUG(
dbgs() <<
"LV: Loop requires scalar epilogue: not exiting "
1387 "from latch block\n");
1392 "interleaved group requires scalar epilogue\n");
1395 LLVM_DEBUG(
dbgs() <<
"LV: Loop does not require scalar epilogue\n");
1404 auto RequiresScalarEpilogue = [
this](
ElementCount VF) {
1407 bool IsRequired =
all_of(
Range, RequiresScalarEpilogue);
1409 (IsRequired ||
none_of(
Range, RequiresScalarEpilogue)) &&
1410 "all VFs in range must agree on whether a scalar epilogue is required");
1422 if (!ChosenTailFoldingStyle)
1424 return IVUpdateMayOverflow ? ChosenTailFoldingStyle->first
1425 : ChosenTailFoldingStyle->second;
1433 assert(!ChosenTailFoldingStyle &&
"Tail folding must not be selected yet.");
1435 ChosenTailFoldingStyle =
1441 ChosenTailFoldingStyle = std::make_pair(
1457 bool EVLIsLegal = UserIC <= 1 && IsScalableVF &&
1465 ChosenTailFoldingStyle =
1470 <<
"LV: Preference for VP intrinsics indicated. Will "
1471 "not try to generate VP Intrinsics "
1473 ?
"since interleave count specified is greater than 1.\n"
1474 :
"due to non-interleaving reasons.\n"));
1509 return InLoopReductions.contains(Phi);
1536 WideningDecisions.
clear();
1537 CallWideningDecisions.
clear();
1556 const unsigned IC)
const;
1566 Type *VectorTy)
const;
1576 unsigned NumPredStores = 0;
1580 std::optional<unsigned> VScaleForTuning;
1585 void initializeVScaleForTuning() {
1590 auto Max = Attr.getVScaleRangeMax();
1591 if (Max && Min == Max) {
1592 VScaleForTuning = Max;
1607 bool FoldTailByMasking);
1612 ElementCount getMaximizedVFForTarget(
unsigned MaxTripCount,
1613 unsigned SmallestType,
1614 unsigned WidestType,
1616 bool FoldTailByMasking);
1620 bool isScalableVectorizationAllowed();
1624 ElementCount getMaxLegalScalableVF(
unsigned MaxSafeElements);
1670 PredicatedBBsAfterVectorization;
1683 std::optional<std::pair<TailFoldingStyle, TailFoldingStyle>>
1684 ChosenTailFoldingStyle;
1687 std::optional<bool> IsScalableVectorizationAllowed;
1693 std::optional<unsigned> MaxSafeElements;
1727 ScalarCostsTy &ScalarCosts,
1753 std::pair<InstWidening, InstructionCost>>;
1755 DecisionList WideningDecisions;
1757 using CallDecisionList =
1760 CallDecisionList CallWideningDecisions;
1784 Ops, [
this, VF](
Value *V) {
return this->needsExtract(V, VF); }));
1845class GeneratedRTChecks {
1851 Value *SCEVCheckCond =
nullptr;
1859 Value *MemRuntimeCheckCond =
nullptr;
1868 bool CostTooHigh =
false;
1869 const bool AddBranchWeights;
1871 Loop *OuterLoop =
nullptr;
1883 : DT(DT), LI(LI),
TTI(
TTI), SCEVExp(*PSE.
getSE(),
DL,
"scev.check"),
1884 MemCheckExp(*PSE.
getSE(),
DL,
"scev.check"),
1885 AddBranchWeights(AddBranchWeights), PSE(PSE), CostKind(CostKind) {}
1913 nullptr,
"vector.scevcheck");
1920 if (RtPtrChecking.Need) {
1921 auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1922 MemCheckBlock =
SplitBlock(Pred, Pred->getTerminator(), DT, LI,
nullptr,
1925 auto DiffChecks = RtPtrChecking.getDiffChecks();
1927 Value *RuntimeVF =
nullptr;
1932 RuntimeVF = getRuntimeVF(B, B.getIntNTy(Bits), VF);
1938 MemCheckBlock->
getTerminator(), L, RtPtrChecking.getChecks(),
1941 assert(MemRuntimeCheckCond &&
1942 "no RT checks generated although RtPtrChecking "
1943 "claimed checks are required");
1946 if (!MemCheckBlock && !SCEVCheckBlock)
1956 if (SCEVCheckBlock) {
1962 if (MemCheckBlock) {
1970 if (MemCheckBlock) {
1974 if (SCEVCheckBlock) {
1980 OuterLoop =
L->getParentLoop();
1984 if (SCEVCheckBlock || MemCheckBlock)
1997 if (SCEVCheckBlock->getTerminator() == &
I)
2003 if (MemCheckBlock) {
2006 if (MemCheckBlock->getTerminator() == &
I)
2028 unsigned BestTripCount = 2;
2032 PSE, OuterLoop,
false))
2033 BestTripCount = *EstimatedTC;
2035 BestTripCount = std::max(BestTripCount, 1U);
2039 NewMemCheckCost = std::max(*NewMemCheckCost.
getValue(),
2042 if (BestTripCount > 1)
2044 <<
"We expect runtime memory checks to be hoisted "
2045 <<
"out of the outer loop. Cost reduced from "
2046 << MemCheckCost <<
" to " << NewMemCheckCost <<
'\n');
2048 MemCheckCost = NewMemCheckCost;
2052 RTCheckCost += MemCheckCost;
2055 if (SCEVCheckBlock || MemCheckBlock)
2056 LLVM_DEBUG(
dbgs() <<
"Total cost of runtime checks: " << RTCheckCost
2064 ~GeneratedRTChecks() {
2068 SCEVCleaner.markResultUsed();
2070 if (!MemRuntimeCheckCond)
2071 MemCheckCleaner.markResultUsed();
2073 if (MemRuntimeCheckCond) {
2074 auto &SE = *MemCheckExp.
getSE();
2081 I.eraseFromParent();
2084 MemCheckCleaner.cleanup();
2085 SCEVCleaner.cleanup();
2088 SCEVCheckBlock->eraseFromParent();
2089 if (MemRuntimeCheckCond)
2090 MemCheckBlock->eraseFromParent();
2103 SCEVCheckCond =
nullptr;
2104 if (
auto *
C = dyn_cast<ConstantInt>(
Cond))
2115 SCEVCheckBlock->getTerminator()->eraseFromParent();
2116 SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2117 Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2124 if (AddBranchWeights)
2127 return SCEVCheckBlock;
2136 if (!MemRuntimeCheckCond)
2145 MemCheckBlock->moveBefore(LoopVectorPreHeader);
2152 if (AddBranchWeights) {
2156 MemCheckBlock->getTerminator()->setDebugLoc(
2157 Pred->getTerminator()->getDebugLoc());
2160 MemRuntimeCheckCond =
nullptr;
2161 return MemCheckBlock;
2167 return Style == TailFoldingStyle::Data ||
2168 Style == TailFoldingStyle::DataAndControlFlow ||
2169 Style == TailFoldingStyle::DataAndControlFlowWithoutRuntimeCheck;
2173 return Style == TailFoldingStyle::DataAndControlFlow ||
2174 Style == TailFoldingStyle::DataAndControlFlowWithoutRuntimeCheck;
2204 LLVM_DEBUG(
dbgs() <<
"LV: Loop hints prevent outer loop vectorization.\n");
2210 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: Interleave is not supported for "
2230 if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2240 for (
Loop *InnerL : L)
2262 ?
B.CreateSExtOrTrunc(Index, StepTy)
2263 :
B.CreateCast(Instruction::SIToFP, Index, StepTy);
2264 if (CastedIndex != Index) {
2266 Index = CastedIndex;
2276 assert(
X->getType() ==
Y->getType() &&
"Types don't match!");
2277 if (
auto *CX = dyn_cast<ConstantInt>(
X))
2280 if (
auto *CY = dyn_cast<ConstantInt>(
Y))
2283 return B.CreateAdd(
X,
Y);
2289 assert(
X->getType()->getScalarType() ==
Y->getType() &&
2290 "Types don't match!");
2291 if (
auto *CX = dyn_cast<ConstantInt>(
X))
2294 if (
auto *CY = dyn_cast<ConstantInt>(
Y))
2297 VectorType *XVTy = dyn_cast<VectorType>(
X->getType());
2298 if (XVTy && !isa<VectorType>(
Y->getType()))
2299 Y =
B.CreateVectorSplat(XVTy->getElementCount(),
Y);
2300 return B.CreateMul(
X,
Y);
2303 switch (InductionKind) {
2305 assert(!isa<VectorType>(Index->getType()) &&
2306 "Vector indices not supported for integer inductions yet");
2308 "Index type does not match StartValue type");
2309 if (isa<ConstantInt>(Step) && cast<ConstantInt>(Step)->isMinusOne())
2310 return B.CreateSub(StartValue, Index);
2315 return B.CreatePtrAdd(StartValue,
CreateMul(Index, Step));
2317 assert(!isa<VectorType>(Index->getType()) &&
2318 "Vector indices not supported for FP inductions yet");
2321 (InductionBinOp->
getOpcode() == Instruction::FAdd ||
2322 InductionBinOp->
getOpcode() == Instruction::FSub) &&
2323 "Original bin op should be defined for FP induction");
2325 Value *MulExp =
B.CreateFMul(Step, Index);
2326 return B.CreateBinOp(InductionBinOp->
getOpcode(), StartValue, MulExp,
2340 if (
F.hasFnAttribute(Attribute::VScaleRange))
2341 return F.getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
2343 return std::nullopt;
2352 ElementCount VF, std::optional<unsigned> UF = std::nullopt) {
2354 unsigned MaxUF = UF ? *UF :
Cost->TTI.getMaxInterleaveFactor(VF);
2356 Type *IdxTy =
Cost->Legal->getWidestInductionType();
2357 APInt MaxUIntTripCount = cast<IntegerType>(IdxTy)->getMask();
2362 if (
unsigned TC =
Cost->PSE.getSmallConstantMaxTripCount()) {
2365 std::optional<unsigned> MaxVScale =
2369 MaxVF *= *MaxVScale;
2372 return (MaxUIntTripCount - TC).ugt(MaxVF * MaxUF);
2393 assert(!Instr->getType()->isAggregateType() &&
"Can't handle vectors");
2396 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2400 Cloned->
setName(Instr->getName() +
".cloned");
2405 "inferred type and type from generated instructions do not match");
2411 if (
auto DL = Instr->getDebugLoc())
2417 auto InputLane = Lane;
2428 State.
set(RepRecipe, Cloned, Lane);
2431 if (
auto *
II = dyn_cast<AssumeInst>(Cloned))
2436 bool IfPredicateInstr = Parent ? Parent->
isReplicator() :
false;
2440 [](
VPValue *
Op) { return Op->isDefinedOutsideLoopRegions(); })) &&
2441 "Expected a recipe is either within a region or all of its operands "
2442 "are defined outside the vectorized region.");
2443 if (IfPredicateInstr)
2467 if (
Cost->foldTailByMasking()) {
2469 "VF*UF must be a power of 2 when folding tail by masking");
2503 "Unexpected successor");
2506 PreVectorPH = CheckVPIRBB;
2513 for (
VPRecipeBase &R : *cast<VPBasicBlock>(ScalarPH)) {
2514 auto *ResumePhi = dyn_cast<VPInstruction>(&R);
2517 ResumePhi->addOperand(ResumePhi->getOperand(1));
2539 auto CreateStep = [&]() ->
Value * {
2554 Value *Step = CreateStep();
2565 TripCountSCEV, SE.
getSCEV(Step))) {
2578 Value *MaxUIntTripCount =
2579 ConstantInt::get(CountTy, cast<IntegerType>(CountTy)->
getMask());
2593 "TC check is expected to dominate Bypass");
2609 if (!SCEVCheckBlock)
2615 "Cannot SCEV check stride or overflow when optimizing for size");
2617 "Should already be a bypass block due to iteration count check");
2622 return SCEVCheckBlock;
2641 "Cannot emit memory checks when optimizing for size, unless forced "
2647 <<
"Code-size may be reduced by not forcing "
2648 "vectorization, or by source-code modifications "
2649 "eliminating the need for runtime checks "
2650 "(e.g., adding 'restrict').";
2659 return MemCheckBlock;
2669 assert(!R.isPhi() &&
"Tried to move phi recipe to end of block");
2670 R.moveBefore(*IRVPBB, IRVPBB->
end());
2682 "loops not exiting via the latch without required epilogue?");
2686 LI,
nullptr,
Twine(Prefix) +
"middle.block");
2690 nullptr,
Twine(Prefix) +
"scalar.ph");
2697 const SCEV2ValueTy &ExpandedSCEVs) {
2698 const SCEV *Step =
ID.getStep();
2699 if (
auto *
C = dyn_cast<SCEVConstant>(Step))
2700 return C->getValue();
2701 if (
auto *U = dyn_cast<SCEVUnknown>(Step))
2702 return U->getValue();
2703 auto I = ExpandedSCEVs.find(Step);
2704 assert(
I != ExpandedSCEVs.end() &&
"SCEV must be expanded at this point");
2714 auto *Cmp = L->getLatchCmpInst();
2716 InstsToIgnore.
insert(Cmp);
2717 for (
const auto &KV : IL) {
2724 cast<Instruction>(
IV->getIncomingValueForBlock(L->getLoopLatch()));
2726 [&](
const User *U) { return U == IV || U == Cmp; }))
2727 InstsToIgnore.
insert(IVInst);
2732 const SCEV2ValueTy &ExpandedSCEVs,
Value *MainVectorTripCount) {
2733 assert(MainVectorTripCount &&
"Must have bypass information");
2739 PHINode *OrigPhi = InductionEntry.first;
2744 Value *EndValueFromAdditionalBypass = MainVectorTripCount;
2745 if (OrigPhi != OldInduction) {
2746 auto *BinOp =
II.getInductionBinOp();
2748 if (isa_and_nonnull<FPMathOperator>(BinOp))
2752 EndValueFromAdditionalBypass =
2754 II.getStartValue(), Step,
II.getKind(), BinOp);
2755 EndValueFromAdditionalBypass->
setName(
"ind.end");
2762 "entry for OrigPhi already exits");
2768 const SCEV2ValueTy &ExpandedSCEVs) {
2829struct CSEDenseMapInfo {
2831 return isa<InsertElementInst>(
I) || isa<ExtractElementInst>(
I) ||
2832 isa<ShuffleVectorInst>(
I) || isa<GetElementPtrInst>(
I);
2844 assert(canHandle(
I) &&
"Unknown instruction!");
2846 I->value_op_end()));
2850 if (
LHS == getEmptyKey() ||
RHS == getEmptyKey() ||
2851 LHS == getTombstoneKey() ||
RHS == getTombstoneKey())
2853 return LHS->isIdenticalTo(
RHS);
2864 if (!CSEDenseMapInfo::canHandle(&In))
2870 In.replaceAllUsesWith(V);
2871 In.eraseFromParent();
2885 return CallWideningDecisions.at(std::make_pair(CI, VF)).Cost;
2893 for (
auto &ArgOp : CI->
args())
2894 Tys.push_back(ArgOp->getType());
2902 return std::min(ScalarCallCost, IntrinsicCost);
2904 return ScalarCallCost;
2917 assert(
ID &&
"Expected intrinsic call!");
2920 if (
auto *FPMO = dyn_cast<FPMathOperator>(CI))
2921 FMF = FPMO->getFastMathFlags();
2927 std::back_inserter(ParamTys),
2928 [&](
Type *Ty) { return maybeVectorizeType(Ty, VF); });
2931 dyn_cast<IntrinsicInst>(CI));
2946 for (
PHINode &PN : Exit->phis())
3000 auto IsBlockOfUsePredicated = [&](
Use &U) ->
bool {
3001 auto *
I = cast<Instruction>(U.getUser());
3003 if (
auto *Phi = dyn_cast<PHINode>(
I))
3004 BB = Phi->getIncomingBlock(
3006 return BB == PredBB;
3017 Worklist.
insert(InstsToReanalyze.
begin(), InstsToReanalyze.
end());
3018 InstsToReanalyze.
clear();
3021 while (!Worklist.
empty()) {
3028 if (!
I || isa<PHINode>(
I) || !VectorLoop->contains(
I) ||
3029 I->mayHaveSideEffects() ||
I->mayReadFromMemory())
3037 if (
I->getParent() == PredBB) {
3038 Worklist.
insert(
I->op_begin(),
I->op_end());
3052 I->moveBefore(PredBB->getFirstInsertionPt());
3053 Worklist.
insert(
I->op_begin(),
I->op_end());
3064 for (
VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
3069 PHINode *NewPhi = cast<PHINode>(State.
get(VPPhi));
3081void LoopVectorizationCostModel::collectLoopScalars(
ElementCount VF) {
3086 "This function should not be visited twice for the same VF");
3092 Scalars[VF].
insert(Uniforms[VF].begin(), Uniforms[VF].end());
3111 "Widening decision should be ready at this moment");
3112 if (
auto *Store = dyn_cast<StoreInst>(MemAccess))
3113 if (
Ptr == Store->getValueOperand())
3116 "Ptr is neither a value or pointer operand");
3122 auto IsLoopVaryingGEP = [&](
Value *
V) {
3133 if (!IsLoopVaryingGEP(
Ptr))
3138 auto *
I = cast<Instruction>(
Ptr);
3145 if (IsScalarUse(MemAccess,
Ptr) &&
3146 all_of(
I->users(), IsaPred<LoadInst, StoreInst>))
3149 PossibleNonScalarPtrs.
insert(
I);
3166 for (
auto &
I : *BB) {
3167 if (
auto *Load = dyn_cast<LoadInst>(&
I)) {
3168 EvaluatePtrUse(Load,
Load->getPointerOperand());
3169 }
else if (
auto *Store = dyn_cast<StoreInst>(&
I)) {
3170 EvaluatePtrUse(Store,
Store->getPointerOperand());
3171 EvaluatePtrUse(Store,
Store->getValueOperand());
3174 for (
auto *
I : ScalarPtrs)
3175 if (!PossibleNonScalarPtrs.
count(
I)) {
3183 auto ForcedScalar = ForcedScalars.
find(VF);
3184 if (ForcedScalar != ForcedScalars.
end())
3185 for (
auto *
I : ForcedScalar->second) {
3186 LLVM_DEBUG(
dbgs() <<
"LV: Found (forced) scalar instruction: " << *
I <<
"\n");
3195 while (
Idx != Worklist.
size()) {
3197 if (!IsLoopVaryingGEP(Dst->getOperand(0)))
3199 auto *Src = cast<Instruction>(Dst->getOperand(0));
3201 auto *J = cast<Instruction>(U);
3202 return !TheLoop->contains(J) || Worklist.count(J) ||
3203 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
3204 IsScalarUse(J, Src));
3207 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Src <<
"\n");
3214 auto *Ind = Induction.first;
3215 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
3224 auto IsDirectLoadStoreFromPtrIndvar = [&](
Instruction *Indvar,
3226 return Induction.second.getKind() ==
3228 (isa<LoadInst>(
I) || isa<StoreInst>(
I)) &&
3234 bool ScalarInd =
all_of(Ind->users(), [&](
User *U) ->
bool {
3235 auto *I = cast<Instruction>(U);
3236 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
3237 IsDirectLoadStoreFromPtrIndvar(Ind, I);
3245 auto *IndUpdatePhi = dyn_cast<PHINode>(IndUpdate);
3251 bool ScalarIndUpdate =
all_of(IndUpdate->users(), [&](
User *U) ->
bool {
3252 auto *I = cast<Instruction>(U);
3253 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
3254 IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
3256 if (!ScalarIndUpdate)
3261 Worklist.
insert(IndUpdate);
3262 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Ind <<
"\n");
3263 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *IndUpdate
3277 switch(
I->getOpcode()) {
3280 case Instruction::Call:
3283 return CallWideningDecisions.at(std::make_pair(cast<CallInst>(
I), VF))
3285 case Instruction::Load:
3286 case Instruction::Store: {
3298 case Instruction::UDiv:
3299 case Instruction::SDiv:
3300 case Instruction::SRem:
3301 case Instruction::URem: {
3319 isa<BranchInst, SwitchInst, PHINode, AllocaInst>(
I))
3332 switch(
I->getOpcode()) {
3335 "instruction should have been considered by earlier checks");
3336 case Instruction::Call:
3340 "should have returned earlier for calls not needing a mask");
3342 case Instruction::Load:
3345 case Instruction::Store: {
3353 case Instruction::UDiv:
3354 case Instruction::SDiv:
3355 case Instruction::SRem:
3356 case Instruction::URem:
3362std::pair<InstructionCost, InstructionCost>
3365 assert(
I->getOpcode() == Instruction::UDiv ||
3366 I->getOpcode() == Instruction::SDiv ||
3367 I->getOpcode() == Instruction::SRem ||
3368 I->getOpcode() == Instruction::URem);
3377 ScalarizationCost = 0;
3392 ScalarizationCost += getScalarizationOverhead(
I, VF);
3412 Value *Op2 =
I->getOperand(1);
3421 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
3423 return {ScalarizationCost, SafeDivisorCost};
3430 "Decision should not be set yet.");
3432 assert(Group &&
"Must have a group.");
3433 unsigned InterleaveFactor = Group->getFactor();
3437 auto &
DL =
I->getDataLayout();
3450 bool ScalarNI =
DL.isNonIntegralPointerType(ScalarTy);
3451 for (
unsigned Idx = 0;
Idx < InterleaveFactor;
Idx++) {
3456 bool MemberNI =
DL.isNonIntegralPointerType(
MemberTy);
3458 if (MemberNI != ScalarNI)
3461 if (MemberNI && ScalarNI &&
3462 ScalarTy->getPointerAddressSpace() !=
3463 MemberTy->getPointerAddressSpace())
3472 bool PredicatedAccessRequiresMasking =
3475 bool LoadAccessWithGapsRequiresEpilogMasking =
3476 isa<LoadInst>(
I) && Group->requiresScalarEpilogue() &&
3478 bool StoreAccessWithGapsRequiresMasking =
3479 isa<StoreInst>(
I) && (Group->getNumMembers() < Group->getFactor());
3480 if (!PredicatedAccessRequiresMasking &&
3481 !LoadAccessWithGapsRequiresEpilogMasking &&
3482 !StoreAccessWithGapsRequiresMasking)
3489 "Masked interleave-groups for predicated accesses are not enabled.");
3491 if (Group->isReverse())
3503 assert((isa<LoadInst, StoreInst>(
I)) &&
"Invalid memory instruction");
3519 auto &
DL =
I->getDataLayout();
3526void LoopVectorizationCostModel::collectLoopUniforms(
ElementCount VF) {
3533 "This function should not be visited twice for the same VF");
3537 Uniforms[VF].
clear();
3545 auto IsOutOfScope = [&](
Value *V) ->
bool {
3557 auto AddToWorklistIfAllowed = [&](
Instruction *
I) ->
void {
3558 if (IsOutOfScope(
I)) {
3565 dbgs() <<
"LV: Found not uniform due to requiring predication: " << *
I
3569 LLVM_DEBUG(
dbgs() <<
"LV: Found uniform instruction: " << *
I <<
"\n");
3582 auto *
Cmp = dyn_cast<Instruction>(E->getTerminator()->getOperand(0));
3584 AddToWorklistIfAllowed(Cmp);
3593 if (PrevVF.isVector()) {
3594 auto Iter = Uniforms.
find(PrevVF);
3595 if (Iter != Uniforms.
end() && !Iter->second.contains(
I))
3600 if (isa<LoadInst>(
I))
3611 "Widening decision should be ready at this moment");
3613 if (IsUniformMemOpUse(
I))
3616 return (WideningDecision ==
CM_Widen ||
3625 if (isa<StoreInst>(
I) &&
I->getOperand(0) ==
Ptr)
3641 for (
auto &
I : *BB) {
3643 switch (
II->getIntrinsicID()) {
3644 case Intrinsic::sideeffect:
3645 case Intrinsic::experimental_noalias_scope_decl:
3646 case Intrinsic::assume:
3647 case Intrinsic::lifetime_start:
3648 case Intrinsic::lifetime_end:
3650 AddToWorklistIfAllowed(&
I);
3659 if (
auto *EVI = dyn_cast<ExtractValueInst>(&
I)) {
3660 assert(IsOutOfScope(EVI->getAggregateOperand()) &&
3661 "Expected aggregate value to be loop invariant");
3662 AddToWorklistIfAllowed(EVI);
3671 if (IsUniformMemOpUse(&
I))
3672 AddToWorklistIfAllowed(&
I);
3674 if (IsVectorizedMemAccessUse(&
I,
Ptr))
3681 for (
auto *V : HasUniformUse) {
3682 if (IsOutOfScope(V))
3684 auto *
I = cast<Instruction>(V);
3685 bool UsersAreMemAccesses =
all_of(
I->users(), [&](
User *U) ->
bool {
3686 auto *UI = cast<Instruction>(U);
3687 return TheLoop->contains(UI) && IsVectorizedMemAccessUse(UI, V);
3689 if (UsersAreMemAccesses)
3690 AddToWorklistIfAllowed(
I);
3697 while (
Idx != Worklist.
size()) {
3700 for (
auto *OV :
I->operand_values()) {
3702 if (IsOutOfScope(OV))
3706 auto *
OP = dyn_cast<PHINode>(OV);
3711 auto *OI = cast<Instruction>(OV);
3713 auto *J = cast<Instruction>(U);
3714 return Worklist.count(J) || IsVectorizedMemAccessUse(J, OI);
3716 AddToWorklistIfAllowed(OI);
3728 auto *Ind = Induction.first;
3729 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
3733 bool UniformInd =
all_of(Ind->users(), [&](
User *U) ->
bool {
3734 auto *I = cast<Instruction>(U);
3735 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
3736 IsVectorizedMemAccessUse(I, Ind);
3743 bool UniformIndUpdate =
all_of(IndUpdate->users(), [&](
User *U) ->
bool {
3744 auto *I = cast<Instruction>(U);
3745 return I == Ind || Worklist.count(I) ||
3746 IsVectorizedMemAccessUse(I, IndUpdate);
3748 if (!UniformIndUpdate)
3752 AddToWorklistIfAllowed(Ind);
3753 AddToWorklistIfAllowed(IndUpdate);
3764 "runtime pointer checks needed. Enable vectorization of this "
3765 "loop with '#pragma clang loop vectorize(enable)' when "
3766 "compiling with -Os/-Oz",
3767 "CantVersionLoopWithOptForSize",
ORE,
TheLoop);
3773 "runtime SCEV checks needed. Enable vectorization of this "
3774 "loop with '#pragma clang loop vectorize(enable)' when "
3775 "compiling with -Os/-Oz",
3776 "CantVersionLoopWithOptForSize",
ORE,
TheLoop);
3783 "runtime stride == 1 checks needed. Enable vectorization of "
3784 "this loop without such check by compiling with -Os/-Oz",
3785 "CantVersionLoopWithOptForSize",
ORE,
TheLoop);
3792bool LoopVectorizationCostModel::isScalableVectorizationAllowed() {
3793 if (IsScalableVectorizationAllowed)
3794 return *IsScalableVectorizationAllowed;
3796 IsScalableVectorizationAllowed =
false;
3802 "ScalableVectorizationDisabled",
ORE,
TheLoop);
3806 LLVM_DEBUG(
dbgs() <<
"LV: Scalable vectorization is available\n");
3809 std::numeric_limits<ElementCount::ScalarTy>::max());
3820 "Scalable vectorization not supported for the reduction "
3821 "operations found in this loop.",
3833 "for all element types found in this loop.",
3840 "for safe distance analysis.",
3845 IsScalableVectorizationAllowed =
true;
3850LoopVectorizationCostModel::getMaxLegalScalableVF(
unsigned MaxSafeElements) {
3851 if (!isScalableVectorizationAllowed())
3855 std::numeric_limits<ElementCount::ScalarTy>::max());
3857 return MaxScalableVF;
3865 "Max legal vector width too small, scalable vectorization "
3869 return MaxScalableVF;
3873 unsigned MaxTripCount,
ElementCount UserVF,
bool FoldTailByMasking) {
3875 unsigned SmallestType, WidestType;
3882 unsigned MaxSafeElements =
3886 auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
3888 this->MaxSafeElements = MaxSafeElements;
3890 LLVM_DEBUG(
dbgs() <<
"LV: The max safe fixed VF is: " << MaxSafeFixedVF
3892 LLVM_DEBUG(
dbgs() <<
"LV: The max safe scalable VF is: " << MaxSafeScalableVF
3897 auto MaxSafeUserVF =
3898 UserVF.
isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
3915 <<
" is unsafe, clamping to max safe VF="
3916 << MaxSafeFixedVF <<
".\n");
3921 <<
"User-specified vectorization factor "
3922 <<
ore::NV(
"UserVectorizationFactor", UserVF)
3923 <<
" is unsafe, clamping to maximum safe vectorization factor "
3924 <<
ore::NV(
"VectorizationFactor", MaxSafeFixedVF);
3926 return MaxSafeFixedVF;
3931 <<
" is ignored because scalable vectors are not "
3937 <<
"User-specified vectorization factor "
3938 <<
ore::NV(
"UserVectorizationFactor", UserVF)
3939 <<
" is ignored because the target does not support scalable "
3940 "vectors. The compiler will pick a more suitable value.";
3944 <<
" is unsafe. Ignoring scalable UserVF.\n");
3949 <<
"User-specified vectorization factor "
3950 <<
ore::NV(
"UserVectorizationFactor", UserVF)
3951 <<
" is unsafe. Ignoring the hint to let the compiler pick a "
3952 "more suitable value.";
3957 LLVM_DEBUG(
dbgs() <<
"LV: The Smallest and Widest types: " << SmallestType
3958 <<
" / " << WidestType <<
" bits.\n");
3963 getMaximizedVFForTarget(MaxTripCount, SmallestType, WidestType,
3964 MaxSafeFixedVF, FoldTailByMasking))
3968 getMaximizedVFForTarget(MaxTripCount, SmallestType, WidestType,
3969 MaxSafeScalableVF, FoldTailByMasking))
3970 if (MaxVF.isScalable()) {
3971 Result.ScalableVF = MaxVF;
3972 LLVM_DEBUG(
dbgs() <<
"LV: Found feasible scalable VF = " << MaxVF
3985 "Not inserting runtime ptr check for divergent target",
3986 "runtime pointer checks needed. Not enabled for divergent target",
3987 "CantVersionLoopWithDivergentTarget",
ORE,
TheLoop);
3996 LLVM_DEBUG(
dbgs() <<
"LV: Found maximum trip count: " << MaxTC <<
'\n');
3999 "loop trip count is one, irrelevant for vectorization",
4008 if (!isa<SCEVCouldNotCompute>(BTC) &&
4014 "Trip count computation wrapped",
4015 "backedge-taken count is -1, loop trip count wrapped to 0",
4020 switch (ScalarEpilogueStatus) {
4022 return computeFeasibleMaxVF(MaxTC, UserVF,
false);
4027 dbgs() <<
"LV: vector predicate hint/switch found.\n"
4028 <<
"LV: Not allowing scalar epilogue, creating predicated "
4029 <<
"vector loop.\n");
4036 dbgs() <<
"LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
4038 LLVM_DEBUG(
dbgs() <<
"LV: Not allowing scalar epilogue due to low trip "
4057 LLVM_DEBUG(
dbgs() <<
"LV: Cannot fold tail by masking: vectorize with a "
4058 "scalar epilogue instead.\n");
4060 return computeFeasibleMaxVF(MaxTC, UserVF,
false);
4071 "No decisions should have been taken at this point");
4081 std::optional<unsigned> MaxPowerOf2RuntimeVF =
4086 MaxPowerOf2RuntimeVF = std::max<unsigned>(
4087 *MaxPowerOf2RuntimeVF,
4090 MaxPowerOf2RuntimeVF = std::nullopt;
4093 if (MaxPowerOf2RuntimeVF && *MaxPowerOf2RuntimeVF > 0) {
4095 "MaxFixedVF must be a power of 2");
4096 unsigned MaxVFtimesIC =
4097 UserIC ? *MaxPowerOf2RuntimeVF * UserIC : *MaxPowerOf2RuntimeVF;
4105 "Invalid loop count");
4107 BackedgeTakenCount, SE->
getOne(BackedgeTakenCount->
getType()));
4113 LLVM_DEBUG(
dbgs() <<
"LV: No tail will remain for any chosen VF.\n");
4128 <<
"LV: tail is folded with EVL, forcing unroll factor to be 1. Will "
4129 "try to generate VP Intrinsics with scalable vector "
4134 assert(ContainsScalableVF &&
"Expected scalable vector factor.");
4144 LLVM_DEBUG(
dbgs() <<
"LV: Cannot fold tail by masking: vectorize with a "
4145 "scalar epilogue instead.\n");
4151 LLVM_DEBUG(
dbgs() <<
"LV: Can't fold tail by masking: don't vectorize\n");
4157 "unable to calculate the loop count due to complex control flow",
4163 "Cannot optimize for size and vectorize at the same time.",
4164 "cannot optimize for size and vectorize at the same time. "
4165 "Enable vectorization of this loop with '#pragma clang loop "
4166 "vectorize(enable)' when compiling with -Os/-Oz",
4171ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
4172 unsigned MaxTripCount,
unsigned SmallestType,
unsigned WidestType,
4174 bool ComputeScalableMaxVF = MaxSafeVF.
isScalable();
4182 "Scalable flags must match");
4190 ComputeScalableMaxVF);
4191 MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
4193 << (MaxVectorElementCount * WidestType) <<
" bits.\n");
4195 if (!MaxVectorElementCount) {
4197 << (ComputeScalableMaxVF ?
"scalable" :
"fixed")
4198 <<
" vector registers.\n");
4202 unsigned WidestRegisterMinEC = MaxVectorElementCount.getKnownMinValue();
4203 if (MaxVectorElementCount.isScalable() &&
4207 WidestRegisterMinEC *= Min;
4216 if (MaxTripCount && MaxTripCount <= WidestRegisterMinEC &&
4224 LLVM_DEBUG(
dbgs() <<
"LV: Clamping the MaxVF to maximum power of two not "
4225 "exceeding the constant trip count: "
4226 << ClampedUpperTripCount <<
"\n");
4228 ClampedUpperTripCount,
4229 FoldTailByMasking ? MaxVectorElementCount.isScalable() :
false);
4242 ComputeScalableMaxVF);
4243 MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
4257 for (
int I = RUs.size() - 1;
I >= 0; --
I) {
4258 const auto &MLU = RUs[
I].MaxLocalUsers;
4259 if (
all_of(MLU, [&](
decltype(MLU.front()) &LU) {
4260 return LU.second <= TTI.getNumberOfRegisters(LU.first);
4270 <<
") with target's minimum: " << MinVF <<
'\n');
4288 std::optional<unsigned> VScale) {
4292 EstimatedVF *= *VScale;
4293 assert(EstimatedVF >= 1 &&
"Estimated VF shouldn't be less than 1");
4297bool LoopVectorizationPlanner::isMoreProfitable(
4299 const unsigned MaxTripCount)
const {
4304 unsigned EstimatedWidthA =
A.Width.getKnownMinValue();
4305 unsigned EstimatedWidthB =
B.Width.getKnownMinValue();
4307 if (
A.Width.isScalable())
4308 EstimatedWidthA *= *VScale;
4309 if (
B.Width.isScalable())
4310 EstimatedWidthB *= *VScale;
4317 A.Width.isScalable() && !
B.Width.isScalable();
4328 return CmpFn(CostA * EstimatedWidthB, CostB * EstimatedWidthA);
4330 auto GetCostForTC = [MaxTripCount,
this](
unsigned VF,
4342 return VectorCost *
divideCeil(MaxTripCount, VF);
4343 return VectorCost * (MaxTripCount / VF) + ScalarCost * (MaxTripCount % VF);
4346 auto RTCostA = GetCostForTC(EstimatedWidthA, CostA,
A.ScalarCost);
4347 auto RTCostB = GetCostForTC(EstimatedWidthB, CostB,
B.ScalarCost);
4348 return CmpFn(RTCostA, RTCostB);
4351bool LoopVectorizationPlanner::isMoreProfitable(
4354 return LoopVectorizationPlanner::isMoreProfitable(
A,
B, MaxTripCount);
4359 using RecipeVFPair = std::pair<VPRecipeBase *, ElementCount>;
4361 for (
const auto &Plan : VPlans) {
4372 precomputeCosts(*Plan, VF, CostCtx);
4374 for (
VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
4375 for (
auto &R : *VPBB) {
4376 if (!R.cost(VF, CostCtx).isValid())
4382 if (InvalidCosts.
empty())
4390 for (
auto &Pair : InvalidCosts)
4391 if (!Numbering.
count(Pair.first))
4392 Numbering[Pair.first] =
I++;
4395 sort(InvalidCosts, [&Numbering](RecipeVFPair &
A, RecipeVFPair &
B) {
4396 if (Numbering[
A.first] != Numbering[
B.first])
4397 return Numbering[
A.first] < Numbering[
B.first];
4398 const auto &
LHS =
A.second;
4399 const auto &
RHS =
B.second;
4400 return std::make_tuple(
LHS.isScalable(),
LHS.getKnownMinValue()) <
4401 std::make_tuple(
RHS.isScalable(),
RHS.getKnownMinValue());
4413 Subset =
Tail.take_front(1);
4420 [](
const auto *R) {
return Instruction::PHI; })
4421 .Case<VPWidenSelectRecipe>(
4422 [](
const auto *R) {
return Instruction::Select; })
4423 .Case<VPWidenStoreRecipe>(
4424 [](
const auto *R) {
return Instruction::Store; })
4425 .Case<VPWidenLoadRecipe>(
4426 [](
const auto *R) {
return Instruction::Load; })
4427 .Case<VPWidenCallRecipe, VPWidenIntrinsicRecipe>(
4428 [](
const auto *R) {
return Instruction::Call; })
4431 [](
const auto *R) {
return R->getOpcode(); })
4433 return R->getStoredValues().empty() ? Instruction::Load
4434 : Instruction::Store;
4442 if (Subset ==
Tail ||
Tail[Subset.size()].first != R) {
4443 std::string OutString;
4445 assert(!Subset.empty() &&
"Unexpected empty range");
4446 OS <<
"Recipe with invalid costs prevented vectorization at VF=(";
4447 for (
const auto &Pair : Subset)
4448 OS << (Pair.second == Subset.front().second ?
"" :
", ") << Pair.second;
4450 if (Opcode == Instruction::Call) {
4452 if (
auto *
Int = dyn_cast<VPWidenIntrinsicRecipe>(R)) {
4453 Name =
Int->getIntrinsicName();
4455 auto *WidenCall = dyn_cast<VPWidenCallRecipe>(R);
4457 WidenCall ? WidenCall->getCalledScalarFunction()
4458 : cast<Function>(R->getOperand(R->getNumOperands() - 1)
4459 ->getLiveInIRValue());
4462 OS <<
" call to " <<
Name;
4467 Tail =
Tail.drop_front(Subset.size());
4471 Subset =
Tail.take_front(Subset.size() + 1);
4472 }
while (!
Tail.empty());
4485 for (
VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
4494 switch (R.getVPDefID()) {
4495 case VPDef::VPDerivedIVSC:
4496 case VPDef::VPScalarIVStepsSC:
4497 case VPDef::VPScalarCastSC:
4498 case VPDef::VPReplicateSC:
4499 case VPDef::VPInstructionSC:
4500 case VPDef::VPCanonicalIVPHISC:
4501 case VPDef::VPVectorPointerSC:
4502 case VPDef::VPReverseVectorPointerSC:
4503 case VPDef::VPExpandSCEVSC:
4504 case VPDef::VPEVLBasedIVPHISC:
4505 case VPDef::VPPredInstPHISC:
4506 case VPDef::VPBranchOnMaskSC:
4508 case VPDef::VPReductionSC:
4509 case VPDef::VPActiveLaneMaskPHISC:
4510 case VPDef::VPWidenCallSC:
4511 case VPDef::VPWidenCanonicalIVSC:
4512 case VPDef::VPWidenCastSC:
4513 case VPDef::VPWidenGEPSC:
4514 case VPDef::VPWidenIntrinsicSC:
4515 case VPDef::VPWidenSC:
4516 case VPDef::VPWidenSelectSC:
4517 case VPDef::VPBlendSC:
4518 case VPDef::VPFirstOrderRecurrencePHISC:
4519 case VPDef::VPWidenPHISC:
4520 case VPDef::VPWidenIntOrFpInductionSC:
4521 case VPDef::VPWidenPointerInductionSC:
4522 case VPDef::VPReductionPHISC:
4523 case VPDef::VPInterleaveSC:
4524 case VPDef::VPWidenLoadEVLSC:
4525 case VPDef::VPWidenLoadSC:
4526 case VPDef::VPWidenStoreEVLSC:
4527 case VPDef::VPWidenStoreSC:
4533 auto WillWiden = [&
TTI, VF](
Type *ScalarTy) {
4551 if (R.getNumDefinedValues() == 0 &&
4552 !isa<VPWidenStoreRecipe, VPWidenStoreEVLRecipe, VPInterleaveRecipe>(
4561 R.getNumDefinedValues() >= 1 ? R.getVPValue(0) : R.getOperand(1);
4563 if (!Visited.
insert({ScalarTy}).second)
4565 if (WillWiden(ScalarTy))
4576 LLVM_DEBUG(
dbgs() <<
"LV: Scalar loop costs: " << ExpectedCost <<
".\n");
4577 assert(ExpectedCost.
isValid() &&
"Unexpected invalid cost for scalar loop");
4580 [](std::unique_ptr<VPlan> &
P) {
return P->hasScalarVFOnly(); }) &&
4581 "Expected Scalar VF to be a candidate");
4588 if (ForceVectorization &&
4589 (VPlans.
size() > 1 || !VPlans[0]->hasScalarVFOnly())) {
4596 for (
auto &
P : VPlans) {
4608 <<
" costs: " << (Candidate.Cost / Width));
4609 if (VF.isScalable())
4617 <<
"LV: Not considering vector loop of width " << VF
4618 <<
" because it will not generate any vector instructions.\n");
4622 if (isMoreProfitable(Candidate, ChosenFactor))
4623 ChosenFactor = Candidate;
4629 "There are conditional stores.",
4630 "store that is conditionally executed prevents vectorization",
4631 "ConditionalStore", ORE, OrigLoop);
4632 ChosenFactor = ScalarCost;
4636 !isMoreProfitable(ChosenFactor, ScalarCost))
dbgs()
4637 <<
"LV: Vectorization seems to be not beneficial, "
4638 <<
"but was forced by a user.\n");
4639 return ChosenFactor;
4643bool LoopVectorizationPlanner::isCandidateForEpilogueVectorization(
4648 [&](
PHINode &Phi) { return Legal->isFixedOrderRecurrence(&Phi); }))
4658 if (!OrigLoop->
contains(cast<Instruction>(U)))
4662 if (!OrigLoop->
contains(cast<Instruction>(U)))
4696 unsigned Multiplier = VF.
isFixed() ? IC : 1;
4708 LLVM_DEBUG(
dbgs() <<
"LEV: Epilogue vectorization is disabled.\n");
4713 LLVM_DEBUG(
dbgs() <<
"LEV: Unable to vectorize epilogue because no "
4714 "epilogue is allowed.\n");
4720 if (!isCandidateForEpilogueVectorization(MainLoopVF)) {
4721 LLVM_DEBUG(
dbgs() <<
"LEV: Unable to vectorize epilogue because the loop "
4722 "is not a supported candidate.\n");
4727 LLVM_DEBUG(
dbgs() <<
"LEV: Epilogue vectorization factor is forced.\n");
4730 return {ForcedEC, 0, 0};
4732 LLVM_DEBUG(
dbgs() <<
"LEV: Epilogue vectorization forced factor is not "
4740 dbgs() <<
"LEV: Epilogue vectorization skipped due to opt for size.\n");
4745 LLVM_DEBUG(
dbgs() <<
"LEV: Epilogue vectorization is not profitable for "
4758 const SCEV *RemainingIterations =
nullptr;
4759 unsigned MaxTripCount = 0;
4760 for (
auto &NextVF : ProfitableVFs) {
4767 if ((!NextVF.Width.isScalable() && MainLoopVF.
isScalable() &&
4769 (NextVF.Width.isScalable() &&
4771 (!NextVF.Width.isScalable() && !MainLoopVF.
isScalable() &&
4777 if (!MainLoopVF.
isScalable() && !NextVF.Width.isScalable()) {
4779 if (!RemainingIterations) {
4782 assert(!isa<SCEVCouldNotCompute>(TC) &&
4783 "Trip count SCEV must be computable");
4793 << MaxTripCount <<
"\n");
4797 SE.
getConstant(TCType, NextVF.Width.getKnownMinValue()),
4798 RemainingIterations))
4802 if (Result.Width.isScalar() ||
4803 isMoreProfitable(NextVF, Result, MaxTripCount))
4809 << Result.Width <<
"\n");
4813std::pair<unsigned, unsigned>
4815 unsigned MinWidth = -1U;
4816 unsigned MaxWidth = 8;
4829 MaxWidth = std::min<unsigned>(
4830 MaxWidth, std::min<unsigned>(
4836 MinWidth = std::min<unsigned>(
4837 MinWidth,
DL.getTypeSizeInBits(
T->getScalarType()).getFixedValue());
4838 MaxWidth = std::max<unsigned>(
4839 MaxWidth,
DL.getTypeSizeInBits(
T->getScalarType()).getFixedValue());
4842 return {MinWidth, MaxWidth};
4850 for (
Instruction &
I : BB->instructionsWithoutDebug()) {
4858 if (!isa<LoadInst>(
I) && !isa<StoreInst>(
I) && !isa<PHINode>(
I))
4863 if (
auto *PN = dyn_cast<PHINode>(&
I)) {
4877 if (
auto *ST = dyn_cast<StoreInst>(&
I))
4878 T = ST->getValueOperand()->getType();
4881 "Expected the load/store/recurrence type to be sized");
4910 LLVM_DEBUG(
dbgs() <<
"LV: Preference for VP intrinsics indicated. "
4911 "Unroll factor forced to be 1.\n");
4930 if (LoopCost == 0) {
4932 assert(LoopCost.
isValid() &&
"Expected to have chosen a VF with valid cost");
4942 for (
auto &Pair : R.MaxLocalUsers) {
4943 Pair.second = std::max(Pair.second, 1U);
4957 unsigned IC = UINT_MAX;
4959 for (
const auto &Pair : R.MaxLocalUsers) {
4964 <<
" register class\n");
4972 unsigned MaxLocalUsers = Pair.second;
4973 unsigned LoopInvariantRegs = 0;
4974 if (R.LoopInvariantRegs.find(Pair.first) != R.LoopInvariantRegs.end())
4975 LoopInvariantRegs = R.LoopInvariantRegs[Pair.first];
4977 unsigned TmpIC =
llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs) /
4981 TmpIC =
llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs - 1) /
4982 std::max(1U, (MaxLocalUsers - 1)));
4985 IC = std::min(IC, TmpIC);
5005 unsigned AvailableTC =
5017 std::max(1u, std::min(AvailableTC / EstimatedVF, MaxInterleaveCount)));
5018 unsigned InterleaveCountLB =
bit_floor(std::max(
5019 1u, std::min(AvailableTC / (EstimatedVF * 2), MaxInterleaveCount)));
5020 MaxInterleaveCount = InterleaveCountLB;
5022 if (InterleaveCountUB != InterleaveCountLB) {
5023 unsigned TailTripCountUB =
5024 (AvailableTC % (EstimatedVF * InterleaveCountUB));
5025 unsigned TailTripCountLB =
5026 (AvailableTC % (EstimatedVF * InterleaveCountLB));
5029 if (TailTripCountUB == TailTripCountLB)
5030 MaxInterleaveCount = InterleaveCountUB;
5032 }
else if (BestKnownTC && *BestKnownTC > 0) {
5036 ? (*BestKnownTC) - 1
5044 MaxInterleaveCount =
bit_floor(std::max(
5045 1u, std::min(AvailableTC / (EstimatedVF * 2), MaxInterleaveCount)));
5048 assert(MaxInterleaveCount > 0 &&
5049 "Maximum interleave count must be greater than 0");
5053 if (IC > MaxInterleaveCount)
5054 IC = MaxInterleaveCount;
5057 IC = std::max(1u, IC);
5059 assert(IC > 0 &&
"Interleave count must be greater than 0.");
5063 if (VF.
isVector() && HasReductions) {
5064 LLVM_DEBUG(
dbgs() <<
"LV: Interleaving because of reductions.\n");
5072 bool ScalarInterleavingRequiresPredication =
5074 return Legal->blockNeedsPredication(BB);
5076 bool ScalarInterleavingRequiresRuntimePointerCheck =
5082 <<
"LV: IC is " << IC <<
'\n'
5083 <<
"LV: VF is " << VF <<
'\n');
5084 const bool AggressivelyInterleaveReductions =
5086 if (!ScalarInterleavingRequiresRuntimePointerCheck &&
5087 !ScalarInterleavingRequiresPredication && LoopCost <
SmallLoopCost) {
5091 unsigned SmallIC = std::min(IC, (
unsigned)llvm::bit_floor<uint64_t>(
5098 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5099 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5105 bool HasSelectCmpReductions =
5108 const RecurrenceDescriptor &RdxDesc = Reduction.second;
5109 RecurKind RK = RdxDesc.getRecurrenceKind();
5110 return RecurrenceDescriptor::isAnyOfRecurrenceKind(RK) ||
5111 RecurrenceDescriptor::isFindLastIVRecurrenceKind(RK);
5113 if (HasSelectCmpReductions) {
5114 LLVM_DEBUG(
dbgs() <<
"LV: Not interleaving select-cmp reductions.\n");
5124 bool HasOrderedReductions =
5126 const RecurrenceDescriptor &RdxDesc = Reduction.second;
5127 return RdxDesc.isOrdered();
5129 if (HasOrderedReductions) {
5131 dbgs() <<
"LV: Not interleaving scalar ordered reductions.\n");
5136 SmallIC = std::min(SmallIC,
F);
5137 StoresIC = std::min(StoresIC,
F);
5138 LoadsIC = std::min(LoadsIC,
F);
5142 std::max(StoresIC, LoadsIC) > SmallIC) {
5144 dbgs() <<
"LV: Interleaving to saturate store or load ports.\n");
5145 return std::max(StoresIC, LoadsIC);
5150 if (VF.
isScalar() && AggressivelyInterleaveReductions) {
5154 return std::max(IC / 2, SmallIC);
5157 LLVM_DEBUG(
dbgs() <<
"LV: Interleaving to reduce branch cost.\n");
5163 if (AggressivelyInterleaveReductions) {
5213 for (
Instruction &
I : BB->instructionsWithoutDebug()) {
5217 for (
Value *U :
I.operands()) {
5218 auto *Instr = dyn_cast<Instruction>(U);
5229 LoopInvariants.
insert(Instr);
5234 EndPoint[Instr] = IdxToInstr.
size();
5252 LLVM_DEBUG(
dbgs() <<
"LV(REG): Calculating max register usage:\n");
5254 const auto &TTICapture =
TTI;
5258 !TTICapture.isElementTypeLegalForScalableVector(Ty)))
5265 for (
unsigned int Idx = 0, Sz = IdxToInstr.
size();
Idx < Sz; ++
Idx) {
5269 InstrList &
List = TransposeEnds[
Idx];
5282 for (
unsigned J = 0, E = VFs.
size(); J < E; ++J) {
5290 if (VFs[J].isScalar()) {
5291 for (
auto *Inst : OpenIntervals) {
5300 for (
auto *Inst : OpenIntervals) {
5313 RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[J]);
5318 for (
const auto &Pair :
RegUsage) {
5319 auto &Entry = MaxUsages[J][Pair.first];
5320 Entry = std::max(Entry, Pair.second);
5325 << OpenIntervals.
size() <<
'\n');
5337 for (
auto *Inst : LoopInvariants) {
5340 bool IsScalar =
all_of(Inst->users(), [&](
User *U) {
5341 auto *I = cast<Instruction>(U);
5342 return TheLoop != LI->getLoopFor(I->getParent()) ||
5343 isScalarAfterVectorization(I, VFs[Idx]);
5349 Invariant[ClassID] += GetRegUsage(Inst->getType(), VF);
5353 dbgs() <<
"LV(REG): VF = " << VFs[
Idx] <<
'\n';
5354 dbgs() <<
"LV(REG): Found max usage: " << MaxUsages[
Idx].
size()
5356 for (
const auto &pair : MaxUsages[
Idx]) {
5357 dbgs() <<
"LV(REG): RegisterClass: "
5361 dbgs() <<
"LV(REG): Found invariant usage: " << Invariant.
size()
5363 for (
const auto &pair : Invariant) {
5364 dbgs() <<
"LV(REG): RegisterClass: "
5378bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(
Instruction *
I,
5389 "Expecting a scalar emulated instruction");
5390 return isa<LoadInst>(
I) ||
5391 (isa<StoreInst>(
I) &&
5408 PredicatedBBsAfterVectorization[VF].
clear();
5425 !useEmulatedMaskMemRefHack(&
I, VF) &&
5426 computePredInstDiscount(&
I, ScalarCosts, VF) >= 0) {
5430 for (
const auto &[
I,
_] : ScalarCosts) {
5431 auto *CI = dyn_cast<CallInst>(
I);
5432 if (!CI || !CallWideningDecisions.contains({CI, VF}))
5435 CallWideningDecisions[{CI, VF}].Cost = ScalarCosts[CI];
5439 PredicatedBBsAfterVectorization[VF].
insert(BB);
5441 if (Pred->getSingleSuccessor() == BB)
5442 PredicatedBBsAfterVectorization[VF].
insert(Pred);
5451 "Instruction marked uniform-after-vectorization will be predicated");
5469 if (!
I->hasOneUse() || PredInst->
getParent() !=
I->getParent() ||
5488 for (
Use &U :
I->operands())
5489 if (
auto *J = dyn_cast<Instruction>(U.get()))
5501 while (!Worklist.
empty()) {
5505 if (ScalarCosts.contains(
I))
5534 for (
Use &U :
I->operands())
5535 if (
auto *J = dyn_cast<Instruction>(
U.get())) {
5537 "Instruction has non-scalar type");
5538 if (CanBeScalarized(J))
5540 else if (needsExtract(J, VF)) {
5542 cast<VectorType>(
toVectorTy(J->getType(), VF)),
5553 Discount += VectorCost - ScalarCost;
5554 ScalarCosts[
I] = ScalarCost;
5570 ValuesToIgnoreForVF);
5577 for (
Instruction &
I : BB->instructionsWithoutDebug()) {
5590 LLVM_DEBUG(
dbgs() <<
"LV: Found an estimated cost of " <<
C <<
" for VF "
5591 << VF <<
" For instruction: " <<
I <<
'\n');
5619 const Loop *TheLoop) {
5621 auto *Gep = dyn_cast<GetElementPtrInst>(
Ptr);
5627 auto *SE = PSE.
getSE();
5628 unsigned NumOperands = Gep->getNumOperands();
5629 for (
unsigned Idx = 1;
Idx < NumOperands; ++
Idx) {
5632 !
Legal->isInductionVariable(Opd))
5641LoopVectorizationCostModel::getMemInstScalarizationCost(
Instruction *
I,
5644 "Scalarization cost of instruction implies vectorization.");
5674 Cost += getScalarizationOverhead(
I, VF);
5690 if (useEmulatedMaskMemRefHack(
I, VF))
5700LoopVectorizationCostModel::getConsecutiveMemOpCost(
Instruction *
I,
5703 auto *VectorTy = cast<VectorType>(
toVectorTy(ValTy, VF));
5708 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
5709 "Stride should be 1 or -1 for consecutive memory access");
5721 bool Reverse = ConsecutiveStride < 0;
5729LoopVectorizationCostModel::getUniformMemOpCost(
Instruction *
I,
5734 auto *VectorTy = cast<VectorType>(
toVectorTy(ValTy, VF));
5737 if (isa<LoadInst>(
I)) {
5750 (IsLoopInvariantStoreValue
5757LoopVectorizationCostModel::getGatherScatterCost(
Instruction *
I,
5760 auto *VectorTy = cast<VectorType>(
toVectorTy(ValTy, VF));
5771LoopVectorizationCostModel::getInterleaveGroupCost(
Instruction *
I,
5774 assert(Group &&
"Fail to get an interleaved access group.");
5778 auto *VectorTy = cast<VectorType>(
toVectorTy(ValTy, VF));
5781 unsigned InterleaveFactor = Group->getFactor();
5786 for (
unsigned IF = 0;
IF < InterleaveFactor;
IF++)
5787 if (Group->getMember(IF))
5791 bool UseMaskForGaps =
5793 (isa<StoreInst>(
I) && (Group->getNumMembers() < Group->getFactor()));
5795 InsertPos->
getOpcode(), WideVecTy, Group->getFactor(), Indices,
5799 if (Group->isReverse()) {
5802 "Reverse masked interleaved access not supported.");
5803 Cost += Group->getNumMembers() *
5810std::optional<InstructionCost>
5816 if (InLoopReductions.
empty() || VF.
isScalar() || !isa<VectorType>(Ty))
5817 return std::nullopt;
5818 auto *VectorTy = cast<VectorType>(Ty);
5835 return std::nullopt;
5846 if (!InLoopReductionImmediateChains.
count(RetI))
5847 return std::nullopt;
5851 Instruction *LastChain = InLoopReductionImmediateChains.
at(RetI);
5853 while (!isa<PHINode>(ReductionPhi))
5854 ReductionPhi = InLoopReductionImmediateChains.
at(ReductionPhi);
5886 : dyn_cast<Instruction>(RetI->
getOperand(1));
5891 if (RedOp && RdxDesc.
getOpcode() == Instruction::Add &&
5904 bool IsUnsigned = isa<ZExtInst>(Op0);
5921 RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
5922 return I == RetI ? RedCost : 0;
5926 bool IsUnsigned = isa<ZExtInst>(RedOp);
5935 if (RedCost.
isValid() && RedCost < BaseCost + ExtCost)
5936 return I == RetI ? RedCost : 0;
5937 }
else if (RedOp && RdxDesc.
getOpcode() == Instruction::Add &&
5942 bool IsUnsigned = isa<ZExtInst>(Op0);
5965 if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
5966 Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
5974 (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
5975 return I == RetI ? RedCost : 0;
5984 if (RedCost.
isValid() && RedCost < MulCost + BaseCost)
5985 return I == RetI ? RedCost : 0;
5989 return I == RetI ? std::optional<InstructionCost>(BaseCost) : std::nullopt;
5993LoopVectorizationCostModel::getMemoryInstructionCost(
Instruction *
I,
6011LoopVectorizationCostModel::getScalarizationOverhead(
Instruction *
I,
6024 if (!
RetTy->isVoidTy() &&
6046 for (
auto *V : filterExtractingOperands(Ops, VF))
6049 filterExtractingOperands(Ops, VF), Tys,
CostKind);
6071 auto IsLegalToScalarize = [&]() {
6085 if (isa<LoadInst>(
I))
6090 auto &SI = cast<StoreInst>(
I);
6103 IsLegalToScalarize() ? getUniformMemOpCost(&
I, VF)
6109 if (GatherScatterCost < ScalarizationCost)
6121 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6122 "Expected consecutive stride.");
6131 unsigned NumAccesses = 1;
6134 assert(Group &&
"Fail to get an interleaved access group.");
6140 NumAccesses = Group->getNumMembers();
6142 InterleaveCost = getInterleaveGroupCost(&
I, VF);
6147 ? getGatherScatterCost(&
I, VF) * NumAccesses
6151 getMemInstScalarizationCost(&
I, VF) * NumAccesses;
6157 if (InterleaveCost <= GatherScatterCost &&
6158 InterleaveCost < ScalarizationCost) {
6160 Cost = InterleaveCost;
6161 }
else if (GatherScatterCost < ScalarizationCost) {
6163 Cost = GatherScatterCost;
6166 Cost = ScalarizationCost;
6200 while (!Worklist.
empty()) {
6202 for (
auto &
Op :
I->operands())
6203 if (
auto *InstOp = dyn_cast<Instruction>(
Op))
6204 if ((InstOp->getParent() ==
I->getParent()) && !isa<PHINode>(InstOp) &&
6205 AddrDefs.
insert(InstOp).second)
6209 for (
auto *
I : AddrDefs) {
6210 if (isa<LoadInst>(
I)) {
6224 for (
unsigned I = 0;
I < Group->getFactor(); ++
I) {
6241 "Trying to set a vectorization decision for a scalar VF");
6243 auto ForcedScalar = ForcedScalars.
find(VF);
6258 for (
auto &ArgOp : CI->
args())
6276 if (VF.
isVector() && ((ForcedScalar != ForcedScalars.
end() &&
6277 ForcedScalar->second.contains(CI)) ||
6288 for (
Type *ScalarTy : ScalarTys)
6297 std::nullopt, *RedCost);
6308 if (
Info.Shape.VF != VF)
6312 if (MaskRequired && !
Info.isMasked())
6316 bool ParamsOk =
true;
6318 switch (Param.ParamKind) {
6337 dyn_cast<SCEVAddRecExpr>(SE->
getSCEV(ScalarParam));
6339 if (!SAR || SAR->getLoop() !=
TheLoop) {
6345 dyn_cast<SCEVConstant>(SAR->getStepRecurrence(*SE));
6382 if (VectorCost <=
Cost) {
6387 if (IntrinsicCost <=
Cost) {
6388 Cost = IntrinsicCost;
6403 auto *OpI = dyn_cast<Instruction>(
Op);
6420 return InstsToScalarize[VF][
I];
6423 auto ForcedScalar = ForcedScalars.
find(VF);
6424 if (VF.
isVector() && ForcedScalar != ForcedScalars.
end()) {
6425 auto InstSet = ForcedScalar->second;
6426 if (InstSet.count(
I))
6436 auto HasSingleCopyAfterVectorization = [
this](
Instruction *
I,
6441 auto Scalarized = InstsToScalarize.
find(VF);
6442 assert(Scalarized != InstsToScalarize.
end() &&
6443 "VF not yet analyzed for scalarization profitability");
6444 return !Scalarized->second.count(
I) &&
6446 auto *UI = cast<Instruction>(U);
6447 return !Scalarized->second.count(UI);
6450 (void)HasSingleCopyAfterVectorization;
6459 assert(
I->getOpcode() == Instruction::GetElementPtr ||
6460 I->getOpcode() == Instruction::PHI ||
6461 (
I->getOpcode() == Instruction::BitCast &&
6462 I->getType()->isPointerTy()) ||
6463 HasSingleCopyAfterVectorization(
I, VF));
6473 switch (
I->getOpcode()) {
6474 case Instruction::GetElementPtr:
6480 case Instruction::Br: {
6487 bool ScalarPredicatedBB =
false;
6493 ScalarPredicatedBB =
true;
6495 if (ScalarPredicatedBB) {
6519 case Instruction::Switch: {
6522 auto *Switch = cast<SwitchInst>(
I);
6523 return Switch->getNumCases() *
6526 toVectorTy(Switch->getCondition()->getType(), VF),
6530 case Instruction::PHI: {
6531 auto *Phi = cast<PHINode>(
I);
6543 cast<VectorType>(VectorTy), Mask,
CostKind,
6551 Type *ResultTy = Phi->getType();
6555 auto *HeaderUser = cast_if_present<PHINode>(
6556 find_singleton<User>(Phi->users(), [
this](
User *U,
bool) ->
User * {
6557 auto *Phi = dyn_cast<PHINode>(U);
6558 if (Phi && Phi->getParent() == TheLoop->getHeader())
6564 auto Iter = ReductionVars.
find(HeaderUser);
6565 if (Iter != ReductionVars.end() &&
6567 Iter->second.getRecurrenceKind()))
6570 return (Phi->getNumIncomingValues() - 1) *
6572 Instruction::Select,
toVectorTy(ResultTy, VF),
6582 Intrinsic::vp_merge,
toVectorTy(Phi->getType(), VF),
6583 {toVectorTy(Type::getInt1Ty(Phi->getContext()), VF)});
6589 case Instruction::UDiv:
6590 case Instruction::SDiv:
6591 case Instruction::URem:
6592 case Instruction::SRem:
6596 ScalarCost : SafeDivisorCost;
6600 case Instruction::Add:
6601 case Instruction::Sub: {
6609 if (!
RHS ||
RHS->getZExtValue() != 1)
6615 Type *ScalarTy =
I->getType();
6619 {PtrTy, ScalarTy, MaskTy});
6627 case Instruction::FAdd:
6628 case Instruction::FSub:
6629 case Instruction::Mul:
6630 case Instruction::FMul:
6631 case Instruction::FDiv:
6632 case Instruction::FRem:
6633 case Instruction::Shl:
6634 case Instruction::LShr:
6635 case Instruction::AShr:
6636 case Instruction::And:
6637 case Instruction::Or:
6638 case Instruction::Xor: {
6642 if (
I->getOpcode() == Instruction::Mul &&
6655 Value *Op2 =
I->getOperand(1);
6658 Op2 = cast<SCEVConstant>(
PSE.
getSCEV(Op2))->getValue();
6668 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6671 case Instruction::FNeg: {
6674 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6675 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6676 I->getOperand(0),
I);
6678 case Instruction::Select: {
6680 const SCEV *CondSCEV = SE->
getSCEV(SI->getCondition());
6683 const Value *Op0, *Op1;
6700 Type *CondTy = SI->getCondition()->getType();
6705 if (
auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
6706 Pred = Cmp->getPredicate();
6708 CostKind, {TTI::OK_AnyValue, TTI::OP_None},
6709 {TTI::OK_AnyValue, TTI::OP_None},
I);
6711 case Instruction::ICmp:
6712 case Instruction::FCmp: {
6713 Type *ValTy =
I->getOperand(0)->getType();
6716 Instruction *Op0AsInstruction = dyn_cast<Instruction>(
I->getOperand(0));
6717 (void)Op0AsInstruction;
6719 MinBWs[
I] == MinBWs[Op0AsInstruction]) &&
6720 "if both the operand and the compare are marked for "
6721 "truncation, they must have the same bitwidth");
6727 cast<CmpInst>(
I)->getPredicate(),
CostKind,
6728 {TTI::OK_AnyValue, TTI::OP_None},
6729 {TTI::OK_AnyValue, TTI::OP_None},
I);
6731 case Instruction::Store:
6732 case Instruction::Load: {
6737 "CM decision should be taken at this point");
6744 return getMemoryInstructionCost(
I, VF);
6746 case Instruction::BitCast:
6747 if (
I->getType()->isPointerTy())
6750 case Instruction::ZExt:
6751 case Instruction::SExt:
6752 case Instruction::FPToUI:
6753 case Instruction::FPToSI:
6754 case Instruction::FPExt:
6755 case Instruction::PtrToInt:
6756 case Instruction::IntToPtr:
6757 case Instruction::SIToFP:
6758 case Instruction::UIToFP:
6759 case Instruction::Trunc:
6760 case Instruction::FPTrunc: {
6763 assert((isa<LoadInst>(
I) || isa<StoreInst>(
I)) &&
6764 "Expected a load or a store!");
6790 unsigned Opcode =
I->getOpcode();
6793 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
6795 if (
StoreInst *Store = dyn_cast<StoreInst>(*
I->user_begin()))
6796 CCH = ComputeCCH(Store);
6799 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
6800 Opcode == Instruction::FPExt) {
6801 if (
LoadInst *Load = dyn_cast<LoadInst>(
I->getOperand(0)))
6802 CCH = ComputeCCH(Load);
6809 auto *Trunc = cast<TruncInst>(
I);
6811 Trunc->getSrcTy(), CCH,
CostKind, Trunc);
6818 Type *SrcScalarTy =
I->getOperand(0)->getType();
6819 Instruction *Op0AsInstruction = dyn_cast<Instruction>(
I->getOperand(0));
6830 (
I->getOpcode() == Instruction::ZExt ||
6831 I->getOpcode() == Instruction::SExt))
6837 case Instruction::Call:
6839 case Instruction::ExtractValue:
6841 case Instruction::Alloca:
6864 auto IsLiveOutDead = [
this, RequiresScalarEpilogue](
User *U) {
6865 return RequiresScalarEpilogue &&
6877 if ((SI = dyn_cast<StoreInst>(&
I)) &&
6880 DeadInvariantStoreOps[SI->getPointerOperand()].push_back(
6881 SI->getValueOperand());
6890 all_of(
I.users(), [
this, IsLiveOutDead](
User *U) {
6891 return VecValuesToIgnore.contains(U) ||
6892 ValuesToIgnore.contains(U) || IsLiveOutDead(U);
6901 if (Group->getInsertPos() == &
I)
6904 DeadInterleavePointerOps.
push_back(PointerOp);
6909 if (
auto *Br = dyn_cast<BranchInst>(&
I)) {
6910 if (Br->isConditional())
6917 for (
unsigned I = 0;
I != DeadInterleavePointerOps.
size(); ++
I) {
6918 auto *
Op = dyn_cast<Instruction>(DeadInterleavePointerOps[
I]);
6920 Instruction *UI = cast<Instruction>(U);
6921 return !VecValuesToIgnore.contains(U) &&
6922 (!isAccessInterleaved(UI) ||
6923 getInterleavedAccessGroup(UI)->getInsertPos() == UI);
6927 DeadInterleavePointerOps.
append(
Op->op_begin(),
Op->op_end());
6930 for (
const auto &[
_, Ops] : DeadInvariantStoreOps) {
6944 (isa<BranchInst>(&
I) && !cast<BranchInst>(&
I)->isConditional());
6947 for (
unsigned I = 0;
I != DeadOps.
size(); ++
I) {
6948 auto *
Op = dyn_cast<Instruction>(DeadOps[
I]);
6951 if (
auto *Br = dyn_cast_or_null<BranchInst>(
Op)) {
6959 if ((ThenEmpty && ElseEmpty) ||
6961 ElseBB->
phis().empty()) ||
6963 ThenBB->
phis().empty())) {
6972 (isa<PHINode>(
Op) &&
Op->getParent() == Header) ||
6975 return !VecValuesToIgnore.contains(U) &&
6976 !ValuesToIgnore.contains(U) && !IsLiveOutDead(U);
6987 [
this](
User *U) { return ValuesToIgnore.contains(U); }))
6991 DeadOps.
append(
Op->op_begin(),
Op->op_end());
7012 if (!InLoopReductions.
empty())
7036 bool InLoop = !ReductionOperations.
empty();
7039 InLoopReductions.
insert(Phi);
7042 for (
auto *
I : ReductionOperations) {
7043 InLoopReductionImmediateChains[
I] = LastChain;
7047 LLVM_DEBUG(
dbgs() <<
"LV: Using " << (InLoop ?
"inloop" :
"out of loop")
7048 <<
" reduction for phi: " << *Phi <<
"\n");
7061 unsigned WidestType;
7070 unsigned N =
RegSize.getKnownMinValue() / WidestType;
7091 <<
"overriding computed VF.\n");
7096 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing. Scalable VF requested, but "
7097 <<
"not supported by the target.\n");
7099 "Scalable vectorization requested but not supported by the target",
7100 "the scalable user-specified vectorization width for outer-loop "
7101 "vectorization cannot be used because the target does not support "
7102 "scalable vectors.",
7103 "ScalableVFUnfeasible", ORE, OrigLoop);
7108 "VF needs to be a power of two");
7110 <<
"VF " << VF <<
" to build VPlans.\n");
7117 return {VF, 0 , 0 };
7121 dbgs() <<
"LV: Not vectorizing. Inner loops aren't supported in the "
7122 "VPlan-native path.\n");
7140 <<
"LV: Invalidate all interleaved groups due to fold-tail by masking "
7141 "which requires masked-interleaved support.\n");
7157 "UserVF ignored because it may be larger than the maximal safe VF",
7158 "InvalidUserVF", ORE, OrigLoop);
7161 "VF needs to be a power of two");
7167 buildVPlansWithVPRecipes(UserVF, UserVF);
7172 "InvalidCost", ORE, OrigLoop);
7186 for (
const auto &VF : VFCandidates) {
7235 for (
unsigned I = 0;
I != IVInsts.
size();
I++) {
7236 for (
Value *
Op : IVInsts[
I]->operands()) {
7237 auto *OpI = dyn_cast<Instruction>(
Op);
7238 if (
Op ==
IV || !OpI || !OrigLoop->
contains(OpI) || !
Op->hasOneUse())
7244 for (
User *U :
IV->users()) {
7245 auto *CI = cast<Instruction>(U);
7266 dbgs() <<
"Cost of " << InductionCost <<
" for VF " << VF
7267 <<
": induction instruction " << *IVInst <<
"\n";
7269 Cost += InductionCost;
7283 auto *
Term = dyn_cast<BranchInst>(EB->getTerminator());
7286 if (
auto *CondI = dyn_cast<Instruction>(
Term->getOperand(0))) {
7287 ExitInstrs.
insert(CondI);
7291 for (
unsigned I = 0;
I != ExitInstrs.
size(); ++
I) {
7298 dbgs() <<
"Cost of " << CondICost <<
" for VF " << VF
7299 <<
": exit condition instruction " << *CondI <<
"\n";
7303 auto *OpI = dyn_cast<Instruction>(
Op);
7304 if (!OpI ||
any_of(OpI->users(), [&ExitInstrs,
this](
User *U) {
7305 return OrigLoop->contains(cast<Instruction>(U)->getParent()) &&
7306 !ExitInstrs.contains(cast<Instruction>(U));
7324 const auto &ChainOps = RdxDesc.getReductionOpChain(RedPhi, OrigLoop);
7327 auto IsZExtOrSExt = [](
const unsigned Opcode) ->
bool {
7328 return Opcode == Instruction::ZExt || Opcode == Instruction::SExt;
7337 for (
auto *ChainOp : ChainOps) {
7338 for (
Value *
Op : ChainOp->operands()) {
7339 if (
auto *
I = dyn_cast<Instruction>(
Op)) {
7340 ChainOpsAndOperands.insert(
I);
7341 if (
I->getOpcode() == Instruction::Mul) {
7342 auto *Ext0 = dyn_cast<Instruction>(
I->getOperand(0));
7343 auto *Ext1 = dyn_cast<Instruction>(
I->getOperand(1));
7344 if (Ext0 && IsZExtOrSExt(Ext0->getOpcode()) && Ext1 &&
7345 Ext0->getOpcode() == Ext1->getOpcode()) {
7346 ChainOpsAndOperands.insert(Ext0);
7347 ChainOpsAndOperands.insert(Ext1);
7356 auto ReductionCost =
7362 "reduction op visited multiple times");
7364 LLVM_DEBUG(
dbgs() <<
"Cost of " << ReductionCost <<
" for VF " << VF
7365 <<
":\n in-loop reduction " << *
I <<
"\n");
7366 Cost += *ReductionCost;
7381 auto BranchCost = CostCtx.
getLegacyCost(BB->getTerminator(), VF);
7388 for (
Instruction *ForcedScalar : CM.ForcedScalars[VF]) {
7394 dbgs() <<
"Cost of " << ForcedCost <<
" for VF " << VF
7395 <<
": forced scalar " << *ForcedScalar <<
"\n";
7399 for (
const auto &[Scalarized, ScalarCost] : CM.InstsToScalarize[VF]) {
7404 dbgs() <<
"Cost of " << ScalarCost <<
" for VF " << VF
7405 <<
": profitable to scalarize " << *Scalarized <<
"\n";
7424 <<
" (Estimated cost per lane: ");
7426 double CostPerLane = double(*
Cost.
getValue()) / EstimatedWidth;
7445 if (
auto *S = dyn_cast<VPSingleDefRecipe>(R))
7446 return dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
7447 if (
auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(R))
7448 return &WidenMem->getIngredient();
7454 for (
VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
7456 if (
auto *
IR = dyn_cast<VPInterleaveRecipe>(&R)) {
7457 auto *IG =
IR->getInterleaveGroup();
7458 unsigned NumMembers = IG->getNumMembers();
7459 for (
unsigned I = 0;
I != NumMembers; ++
I) {
7467 if (isa<VPPartialReductionRecipe>(&R))
7477 return any_of(TheLoop->
blocks(), [&SeenInstrs, &CostCtx,
7479 return any_of(*BB, [&SeenInstrs, &CostCtx, TheLoop, BB](Instruction &I) {
7480 if (isa<PHINode>(&I) && BB == TheLoop->getHeader())
7482 return !SeenInstrs.contains(&I) && !CostCtx.skipCostComputation(&I, true);
7492 VPlan &FirstPlan = *VPlans[0];
7498 ?
"Reciprocal Throughput\n"
7500 ?
"Instruction Latency\n"
7503 ?
"Code Size and Latency\n"
7508 "More than a single plan/VF w/o any plan having scalar VF");
7512 LLVM_DEBUG(
dbgs() <<
"LV: Scalar loop costs: " << ScalarCost <<
".\n");
7517 if (ForceVectorization) {
7524 for (
auto &
P : VPlans) {
7531 <<
"LV: Not considering vector loop of width " << VF
7532 <<
" because it will not generate any vector instructions.\n");
7538 if (isMoreProfitable(CurrentFactor, BestFactor))
7539 BestFactor = CurrentFactor;
7542 if (isMoreProfitable(CurrentFactor, ScalarFactor))
7543 ProfitableVFs.push_back(CurrentFactor);
7561 precomputeCosts(BestPlan, BestFactor.
Width, CostCtx);
7565 bool PlanForEarlyExitLoop =
7571 CostCtx, OrigLoop) ||
7573 CostCtx, OrigLoop)) &&
7574 " VPlan cost model and legacy cost model disagreed");
7576 "when vectorizing, the scalar cost must be computed.");
7587 bool IsUnrollMetadata =
false;
7588 MDNode *LoopID = L->getLoopID();
7592 auto *MD = dyn_cast<MDNode>(LoopID->
getOperand(
I));
7594 const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7596 S && S->getString().starts_with(
"llvm.loop.unroll.disable");
7602 if (!IsUnrollMetadata) {
7604 LLVMContext &Context = L->getHeader()->getContext();
7607 MDString::get(Context,
"llvm.loop.unroll.runtime.disable"));
7613 L->setLoopID(NewLoopID);
7623 auto *EpiRedResult = dyn_cast<VPInstruction>(R);
7624 if (!EpiRedResult ||
7628 auto *EpiRedHeaderPhi =
7629 cast<VPReductionPHIRecipe>(EpiRedResult->getOperand(0));
7631 EpiRedHeaderPhi->getRecurrenceDescriptor();
7632 Value *MainResumeValue =
7633 EpiRedHeaderPhi->getStartValue()->getUnderlyingValue();
7636 auto *Cmp = cast<ICmpInst>(MainResumeValue);
7638 "AnyOf expected to start with ICMP_NE");
7640 "AnyOf expected to start by comparing main resume value to original "
7642 MainResumeValue = Cmp->getOperand(0);
7646 Value *Cmp, *OrigResumeV;
7647 bool IsExpectedPattern =
7654 assert(IsExpectedPattern &&
"Unexpected reduction resume pattern");
7655 (void)IsExpectedPattern;
7656 MainResumeValue = OrigResumeV;
7658 PHINode *MainResumePhi = cast<PHINode>(MainResumeValue);
7663 using namespace VPlanPatternMatch;
7664 auto IsResumePhi = [](
VPUser *U) {
7665 auto *VPI = dyn_cast<VPInstruction>(U);
7669 "ResumePhi must have a single user");
7670 auto *EpiResumePhiVPI =
7671 cast<VPInstruction>(*
find_if(EpiRedResult->users(), IsResumePhi));
7672 auto *EpiResumePhi = cast<PHINode>(State.
get(EpiResumePhiVPI,
true));
7673 EpiResumePhi->setIncomingValueForBlock(
7682 "Trying to execute plan with unsupported VF");
7684 "Trying to execute plan with unsupported UF");
7686 ((VectorizingEpilogue && ExpandedSCEVs) ||
7687 (!VectorizingEpilogue && !ExpandedSCEVs)) &&
7688 "expanded SCEVs to reuse can only be used during epilogue vectorization");
7704#ifdef EXPENSIVE_CHECKS
7705 assert(DT->
verify(DominatorTree::VerificationLevel::Fast));
7716 assert(VectorizingEpilogue &&
"should only re-use the existing trip "
7717 "count during epilogue vectorization");
7725 if (VectorizingEpilogue)
7731 std::unique_ptr<LoopVersioning> LVer =
nullptr;
7739 LVer = std::make_unique<LoopVersioning>(
7742 State.
LVer = &*LVer;
7767 if (VectorizingEpilogue) {
7769 "Epilogue vectorisation not yet supported with early exits");
7774 if (Phi.getBasicBlockIndex(Pred) != -1)
7776 Phi.addIncoming(Phi.getIncomingValueForBlock(BypassBlock), Pred);
7782 &R, State, State.
CFG.
VPBB2IRBB[MiddleVPBB], BypassBlock);
7785 auto *Inc = cast<PHINode>(IVPhi->getIncomingValueForBlock(PH));
7787 Inc->setIncomingValueForBlock(BypassBlock, V);
7797 std::optional<MDNode *> VectorizedLoopID =
7803 if (VectorizedLoopID) {
7804 L->setLoopID(*VectorizedLoopID);
7830 cast<BranchInst>(State.
CFG.
VPBB2IRBB[MiddleVPBB]->getTerminator());
7831 if (MiddleTerm->isConditional() &&
7835 assert(TripCount > 0 &&
"trip count should not be zero");
7836 const uint32_t Weights[] = {1, TripCount - 1};
7851 const SCEV2ValueTy &ExpandedSCEVs) {
7886 dbgs() <<
"Create Skeleton for epilogue vectorized loop (first pass)\n"
7896 dbgs() <<
"intermediate fn:\n"
7904 assert(Bypass &&
"Expected valid bypass basic block.");
7925 TCCheckBlock->
setName(
"vector.main.loop.iter.check");
7929 DT,
LI,
nullptr,
"vector.ph");
7934 "TC check is expected to dominate Bypass");
7951 return TCCheckBlock;
7962 const SCEV2ValueTy &ExpandedSCEVs) {
7970 nullptr,
"vec.epilog.iter.check",
true);
7972 VecEpilogueIterationCountCheck);
7978 "expected this to be saved from the previous pass.");
8006 for (
PHINode &Phi : VecEpilogueIterationCountCheck->
phis())
8009 for (
PHINode *Phi : PhisInBlock) {
8011 Phi->replaceIncomingBlockWith(
8013 VecEpilogueIterationCountCheck);
8020 return EPI.EpilogueIterationCountCheck == IncB;
8043 "Expected trip count to have been saved in the first pass.");
8047 "saved trip count does not dominate insertion point.");
8058 Value *CheckMinIters =
8062 "min.epilog.iters.check");
8068 unsigned EpilogueLoopStep =
8074 unsigned EstimatedSkipCount = std::min(MainLoopStep, EpilogueLoopStep);
8075 const uint32_t Weights[] = {EstimatedSkipCount,
8076 MainLoopStep - EstimatedSkipCount};
8096 dbgs() <<
"Create Skeleton for epilogue vectorized loop (second pass)\n"
8111 return getVPValueOrAddLiveIn(
Op);
8123 "unsupported switch either exiting loop or continuing to header");
8128 BasicBlock *DefaultDst = SI->getDefaultDest();
8130 for (
auto &
C : SI->cases()) {
8132 assert(!EdgeMaskCache.
contains({Src, Dst}) &&
"Edge masks already created");
8135 if (Dst == DefaultDst)
8137 auto &Compares = Dst2Compares[Dst];
8145 VPValue *DefaultMask =
nullptr;
8146 for (
const auto &[Dst, Conds] : Dst2Compares) {
8155 EdgeMaskCache[{Src, Dst}] = Mask;
8161 DefaultMask = DefaultMask ? Builder.
createOr(DefaultMask, Mask) : Mask;
8165 DefaultMask = Builder.
createNot(DefaultMask);
8169 EdgeMaskCache[{Src, DefaultDst}] = DefaultMask;
8176 std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8178 if (ECEntryIt != EdgeMaskCache.
end())
8179 return ECEntryIt->second;
8181 if (
auto *SI = dyn_cast<SwitchInst>(Src->getTerminator())) {
8183 assert(EdgeMaskCache.
contains(Edge) &&
"Mask for Edge not created?");
8184 return EdgeMaskCache[Edge];
8190 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8191 assert(BI &&
"Unexpected terminator found");
8193 return EdgeMaskCache[Edge] = SrcMask;
8202 return EdgeMaskCache[Edge] = SrcMask;
8205 assert(EdgeMask &&
"No Edge Mask found for condition");
8217 return EdgeMaskCache[Edge] = EdgeMask;
8224 std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8226 assert(ECEntryIt != EdgeMaskCache.
end() &&
8227 "looking up mask for edge which has not been created");
8228 return ECEntryIt->second;
8236 BlockMaskCache[Header] =
nullptr;
8248 HeaderVPBB->
insert(
IV, NewInsertionPoint);
8255 BlockMaskCache[Header] = BlockMask;
8261 assert(BCEntryIt != BlockMaskCache.
end() &&
8262 "Trying to access mask for block without one.");
8263 return BCEntryIt->second;
8267 assert(OrigLoop->
contains(BB) &&
"Block is not a part of a loop");
8268 assert(BlockMaskCache.
count(BB) == 0 &&
"Mask for block already computed");
8270 "Loop header must have cached block mask");
8276 for (
auto *Predecessor :
8280 BlockMaskCache[BB] = EdgeMask;
8285 BlockMask = EdgeMask;
8289 BlockMask = Builder.
createOr(BlockMask, EdgeMask, {});
8292 BlockMaskCache[BB] = BlockMask;
8298 assert((isa<LoadInst>(
I) || isa<StoreInst>(
I)) &&
8299 "Must be called with either a load or store");
8305 "CM decision should be taken at this point.");
8331 auto *
GEP = dyn_cast<GetElementPtrInst>(
8332 Ptr->getUnderlyingValue()->stripPointerCasts());
8346 GEP ?
GEP->getNoWrapFlags()
8350 Builder.
insert(VectorPtr);
8353 if (
LoadInst *Load = dyn_cast<LoadInst>(
I))
8371 "step must be loop invariant");
8375 if (
auto *TruncI = dyn_cast<TruncInst>(PhiOrTrunc)) {
8378 TruncI->getDebugLoc());
8380 assert(isa<PHINode>(PhiOrTrunc) &&
"must be a phi node here");
8382 IndDesc, Phi->getDebugLoc());
8392 *PSE.
getSE(), *OrigLoop);
8405 Phi->getDebugLoc());
8419 auto IsOptimizableIVTruncate =
8427 IsOptimizableIVTruncate(
I),
Range)) {
8429 auto *
Phi = cast<PHINode>(
I->getOperand(0));
8440 unsigned NumIncoming =
Phi->getNumIncomingValues();
8449 for (
unsigned In = 0;
In < NumIncoming;
In++) {
8454 assert(In == 0 &&
"Both null and non-null edge masks found");
8456 "Distinct incoming values with one having a full mask");
8477 if (
ID && (
ID == Intrinsic::assume ||
ID == Intrinsic::lifetime_end ||
8478 ID == Intrinsic::lifetime_start ||
ID == Intrinsic::sideeffect ||
8479 ID == Intrinsic::pseudoprobe ||
8480 ID == Intrinsic::experimental_noalias_scope_decl))
8486 bool ShouldUseVectorIntrinsic =
8493 if (ShouldUseVectorIntrinsic)
8498 std::optional<unsigned> MaskPos;
8520 Variant = Decision.Variant;
8521 MaskPos = Decision.MaskPos;
8528 if (ShouldUseVectorCall) {
8529 if (MaskPos.has_value()) {
8544 Ops.insert(Ops.
begin() + *MaskPos, Mask);
8555 assert(!isa<BranchInst>(
I) && !isa<PHINode>(
I) && !isa<LoadInst>(
I) &&
8556 !isa<StoreInst>(
I) &&
"Instruction should have been handled earlier");
8570 switch (
I->getOpcode()) {
8573 case Instruction::SDiv:
8574 case Instruction::UDiv:
8575 case Instruction::SRem:
8576 case Instruction::URem: {
8584 auto *SafeRHS = Builder.
createSelect(Mask, Ops[1], One,
I->getDebugLoc());
8590 case Instruction::Add:
8591 case Instruction::And:
8592 case Instruction::AShr:
8593 case Instruction::FAdd:
8594 case Instruction::FCmp:
8595 case Instruction::FDiv:
8596 case Instruction::FMul:
8597 case Instruction::FNeg:
8598 case Instruction::FRem:
8599 case Instruction::FSub:
8600 case Instruction::ICmp:
8601 case Instruction::LShr:
8602 case Instruction::Mul:
8603 case Instruction::Or:
8604 case Instruction::Select:
8605 case Instruction::Shl:
8606 case Instruction::Sub:
8607 case Instruction::Xor:
8608 case Instruction::Freeze:
8615 auto GetConstantViaSCEV = [
this, &SE](
VPValue *
Op) {
8616 if (!
Op->isLiveIn())
8618 Value *
V =
Op->getUnderlyingValue();
8619 if (isa<Constant>(V) || !SE.
isSCEVable(
V->getType()))
8621 auto *
C = dyn_cast<SCEVConstant>(SE.
getSCEV(V));
8627 if (
I->getOpcode() == Instruction::Mul)
8628 NewOps[0] = GetConstantViaSCEV(NewOps[0]);
8630 NewOps[1] = GetConstantViaSCEV(NewOps[1]);
8637VPRecipeBuilder::tryToWidenHistogram(
const HistogramInfo *HI,
8640 unsigned Opcode =
HI->Update->getOpcode();
8641 assert((Opcode == Instruction::Add || Opcode == Instruction::Sub) &&
8642 "Histogram update operation must be an Add or Sub");
8657 HI->Store->getDebugLoc());
8663 auto *PN = cast<PHINode>(R->getUnderlyingValue());
8665 getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8683 if (!IsUniform &&
Range.Start.isScalable() && isa<IntrinsicInst>(
I)) {
8685 case Intrinsic::assume:
8686 case Intrinsic::lifetime_start:
8687 case Intrinsic::lifetime_end:
8709 VPValue *BlockInMask =
nullptr;
8710 if (!IsPredicated) {
8714 LLVM_DEBUG(
dbgs() <<
"LV: Scalarizing and predicating:" << *
I <<
"\n");
8725 assert((
Range.Start.isScalar() || !IsUniform || !IsPredicated ||
8726 (
Range.Start.isScalable() && isa<IntrinsicInst>(
I))) &&
8727 "Should not predicate a uniform recipe");
8738 PartialReductionChains;
8740 getScaledReductions(Phi, RdxDesc.getLoopExitInstr(),
Range,
8741 PartialReductionChains);
8750 for (
const auto &[PartialRdx,
_] : PartialReductionChains)
8751 PartialReductionBinOps.
insert(PartialRdx.BinOp);
8753 auto ExtendIsOnlyUsedByPartialReductions =
8755 return all_of(Extend->users(), [&](
const User *U) {
8756 return PartialReductionBinOps.contains(U);
8762 for (
auto Pair : PartialReductionChains) {
8764 if (ExtendIsOnlyUsedByPartialReductions(Chain.
ExtendA) &&
8765 ExtendIsOnlyUsedByPartialReductions(Chain.
ExtendB))
8766 ScaledReductionMap.
insert(std::make_pair(Chain.
Reduction, Pair.second));
8770bool VPRecipeBuilder::getScaledReductions(
8772 SmallVectorImpl<std::pair<PartialReductionChain, unsigned>> &Chains) {
8777 auto *Update = dyn_cast<BinaryOperator>(RdxExitInstr);
8781 Value *
Op = Update->getOperand(0);
8782 Value *PhiOp = Update->getOperand(1);
8789 if (
auto *OpInst = dyn_cast<Instruction>(
Op)) {
8790 if (getScaledReductions(
PHI, OpInst,
Range, Chains)) {
8791 PHI = Chains.rbegin()->first.Reduction;
8793 Op = Update->getOperand(0);
8794 PhiOp = Update->getOperand(1);
8802 auto *BinOp = dyn_cast<BinaryOperator>(
Op);
8803 if (!BinOp || !BinOp->hasOneUse())
8812 Instruction *ExtA = cast<Instruction>(BinOp->getOperand(0));
8813 Instruction *ExtB = cast<Instruction>(BinOp->getOperand(1));
8822 unsigned TargetScaleFactor =
8823 PHI->getType()->getPrimitiveSizeInBits().getKnownScalarFactor(
8824 A->getType()->getPrimitiveSizeInBits());
8829 Update->getOpcode(),
A->getType(),
B->getType(),
PHI->getType(),
8830 VF, OpAExtend, OpBExtend,
8831 std::make_optional(BinOp->getOpcode()));
8835 Chains.push_back(std::make_pair(Chain, TargetScaleFactor));
8847 if (
auto *Phi = dyn_cast<PHINode>(Instr)) {
8848 if (Phi->getParent() != OrigLoop->
getHeader())
8851 if ((Recipe = tryToOptimizeInductionPHI(Phi,
Operands,
Range)))
8857 "can only widen reductions and fixed-order recurrences here");
8866 unsigned ScaleFactor =
8879 PhisToFix.push_back(PhiRecipe);
8883 if (isa<TruncInst>(Instr) && (Recipe = tryToOptimizeInductionTruncate(
8892 if (
auto *CI = dyn_cast<CallInst>(Instr))
8895 if (
StoreInst *SI = dyn_cast<StoreInst>(Instr))
8897 return tryToWidenHistogram(*HistInfo,
Operands);
8899 if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8905 if (!shouldWiden(Instr,
Range))
8908 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(Instr))
8912 if (
auto *SI = dyn_cast<SelectInst>(Instr)) {
8917 if (
auto *CI = dyn_cast<CastInst>(Instr)) {
8922 return tryToWiden(Instr,
Operands);
8929 "Unexpected number of operands for partial reduction");
8934 if (isa<VPReductionPHIRecipe>(BinOpRecipe) ||
8935 isa<VPPartialReductionRecipe>(BinOpRecipe))
8938 unsigned ReductionOpcode =
Reduction->getOpcode();
8940 assert((ReductionOpcode == Instruction::Add ||
8941 ReductionOpcode == Instruction::Sub) &&
8942 "Expected an ADD or SUB operation for predicated partial "
8943 "reductions (because the neutral element in the mask is zero)!");
8953void LoopVectorizationPlanner::buildVPlansWithVPRecipes(
ElementCount MinVF,
8957 auto MaxVFTimes2 = MaxVF * 2;
8959 VFRange SubRange = {VF, MaxVFTimes2};
8960 if (
auto Plan = tryToBuildVPlanWithVPRecipes(SubRange)) {
8974 VPlans.push_back(std::move(Plan));
8984 Value *StartIdx = ConstantInt::get(IdxTy, 0);
8991 Header->insert(CanonicalIVPHI, Header->begin());
8996 Instruction::Add, {CanonicalIVPHI, &Plan.
getVFxUF()}, {HasNUW,
false},
DL,
8998 CanonicalIVPHI->
addOperand(CanonicalIVIncrement);
9011 auto *WideIntOrFp = dyn_cast<VPWidenIntOrFpInductionRecipe>(WideIV);
9014 if (WideIntOrFp && WideIntOrFp->getTruncInst())
9021 if (!WideIntOrFp || !WideIntOrFp->isCanonical()) {
9023 ID.getKind(), dyn_cast_or_null<FPMathOperator>(
ID.getInductionBinOp()),
9024 Start, VectorTC, Step);
9036 auto *ResumePhiRecipe =
9039 return ResumePhiRecipe;
9050 auto *MiddleVPBB = cast<VPBasicBlock>(ScalarPH->getSinglePredecessor());
9054 VPBuilder MiddleBuilder(MiddleVPBB, MiddleVPBB->getFirstNonPhi());
9059 auto *ScalarPhiIRI = cast<VPIRInstruction>(&ScalarPhiR);
9060 auto *ScalarPhiI = dyn_cast<PHINode>(&ScalarPhiIRI->getInstruction());
9066 auto *VectorPhiR = cast<VPHeaderPHIRecipe>(Builder.
getRecipe(ScalarPhiI));
9067 if (
auto *WideIVR = dyn_cast<VPWidenInductionRecipe>(VectorPhiR)) {
9069 WideIVR, VectorPHBuilder, ScalarPHBuilder, TypeInfo,
9072 "Expected a ResumePhi");
9073 IVEndValues[WideIVR] = ResumePhi->getOperand(0);
9074 ScalarPhiIRI->addOperand(ResumePhi);
9080 assert(cast<VPWidenIntOrFpInductionRecipe>(VectorPhiR)->getTruncInst() &&
9081 "should only skip truncated wide inductions");
9088 bool IsFOR = isa<VPFirstOrderRecurrencePHIRecipe>(VectorPhiR);
9089 auto *ResumeFromVectorLoop = VectorPhiR->getBackedgeValue();
9091 "Cannot handle loops with uncountable early exits");
9095 "vector.recur.extract");
9096 StringRef Name = IsFOR ?
"scalar.recur.init" :
"bc.merge.rdx";
9099 {ResumeFromVectorLoop, VectorPhiR->getStartValue()}, {},
Name);
9112 auto *ExitIRI = dyn_cast<VPIRInstruction>(&R);
9115 auto *ExitPhi = dyn_cast<PHINode>(&ExitIRI->getInstruction());
9119 assert(ExitIRI->getNumOperands() ==
9120 ExitVPBB->getPredecessors().size() &&
9121 "early-exit must update exit values on construction");
9125 Value *IncomingValue = ExitPhi->getIncomingValueForBlock(ExitingBB);
9127 ExitIRI->addOperand(V);
9130 assert(V->getDefiningRecipe()->getParent()->getEnclosingLoopRegion() &&
9131 "Only recipes defined inside a region should need fixing.");
9132 ExitUsersToFix.
insert(ExitIRI);
9135 return ExitUsersToFix;
9143 if (ExitUsersToFix.
empty())
9147 VPBuilder B(MiddleVPBB, MiddleVPBB->getFirstNonPhi());
9152 assert(ExitIRI->getNumOperands() == 1 &&
9153 ExitIRI->getParent()->getSinglePredecessor() == MiddleVPBB &&
9154 "exit values from early exits must be fixed when branch to "
9155 "early-exit is added");
9156 ExitIRI->extractLastLaneOfOperand(
B);
9169 VPBuilder ScalarPHBuilder(ScalarPHVPBB);
9170 VPBuilder MiddleBuilder(MiddleVPBB, MiddleVPBB->getFirstNonPhi());
9175 auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&HeaderPhi);
9180 "Cannot handle loops with uncountable early exits");
9253 if (ExitIRI->getOperand(0) != FOR)
9257 "vector.recur.extract.for.phi");
9259 ExitUsersToFix.remove(ExitIRI);
9265LoopVectorizationPlanner::tryToBuildVPlanWithVPRecipes(
VFRange &
Range) {
9280 bool RequiresScalarEpilogueCheck =
9287 PSE, RequiresScalarEpilogueCheck,
9294 bool IVUpdateMayOverflow =
false;
9328 "Unsupported interleave factor for scalable vectors");
9333 InterleaveGroups.
insert(IG);
9351 bool NeedsBlends = BB != HeaderBB && !BB->phis().empty();
9352 return Legal->blockNeedsPredication(BB) || NeedsBlends;
9355 RecipeBuilder.collectScaledReductions(
Range);
9357 auto *MiddleVPBB = Plan->getMiddleBlock();
9362 if (VPBB != HeaderVPBB)
9366 if (VPBB == HeaderVPBB)
9367 RecipeBuilder.createHeaderMask();
9368 else if (NeedsMasks)
9369 RecipeBuilder.createBlockInMask(BB);
9376 auto *
Phi = dyn_cast<PHINode>(Instr);
9377 if (Phi &&
Phi->getParent() == HeaderBB) {
9378 Operands.push_back(Plan->getOrAddLiveIn(
9381 auto OpRange = RecipeBuilder.mapToVPValues(
Instr->operands());
9382 Operands = {OpRange.begin(), OpRange.end()};
9389 if ((SI = dyn_cast<StoreInst>(&
I)) &&
9397 Recipe->insertBefore(*MiddleVPBB, MBIP);
9402 RecipeBuilder.tryToCreateWidenRecipe(Instr,
Operands,
Range);
9404 Recipe = RecipeBuilder.handleReplication(Instr,
Operands,
Range);
9406 RecipeBuilder.setRecipe(Instr, Recipe);
9407 if (isa<VPHeaderPHIRecipe>(Recipe)) {
9418 "unexpected recipe needs moving");
9431 assert(isa<VPRegionBlock>(Plan->getVectorLoopRegion()) &&
9432 !Plan->getVectorLoopRegion()->getEntryBasicBlock()->empty() &&
9433 "entry block must be set to a VPRegionBlock having a non-empty entry "
9435 RecipeBuilder.fixHeaderPhis();
9441 auto *IVInc = cast<Instruction>(
9446 cast<VPWidenInductionRecipe>(RecipeBuilder.getRecipe(Phi));
9451 if (
auto *UncountableExitingBlock =
9454 *PSE.
getSE(), OrigLoop, UncountableExitingBlock,
9470 adjustRecipesForReductions(Plan, RecipeBuilder,
Range.Start);
9476 InterleaveGroups, RecipeBuilder,
9481 Plan->setName(
"Initial VPlan");
9486 auto *
R = cast<VPRecipeBase>(&U);
9487 return R->getParent()->getParent() ||
9489 Plan->getVectorLoopRegion()->getSinglePredecessor();
9492 auto *StrideV = cast<SCEVUnknown>(Stride)->getValue();
9493 auto *ScevStride = dyn_cast<SCEVConstant>(PSE.
getSCEV(StrideV));
9498 auto *CI = Plan->getOrAddLiveIn(
9499 ConstantInt::get(Stride->getType(), ScevStride->getAPInt()));
9500 if (
VPValue *StrideVPV = Plan->getLiveIn(StrideV))
9506 if (!isa<SExtInst, ZExtInst>(U))
9508 VPValue *StrideVPV = Plan->getLiveIn(U);
9511 unsigned BW =
U->getType()->getScalarSizeInBits();
9512 APInt C = isa<SExtInst>(U) ? ScevStride->getAPInt().sext(BW)
9513 : ScevStride->getAPInt().zext(BW);
9514 VPValue *CI = Plan->getOrAddLiveIn(ConstantInt::get(
U->getType(),
C));
9519 auto BlockNeedsPredication = [
this](
BasicBlock *BB) {
9523 BlockNeedsPredication);
9535 bool WithoutRuntimeCheck =
9538 WithoutRuntimeCheck);
9556 true,
false, OrigLoop);
9560 HCFGBuilder.buildHierarchicalCFG();
9568 *PSE.
getSE(), *TLI);
9580 for (
auto &R : Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
9581 if (isa<VPCanonicalIVPHIRecipe>(&R))
9583 auto *HeaderR = cast<VPHeaderPHIRecipe>(&R);
9584 RecipeBuilder.setRecipe(HeaderR->getUnderlyingInstr(), HeaderR);
9608void LoopVectorizationPlanner::adjustRecipesForReductions(
9610 using namespace VPlanPatternMatch;
9611 VPRegionBlock *VectorLoopRegion = Plan->getVectorLoopRegion();
9617 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9618 if (!PhiR || !PhiR->isInLoop() || (MinVF.
isScalar() && !PhiR->isOrdered()))
9626 "AnyOf and FindLast reductions are not allowed for in-loop reductions");
9631 for (
unsigned I = 0;
I != Worklist.
size(); ++
I) {
9634 auto *UserRecipe = cast<VPSingleDefRecipe>(U);
9635 if (!UserRecipe->getParent()->getEnclosingLoopRegion()) {
9636 assert((UserRecipe->getParent() == MiddleVPBB ||
9637 UserRecipe->getParent() == Plan->getScalarPreheader()) &&
9638 "U must be either in the loop region, the middle block or the "
9639 "scalar preheader.");
9642 Worklist.
insert(UserRecipe);
9655 Instruction *CurrentLinkI = CurrentLink->getUnderlyingInstr();
9658 unsigned IndexOfFirstOperand;
9666 "Expected instruction to be a call to the llvm.fmuladd intrinsic");
9667 assert(((MinVF.
isScalar() && isa<VPReplicateRecipe>(CurrentLink)) ||
9668 isa<VPWidenIntrinsicRecipe>(CurrentLink)) &&
9669 CurrentLink->getOperand(2) == PreviousLink &&
9670 "expected a call where the previous link is the added operand");
9678 {CurrentLink->getOperand(0), CurrentLink->getOperand(1)},
9680 LinkVPBB->
insert(FMulRecipe, CurrentLink->getIterator());
9683 auto *Blend = dyn_cast<VPBlendRecipe>(CurrentLink);
9684 if (PhiR->isInLoop() && Blend) {
9685 assert(Blend->getNumIncomingValues() == 2 &&
9686 "Blend must have 2 incoming values");
9687 if (Blend->getIncomingValue(0) == PhiR)
9688 Blend->replaceAllUsesWith(Blend->getIncomingValue(1));
9690 assert(Blend->getIncomingValue(1) == PhiR &&
9691 "PhiR must be an operand of the blend");
9692 Blend->replaceAllUsesWith(Blend->getIncomingValue(0));
9698 if (isa<VPWidenRecipe>(CurrentLink)) {
9699 assert(isa<CmpInst>(CurrentLinkI) &&
9700 "need to have the compare of the select");
9703 assert(isa<VPWidenSelectRecipe>(CurrentLink) &&
9704 "must be a select recipe");
9705 IndexOfFirstOperand = 1;
9708 "Expected to replace a VPWidenSC");
9709 IndexOfFirstOperand = 0;
9714 CurrentLink->getOperand(IndexOfFirstOperand) == PreviousLink
9715 ? IndexOfFirstOperand + 1
9716 : IndexOfFirstOperand;
9717 VecOp = CurrentLink->getOperand(VecOpId);
9718 assert(VecOp != PreviousLink &&
9719 CurrentLink->getOperand(CurrentLink->getNumOperands() - 1 -
9720 (VecOpId - IndexOfFirstOperand)) ==
9722 "PreviousLink must be the operand other than VecOp");
9731 RdxDesc, CurrentLinkI, PreviousLink, VecOp, CondOp,
9738 CurrentLink->replaceAllUsesWith(RedRecipe);
9740 PreviousLink = RedRecipe;
9747 Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
9762 !isa<VPPartialReductionRecipe>(OrigExitingVPV->getDefiningRecipe())) {
9764 assert(OrigExitingVPV->getDefiningRecipe()->getParent() != LatchVPBB &&
9765 "reduction recipe must be defined before latch");
9767 std::optional<FastMathFlags> FMFs =
9774 return isa<VPInstruction>(&U) &&
9775 cast<VPInstruction>(&U)->getOpcode() ==
9790 assert(!PhiR->
isInLoop() &&
"Unexpected truncated inloop reduction!");
9799 Trunc->
insertAfter(NewExitingVPV->getDefiningRecipe());
9800 Extnd->insertAfter(Trunc);
9802 PhiR->
setOperand(1, Extnd->getVPSingleValue());
9803 NewExitingVPV = Extnd;
9823 FinalReductionResult, [](
VPUser &
User,
unsigned) {
9824 auto *Parent = cast<VPRecipeBase>(&
User)->getParent();
9825 return Parent && !Parent->getParent();
9827 FinalReductionResult->insertBefore(*MiddleVPBB, IP);
9836 return isa<VPWidenSelectRecipe>(U) ||
9837 (isa<VPReplicateRecipe>(U) &&
9838 cast<VPReplicateRecipe>(U)->getUnderlyingInstr()->getOpcode() ==
9839 Instruction::Select);
9845 for (
unsigned I = 0;
I != CmpR->getNumOperands(); ++
I)
9846 if (CmpR->getOperand(
I) == PhiR)
9854 if (
Select->getOperand(1) == PhiR)
9857 Select->getVPSingleValue()->replaceAllUsesWith(
Or);
9876 R->eraseFromParent();
9882 assert(!State.
Lane &&
"VPDerivedIVRecipe being replicated.");
9893 cast_if_present<BinaryOperator>(FPBinOp));
9899 assert((DerivedIV != Index ||
9901 "IV didn't need transforming?");
9909 "uniform recipe shouldn't be predicated");
9915 if (State.
Lane->isFirstLane()) {
9934 if (isa<StoreInst>(UI) &&
9944 for (
unsigned Lane = 0; Lane < EndLane; ++Lane)
10010 LLVM_DEBUG(
dbgs() <<
"LV: cannot compute the outer-loop trip count\n");
10014 Function *
F = L->getHeader()->getParent();
10020 LoopVectorizationCostModel CM(
SEL, L, PSE, LI, LVL, *
TTI, TLI, DB, AC, ORE,
F,
10025 LoopVectorizationPlanner LVP(L, LI, DT, TLI, *
TTI, LVL, CM, IAI, PSE, Hints,
10045 bool AddBranchWeights =
10047 GeneratedRTChecks Checks(PSE, DT, LI,
TTI,
F->getDataLayout(),
10050 VF.
Width, 1, LVL, &CM, BFI, PSI, Checks, BestPlan);
10052 << L->getHeader()->getParent()->getName() <<
"\"\n");
10072 if (
auto *S = dyn_cast<StoreInst>(&Inst)) {
10073 if (S->getValueOperand()->getType()->isFloatTy())
10083 while (!Worklist.
empty()) {
10085 if (!L->contains(
I))
10087 if (!Visited.
insert(
I).second)
10094 if (isa<FPExtInst>(
I) && EmittedRemark.
insert(
I).second)
10097 I->getDebugLoc(), L->getHeader())
10098 <<
"floating point conversion changes vector width. "
10099 <<
"Mixed floating point precision requires an up/down "
10100 <<
"cast that will negatively impact performance.";
10103 for (
Use &
Op :
I->operands())
10104 if (
auto *OpI = dyn_cast<Instruction>(
Op))
10113 std::optional<unsigned> VScale) {
10124 <<
"LV: Interleaving only is not profitable due to runtime checks\n");
10180 uint64_t MinTC = std::max(MinTC1, MinTC2);
10182 MinTC =
alignTo(MinTC, IntVF);
10186 dbgs() <<
"LV: Minimum required TC for runtime checks to be profitable:"
10194 LLVM_DEBUG(
dbgs() <<
"LV: Vectorization is not beneficial: expected "
10195 "trip count < minimum profitable VF ("
10206 : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
10208 VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
10221 if (isa<VPCanonicalIVPHIRecipe>(&R))
10224 cast<PHINode>(R.getVPSingleValue()->getUnderlyingValue()));
10228 auto *VPIRInst = cast<VPIRInstruction>(&R);
10229 auto *IRI = dyn_cast<PHINode>(&VPIRInst->getInstruction());
10244 using namespace VPlanPatternMatch;
10251 return match(&R, m_VPInstruction<VPInstruction::ResumePhi>(
10259 "vec.epilog.resume.val");
10266 const SCEV2ValueTy &ExpandedSCEVs,
10270 Header->setName(
"vec.epilog.vector.body");
10279 auto *ExpandR = dyn_cast<VPExpandSCEVRecipe>(&R);
10282 auto *ExpandedVal =
10283 Plan.
getOrAddLiveIn(ExpandedSCEVs.find(ExpandR->getSCEV())->second);
10287 ExpandR->eraseFromParent();
10293 if (
auto *
IV = dyn_cast<VPCanonicalIVPHIRecipe>(&R)) {
10300 BasicBlock *MainMiddle = find_singleton<BasicBlock>(
10303 if (BB != EPI.MainLoopIterationCountCheck &&
10304 BB != EPI.EpilogueIterationCountCheck &&
10305 BB != EPI.SCEVSafetyCheck && BB != EPI.MemSafetyCheck)
10310 Type *IdxTy =
IV->getScalarType();
10311 PHINode *EPResumeVal = find_singleton<PHINode>(
10312 L->getLoopPreheader()->phis(),
10314 if (P.getType() == IdxTy &&
10315 P.getIncomingValueForBlock(MainMiddle) == EPI.VectorTripCount &&
10317 P.getIncomingValueForBlock(EPI.MainLoopIterationCountCheck),
10322 assert(EPResumeVal &&
"must have a resume value for the canonical IV");
10326 return isa<VPScalarIVStepsRecipe>(U) ||
10327 isa<VPScalarCastRecipe>(U) ||
10328 isa<VPDerivedIVRecipe>(U) ||
10329 cast<VPInstruction>(U)->getOpcode() ==
10332 "the canonical IV should only be used by its increment or "
10333 "ScalarIVSteps when resetting the start value");
10334 IV->setOperand(0, VPV);
10338 Value *ResumeV =
nullptr;
10340 if (
auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
10341 ResumeV = cast<PHINode>(ReductionPhi->getUnderlyingInstr())
10342 ->getIncomingValueForBlock(L->getLoopPreheader());
10344 ReductionPhi->getRecurrenceDescriptor();
10371 PHINode *IndPhi = cast<VPWidenInductionRecipe>(&R)->getPHINode();
10376 assert(ResumeV &&
"Must have a resume value");
10378 cast<VPHeaderPHIRecipe>(&R)->setStartValue(StartVal);
10384 "VPlan-native path is not enabled. Only process inner loops.");
10387 << L->getHeader()->getParent()->getName() <<
"' from "
10388 << L->getLocStr() <<
"\n");
10393 dbgs() <<
"LV: Loop hints:"
10404 Function *
F = L->getHeader()->getParent();
10415 LLVM_DEBUG(
dbgs() <<
"LV: Loop hints prevent vectorization.\n");
10426 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: Cannot prove legality.\n");
10433 "early exit is not enabled",
10434 "UncountableEarlyExitLoopsDisabled",
ORE, L);
10440 "types is not yet supported",
10441 "StructCallVectorizationUnsupported",
ORE, L);
10450 if (!L->isInnermost())
10454 assert(L->isInnermost() &&
"Inner loop expected.");
10464 if (UseInterleaved)
10471 [LoopLatch](
BasicBlock *BB) { return BB != LoopLatch; })) {
10473 "requiring a scalar epilogue is unsupported",
10474 "UncountableEarlyExitUnsupported",
ORE, L);
10488 LLVM_DEBUG(
dbgs() <<
"LV: Found a loop with a very small trip count. "
10489 <<
"This loop is worth vectorizing only if no scalar "
10490 <<
"iteration overheads are incurred.");
10492 LLVM_DEBUG(
dbgs() <<
" But vectorizing was explicitly forced.\n");
10505 LLVM_DEBUG(
dbgs() <<
" But the target considers the trip count too "
10506 "small to consider vectorizing.\n");
10508 "The trip count is below the minial threshold value.",
10509 "loop trip count is too low, avoiding vectorization",
10510 "LowTripCount",
ORE, L);
10519 if (
F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10521 "Can't vectorize when the NoImplicitFloat attribute is used",
10522 "loop not vectorized due to NoImplicitFloat attribute",
10523 "NoImplicitFloat",
ORE, L);
10535 "Potentially unsafe FP op prevents vectorization",
10536 "loop not vectorized due to unsafe FP support.",
10537 "UnsafeFP",
ORE, L);
10542 bool AllowOrderedReductions;
10552 ExactFPMathInst->getDebugLoc(),
10553 ExactFPMathInst->getParent())
10554 <<
"loop not vectorized: cannot prove it is safe to reorder "
10555 "floating-point operations";
10557 LLVM_DEBUG(
dbgs() <<
"LV: loop not vectorized: cannot prove it is safe to "
10558 "reorder floating-point operations\n");
10564 LoopVectorizationCostModel CM(
SEL, L, PSE,
LI, &LVL, *
TTI,
TLI,
DB,
AC,
ORE,
10567 LoopVectorizationPlanner LVP(L,
LI,
DT,
TLI, *
TTI, &LVL, CM, IAI, PSE, Hints,
10575 LVP.
plan(UserVF, UserIC);
10582 bool AddBranchWeights =
10584 GeneratedRTChecks Checks(PSE,
DT,
LI,
TTI,
F->getDataLayout(),
10590 unsigned SelectedIC = std::max(IC, UserIC);
10597 bool ForceVectorization =
10599 if (!ForceVectorization &&
10604 DEBUG_TYPE,
"CantReorderMemOps", L->getStartLoc(),
10606 <<
"loop not vectorized: cannot prove it is safe to reorder "
10607 "memory operations";
10616 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10617 bool VectorizeLoop =
true, InterleaveLoop =
true;
10619 LLVM_DEBUG(
dbgs() <<
"LV: Vectorization is possible but not beneficial.\n");
10620 VecDiagMsg = std::make_pair(
10621 "VectorizationNotBeneficial",
10622 "the cost-model indicates that vectorization is not beneficial");
10623 VectorizeLoop =
false;
10629 LLVM_DEBUG(
dbgs() <<
"LV: Ignoring UserIC, because vectorization and "
10630 "interleaving should be avoided up front\n");
10631 IntDiagMsg = std::make_pair(
10632 "InterleavingAvoided",
10633 "Ignoring UserIC, because interleaving was avoided up front");
10634 InterleaveLoop =
false;
10635 }
else if (IC == 1 && UserIC <= 1) {
10638 IntDiagMsg = std::make_pair(
10639 "InterleavingNotBeneficial",
10640 "the cost-model indicates that interleaving is not beneficial");
10641 InterleaveLoop =
false;
10643 IntDiagMsg.first =
"InterleavingNotBeneficialAndDisabled";
10644 IntDiagMsg.second +=
10645 " and is explicitly disabled or interleave count is set to 1";
10647 }
else if (IC > 1 && UserIC == 1) {
10650 dbgs() <<
"LV: Interleaving is beneficial but is explicitly disabled.");
10651 IntDiagMsg = std::make_pair(
10652 "InterleavingBeneficialButDisabled",
10653 "the cost-model indicates that interleaving is beneficial "
10654 "but is explicitly disabled or interleave count is set to 1");
10655 InterleaveLoop =
false;
10661 if (!VectorizeLoop && InterleaveLoop && LVL.
hasHistograms()) {
10662 LLVM_DEBUG(
dbgs() <<
"LV: Not interleaving without vectorization due "
10663 <<
"to histogram operations.\n");
10664 IntDiagMsg = std::make_pair(
10665 "HistogramPreventsScalarInterleaving",
10666 "Unable to interleave without vectorization due to constraints on "
10667 "the order of histogram operations");
10668 InterleaveLoop =
false;
10672 IC = UserIC > 0 ? UserIC : IC;
10676 if (!VectorizeLoop && !InterleaveLoop) {
10680 L->getStartLoc(), L->getHeader())
10681 << VecDiagMsg.second;
10685 L->getStartLoc(), L->getHeader())
10686 << IntDiagMsg.second;
10691 if (!VectorizeLoop && InterleaveLoop) {
10695 L->getStartLoc(), L->getHeader())
10696 << VecDiagMsg.second;
10698 }
else if (VectorizeLoop && !InterleaveLoop) {
10700 <<
") in " << L->getLocStr() <<
'\n');
10703 L->getStartLoc(), L->getHeader())
10704 << IntDiagMsg.second;
10706 }
else if (VectorizeLoop && InterleaveLoop) {
10708 <<
") in " << L->getLocStr() <<
'\n');
10712 bool DisableRuntimeUnroll =
false;
10713 MDNode *OrigLoopID = L->getLoopID();
10715 using namespace ore;
10716 if (!VectorizeLoop) {
10717 assert(IC > 1 &&
"interleave count should not be 1 or 0");
10730 <<
"interleaved loop (interleaved count: "
10731 << NV(
"InterleaveCount", IC) <<
")";
10741 std::unique_ptr<VPlan> BestMainPlan(BestPlan.
duplicate());
10751 EPI, &LVL, &CM,
BFI,
PSI, Checks,
10754 *BestMainPlan, MainILV,
DT,
false);
10763 Checks, BestEpiPlan);
10768 DT,
true, &ExpandedSCEVs);
10769 ++LoopsEpilogueVectorized;
10772 DisableRuntimeUnroll =
true;
10776 PSI, Checks, BestPlan);
10784 DisableRuntimeUnroll =
true;
10795 "DT not preserved correctly");
10797 std::optional<MDNode *> RemainderLoopID =
10800 if (RemainderLoopID) {
10801 L->setLoopID(*RemainderLoopID);
10803 if (DisableRuntimeUnroll)
10827 bool Changed =
false, CFGChanged =
false;
10834 for (
const auto &L : *
LI)
10835 Changed |= CFGChanged |=
10846 LoopsAnalyzed += Worklist.
size();
10849 while (!Worklist.
empty()) {
10894 if (!Result.MadeAnyChange)
10908 if (Result.MadeCFGChange) {
10924 OS, MapClassName2PassName);
10927 OS << (InterleaveOnlyWhenForced ?
"" :
"no-") <<
"interleave-forced-only;";
10928 OS << (VectorizeOnlyWhenForced ?
"" :
"no-") <<
"vectorize-forced-only;";
static unsigned getIntrinsicID(const SDNode *N)
AMDGPU Lower Kernel Arguments
AMDGPU Register Bank Select
This file implements a class to represent arbitrary precision integral constant values and operations...
ReachingDefAnalysis InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool isEqual(const Function &Caller, const Function &Callee)
This file contains the simple types necessary to represent the attributes associated with functions a...
This is the interface for LLVM's primary stateless and local alias analysis.
static bool IsEmptyBlock(MachineBasicBlock *MBB)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This is the interface for a simple mod/ref and alias analysis over globals.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
static Value * getMask(Value *WideMask, unsigned Factor, VectorType *LeafValueTy)
Legalize the Machine IR a function s Machine IR
This header provides classes for managing per-loop analyses.
static const char * VerboseDebug
loop Loop Strength Reduction
This file defines the LoopVectorizationLegality class.
This file provides a LoopVectorizationPlanner class.
static void collectSupportedLoops(Loop &L, LoopInfo *LI, OptimizationRemarkEmitter *ORE, SmallVectorImpl< Loop * > &V)
static cl::opt< unsigned > EpilogueVectorizationMinVF("epilogue-vectorization-minimum-VF", cl::Hidden, cl::desc("Only loops with vectorization factor equal to or larger than " "the specified value are considered for epilogue vectorization."))
static cl::opt< unsigned > EpilogueVectorizationForceVF("epilogue-vectorization-force-VF", cl::init(1), cl::Hidden, cl::desc("When epilogue vectorization is enabled, and a value greater than " "1 is specified, forces the given VF for all applicable epilogue " "loops."))
static void addScalarResumePhis(VPRecipeBuilder &Builder, VPlan &Plan, DenseMap< VPValue *, VPValue * > &IVEndValues)
Create resume phis in the scalar preheader for first-order recurrences, reductions and inductions,...
static void addRuntimeUnrollDisableMetaData(Loop *L)
static ElementCount determineVPlanVF(const TargetTransformInfo &TTI, LoopVectorizationCostModel &CM)
static cl::opt< unsigned > VectorizeMemoryCheckThreshold("vectorize-memory-check-threshold", cl::init(128), cl::Hidden, cl::desc("The maximum allowed number of runtime memory checks"))
static void preparePlanForMainVectorLoop(VPlan &MainPlan, VPlan &EpiPlan)
Prepare MainPlan for vectorizing the main vector loop during epilogue vectorization.
static bool areRuntimeChecksProfitable(GeneratedRTChecks &Checks, VectorizationFactor &VF, Loop *L, PredicatedScalarEvolution &PSE, ScalarEpilogueLowering SEL, std::optional< unsigned > VScale)
static cl::opt< unsigned > TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16), cl::Hidden, cl::desc("Loops with a constant trip count that is smaller than this " "value are vectorized only if no scalar iteration overheads " "are incurred."))
Loops with a known constant trip count below this number are vectorized only if no scalar iteration o...
static void debugVectorizationMessage(const StringRef Prefix, const StringRef DebugMsg, Instruction *I)
Write a DebugMsg about vectorization to the debug output stream.
static cl::opt< bool > EnableCondStoresVectorization("enable-cond-stores-vec", cl::init(true), cl::Hidden, cl::desc("Enable if predication of stores during vectorization."))
static VPInstruction * addResumePhiRecipeForInduction(VPWidenInductionRecipe *WideIV, VPBuilder &VectorPHBuilder, VPBuilder &ScalarPHBuilder, VPTypeAnalysis &TypeInfo, VPValue *VectorTC)
Create and return a ResumePhi for WideIV, unless it is truncated.
static Value * emitTransformedIndex(IRBuilderBase &B, Value *Index, Value *StartValue, Value *Step, InductionDescriptor::InductionKind InductionKind, const BinaryOperator *InductionBinOp)
Compute the transformed value of Index at offset StartValue using step StepValue.
static DebugLoc getDebugLocFromInstOrOperands(Instruction *I)
Look for a meaningful debug location on the instruction or its operands.
static void replaceVPBBWithIRVPBB(VPBasicBlock *VPBB, BasicBlock *IRBB)
Replace VPBB with a VPIRBasicBlock wrapping IRBB.
const char LLVMLoopVectorizeFollowupAll[]
static SetVector< VPIRInstruction * > collectUsersInExitBlocks(Loop *OrigLoop, VPRecipeBuilder &Builder, VPlan &Plan)
static void addExitUsersForFirstOrderRecurrences(VPlan &Plan, SetVector< VPIRInstruction * > &ExitUsersToFix)
Handle users in the exit block for first order reductions in the original exit block.
static cl::opt< bool > ForceTargetSupportsScalableVectors("force-target-supports-scalable-vectors", cl::init(false), cl::Hidden, cl::desc("Pretend that scalable vectors are supported, even if the target does " "not support them. This flag should only be used for testing."))
static void addCanonicalIVRecipes(VPlan &Plan, Type *IdxTy, bool HasNUW, DebugLoc DL)
static bool useActiveLaneMaskForControlFlow(TailFoldingStyle Style)
static constexpr uint32_t MemCheckBypassWeights[]
static unsigned getEstimatedRuntimeVF(ElementCount VF, std::optional< unsigned > VScale)
This function attempts to return a value that represents the vectorization factor at runtime.
cl::opt< unsigned > ForceTargetInstructionCost("force-target-instruction-cost", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's expected cost for " "an instruction to a single constant value. Mostly " "useful for getting consistent testing."))
std::optional< unsigned > getMaxVScale(const Function &F, const TargetTransformInfo &TTI)
static constexpr uint32_t MinItersBypassWeights[]
static cl::opt< unsigned > ForceTargetNumScalarRegs("force-target-num-scalar-regs", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's number of scalar registers."))
static cl::opt< bool > UseWiderVFIfCallVariantsPresent("vectorizer-maximize-bandwidth-for-vector-calls", cl::init(true), cl::Hidden, cl::desc("Try wider VFs if they enable the use of vector variants"))
static bool planContainsAdditionalSimplifications(VPlan &Plan, VPCostContext &CostCtx, Loop *TheLoop)
Return true if the original loop \ TheLoop contains any instructions that do not have corresponding r...
static cl::opt< unsigned > SmallLoopCost("small-loop-cost", cl::init(20), cl::Hidden, cl::desc("The cost of a loop that is considered 'small' by the interleaver."))
static cl::opt< unsigned > ForceTargetNumVectorRegs("force-target-num-vector-regs", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's number of vector registers."))
static bool isExplicitVecOuterLoop(Loop *OuterLp, OptimizationRemarkEmitter *ORE)
static cl::opt< bool > EnableIndVarRegisterHeur("enable-ind-var-reg-heur", cl::init(true), cl::Hidden, cl::desc("Count the induction variable only once when interleaving"))
static Type * maybeVectorizeType(Type *Elt, ElementCount VF)
static std::optional< unsigned > getSmallBestKnownTC(PredicatedScalarEvolution &PSE, Loop *L, bool CanUseConstantMax=true)
Returns "best known" trip count for the specified loop L as defined by the following procedure: 1) Re...
static cl::opt< TailFoldingStyle > ForceTailFoldingStyle("force-tail-folding-style", cl::desc("Force the tail folding style"), cl::init(TailFoldingStyle::None), cl::values(clEnumValN(TailFoldingStyle::None, "none", "Disable tail folding"), clEnumValN(TailFoldingStyle::Data, "data", "Create lane mask for data only, using active.lane.mask intrinsic"), clEnumValN(TailFoldingStyle::DataWithoutLaneMask, "data-without-lane-mask", "Create lane mask with compare/stepvector"), clEnumValN(TailFoldingStyle::DataAndControlFlow, "data-and-control", "Create lane mask using active.lane.mask intrinsic, and use " "it for both data and control flow"), clEnumValN(TailFoldingStyle::DataAndControlFlowWithoutRuntimeCheck, "data-and-control-without-rt-check", "Similar to data-and-control, but remove the runtime check"), clEnumValN(TailFoldingStyle::DataWithEVL, "data-with-evl", "Use predicated EVL instructions for tail folding. If EVL " "is unsupported, fallback to data-without-lane-mask.")))
static cl::opt< bool > EnableEpilogueVectorization("enable-epilogue-vectorization", cl::init(true), cl::Hidden, cl::desc("Enable vectorization of epilogue loops."))
static ScalarEpilogueLowering getScalarEpilogueLowering(Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, LoopVectorizationLegality &LVL, InterleavedAccessInfo *IAI)
const char VerboseDebug[]
static void fixReductionScalarResumeWhenVectorizingEpilog(VPRecipeBase *R, VPTransformState &State, BasicBlock *LoopMiddleBlock, BasicBlock *BypassBlock)
static cl::opt< bool > PreferPredicatedReductionSelect("prefer-predicated-reduction-select", cl::init(false), cl::Hidden, cl::desc("Prefer predicating a reduction operation over an after loop select."))
static VPWidenIntOrFpInductionRecipe * createWidenInductionRecipes(PHINode *Phi, Instruction *PhiOrTrunc, VPValue *Start, const InductionDescriptor &IndDesc, VPlan &Plan, ScalarEvolution &SE, Loop &OrigLoop)
Creates a VPWidenIntOrFpInductionRecpipe for Phi.
static constexpr uint32_t SCEVCheckBypassWeights[]
static cl::opt< bool > PreferInLoopReductions("prefer-inloop-reductions", cl::init(false), cl::Hidden, cl::desc("Prefer in-loop vector reductions, " "overriding the targets preference."))
const char LLVMLoopVectorizeFollowupVectorized[]
static cl::opt< bool > EnableLoadStoreRuntimeInterleave("enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden, cl::desc("Enable runtime interleaving until load/store ports are saturated"))
static cl::opt< bool > VPlanBuildStressTest("vplan-build-stress-test", cl::init(false), cl::Hidden, cl::desc("Build VPlan for every supported loop nest in the function and bail " "out right after the build (stress test the VPlan H-CFG construction " "in the VPlan-native vectorization path)."))
static bool hasIrregularType(Type *Ty, const DataLayout &DL)
A helper function that returns true if the given type is irregular.
static cl::opt< bool > LoopVectorizeWithBlockFrequency("loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden, cl::desc("Enable the use of the block frequency analysis to access PGO " "heuristics minimizing code growth in cold regions and being more " "aggressive in hot regions."))
static Value * getExpandedStep(const InductionDescriptor &ID, const SCEV2ValueTy &ExpandedSCEVs)
Return the expanded step for ID using ExpandedSCEVs to look up SCEV expansion results.
const char LLVMLoopVectorizeFollowupEpilogue[]
static void preparePlanForEpilogueVectorLoop(VPlan &Plan, Loop *L, const SCEV2ValueTy &ExpandedSCEVs, const EpilogueLoopVectorizationInfo &EPI)
Prepare Plan for vectorizing the epilogue loop.
static bool useActiveLaneMask(TailFoldingStyle Style)
static bool isIndvarOverflowCheckKnownFalse(const LoopVectorizationCostModel *Cost, ElementCount VF, std::optional< unsigned > UF=std::nullopt)
For the given VF and UF and maximum trip count computed for the loop, return whether the induction va...
static void addFullyUnrolledInstructionsToIgnore(Loop *L, const LoopVectorizationLegality::InductionList &IL, SmallPtrSetImpl< Instruction * > &InstsToIgnore)
Knowing that loop L executes a single vector iteration, add instructions that will get simplified and...
static cl::opt< PreferPredicateTy::Option > PreferPredicateOverEpilogue("prefer-predicate-over-epilogue", cl::init(PreferPredicateTy::ScalarEpilogue), cl::Hidden, cl::desc("Tail-folding and predication preferences over creating a scalar " "epilogue loop."), cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue, "scalar-epilogue", "Don't tail-predicate loops, create scalar epilogue"), clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue, "predicate-else-scalar-epilogue", "prefer tail-folding, create scalar epilogue if tail " "folding fails."), clEnumValN(PreferPredicateTy::PredicateOrDontVectorize, "predicate-dont-vectorize", "prefers tail-folding, don't attempt vectorization if " "tail-folding fails.")))
static cl::opt< bool > EnableInterleavedMemAccesses("enable-interleaved-mem-accesses", cl::init(false), cl::Hidden, cl::desc("Enable vectorization on interleaved memory accesses in a loop"))
static cl::opt< bool > EnableMaskedInterleavedMemAccesses("enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden, cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"))
An interleave-group may need masking if it resides in a block that needs predication,...
static cl::opt< bool > ForceOrderedReductions("force-ordered-reductions", cl::init(false), cl::Hidden, cl::desc("Enable the vectorisation of loops with in-order (strict) " "FP reductions"))
static void cse(BasicBlock *BB)
Perform cse of induction variable instructions.
static const SCEV * getAddressAccessSCEV(Value *Ptr, LoopVectorizationLegality *Legal, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets Address Access SCEV after verifying that the access pattern is loop invariant except the inducti...
static cl::opt< cl::boolOrDefault > ForceSafeDivisor("force-widen-divrem-via-safe-divisor", cl::Hidden, cl::desc("Override cost based safe divisor widening for div/rem instructions"))
static cl::opt< unsigned > ForceTargetMaxVectorInterleaveFactor("force-target-max-vector-interleave", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's max interleave factor for " "vectorized loops."))
static bool processLoopInVPlanNativePath(Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, LoopVectorizationLegality *LVL, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints, LoopVectorizationRequirements &Requirements)
static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI)
static cl::opt< unsigned > NumberOfStoresToPredicate("vectorize-num-stores-pred", cl::init(1), cl::Hidden, cl::desc("Max number of stores to be predicated behind an if."))
The number of stores in a loop that are allowed to need predication.
static cl::opt< unsigned > MaxNestedScalarReductionIC("max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden, cl::desc("The maximum interleave count to use when interleaving a scalar " "reduction in a nested loop."))
static cl::opt< unsigned > ForceTargetMaxScalarInterleaveFactor("force-target-max-scalar-interleave", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's max interleave factor for " "scalar loops."))
static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE)
static void addUsersInExitBlocks(VPlan &Plan, const SetVector< VPIRInstruction * > &ExitUsersToFix)
static bool willGenerateVectors(VPlan &Plan, ElementCount VF, const TargetTransformInfo &TTI)
Check if any recipe of Plan will generate a vector value, which will be assigned a vector register.
static cl::opt< bool > EnableEarlyExitVectorization("enable-early-exit-vectorization", cl::init(false), cl::Hidden, cl::desc("Enable vectorization of early exit loops with uncountable exits."))
static cl::opt< bool > MaximizeBandwidth("vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden, cl::desc("Maximize bandwidth when selecting vectorization factor which " "will be determined by the smallest type in loop."))
static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop, Instruction *I, DebugLoc DL={})
Create an analysis remark that explains why vectorization failed.
mir Rename Register Operands
This file implements a map that provides insertion order iteration.
std::pair< uint64_t, uint64_t > Interval
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static BinaryOperator * CreateMul(Value *S1, Value *S2, const Twine &Name, BasicBlock::iterator InsertBefore, Value *FlagsOp)
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, BasicBlock::iterator InsertBefore, Value *FlagsOp)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
This file implements the TypeSwitch template, which mimics a switch() statement whose cases are type ...
This file defines the VPlanHCFGBuilder class which contains the public interface (buildHierarchicalCF...
This file contains the declarations of different VPlan-related auxiliary helpers.
This file declares the class VPlanVerifier, which contains utility functions to check the consistency...
This file contains the declarations of the Vectorization Plan base classes:
static const char PassName[]
static const uint32_t IV[8]
Class for arbitrary precision integers.
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
uint64_t getZExtValue() const
Get zero extended value.
int64_t getSExtValue() const
Get sign extended value.
A container for analyses that lazily runs them and caches their results.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
unsigned getVScaleRangeMin() const
Returns the minimum value for the vscale_range attribute.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
BinaryOps getOpcode() const
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Conditional or Unconditional Branch instruction.
bool isConditional() const
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
Value * getCondition() const
Represents analyses that only rely on functions' control flow.
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Value * getArgOperand(unsigned i) const
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_UGT
unsigned greater than
@ ICMP_ULT
unsigned less than
@ ICMP_ULE
unsigned less or equal
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
This is the shared class of boolean and integer constants.
static ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getFalse(LLVMContext &Context)
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
An analysis that produces DemandedBits for a function.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
iterator find(const_arg_type_t< KeyT > Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
const ValueT & at(const_arg_type_t< KeyT > Val) const
at - Return the entry for the specified key, or abort if no such entry exists.
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
DomTreeNodeBase * getIDom() const
Analysis pass which computes a DominatorTree.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
constexpr bool isVector() const
One or more elements.
static constexpr ElementCount getScalable(ScalarTy MinVal)
static constexpr ElementCount getFixed(ScalarTy MinVal)
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
constexpr bool isScalar() const
Exactly one element.
BasicBlock * emitMinimumVectorEpilogueIterCountCheck(BasicBlock *Bypass, BasicBlock *Insert)
Emits an iteration count bypass check after the main vector loop has finished to see if there are any...
void printDebugTracesAtEnd() override
EpilogueVectorizerEpilogueLoop(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, const TargetTransformInfo *TTI, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI, LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, GeneratedRTChecks &Checks, VPlan &Plan)
void printDebugTracesAtStart() override
Allow subclasses to override and print debug traces before/after vplan execution, when trace informat...
BasicBlock * createEpilogueVectorizedLoopSkeleton(const SCEV2ValueTy &ExpandedSCEVs) final
Implements the interface for creating a vectorized skeleton using the epilogue loop strategy (ie the ...
A specialized derived class of inner loop vectorizer that performs vectorization of main loops in the...
void printDebugTracesAtEnd() override
BasicBlock * createEpilogueVectorizedLoopSkeleton(const SCEV2ValueTy &ExpandedSCEVs) final
Implements the interface for creating a vectorized skeleton using the main loop strategy (ie the firs...
EpilogueVectorizerMainLoop(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, const TargetTransformInfo *TTI, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI, LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, GeneratedRTChecks &Check, VPlan &Plan)
void printDebugTracesAtStart() override
Allow subclasses to override and print debug traces before/after vplan execution, when trace informat...
BasicBlock * emitIterationCountCheck(BasicBlock *Bypass, bool ForEpilogue)
Emits an iteration count bypass check once for the main loop (when ForEpilogue is false) and once for...
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags.
Convenience struct for specifying and reasoning about fast-math flags.
Class to represent function types.
param_iterator param_begin() const
param_iterator param_end() const
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
FunctionType * getFunctionType() const
Returns the FunctionType for me.
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags none()
Common base class shared among various IRBuilders.
ConstantInt * getTrue()
Get the constant value for i1 true.
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 2 operands which is mangled on the first type.
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
ConstantInt * getFalse()
Get the constant value for i1 false.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateURem(Value *LHS, Value *RHS, const Twine &Name="")
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
A struct for saving information about induction variables.
const SCEV * getStep() const
InductionKind
This enum represents the kinds of inductions that we support.
@ IK_NoInduction
Not an induction variable.
@ IK_FpInduction
Floating point induction variable.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
const SmallVectorImpl< Instruction * > & getCastInsts() const
Returns a reference to the type cast instructions in the induction update chain, that are redundant w...
Value * getStartValue() const
An extension of the inner loop vectorizer that creates a skeleton for a vectorized loop that has its ...
InnerLoopAndEpilogueVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, const TargetTransformInfo *TTI, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI, LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, GeneratedRTChecks &Checks, VPlan &Plan)
BasicBlock * createVectorizedLoopSkeleton(const SCEV2ValueTy &ExpandedSCEVs) final
Create a new empty loop that will contain vectorized instructions later on, while the old loop will b...
virtual BasicBlock * createEpilogueVectorizedLoopSkeleton(const SCEV2ValueTy &ExpandedSCEVs)=0
The interface for creating a vectorized skeleton using one of two different strategies,...
EpilogueLoopVectorizationInfo & EPI
Holds and updates state information required to vectorize the main loop and its epilogue in two separ...
InnerLoopVectorizer vectorizes loops which contain only one basic block to a specified vectorization ...
virtual void printDebugTracesAtStart()
Allow subclasses to override and print debug traces before/after vplan execution, when trace informat...
Value * TripCount
Trip count of the original loop.
void sinkScalarOperands(Instruction *PredInst)
Iteratively sink the scalarized operands of a predicated instruction into the block that was created ...
const TargetLibraryInfo * TLI
Target Library Info.
ElementCount MinProfitableTripCount
const TargetTransformInfo * TTI
Target Transform Info.
Value * VectorTripCount
Trip count of the widened loop (TripCount - TripCount % (VF*UF))
bool areSafetyChecksAdded()
BasicBlock * emitSCEVChecks(BasicBlock *Bypass)
Emit a bypass check to see if all of the SCEV assumptions we've had to make are correct.
virtual BasicBlock * createVectorizedLoopSkeleton(const SCEV2ValueTy &ExpandedSCEVs)
Create a new empty loop that will contain vectorized instructions later on, while the old loop will b...
LoopVectorizationCostModel * Cost
The profitablity analysis.
BasicBlock * AdditionalBypassBlock
The additional bypass block which conditionally skips over the epilogue loop after executing the main...
BlockFrequencyInfo * BFI
BFI and PSI are used to check for profile guided size optimizations.
Value * getTripCount() const
Returns the original loop trip count.
BasicBlock * LoopMiddleBlock
Middle Block between the vector and the scalar.
OptimizationRemarkEmitter * ORE
Interface to emit optimization remarks.
void scalarizeInstruction(const Instruction *Instr, VPReplicateRecipe *RepRecipe, const VPLane &Lane, VPTransformState &State)
A helper function to scalarize a single Instruction in the innermost loop.
SmallVector< Instruction *, 4 > PredicatedInstructions
Store instructions that were predicated.
DenseMap< PHINode *, Value * > Induction2AdditionalBypassValue
Mapping of induction phis to their additional bypass values.
void introduceCheckBlockInVPlan(BasicBlock *CheckIRBB)
Introduces a new VPIRBasicBlock for CheckIRBB to Plan between the vector preheader and its predecesso...
void createVectorLoopSkeleton(StringRef Prefix)
Emit basic blocks (prefixed with Prefix) for the iteration check, vector loop preheader,...
BasicBlock * emitMemRuntimeChecks(BasicBlock *Bypass)
Emit bypass checks to check any memory assumptions we may have made.
BasicBlock * LoopScalarPreHeader
The scalar-loop preheader.
void createInductionAdditionalBypassValues(const SCEV2ValueTy &ExpandedSCEVs, Value *MainVectorTripCount)
Create and record the values for induction variables to resume coming from the additional bypass bloc...
VPBlockBase * VectorPHVPB
The vector preheader block of Plan, used as target for check blocks introduced during skeleton creati...
LoopVectorizationLegality * Legal
The legality analysis.
InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, const TargetTransformInfo *TTI, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, ElementCount VecWidth, ElementCount MinProfitableTripCount, unsigned UnrollFactor, LoopVectorizationLegality *LVL, LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks, VPlan &Plan)
void emitIterationCountCheck(BasicBlock *Bypass)
Emit a bypass check to see if the vector trip count is zero, including if it overflows.
PredicatedScalarEvolution & PSE
A wrapper around ScalarEvolution used to add runtime SCEV checks.
Value * getInductionAdditionalBypassValue(PHINode *OrigPhi) const
induction header phi.
BasicBlock * getAdditionalBypassBlock() const
Return the additional bypass block which targets the scalar loop by skipping the epilogue loop after ...
DominatorTree * DT
Dominator Tree.
void setTripCount(Value *TC)
Used to set the trip count after ILV's construction and after the preheader block has been executed.
bool OptForSizeBasedOnProfile
void fixVectorizedLoop(VPTransformState &State)
Fix the vectorized code, taking care of header phi's, and more.
BasicBlock * LoopVectorPreHeader
The vector-loop preheader.
virtual void printDebugTracesAtEnd()
AssumptionCache * AC
Assumption Cache.
Value * getOrCreateVectorTripCount(BasicBlock *InsertBlock)
Returns (and creates if needed) the trip count of the widened loop.
IRBuilder Builder
The builder that we use.
void fixNonInductionPHIs(VPTransformState &State)
Fix the non-induction PHIs in Plan.
unsigned UF
The vectorization unroll factor to use.
SmallVector< BasicBlock *, 4 > LoopBypassBlocks
A list of all bypass blocks. The first block is the entry of the loop.
GeneratedRTChecks & RTChecks
Structure to hold information about generated runtime checks, responsible for cleaning the checks,...
virtual ~InnerLoopVectorizer()=default
ElementCount VF
The vectorization SIMD factor to use.
Loop * OrigLoop
The original loop.
static InstructionCost getInvalid(CostType Val=0)
static InstructionCost getMax()
std::optional< CostType > getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
const char * getOpcodeName() const
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
The group of interleaved loads/stores sharing the same stride and close to each other.
uint32_t getFactor() const
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
InstTy * getInsertPos() const
uint32_t getNumMembers() const
Drive the analysis of interleaved memory accesses in the loop.
InterleaveGroup< Instruction > * getInterleaveGroup(const Instruction *Instr) const
Get the interleave group that Instr belongs to.
bool requiresScalarEpilogue() const
Returns true if an interleaved group that may access memory out-of-bounds requires a scalar epilogue ...
bool isInterleaved(Instruction *Instr) const
Check if Instr belongs to any interleave group.
bool invalidateGroups()
Invalidate groups, e.g., in case all blocks in loop will be predicated contrary to original assumptio...
iterator_range< SmallPtrSetIterator< llvm::InterleaveGroup< Instruction > * > > getInterleaveGroups()
void analyzeInterleaving(bool EnableMaskedInterleavedGroup)
Analyze the interleaved accesses and collect them in interleave groups.
void invalidateGroupsRequiringScalarEpilogue()
Invalidate groups that require a scalar epilogue (due to gaps).
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
Type * getPointerOperandType() const
This analysis provides dependence information for the memory accesses of a loop.
Drive the analysis of memory accesses in the loop.
const RuntimePointerChecking * getRuntimePointerChecking() const
unsigned getNumRuntimePointerChecks() const
Number of memchecks required to prove independence of otherwise may-alias pointers.
const DenseMap< Value *, const SCEV * > & getSymbolicStrides() const
If an access has a symbolic strides, this maps the pointer value to the stride symbol.
Analysis pass that exposes the LoopInfo for a function.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of this loop.
BlockT * getUniqueLatchExitBlock() const
Return the unique exit block for the latch, or null if there are multiple different exit blocks or th...
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
iterator_range< block_iterator > blocks() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop.
Store the result of a depth first search within basic blocks contained by a single loop.
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
RPOIterator endRPO() const
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LoopVectorizationCostModel - estimates the expected speedups due to vectorization.
SmallPtrSet< Type *, 16 > ElementTypesInLoop
All element types found in the loop.
void collectElementTypesForWidening()
Collect all element types in the loop for which widening is needed.
bool canVectorizeReductions(ElementCount VF) const
Returns true if the target machine supports all of the reduction variables found for the given VF.
bool isEpilogueVectorizationProfitable(const ElementCount VF, const unsigned IC) const
Returns true if epilogue vectorization is considered profitable, and false otherwise.
bool requiresScalarEpilogue(VFRange Range) const
Returns true if we're required to use a scalar epilogue for at least the final iteration of the origi...
bool isPredicatedInst(Instruction *I) const
Returns true if I is an instruction that needs to be predicated at runtime.
bool hasPredStores() const
void collectValuesToIgnore()
Collect values we want to ignore in the cost model.
void collectInLoopReductions()
Split reductions into those that happen in the loop, and those that happen outside.
std::pair< unsigned, unsigned > getSmallestAndWidestTypes()
bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const
Returns true if I is known to be uniform after vectorization.
bool usePredicatedReductionSelect(unsigned Opcode, Type *PhiTy) const
Returns true if the predicated reduction select should be used to set the incoming value for the redu...
PredicatedScalarEvolution & PSE
Predicated scalar evolution analysis.
const LoopVectorizeHints * Hints
Loop Vectorize Hint.
std::optional< unsigned > getMaxSafeElements() const
Return maximum safe number of elements to be processed per vector iteration, which do not prevent sto...
const TargetTransformInfo & TTI
Vector target information.
LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, LoopVectorizationLegality *Legal, const TargetTransformInfo &TTI, const TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, const Function *F, const LoopVectorizeHints *Hints, InterleavedAccessInfo &IAI)
const Function * TheFunction
LoopVectorizationLegality * Legal
Vectorization legality.
bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const
Returns true if the target machine supports masked load operation for the given DataType and kind of ...
std::optional< InstructionCost > getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy) const
Return the cost of instructions in an inloop reduction pattern, if I is part of that pattern.
InstructionCost getInstructionCost(Instruction *I, ElementCount VF)
Returns the execution time cost of an instruction for a given vector width.
DemandedBits * DB
Demanded bits analysis.
bool interleavedAccessCanBeWidened(Instruction *I, ElementCount VF) const
Returns true if I is a memory instruction in an interleaved-group of memory accesses that can be vect...
const TargetLibraryInfo * TLI
Target Library Info.
bool memoryInstructionCanBeWidened(Instruction *I, ElementCount VF)
Returns true if I is a memory instruction with consecutive memory access that can be widened.
const InterleaveGroup< Instruction > * getInterleavedAccessGroup(Instruction *Instr) const
Get the interleaved access group that Instr belongs to.
InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const
Estimate cost of an intrinsic call instruction CI if it were vectorized with factor VF.
bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const
Returns true if I is known to be scalar after vectorization.
bool isOptimizableIVTruncate(Instruction *I, ElementCount VF)
Return True if instruction I is an optimizable truncate whose operand is an induction variable.
FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC)
Loop * TheLoop
The loop that we evaluate.
TTI::TargetCostKind CostKind
The kind of cost that we are calculating.
TailFoldingStyle getTailFoldingStyle(bool IVUpdateMayOverflow=true) const
Returns the TailFoldingStyle that is best for the current loop.
InterleavedAccessInfo & InterleaveInfo
The interleave access information contains groups of interleaved accesses with the same stride and cl...
SmallPtrSet< const Value *, 16 > ValuesToIgnore
Values to ignore in the cost model.
void setVectorizedCallDecision(ElementCount VF)
A call may be vectorized in different ways depending on whether we have vectorized variants available...
void invalidateCostModelingDecisions()
Invalidates decisions already taken by the cost model.
bool isAccessInterleaved(Instruction *Instr) const
Check if Instr belongs to any interleaved access group.
bool selectUserVectorizationFactor(ElementCount UserVF)
Setup cost-based decisions for user vectorization factor.
std::optional< unsigned > getVScaleForTuning() const
Return the value of vscale used for tuning the cost model.
OptimizationRemarkEmitter * ORE
Interface to emit optimization remarks.
bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const
Returns true if the target machine supports masked store operation for the given DataType and kind of...
LoopInfo * LI
Loop Info analysis.
bool requiresScalarEpilogue(bool IsVectorizing) const
Returns true if we're required to use a scalar epilogue for at least the final iteration of the origi...
SmallVector< RegisterUsage, 8 > calculateRegisterUsage(ArrayRef< ElementCount > VFs)
SmallPtrSet< const Value *, 16 > VecValuesToIgnore
Values to ignore in the cost model when VF > 1.
bool isInLoopReduction(PHINode *Phi) const
Returns true if the Phi is part of an inloop reduction.
bool isProfitableToScalarize(Instruction *I, ElementCount VF) const
void setWideningDecision(const InterleaveGroup< Instruction > *Grp, ElementCount VF, InstWidening W, InstructionCost Cost)
Save vectorization decision W and Cost taken by the cost model for interleaving group Grp and vector ...
const MapVector< Instruction *, uint64_t > & getMinimalBitwidths() const
CallWideningDecision getCallWideningDecision(CallInst *CI, ElementCount VF) const
bool isLegalGatherOrScatter(Value *V, ElementCount VF)
Returns true if the target machine can represent V as a masked gather or scatter operation.
bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const
bool runtimeChecksRequired()
bool shouldConsiderInvariant(Value *Op)
Returns true if Op should be considered invariant and if it is trivially hoistable.
bool foldTailByMasking() const
Returns true if all loop blocks should be masked to fold tail loop.
bool foldTailWithEVL() const
Returns true if VP intrinsics with explicit vector length support should be generated in the tail fol...
void collectUniformsAndScalars(ElementCount VF)
Collect Uniform and Scalar values for the given VF.
bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const
Returns true if the instructions in this block requires predication for any reason,...
void setCallWideningDecision(CallInst *CI, ElementCount VF, InstWidening Kind, Function *Variant, Intrinsic::ID IID, std::optional< unsigned > MaskPos, InstructionCost Cost)
void setTailFoldingStyles(bool IsScalableVF, unsigned UserIC)
Selects and saves TailFoldingStyle for 2 options - if IV update may overflow or not.
AssumptionCache * AC
Assumption cache.
void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W, InstructionCost Cost)
Save vectorization decision W and Cost taken by the cost model for instruction I and vector width VF.
InstWidening
Decision that was taken during cost calculation for memory instruction.
bool isScalarWithPredication(Instruction *I, ElementCount VF) const
Returns true if I is an instruction which requires predication and for which our chosen predication s...
InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF) const
Estimate cost of a call instruction CI if it were vectorized with factor VF.
bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) const
Returns true if we should use strict in-order reductions for the given RdxDesc.
std::pair< InstructionCost, InstructionCost > getDivRemSpeculationCost(Instruction *I, ElementCount VF) const
Return the costs for our two available strategies for lowering a div/rem operation which requires spe...
bool isDivRemScalarWithPredication(InstructionCost ScalarCost, InstructionCost SafeDivisorCost) const
Given costs for both strategies, return true if the scalar predication lowering should be used for di...
InstructionCost expectedCost(ElementCount VF)
Returns the expected execution cost.
void setCostBasedWideningDecision(ElementCount VF)
Memory access instruction may be vectorized in more than one way.
InstWidening getWideningDecision(Instruction *I, ElementCount VF) const
Return the cost model decision for the given instruction I and vector width VF.
bool isScalarEpilogueAllowed() const
Returns true if a scalar epilogue is not allowed due to optsize or a loop hint annotation.
InstructionCost getWideningCost(Instruction *I, ElementCount VF)
Return the vectorization cost for the given instruction I and vector width VF.
unsigned selectInterleaveCount(ElementCount VF, InstructionCost LoopCost)
void collectInstsToScalarize(ElementCount VF)
Collects the instructions to scalarize for each predicated instruction in the loop.
LoopVectorizationLegality checks if it is legal to vectorize a loop, and to what vectorization factor...
unsigned getNumStores() const
bool isInvariantStoreOfReduction(StoreInst *SI)
Returns True if given store is a final invariant store of one of the reductions found in the loop.
bool hasVectorCallVariants() const
Returns true if there is at least one function call in the loop which has a vectorized variant availa...
uint64_t getMaxSafeVectorWidthInBits() const
RecurrenceSet & getFixedOrderRecurrences()
Return the fixed-order recurrences found in the loop.
bool isInvariantAddressOfReduction(Value *V)
Returns True if given address is invariant and is used to store recurrent expression.
bool blockNeedsPredication(BasicBlock *BB) const
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
int isConsecutivePtr(Type *AccessTy, Value *Ptr) const
Check if this pointer is consecutive when vectorizing.
std::optional< const HistogramInfo * > getHistogramInfo(Instruction *I) const
Returns a HistogramInfo* for the given instruction if it was determined to be part of a load -> updat...
bool canVectorizeFPMath(bool EnableStrictReductions)
Returns true if it is legal to vectorize the FP math operations in this loop.
bool isReductionVariable(PHINode *PN) const
Returns True if PN is a reduction variable in this loop.
bool isFixedOrderRecurrence(const PHINode *Phi) const
Returns True if Phi is a fixed-order recurrence in this loop.
const InductionDescriptor * getPointerInductionDescriptor(PHINode *Phi) const
Returns a pointer to the induction descriptor, if Phi is pointer induction.
const InductionDescriptor * getIntOrFpInductionDescriptor(PHINode *Phi) const
Returns a pointer to the induction descriptor, if Phi is an integer or floating point induction.
bool isInductionPhi(const Value *V) const
Returns True if V is a Phi node of an induction variable in this loop.
PHINode * getPrimaryInduction()
Returns the primary induction variable.
const SmallVector< BasicBlock *, 4 > & getCountableExitingBlocks() const
Returns all exiting blocks with a countable exit, i.e.
const InductionList & getInductionVars() const
Returns the induction variables found in the loop.
bool hasStructVectorCall() const
Returns true if there is at least one function call in the loop which returns a struct type and needs...
bool isInvariant(Value *V) const
Returns true if V is invariant across all loop iterations according to SCEV.
const ReductionList & getReductionVars() const
Returns the reduction variables found in the loop.
bool isSafeForAnyVectorWidth() const
unsigned getNumLoads() const
bool canFoldTailByMasking() const
Return true if we can vectorize this loop while folding its tail by masking.
void prepareToFoldTailByMasking()
Mark all respective loads/stores for masking.
Type * getWidestInductionType()
Returns the widest induction type.
bool hasUncountableEarlyExit() const
Returns true if the loop has exactly one uncountable early exit, i.e.
bool hasHistograms() const
Returns a list of all known histogram operations in the loop.
const LoopAccessInfo * getLAI() const
bool isUniformMemOp(Instruction &I, ElementCount VF) const
A uniform memory op is a load or store which accesses the same memory location on all VF lanes,...
BasicBlock * getUncountableEarlyExitingBlock() const
Returns the uncountable early exiting block, if there is exactly one.
bool isMaskRequired(const Instruction *I) const
Returns true if vector representation of the instruction I requires mask.
const RuntimePointerChecking * getRuntimePointerChecking() const
Returns the information that we collected about runtime memory check.
Planner drives the vectorization process after having passed Legality checks.
VectorizationFactor selectEpilogueVectorizationFactor(const ElementCount MaxVF, unsigned IC)
VPlan & getPlanFor(ElementCount VF) const
Return the VPlan for VF.
VectorizationFactor planInVPlanNativePath(ElementCount UserVF)
Use the VPlan-native path to plan how to best vectorize, return the best VF and its cost.
void buildVPlans(ElementCount MinVF, ElementCount MaxVF)
Build VPlans for power-of-2 VF's between MinVF and MaxVF inclusive, according to the information gath...
VectorizationFactor computeBestVF()
Compute and return the most profitable vectorization factor.
void emitInvalidCostRemarks(OptimizationRemarkEmitter *ORE)
Emit remarks for recipes with invalid costs in the available VPlans.
static bool getDecisionAndClampRange(const std::function< bool(ElementCount)> &Predicate, VFRange &Range)
Test a Predicate on a Range of VF's.
void printPlans(raw_ostream &O)
void plan(ElementCount UserVF, unsigned UserIC)
Build VPlans for the specified UserVF and UserIC if they are non-zero or all applicable candidate VFs...
DenseMap< const SCEV *, Value * > executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan, InnerLoopVectorizer &LB, DominatorTree *DT, bool VectorizingEpilogue, const DenseMap< const SCEV *, Value * > *ExpandedSCEVs=nullptr)
Generate the IR code for the vectorized loop captured in VPlan BestPlan according to the best selecte...
bool hasPlanWithVF(ElementCount VF) const
Look through the existing plans and return true if we have one with vectorization factor VF.
This holds vectorization requirements that must be verified late in the process.
Instruction * getExactFPInst()
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
bool isScalableVectorizationDisabled() const
enum ForceKind getForce() const
bool allowVectorization(Function *F, Loop *L, bool VectorizeOnlyWhenForced) const
bool allowReordering() const
When enabling loop hints are provided we allow the vectorizer to change the order of operations that ...
void emitRemarkWithHints() const
Dumps all the hint information.
bool isPotentiallyUnsafe() const
ElementCount getWidth() const
@ FK_Enabled
Forcing enabled.
@ FK_Undefined
Not selected.
@ FK_Disabled
Forcing disabled.
unsigned getPredicate() const
void setAlreadyVectorized()
Mark the loop L as already vectorized by setting the width to 1.
const char * vectorizeAnalysisPassName() const
If hints are provided that force vectorization, use the AlwaysPrint pass name to force the frontend t...
unsigned getInterleave() const
void prepareNoAliasMetadata()
Set up the aliasing scopes based on the memchecks.
Represents a single loop in the control flow graph.
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
const MDOperand & getOperand(unsigned I) const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
unsigned getNumOperands() const
Return number of MDNode operands.
static MDString * get(LLVMContext &Context, StringRef Str)
This class implements a map that also provides access to all stored values in a deterministic order.
iterator find(const KeyT &Key)
bool contains(const KeyT &Key) const
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
static unsigned getIncomingValueNumForOperand(unsigned i)
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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.
const SCEVPredicate & getPredicate() const
unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
void preserveSet()
Mark an analysis set as preserved.
void preserve()
Mark an analysis as preserved.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
bool hasProfileSummary() const
Returns true if profile summary is available.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
static bool isFMulAddIntrinsic(Instruction *I)
Returns true if the instruction is a call to the llvm.fmuladd intrinsic.
FastMathFlags getFastMathFlags() const
Instruction * getLoopExitInstr() const
static unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
Type * getRecurrenceType() const
Returns the type of the recurrence.
const SmallPtrSet< Instruction *, 8 > & getCastInsts() const
Returns a reference to the instructions used for type-promoting the recurrence.
unsigned getMinWidthCastToRecurrenceTypeInBits() const
Returns the minimum width used by the recurrence in bits.
TrackingVH< Value > getRecurrenceStartValue() const
SmallVector< Instruction *, 4 > getReductionOpChain(PHINode *Phi, Loop *L) const
Attempts to find a chain of operations from Phi to LoopExitInst that can be treated as a set of reduc...
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isFindLastIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
bool isSigned() const
Returns true if all source operands of the recurrence are SExtInsts.
RecurKind getRecurrenceKind() const
bool isOrdered() const
Expose an ordered FP reduction to the instance users.
Value * getSentinelValue() const
Returns the sentinel value for FindLastIV recurrences to replace the start value.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
bool Need
This flag indicates if we need to add the runtime check.
std::optional< ArrayRef< PointerDiffInfo > > getDiffChecks() const
const SmallVectorImpl< RuntimePointerCheck > & getChecks() const
Returns the checks that generateChecks created.
This class represents a constant integer value.
const APInt & getAPInt() const
Helper to remove instructions inserted during SCEV expansion, unless they are marked as used.
This class uses information about analyze scalars to rewrite expressions in canonical form.
ScalarEvolution * getSE()
bool isInsertedInstruction(Instruction *I) const
Return true if the specified instruction was inserted by the code rewriter.
Value * expandCodeForPredicate(const SCEVPredicate *Pred, Instruction *Loc)
Generates a code sequence that evaluates this predicate.
This class represents an assumption made using SCEV expressions which can be checked at run-time.
virtual bool isAlwaysTrue() const =0
Returns true if the predicate is always true.
This class represents an analyzed expression in the program.
bool isOne() const
Return true if the expression is a constant one.
bool isZero() const
Return true if the expression is a constant zero.
Type * getType() const
Return the LLVM type of this SCEV expression.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
const SCEV * getURemExpr(const SCEV *LHS, const SCEV *RHS)
Represents an unsigned remainder expression based on unsigned division.
const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
const SCEV * getConstant(ConstantInt *V)
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
bool isKnownPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
This class represents the LLVM 'select' instruction.
A vector that has set insertion semantics.
ArrayRef< value_type > getArrayRef() const
size_type size() const
Determine the number of elements in the SetVector.
iterator end()
Get an iterator to the end of the SetVector.
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
bool empty() const
Determine if the SetVector is empty or not.
iterator begin()
Get an iterator to the beginning of the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
value_type pop_back_val()
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
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.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
StringRef - Represent a constant reference to a string, i.e.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This class represents a truncation of integer types.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
This class implements a switch-like dispatch statement for a value of 'T' using dyn_cast functionalit...
TypeSwitch< T, ResultT > & Case(CallableT &&caseFn)
Add a case on the given type.
The instances of the Type class are immutable: once they are created, they are never changed.
unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
static IntegerType * getInt1Ty(LLVMContext &C)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static Type * getVoidTy(LLVMContext &C)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isTokenTy() const
Return true if this is 'token'.
bool isVoidTy() const
Return true if this is 'void'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
static SmallVector< VFInfo, 8 > getMappings(const CallInst &CI)
Retrieve all the VFInfo instances associated to the CallInst CI.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
RecipeListTy::iterator iterator
Instruction iterators...
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPBasicBlock,...
iterator begin()
Recipe iterator methods.
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
void insert(VPRecipeBase *Recipe, iterator InsertPt)
A recipe for vectorizing a phi-node as a sequence of mask-based select instructions.
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
VPRegionBlock * getParent()
const VPBasicBlock * getExitingBasicBlock() const
void setName(const Twine &newName)
size_t getNumSuccessors() const
void swapSuccessors()
Swap successors of the block. The block must have exactly 2 successors.
VPBlockBase * getSinglePredecessor() const
const VPBasicBlock * getEntryBasicBlock() const
VPBlockBase * getSingleSuccessor() const
const VPBlocksTy & getSuccessors() const
static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBase NewBlock after BlockPtr.
static void insertOnEdge(VPBlockBase *From, VPBlockBase *To, VPBlockBase *BlockPtr)
Inserts BlockPtr on the edge between From and To.
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
static void reassociateBlocks(VPBlockBase *Old, VPBlockBase *New)
Reassociate all the blocks connected to Old so that they now point to New.
RAII object that stores the current insertion point and restores it when the object is destroyed.
VPlan-based builder utility analogous to IRBuilder.
VPValue * createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, DebugLoc DL={}, const Twine &Name="")
Create a new ICmp VPInstruction with predicate Pred and operands A and B.
VPValue * createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL={}, const Twine &Name="")
VPDerivedIVRecipe * createDerivedIV(InductionDescriptor::InductionKind Kind, FPMathOperator *FPBinOp, VPValue *Start, VPValue *Current, VPValue *Step, const Twine &Name="")
Convert the input value Current to the corresponding value of an induction with Start and Step values...
void insert(VPRecipeBase *R)
Insert R at the current insertion point.
VPScalarCastRecipe * createScalarCast(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, DebugLoc DL)
VPInstruction * createOverflowingOp(unsigned Opcode, std::initializer_list< VPValue * > Operands, VPRecipeWithIRFlags::WrapFlagsTy WrapFlags, DebugLoc DL={}, const Twine &Name="")
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const Twine &Name="")
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
VPValue * createNot(VPValue *Operand, DebugLoc DL={}, const Twine &Name="")
VPValue * createLogicalAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL={}, const Twine &Name="")
VPValue * createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal, DebugLoc DL={}, const Twine &Name="", std::optional< FastMathFlags > FMFs=std::nullopt)
void setInsertPoint(VPBasicBlock *TheBB)
This specifies that created VPInstructions should be appended to the end of the specified block.
Canonical scalar induction phi of the vector loop.
Type * getScalarType() const
Returns the scalar type of the induction.
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
void execute(VPTransformState &State) override
Generate the transformed value of the induction at offset StartValue (1.
VPValue * getStepValue() const
VPValue * getStartValue() const
A recipe representing a sequence of load -> update -> store as part of a histogram operation.
A special type of VPBasicBlock that wraps an existing IR basic block.
A recipe to wrap on original IR instruction not to be modified during execution, execept for PHIs.
This is a concrete Recipe that models a single VPlan-level instruction.
@ ResumePhi
Creates a scalar phi in a leaf VPBB with a single predecessor in VPlan.
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
static VPLane getLastLaneForVF(const ElementCount &VF)
static VPLane getFirstLane()
A recipe for forming partial reductions.
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
VPBasicBlock * getParent()
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
void insertAfter(VPRecipeBase *InsertPos)
Insert an unlinked Recipe into a basic block immediately after the specified Recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Helper class to create VPRecipies from IR instructions.
VPRecipeBase * tryToCreatePartialReduction(Instruction *Reduction, ArrayRef< VPValue * > Operands)
Create and return a partial reduction recipe for a reduction instruction along with binary operation ...
VPValue * createEdgeMask(BasicBlock *Src, BasicBlock *Dst)
A helper function that computes the predicate of the edge between SRC and DST.
VPRecipeBase * tryToCreateWidenRecipe(Instruction *Instr, ArrayRef< VPValue * > Operands, VFRange &Range)
Create and return a widened recipe for I if one can be created within the given VF Range.
void createSwitchEdgeMasks(SwitchInst *SI)
Create an edge mask for every destination of cases and/or default.
VPValue * getBlockInMask(BasicBlock *BB) const
Returns the entry mask for the block BB.
VPValue * getEdgeMask(BasicBlock *Src, BasicBlock *Dst) const
A helper that returns the previously computed predicate of the edge between SRC and DST.
iterator_range< mapped_iterator< Use *, std::function< VPValue *(Value *)> > > mapToVPValues(User::op_range Operands)
Returns a range mapping the values of the range Operands to their corresponding VPValues.
void fixHeaderPhis()
Add the incoming values from the backedge to reduction & first-order recurrence cross-iteration phis.
VPValue * getVPValueOrAddLiveIn(Value *V)
void createHeaderMask()
Create the mask for the vector loop header block.
std::optional< unsigned > getScalingForReduction(const Instruction *ExitInst)
void createBlockInMask(BasicBlock *BB)
A helper function that computes the predicate of the block BB, assuming that the header block of the ...
void collectScaledReductions(VFRange &Range)
Find all possible partial reductions in the loop and track all of those that are valid so recipes can...
VPReplicateRecipe * handleReplication(Instruction *I, ArrayRef< VPValue * > Operands, VFRange &Range)
Build a VPReplicationRecipe for I using Operands.
VPRecipeBase * getRecipe(Instruction *I)
Return the recipe created for given ingredient.
void setFlags(Instruction *I) const
Set the IR flags for I.
A recipe for handling reduction phis.
bool isInLoop() const
Returns true, if the phi is part of an in-loop reduction.
const RecurrenceDescriptor & getRecurrenceDescriptor() const
A recipe to represent inloop reduction operations, performing a reduction on a vector operand into a ...
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
const VPBlockBase * getEntry() const
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool shouldPack() const
Returns true if the recipe is used by a widened recipe via an intervening VPPredInstPHIRecipe.
A recipe to compute the pointers for widened memory accesses of IndexTy in reverse order.
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
An analysis for type-inference for VPValues.
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
void setOperand(unsigned I, VPValue *New)
unsigned getNumOperands() const
VPValue * getOperand(unsigned N) const
void addOperand(VPValue *Operand)
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
void replaceAllUsesWith(VPValue *New)
Value * getLiveInIRValue()
Returns the underlying IR value, if this VPValue is defined outside the scope of VPlan.
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser &U, unsigned Idx)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
A recipe to compute the pointers for widened memory accesses of IndexTy.
A recipe for widening Call instructions using library calls.
A Recipe for widening the canonical induction variable of the vector loop.
VPWidenCastRecipe is a recipe to create vector cast instructions.
A recipe for handling GEP instructions.
Base class for widened induction (VPWidenIntOrFpInductionRecipe and VPWidenPointerInductionRecipe),...
VPValue * getStepValue()
Returns the step value of the induction.
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
A recipe for widening vector intrinsics.
A common base class for widening memory operations.
A recipe for handling phis that are widened in the vector loop.
VPValue * getIncomingValue(unsigned I)
Returns the I th incoming VPValue.
VPBasicBlock * getIncomingBlock(unsigned I)
Returns the I th incoming VPBasicBlock.
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Main class to build the VPlan H-CFG for an incoming IR.
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
bool hasVF(ElementCount VF) const
void prepareToExecute(Value *TripCount, Value *VectorTripCount, VPTransformState &State)
Prepare the plan for execution, setting up the required live-in values.
VPBasicBlock * getEntry()
VPValue & getVectorTripCount()
The vector trip count.
VPValue & getVFxUF()
Returns VF * UF of the vector loop region.
VPValue & getVF()
Returns the VF of the vector loop region.
VPValue * getTripCount() const
The trip count of the original loop.
VPValue * getOrCreateBackedgeTakenCount()
The backedge taken count of the original loop.
iterator_range< SmallSetVector< ElementCount, 2 >::iterator > vectorFactors() const
Returns an iterator range over all VFs of the plan.
static VPlanPtr createInitialVPlan(Type *InductionTy, PredicatedScalarEvolution &PSE, bool RequiresScalarEpilogueCheck, bool TailFolded, Loop *TheLoop)
Create initial VPlan, having an "entry" VPBasicBlock (wrapping original scalar pre-header) which cont...
bool hasUF(unsigned UF) const
auto getExitBlocks()
Return an iterator range over the VPIRBasicBlock wrapping the exit blocks of the VPlan,...
VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this plan.
const VPBasicBlock * getMiddleBlock() const
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
void setEntry(VPBasicBlock *VPBB)
VPIRBasicBlock * createVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock from IRBB containing VPIRInstructions for all instructions in IRBB,...
VPValue * getOrAddLiveIn(Value *V)
Gets the live-in VPValue for V or adds a new live-in (if none exists yet) for V.
bool hasScalarVFOnly() const
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
VPCanonicalIVPHIRecipe * getCanonicalIV()
Returns the canonical induction recipe of the vector loop.
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
VPlan * duplicate()
Clone the current VPlan, update all VPValues of the new VPlan and cloned recipes to refer to the clon...
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
bool hasOneUser() const
Return true if there is exactly one user of this value.
void setName(const Twine &Name)
Change the name of the value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
void replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
LLVMContext & getContext() const
All values hold a context through their type.
StringRef getName() const
Return a constant reference to the value's name.
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
int getNumOccurrences() const
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
constexpr ScalarTy getFixedValue() const
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
constexpr bool isNonZero() const
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
constexpr LeafTy multiplyCoefficientBy(ScalarTy RHS) const
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
constexpr bool isZero() const
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ PredicateElseScalarEpilogue
@ PredicateOrDontVectorize
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
@ C
The default llvm calling convention, compatible with C.
ID ArrayRef< Type * > Tys
std::variant< std::monostate, Loc::Single, Loc::Multi, Loc::MMI, Loc::EntryValue > Variant
Alias for the std::variant specialization base class of DbgVariable.
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)
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
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)
OneUse_match< T > m_OneUse(const T &SubPattern)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< InstrNode * > Instr
NodeAddr< PhiNode * > Phi
const_iterator begin(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get begin iterator over path.
const_iterator end(StringRef path LLVM_LIFETIME_BOUND)
Get end iterator over path.
bool isUniformAfterVectorization(const VPValue *VPV)
Returns true if VPV is uniform after vectorization.
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, ScalarEvolution &SE)
Get or create a VPValue that corresponds to the expansion of Expr.
const SCEV * getSCEVExprForVPValue(VPValue *V, ScalarEvolution &SE)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
Value * addRuntimeChecks(Instruction *Loc, Loop *TheLoop, const SmallVectorImpl< RuntimePointerCheck > &PointerChecks, SCEVExpander &Expander, bool HoistRuntimeChecks=false)
Add code that checks at runtime if the accessed arrays in PointerChecks overlap.
bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Returns a loop's estimated trip count based on branch weight metadata.
static void reportVectorization(OptimizationRemarkEmitter *ORE, Loop *TheLoop, VectorizationFactor VF, unsigned IC)
Report successful vectorization of the loop.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
unsigned getLoadStoreAddressSpace(const Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
auto pred_end(const MachineBasicBlock *BB)
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
std::pair< Instruction *, ElementCount > InstructionVFPair
Value * getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF)
Return the runtime value for VF.
bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
std::optional< MDNode * > makeFollowupLoopID(MDNode *OrigLoopID, ArrayRef< StringRef > FollowupAttrs, const char *InheritOptionsAttrsPrefix="", bool AlwaysNew=false)
Create a new loop identifier for a loop created from a loop transformation.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
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...
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
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.
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...
auto map_range(ContainerTy &&C, FuncTy F)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
void collectEphemeralRecipesForVPlan(VPlan &Plan, DenseSet< VPRecipeBase * > &EphRecipes)
auto reverse(ContainerTy &&C)
void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
cl::opt< bool > EnableVPlanNativePath("enable-vplan-native-path", cl::Hidden, cl::desc("Enable VPlan-native vectorization path with " "support for outer loop vectorization."))
void sort(IteratorTy Start, IteratorTy End)
std::unique_ptr< VPlan > VPlanPtr
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
cl::opt< bool > EnableLoopVectorization
bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
void llvm_unreachable_internal(const char *msg=nullptr, const char *file=nullptr, unsigned line=0)
This function calls abort(), and prints the optional message to stderr.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
static void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I=nullptr, DebugLoc DL={})
Reports an informative message: print Msg for debugging purposes as well as an optimization remark.
bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
RecurKind
These are the kinds of recurrences that we support.
@ Or
Bitwise or logical OR of integers.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
cl::opt< bool > VerifyEachVPlan("vplan-verify-each", cl::init(false), cl::Hidden, cl::desc("Verfiy VPlans after VPlan transforms."))
void setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop, Loop *RemainderLoop, uint64_t UF)
Set weights for UnrolledLoop and RemainderLoop based on weights for OrigLoop and the following distri...
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
void reportVectorizationFailure(const StringRef DebugMsg, const StringRef OREMsg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I=nullptr)
Reports a vectorization failure: print DebugMsg for debugging purposes along with the corresponding o...
DWARFExpression::Operation Op
@ CM_ScalarEpilogueNotAllowedLowTripLoop
@ CM_ScalarEpilogueNotNeededUsePredicate
@ CM_ScalarEpilogueNotAllowedOptSize
@ CM_ScalarEpilogueAllowed
@ CM_ScalarEpilogueNotAllowedUsePredicate
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
auto pred_begin(const MachineBasicBlock *BB)
Value * createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF, int64_t Step)
Return a value for Step multiplied by VF.
BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
Value * addDiffRuntimeChecks(Instruction *Loc, ArrayRef< PointerDiffInfo > Checks, SCEVExpander &Expander, function_ref< Value *(IRBuilderBase &, unsigned)> GetVF, unsigned IC)
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
@ DataAndControlFlowWithoutRuntimeCheck
Use predicate to control both data and control flow, but modify the trip count so that a runtime over...
@ None
Don't use tail folding.
@ DataWithEVL
Use predicated EVL instructions for tail-folding.
@ DataWithoutLaneMask
Same as Data, but avoids using the get.active.lane.mask intrinsic to calculate the mask and instead i...
unsigned getReciprocalPredBlockProb()
A helper function that returns the reciprocal of the block probability of predicated blocks.
bool hasBranchWeightMD(const Instruction &I)
Checks if an instructions has Branch Weight Metadata.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
bool verifyVPlanIsValid(const VPlan &Plan)
Verify invariants for general VPlans.
MapVector< Instruction *, uint64_t > computeMinimumValueSizes(ArrayRef< BasicBlock * > Blocks, DemandedBits &DB, const TargetTransformInfo *TTI=nullptr)
Compute a map of integer instructions to their minimum legal type size.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
cl::opt< bool > EnableLoopInterleaving
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
This struct is a compact representation of a valid (non-zero power of two) alignment.
A special type used by analysis passes to provide an address that identifies that particular analysis...
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).
An information struct used to provide DenseMap with the various necessary components for a given valu...
Encapsulate information regarding vectorization of a loop and its epilogue.
BasicBlock * SCEVSafetyCheck
EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF, ElementCount EVF, unsigned EUF, VPlan &EpiloguePlan)
BasicBlock * MemSafetyCheck
BasicBlock * MainLoopIterationCountCheck
BasicBlock * EpilogueIterationCountCheck
A class that represents two vectorization factors (initialized with 0 by default).
static FixedScalableVFPair getNone()
This holds details about a histogram operation – a load -> update -> store sequence where each lane i...
std::optional< unsigned > MaskPos
A struct that represents some properties of the register usage of a loop.
SmallMapVector< unsigned, unsigned, 4 > MaxLocalUsers
Holds the maximum number of concurrent live intervals in the loop.
SmallMapVector< unsigned, unsigned, 4 > LoopInvariantRegs
Holds the number of loop invariant values that are used in the loop.
LoopVectorizeResult runImpl(Function &F)
bool processLoop(Loop *L)
LoopAccessInfoManager * LAIs
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LoopVectorizePass(LoopVectorizeOptions Opts={})
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
OptimizationRemarkEmitter * ORE
Storage for information about made changes.
A chain of instructions that form a partial reduction.
Instruction * Reduction
The top-level binary operation that forms the reduction to a scalar after the loop body.
Instruction * ExtendA
The extension of each of the inner binary operation's operands.
A CRTP mix-in to automatically provide informational APIs needed for passes.
A MapVector that performs no allocations if smaller than a certain size.
Holds the VFShape for a specific scalar to vector function mapping.
std::optional< unsigned > getParamIndexForOptionalMask() const
Instruction Set Architecture.
Encapsulates information needed to describe a parameter.
A range of powers-of-2 vectorization factors with fixed start and adjustable end.
Struct to hold various analysis needed for cost computations.
LoopVectorizationCostModel & CM
bool skipCostComputation(Instruction *UI, bool IsVector) const
Return true if the cost for UI shouldn't be computed, e.g.
InstructionCost getLegacyCost(Instruction *UI, ElementCount VF) const
Return the cost for UI with VF using the legacy cost model as fallback until computing the cost of al...
SmallPtrSet< Instruction *, 8 > SkipCostComputation
A recipe for handling first-order recurrence phis.
A recipe for widening load operations, using the address to load from and an optional mask.
A recipe for widening select instructions.
A recipe for widening store operations, using the stored value, the address to store to and an option...
TODO: The following VectorizationFactor was pulled out of LoopVectorizationCostModel class.
InstructionCost Cost
Cost of the loop with that width.
ElementCount MinProfitableTripCount
The minimum trip count required to make vectorization profitable, e.g.
ElementCount Width
Vector width with best cost.
InstructionCost ScalarCost
Cost of the scalar loop.
static VectorizationFactor Disabled()
Width 1 means no vectorization, cost 0 means uncomputed cost.
static bool HoistRuntimeChecks