161#define LV_NAME "loop-vectorize"
162#define DEBUG_TYPE LV_NAME
172 "llvm.loop.vectorize.followup_vectorized";
174 "llvm.loop.vectorize.followup_epilogue";
177STATISTIC(LoopsVectorized,
"Number of loops vectorized");
178STATISTIC(LoopsAnalyzed,
"Number of loops analyzed for vectorization");
179STATISTIC(LoopsEpilogueVectorized,
"Number of epilogues vectorized");
183 cl::desc(
"Enable vectorization of epilogue loops."));
187 cl::desc(
"When epilogue vectorization is enabled, and a value greater than "
188 "1 is specified, forces the given VF for all applicable epilogue "
193 cl::desc(
"Only loops with vectorization factor equal to or larger than "
194 "the specified value are considered for epilogue vectorization."));
200 cl::desc(
"Loops with a constant trip count that is smaller than this "
201 "value are vectorized only if no scalar iteration overheads "
206 cl::desc(
"The maximum allowed number of runtime memory checks"));
222 "prefer-predicate-over-epilogue",
225 cl::desc(
"Tail-folding and predication preferences over creating a scalar "
229 "Don't tail-predicate loops, create scalar epilogue"),
231 "predicate-else-scalar-epilogue",
232 "prefer tail-folding, create scalar epilogue if tail "
235 "predicate-dont-vectorize",
236 "prefers tail-folding, don't attempt vectorization if "
237 "tail-folding fails.")));
240 "force-tail-folding-style",
cl::desc(
"Force the tail folding style"),
243 clEnumValN(TailFoldingStyle::None,
"none",
"Disable tail folding"),
245 TailFoldingStyle::Data,
"data",
246 "Create lane mask for data only, using active.lane.mask intrinsic"),
247 clEnumValN(TailFoldingStyle::DataWithoutLaneMask,
248 "data-without-lane-mask",
249 "Create lane mask with compare/stepvector"),
250 clEnumValN(TailFoldingStyle::DataAndControlFlow,
"data-and-control",
251 "Create lane mask using active.lane.mask intrinsic, and use "
252 "it for both data and control flow"),
253 clEnumValN(TailFoldingStyle::DataAndControlFlowWithoutRuntimeCheck,
254 "data-and-control-without-rt-check",
255 "Similar to data-and-control, but remove the runtime check"),
256 clEnumValN(TailFoldingStyle::DataWithEVL,
"data-with-evl",
257 "Use predicated EVL instructions for tail folding. If EVL "
258 "is unsupported, fallback to data-without-lane-mask.")));
262 cl::desc(
"Maximize bandwidth when selecting vectorization factor which "
263 "will be determined by the smallest type in loop."));
267 cl::desc(
"Enable vectorization on interleaved memory accesses in a loop"));
273 cl::desc(
"Enable vectorization on masked interleaved memory accesses in a loop"));
277 cl::desc(
"A flag that overrides the target's number of scalar registers."));
281 cl::desc(
"A flag that overrides the target's number of vector registers."));
285 cl::desc(
"A flag that overrides the target's max interleave factor for "
290 cl::desc(
"A flag that overrides the target's max interleave factor for "
291 "vectorized loops."));
295 cl::desc(
"A flag that overrides the target's expected cost for "
296 "an instruction to a single constant value. Mostly "
297 "useful for getting consistent testing."));
302 "Pretend that scalable vectors are supported, even if the target does "
303 "not support them. This flag should only be used for testing."));
308 "The cost of a loop that is considered 'small' by the interleaver."));
312 cl::desc(
"Enable the use of the block frequency analysis to access PGO "
313 "heuristics minimizing code growth in cold regions and being more "
314 "aggressive in hot regions."));
320 "Enable runtime interleaving until load/store ports are saturated"));
325 cl::desc(
"Max number of stores to be predicated behind an if."));
329 cl::desc(
"Count the induction variable only once when interleaving"));
333 cl::desc(
"Enable if predication of stores during vectorization."));
337 cl::desc(
"The maximum interleave count to use when interleaving a scalar "
338 "reduction in a nested loop."));
343 cl::desc(
"Prefer in-loop vector reductions, "
344 "overriding the targets preference."));
348 cl::desc(
"Enable the vectorisation of loops with in-order (strict) "
354 "Prefer predicating a reduction operation over an after loop select."));
359 cl::desc(
"Enable VPlan-native vectorization path with "
360 "support for outer loop vectorization."));
370 "Build VPlan for every supported loop nest in the function and bail "
371 "out right after the build (stress test the VPlan H-CFG construction "
372 "in the VPlan-native vectorization path)."));
376 cl::desc(
"Enable loop interleaving in Loop vectorization passes"));
379 cl::desc(
"Run the Loop vectorization passes"));
383 cl::desc(
"Use dot format instead of plain text when dumping VPlans"));
386 "force-widen-divrem-via-safe-divisor",
cl::Hidden,
388 "Override cost based safe divisor widening for div/rem instructions"));
391 "vectorizer-maximize-bandwidth-for-vector-calls",
cl::init(
true),
393 cl::desc(
"Try wider VFs if they enable the use of vector variants"));
412 return DL.getTypeAllocSizeInBits(Ty) !=
DL.getTypeSizeInBits(Ty);
451 unsigned Factor = Vals.
size();
452 assert(Factor > 1 &&
"Tried to interleave invalid number of vectors");
456 for (
Value *Val : Vals)
457 assert(Val->getType() == VecTy &&
"Tried to interleave mismatched types");
462 if (VecTy->isScalableTy()) {
463 VectorType *WideVecTy = VectorType::getDoubleElementsVectorType(VecTy);
464 return Builder.
CreateIntrinsic(WideVecTy, Intrinsic::vector_interleave2,
473 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
480class GeneratedRTChecks;
524 this->MinProfitableTripCount = VecWidth;
540 virtual std::pair<BasicBlock *, Value *>
567 VPValue *BlockInMask,
bool NeedsMaskForGaps);
582 std::pair<BasicBlock *, Value *> AdditionalBypass = {
nullptr,
nullptr});
651 const SCEV2ValueTy &ExpandedSCEVs,
652 std::pair<BasicBlock *, Value *> AdditionalBypass = {
nullptr,
nullptr});
799 "A high UF for the epilogue loop is likely not beneficial.");
819 GeneratedRTChecks &Checks)
821 EPI.MainLoopVF,
EPI.MainLoopVF,
EPI.MainLoopUF, LVL,
828 const SCEV2ValueTy &ExpandedSCEVs)
final {
835 virtual std::pair<BasicBlock *, Value *>
859 GeneratedRTChecks &Check)
864 std::pair<BasicBlock *, Value *>
888 GeneratedRTChecks &Checks)
895 std::pair<BasicBlock *, Value *>
917 if (
I->getDebugLoc() !=
Empty)
918 return I->getDebugLoc();
920 for (
Use &
Op :
I->operands()) {
922 if (OpInst->getDebugLoc() !=
Empty)
923 return OpInst->getDebugLoc();
926 return I->getDebugLoc();
935 dbgs() <<
"LV: " << Prefix << DebugMsg;
957 CodeRegion =
I->getParent();
960 if (
I->getDebugLoc())
961 DL =
I->getDebugLoc();
978 return B.CreateElementCount(Ty, VF);
984 assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
"Invalid loop count");
998 <<
"loop not vectorized: " << OREMsg);
1016 "Vectorizing: ", TheLoop->
isInnermost() ?
"innermost loop" :
"outer loop",
1022 <<
"vectorized " << LoopType <<
"loop (vectorization width: "
1024 <<
", interleaved count: " <<
ore::NV(
"InterleaveCount", IC) <<
")";
1168 "Profitable to scalarize relevant only for VF > 1.");
1171 "cost-model should not be used for outer loops (in VPlan-native path)");
1173 auto Scalars = InstsToScalarize.find(VF);
1174 assert(Scalars != InstsToScalarize.end() &&
1175 "VF not yet analyzed for scalarization profitability");
1176 return Scalars->second.contains(
I);
1183 "cost-model should not be used for outer loops (in VPlan-native path)");
1187 if (isa<PseudoProbeInst>(
I))
1193 auto UniformsPerVF = Uniforms.find(VF);
1194 assert(UniformsPerVF != Uniforms.end() &&
1195 "VF not yet analyzed for uniformity");
1196 return UniformsPerVF->second.count(
I);
1203 "cost-model should not be used for outer loops (in VPlan-native path)");
1207 auto ScalarsPerVF = Scalars.find(VF);
1208 assert(ScalarsPerVF != Scalars.end() &&
1209 "Scalar values are not calculated for VF");
1210 return ScalarsPerVF->second.count(
I);
1216 return VF.
isVector() && MinBWs.contains(
I) &&
1238 WideningDecisions[std::make_pair(
I, VF)] = std::make_pair(W,
Cost);
1249 for (
unsigned i = 0; i < Grp->
getFactor(); ++i) {
1252 WideningDecisions[std::make_pair(
I, VF)] = std::make_pair(W,
Cost);
1254 WideningDecisions[std::make_pair(
I, VF)] = std::make_pair(W, 0);
1266 "cost-model should not be used for outer loops (in VPlan-native path)");
1268 std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(
I, VF);
1269 auto Itr = WideningDecisions.
find(InstOnVF);
1270 if (Itr == WideningDecisions.
end())
1272 return Itr->second.first;
1279 std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(
I, VF);
1281 "The cost is not calculated");
1282 return WideningDecisions[InstOnVF].second;
1295 std::optional<unsigned> MaskPos,
1298 CallWideningDecisions[std::make_pair(CI, VF)] = {Kind, Variant, IID,
1305 return CallWideningDecisions.
at(std::make_pair(CI, VF));
1313 auto *Trunc = dyn_cast<TruncInst>(
I);
1326 Value *
Op = Trunc->getOperand(0);
1346 if (VF.
isScalar() || Uniforms.contains(VF))
1350 collectLoopUniforms(VF);
1351 collectLoopScalars(VF);
1371 bool LI = isa<LoadInst>(V);
1372 bool SI = isa<StoreInst>(V);
1387 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1388 return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1399 return ScalarCost < SafeDivisorCost;
1423 std::pair<InstructionCost, InstructionCost>
1451 LLVM_DEBUG(
dbgs() <<
"LV: Loop does not require scalar epilogue\n");
1458 dbgs() <<
"LV: Loop requires scalar epilogue: multiple exits\n");
1463 "interleaved group requires scalar epilogue\n");
1466 LLVM_DEBUG(
dbgs() <<
"LV: Loop does not require scalar epilogue\n");
1475 auto RequiresScalarEpilogue = [
this](
ElementCount VF) {
1478 bool IsRequired =
all_of(
Range, RequiresScalarEpilogue);
1480 (IsRequired ||
none_of(
Range, RequiresScalarEpilogue)) &&
1481 "all VFs in range must agree on whether a scalar epilogue is required");
1493 if (!ChosenTailFoldingStyle)
1495 return IVUpdateMayOverflow ? ChosenTailFoldingStyle->first
1496 : ChosenTailFoldingStyle->second;
1504 assert(!ChosenTailFoldingStyle &&
"Tail folding must not be selected yet.");
1506 ChosenTailFoldingStyle =
1512 ChosenTailFoldingStyle = std::make_pair(
1527 IsScalableVF && UserIC <= 1 &&
1538 ChosenTailFoldingStyle =
1543 <<
"LV: Preference for VP intrinsics indicated. Will "
1544 "not try to generate VP Intrinsics "
1546 ?
"since interleave count specified is greater than 1.\n"
1547 :
"due to non-interleaving reasons.\n"));
1573 return InLoopReductions.contains(Phi);
1588 WideningDecisions.
clear();
1589 CallWideningDecisions.
clear();
1619 unsigned NumPredStores = 0;
1628 bool FoldTailByMasking);
1633 ElementCount getMaximizedVFForTarget(
unsigned MaxTripCount,
1634 unsigned SmallestType,
1635 unsigned WidestType,
1637 bool FoldTailByMasking);
1641 ElementCount getMaxLegalScalableVF(
unsigned MaxSafeElements);
1654 std::optional<InstructionCost>
1702 PredicatedBBsAfterVectorization;
1715 std::optional<std::pair<TailFoldingStyle, TailFoldingStyle>>
1716 ChosenTailFoldingStyle;
1750 ScalarCostsTy &ScalarCosts,
1776 std::pair<InstWidening, InstructionCost>>;
1778 DecisionList WideningDecisions;
1780 using CallDecisionList =
1783 CallDecisionList CallWideningDecisions;
1806 Ops, [
this, VF](
Value *V) {
return this->needsExtract(V, VF); }));
1864class GeneratedRTChecks {
1870 Value *SCEVCheckCond =
nullptr;
1878 Value *MemRuntimeCheckCond =
nullptr;
1887 bool CostTooHigh =
false;
1888 const bool AddBranchWeights;
1890 Loop *OuterLoop =
nullptr;
1895 bool AddBranchWeights)
1896 : DT(DT), LI(LI),
TTI(
TTI), SCEVExp(SE,
DL,
"scev.check"),
1897 MemCheckExp(SE,
DL,
"scev.check"), AddBranchWeights(AddBranchWeights) {}
1925 nullptr,
"vector.scevcheck");
1932 if (RtPtrChecking.Need) {
1933 auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1934 MemCheckBlock =
SplitBlock(Pred, Pred->getTerminator(), DT, LI,
nullptr,
1937 auto DiffChecks = RtPtrChecking.getDiffChecks();
1939 Value *RuntimeVF =
nullptr;
1944 RuntimeVF = getRuntimeVF(B, B.getIntNTy(Bits), VF);
1950 MemCheckBlock->
getTerminator(), L, RtPtrChecking.getChecks(),
1953 assert(MemRuntimeCheckCond &&
1954 "no RT checks generated although RtPtrChecking "
1955 "claimed checks are required");
1958 if (!MemCheckBlock && !SCEVCheckBlock)
1968 if (SCEVCheckBlock) {
1973 if (MemCheckBlock) {
1980 if (MemCheckBlock) {
1984 if (SCEVCheckBlock) {
1990 OuterLoop =
L->getParentLoop();
1994 if (SCEVCheckBlock || MemCheckBlock)
2007 if (SCEVCheckBlock->getTerminator() == &
I)
2014 if (MemCheckBlock) {
2017 if (MemCheckBlock->getTerminator() == &
I)
2040 unsigned BestTripCount = 2;
2044 BestTripCount = SmallTC;
2048 BestTripCount = *EstimatedTC;
2051 BestTripCount = std::max(BestTripCount, 1U);
2055 NewMemCheckCost = std::max(*NewMemCheckCost.
getValue(),
2058 if (BestTripCount > 1)
2060 <<
"We expect runtime memory checks to be hoisted "
2061 <<
"out of the outer loop. Cost reduced from "
2062 << MemCheckCost <<
" to " << NewMemCheckCost <<
'\n');
2064 MemCheckCost = NewMemCheckCost;
2068 RTCheckCost += MemCheckCost;
2071 if (SCEVCheckBlock || MemCheckBlock)
2072 LLVM_DEBUG(
dbgs() <<
"Total cost of runtime checks: " << RTCheckCost
2080 ~GeneratedRTChecks() {
2084 SCEVCleaner.markResultUsed();
2086 if (!MemRuntimeCheckCond)
2087 MemCheckCleaner.markResultUsed();
2089 if (MemRuntimeCheckCond) {
2090 auto &SE = *MemCheckExp.
getSE();
2097 I.eraseFromParent();
2100 MemCheckCleaner.cleanup();
2101 SCEVCleaner.cleanup();
2104 SCEVCheckBlock->eraseFromParent();
2105 if (MemRuntimeCheckCond)
2106 MemCheckBlock->eraseFromParent();
2120 SCEVCheckCond =
nullptr;
2121 if (
auto *
C = dyn_cast<ConstantInt>(
Cond))
2132 SCEVCheckBlock->getTerminator()->eraseFromParent();
2133 SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2134 Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2141 if (AddBranchWeights)
2144 return SCEVCheckBlock;
2153 if (!MemRuntimeCheckCond)
2162 MemCheckBlock->moveBefore(LoopVectorPreHeader);
2169 if (AddBranchWeights) {
2173 MemCheckBlock->getTerminator()->setDebugLoc(
2174 Pred->getTerminator()->getDebugLoc());
2177 MemRuntimeCheckCond =
nullptr;
2178 return MemCheckBlock;
2184 return Style == TailFoldingStyle::Data ||
2185 Style == TailFoldingStyle::DataAndControlFlow ||
2186 Style == TailFoldingStyle::DataAndControlFlowWithoutRuntimeCheck;
2190 return Style == TailFoldingStyle::DataAndControlFlow ||
2191 Style == TailFoldingStyle::DataAndControlFlowWithoutRuntimeCheck;
2221 LLVM_DEBUG(
dbgs() <<
"LV: Loop hints prevent outer loop vectorization.\n");
2227 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: Interleave is not supported for "
2247 if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2257 for (
Loop *InnerL : L)
2279 ?
B.CreateSExtOrTrunc(
Index, StepTy)
2280 :
B.CreateCast(Instruction::SIToFP,
Index, StepTy);
2281 if (CastedIndex !=
Index) {
2283 Index = CastedIndex;
2293 assert(
X->getType() ==
Y->getType() &&
"Types don't match!");
2294 if (
auto *CX = dyn_cast<ConstantInt>(
X))
2297 if (
auto *CY = dyn_cast<ConstantInt>(
Y))
2300 return B.CreateAdd(
X,
Y);
2306 assert(
X->getType()->getScalarType() ==
Y->getType() &&
2307 "Types don't match!");
2308 if (
auto *CX = dyn_cast<ConstantInt>(
X))
2311 if (
auto *CY = dyn_cast<ConstantInt>(
Y))
2314 VectorType *XVTy = dyn_cast<VectorType>(
X->getType());
2315 if (XVTy && !isa<VectorType>(
Y->getType()))
2316 Y =
B.CreateVectorSplat(XVTy->getElementCount(),
Y);
2317 return B.CreateMul(
X,
Y);
2320 switch (InductionKind) {
2323 "Vector indices not supported for integer inductions yet");
2325 "Index type does not match StartValue type");
2326 if (isa<ConstantInt>(Step) && cast<ConstantInt>(Step)->isMinusOne())
2327 return B.CreateSub(StartValue,
Index);
2335 "Vector indices not supported for FP inductions yet");
2338 (InductionBinOp->
getOpcode() == Instruction::FAdd ||
2339 InductionBinOp->
getOpcode() == Instruction::FSub) &&
2340 "Original bin op should be defined for FP induction");
2343 return B.CreateBinOp(InductionBinOp->
getOpcode(), StartValue, MulExp,
2357 if (
F.hasFnAttribute(Attribute::VScaleRange))
2358 return F.getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
2360 return std::nullopt;
2369 ElementCount VF, std::optional<unsigned> UF = std::nullopt) {
2371 unsigned MaxUF = UF ? *UF :
Cost->TTI.getMaxInterleaveFactor(VF);
2373 Type *IdxTy =
Cost->Legal->getWidestInductionType();
2374 APInt MaxUIntTripCount = cast<IntegerType>(IdxTy)->getMask();
2380 Cost->PSE.getSE()->getSmallConstantMaxTripCount(
Cost->TheLoop)) {
2383 std::optional<unsigned> MaxVScale =
2387 MaxVF *= *MaxVScale;
2390 return (MaxUIntTripCount - TC).ugt(MaxVF * MaxUF);
2438 VPValue *BlockInMask,
bool NeedsMaskForGaps) {
2444 unsigned InterleaveFactor = Group->
getFactor();
2453 "Reversed masked interleave-group not supported.");
2471 for (
unsigned Part = 0; Part < State.
UF; Part++) {
2473 if (
auto *
I = dyn_cast<Instruction>(AddrPart))
2488 bool InBounds =
false;
2490 InBounds =
gep->isInBounds();
2498 auto CreateGroupMask = [
this, &BlockInMask, &State, &InterleaveFactor](
2499 unsigned Part,
Value *MaskForGaps) ->
Value * {
2501 assert(!MaskForGaps &&
"Interleaved groups with gaps are not supported.");
2502 assert(InterleaveFactor == 2 &&
2503 "Unsupported deinterleave factor for scalable vectors");
2504 auto *BlockInMaskPart = State.
get(BlockInMask, Part);
2509 nullptr,
"interleaved.mask");
2515 Value *BlockInMaskPart = State.
get(BlockInMask, Part);
2519 "interleaved.mask");
2526 if (isa<LoadInst>(Instr)) {
2527 Value *MaskForGaps =
nullptr;
2528 if (NeedsMaskForGaps) {
2531 assert(MaskForGaps &&
"Mask for Gaps is required but it is null");
2536 for (
unsigned Part = 0; Part < State.
UF; Part++) {
2538 if (BlockInMask || MaskForGaps) {
2540 "masked interleaved groups are not allowed.");
2541 Value *GroupMask = CreateGroupMask(Part, MaskForGaps);
2544 GroupMask, PoisonVec,
"wide.masked.vec");
2553 if (VecTy->isScalableTy()) {
2554 assert(InterleaveFactor == 2 &&
2555 "Unsupported deinterleave factor for scalable vectors");
2557 for (
unsigned Part = 0; Part < State.
UF; ++Part) {
2561 Intrinsic::vector_deinterleave2, VecTy, NewLoads[Part],
2562 nullptr,
"strided.vec");
2564 for (
unsigned I = 0;
I < InterleaveFactor; ++
I) {
2572 if (Member->getType() != ScalarTy) {
2580 State.
set(VPDefs[J], StridedVec, Part);
2591 for (
unsigned I = 0;
I < InterleaveFactor; ++
I) {
2600 for (
unsigned Part = 0; Part < State.
UF; Part++) {
2602 NewLoads[Part], StrideMask,
"strided.vec");
2605 if (Member->getType() != ScalarTy) {
2614 State.
set(VPDefs[J], StridedVec, Part);
2625 Value *MaskForGaps =
2628 "masked interleaved groups are not allowed.");
2630 "masking gaps for scalable vectors is not yet supported.");
2631 for (
unsigned Part = 0; Part < State.
UF; Part++) {
2634 unsigned StoredIdx = 0;
2635 for (
unsigned i = 0; i < InterleaveFactor; i++) {
2637 "Fail to get a member from an interleaved store group");
2647 Value *StoredVec = State.
get(StoredValues[StoredIdx], Part);
2655 if (StoredVec->
getType() != SubVT)
2664 if (BlockInMask || MaskForGaps) {
2665 Value *GroupMask = CreateGroupMask(Part, MaskForGaps);
2680 assert(!Instr->getType()->isAggregateType() &&
"Can't handle vectors");
2684 if (isa<NoAliasScopeDeclInst>(Instr))
2689 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2693 Cloned->
setName(Instr->getName() +
".cloned");
2698 "inferred type and type from generated instructions do not match");
2704 if (
auto DL = Instr->getDebugLoc())
2710 auto InputInstance = Instance;
2714 Cloned->
setOperand(
I.index(), State.
get(Operand, InputInstance));
2721 State.
set(RepRecipe, Cloned, Instance);
2724 if (
auto *
II = dyn_cast<AssumeInst>(Cloned))
2729 if (IfPredicateInstr)
2753 if (
Cost->foldTailByMasking()) {
2755 "VF*UF must be a power of 2 when folding tail by masking");
2786 auto *DstFVTy = cast<VectorType>(DstVTy);
2787 auto VF = DstFVTy->getElementCount();
2788 auto *SrcVecTy = cast<VectorType>(V->getType());
2789 assert(
VF == SrcVecTy->getElementCount() &&
"Vector dimensions do not match");
2790 Type *SrcElemTy = SrcVecTy->getElementType();
2791 Type *DstElemTy = DstFVTy->getElementType();
2792 assert((
DL.getTypeSizeInBits(SrcElemTy) ==
DL.getTypeSizeInBits(DstElemTy)) &&
2793 "Vector elements must have same size");
2804 "Only one type should be a pointer type");
2806 "Only one type should be a floating point type");
2832 auto CreateStep = [&]() ->
Value * {
2857 Value *MaxUIntTripCount =
2858 ConstantInt::get(CountTy, cast<IntegerType>(CountTy)->getMask());
2872 "TC check is expected to dominate Bypass");
2893 if (!SCEVCheckBlock)
2899 "Cannot SCEV check stride or overflow when optimizing for size");
2914 return SCEVCheckBlock;
2933 "Cannot emit memory checks when optimizing for size, unless forced "
2939 <<
"Code-size may be reduced by not forcing "
2940 "vectorization, or by source-code modifications "
2941 "eliminating the need for runtime checks "
2942 "(e.g., adding 'restrict').";
2950 return MemCheckBlock;
2959 "multiple exit loop without required epilogue?");
2963 LI,
nullptr,
Twine(Prefix) +
"middle.block");
2966 nullptr,
Twine(Prefix) +
"scalar.ph");
2976 " middle block should have the scalar preheader as single successor");
2988 BrInst->
setDebugLoc(ScalarLatchTerm->getDebugLoc());
3000 std::pair<BasicBlock *, Value *> AdditionalBypass) {
3006 Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3007 if (OrigPhi == OldInduction) {
3014 if (
II.getInductionBinOp() && isa<FPMathOperator>(
II.getInductionBinOp()))
3015 B.setFastMathFlags(
II.getInductionBinOp()->getFastMathFlags());
3018 Step,
II.getKind(),
II.getInductionBinOp());
3022 if (AdditionalBypass.first) {
3023 B.SetInsertPoint(AdditionalBypass.first,
3024 AdditionalBypass.first->getFirstInsertionPt());
3025 EndValueFromAdditionalBypass =
3027 Step,
II.getKind(),
II.getInductionBinOp());
3028 EndValueFromAdditionalBypass->
setName(
"ind.end");
3048 if (AdditionalBypass.first)
3050 EndValueFromAdditionalBypass);
3057 const SCEV2ValueTy &ExpandedSCEVs) {
3058 const SCEV *Step =
ID.getStep();
3059 if (
auto *
C = dyn_cast<SCEVConstant>(Step))
3060 return C->getValue();
3061 if (
auto *U = dyn_cast<SCEVUnknown>(Step))
3062 return U->getValue();
3063 auto I = ExpandedSCEVs.find(Step);
3064 assert(
I != ExpandedSCEVs.end() &&
"SCEV must be expanded at this point");
3069 const SCEV2ValueTy &ExpandedSCEVs,
3070 std::pair<BasicBlock *, Value *> AdditionalBypass) {
3071 assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3072 (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3073 "Inconsistent information about additional bypass.");
3082 PHINode *OrigPhi = InductionEntry.first;
3107 !
Cost->foldTailByMasking()) {
3116 B.SetCurrentDebugLocation(ScalarLatchTerm->getDebugLoc());
3129#ifdef EXPENSIVE_CHECKS
3136std::pair<BasicBlock *, Value *>
3138 const SCEV2ValueTy &ExpandedSCEVs) {
3223 assert(isa<PHINode>(UI) &&
"Expected LCSSA form");
3224 MissingVals[UI] = EndValue;
3232 auto *UI = cast<Instruction>(U);
3234 assert(isa<PHINode>(UI) &&
"Expected LCSSA form");
3238 if (
II.getInductionBinOp() && isa<FPMathOperator>(
II.getInductionBinOp()))
3239 B.setFastMathFlags(
II.getInductionBinOp()->getFastMathFlags());
3241 Value *CountMinusOne =
B.CreateSub(
3243 CountMinusOne->
setName(
"cmo");
3246 assert(StepVPV &&
"step must have been expanded during VPlan execution");
3248 : State.
get(StepVPV, {0, 0});
3251 II.getKind(),
II.getInductionBinOp());
3252 Escape->
setName(
"ind.escape");
3253 MissingVals[UI] = Escape;
3257 for (
auto &
I : MissingVals) {
3264 if (
PHI->getBasicBlockIndex(MiddleBlock) == -1) {
3265 PHI->addIncoming(
I.second, MiddleBlock);
3273struct CSEDenseMapInfo {
3275 return isa<InsertElementInst>(
I) || isa<ExtractElementInst>(
I) ||
3276 isa<ShuffleVectorInst>(
I) || isa<GetElementPtrInst>(
I);
3288 assert(canHandle(
I) &&
"Unknown instruction!");
3290 I->value_op_end()));
3294 if (
LHS == getEmptyKey() ||
RHS == getEmptyKey() ||
3295 LHS == getTombstoneKey() ||
RHS == getTombstoneKey())
3297 return LHS->isIdenticalTo(
RHS);
3308 if (!CSEDenseMapInfo::canHandle(&In))
3314 In.replaceAllUsesWith(V);
3315 In.eraseFromParent();
3329 return CallWideningDecisions.at(std::make_pair(CI, VF)).Cost;
3334 if (
auto RedCost = getReductionPatternCost(CI, VF,
RetTy,
CostKind))
3338 for (
auto &ArgOp : CI->
args())
3347 return std::min(ScalarCallCost, IntrinsicCost);
3349 return ScalarCallCost;
3362 assert(
ID &&
"Expected intrinsic call!");
3365 if (
auto *FPMO = dyn_cast<FPMathOperator>(CI))
3366 FMF = FPMO->getFastMathFlags();
3372 std::back_inserter(ParamTys),
3373 [&](
Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3376 dyn_cast<IntrinsicInst>(CI));
3410 for (
PHINode &PN : Exit->phis())
3441 KV.second->fixPhi(Plan, State);
3471 VPValue *VPExtract = LO->getOperand(0);
3473 assert(
match(VPExtract, m_VPInstruction<VPInstruction::ExtractFromEnd>(
3474 m_VPValue(), m_VPValue())) &&
3475 "FOR LiveOut expects to use an extract from end.");
3476 Value *ResumeScalarFOR = State.
get(VPExtract,
UF - 1,
true);
3479 PHINode *ScalarHeaderPhi = LO->getPhi();
3480 auto *InitScalarFOR =
3483 auto *ScalarPreheaderPhi =
3487 ScalarPreheaderPhi->addIncoming(
Incoming, BB);
3490 ScalarPreheaderPhi);
3491 ScalarHeaderPhi->
setName(
"scalar.recur");
3508 auto isBlockOfUsePredicated = [&](
Use &U) ->
bool {
3509 auto *
I = cast<Instruction>(U.getUser());
3511 if (
auto *Phi = dyn_cast<PHINode>(
I))
3512 BB = Phi->getIncomingBlock(
3514 return BB == PredBB;
3525 Worklist.
insert(InstsToReanalyze.
begin(), InstsToReanalyze.
end());
3526 InstsToReanalyze.
clear();
3529 while (!Worklist.
empty()) {
3535 if (!
I || isa<PHINode>(
I) || !VectorLoop->contains(
I) ||
3536 I->mayHaveSideEffects() ||
I->mayReadFromMemory())
3544 if (
I->getParent() == PredBB) {
3545 Worklist.
insert(
I->op_begin(),
I->op_end());
3559 I->moveBefore(&*PredBB->getFirstInsertionPt());
3560 Worklist.
insert(
I->op_begin(),
I->op_end());
3572 for (
VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
3577 PHINode *NewPhi = cast<PHINode>(State.
get(VPPhi, 0));
3589void LoopVectorizationCostModel::collectLoopScalars(
ElementCount VF) {
3594 "This function should not be visited twice for the same VF");
3600 Scalars[VF].
insert(Uniforms[VF].begin(), Uniforms[VF].end());
3619 "Widening decision should be ready at this moment");
3620 if (
auto *Store = dyn_cast<StoreInst>(MemAccess))
3621 if (
Ptr == Store->getValueOperand())
3624 "Ptr is neither a value or pointer operand");
3630 auto isLoopVaryingBitCastOrGEP = [&](
Value *
V) {
3631 return ((isa<BitCastInst>(V) &&
V->getType()->isPointerTy()) ||
3632 isa<GetElementPtrInst>(V)) &&
3643 if (!isLoopVaryingBitCastOrGEP(
Ptr))
3648 auto *
I = cast<Instruction>(
Ptr);
3656 return isa<LoadInst>(U) || isa<StoreInst>(U);
3660 PossibleNonScalarPtrs.
insert(
I);
3678 for (
auto &
I : *BB) {
3679 if (
auto *Load = dyn_cast<LoadInst>(&
I)) {
3680 evaluatePtrUse(Load,
Load->getPointerOperand());
3681 }
else if (
auto *Store = dyn_cast<StoreInst>(&
I)) {
3682 evaluatePtrUse(Store,
Store->getPointerOperand());
3683 evaluatePtrUse(Store,
Store->getValueOperand());
3686 for (
auto *
I : ScalarPtrs)
3687 if (!PossibleNonScalarPtrs.
count(
I)) {
3695 auto ForcedScalar = ForcedScalars.
find(VF);
3696 if (ForcedScalar != ForcedScalars.
end())
3697 for (
auto *
I : ForcedScalar->second) {
3698 LLVM_DEBUG(
dbgs() <<
"LV: Found (forced) scalar instruction: " << *
I <<
"\n");
3707 while (
Idx != Worklist.
size()) {
3709 if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
3711 auto *Src = cast<Instruction>(Dst->getOperand(0));
3713 auto *J = cast<Instruction>(U);
3714 return !TheLoop->contains(J) || Worklist.count(J) ||
3715 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
3716 isScalarUse(J, Src));
3719 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Src <<
"\n");
3726 auto *Ind = Induction.first;
3727 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
3736 auto IsDirectLoadStoreFromPtrIndvar = [&](
Instruction *Indvar,
3738 return Induction.second.getKind() ==
3740 (isa<LoadInst>(
I) || isa<StoreInst>(
I)) &&
3747 auto *I = cast<Instruction>(U);
3748 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
3749 IsDirectLoadStoreFromPtrIndvar(Ind, I);
3757 auto *IndUpdatePhi = dyn_cast<PHINode>(IndUpdate);
3763 auto ScalarIndUpdate =
3765 auto *I = cast<Instruction>(U);
3766 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
3767 IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
3769 if (!ScalarIndUpdate)
3774 Worklist.
insert(IndUpdate);
3775 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Ind <<
"\n");
3776 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *IndUpdate
3790 switch(
I->getOpcode()) {
3793 case Instruction::Call:
3796 return CallWideningDecisions.at(std::make_pair(cast<CallInst>(
I), VF))
3798 case Instruction::Load:
3799 case Instruction::Store: {
3811 case Instruction::UDiv:
3812 case Instruction::SDiv:
3813 case Instruction::SRem:
3814 case Instruction::URem: {
3830 switch(
I->getOpcode()) {
3833 case Instruction::Load:
3834 case Instruction::Store: {
3847 (isa<LoadInst>(
I) ||
3848 (isa<StoreInst>(
I) &&
3854 case Instruction::UDiv:
3855 case Instruction::SDiv:
3856 case Instruction::SRem:
3857 case Instruction::URem:
3861 case Instruction::Call:
3866std::pair<InstructionCost, InstructionCost>
3869 assert(
I->getOpcode() == Instruction::UDiv ||
3870 I->getOpcode() == Instruction::SDiv ||
3871 I->getOpcode() == Instruction::SRem ||
3872 I->getOpcode() == Instruction::URem);
3883 ScalarizationCost = 0;
3898 ScalarizationCost += getScalarizationOverhead(
I, VF,
CostKind);
3912 Instruction::Select, VecTy,
3918 Value *Op2 =
I->getOperand(1);
3927 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
3929 return {ScalarizationCost, SafeDivisorCost};
3936 "Decision should not be set yet.");
3938 assert(Group &&
"Must have a group.");
3942 auto &
DL =
I->getDataLayout();
3949 unsigned InterleaveFactor = Group->getFactor();
3950 bool ScalarNI =
DL.isNonIntegralPointerType(ScalarTy);
3951 for (
unsigned i = 0; i < InterleaveFactor; i++) {
3956 bool MemberNI =
DL.isNonIntegralPointerType(
MemberTy);
3958 if (MemberNI != ScalarNI) {
3961 }
else if (MemberNI && ScalarNI &&
3962 ScalarTy->getPointerAddressSpace() !=
3963 MemberTy->getPointerAddressSpace()) {
3973 bool PredicatedAccessRequiresMasking =
3976 bool LoadAccessWithGapsRequiresEpilogMasking =
3977 isa<LoadInst>(
I) && Group->requiresScalarEpilogue() &&
3979 bool StoreAccessWithGapsRequiresMasking =
3980 isa<StoreInst>(
I) && (Group->getNumMembers() < Group->getFactor());
3981 if (!PredicatedAccessRequiresMasking &&
3982 !LoadAccessWithGapsRequiresEpilogMasking &&
3983 !StoreAccessWithGapsRequiresMasking)
3990 "Masked interleave-groups for predicated accesses are not enabled.");
3992 if (Group->isReverse())
4004 assert((isa<LoadInst, StoreInst>(
I)) &&
"Invalid memory instruction");
4020 auto &
DL =
I->getDataLayout();
4027void LoopVectorizationCostModel::collectLoopUniforms(
ElementCount VF) {
4034 "This function should not be visited twice for the same VF");
4038 Uniforms[VF].
clear();
4046 auto isOutOfScope = [&](
Value *V) ->
bool {
4059 auto addToWorklistIfAllowed = [&](
Instruction *
I) ->
void {
4060 if (isOutOfScope(
I)) {
4066 LLVM_DEBUG(
dbgs() <<
"LV: Found not uniform being ScalarWithPredication: "
4070 LLVM_DEBUG(
dbgs() <<
"LV: Found uniform instruction: " << *
I <<
"\n");
4080 auto *
Cmp = dyn_cast<Instruction>(E->getTerminator()->getOperand(0));
4082 addToWorklistIfAllowed(Cmp);
4091 if (PrevVF.isVector()) {
4092 auto Iter = Uniforms.
find(PrevVF);
4093 if (Iter != Uniforms.
end() && !Iter->second.contains(
I))
4098 if (isa<LoadInst>(
I))
4109 "Widening decision should be ready at this moment");
4111 if (isUniformMemOpUse(
I))
4114 return (WideningDecision ==
CM_Widen ||
4123 if (isa<StoreInst>(
I) &&
I->getOperand(0) ==
Ptr)
4139 for (
auto &
I : *BB) {
4141 switch (
II->getIntrinsicID()) {
4142 case Intrinsic::sideeffect:
4143 case Intrinsic::experimental_noalias_scope_decl:
4144 case Intrinsic::assume:
4145 case Intrinsic::lifetime_start:
4146 case Intrinsic::lifetime_end:
4148 addToWorklistIfAllowed(&
I);
4157 if (
auto *EVI = dyn_cast<ExtractValueInst>(&
I)) {
4158 assert(isOutOfScope(EVI->getAggregateOperand()) &&
4159 "Expected aggregate value to be loop invariant");
4160 addToWorklistIfAllowed(EVI);
4169 if (isUniformMemOpUse(&
I))
4170 addToWorklistIfAllowed(&
I);
4172 if (isVectorizedMemAccessUse(&
I,
Ptr))
4179 for (
auto *V : HasUniformUse) {
4180 if (isOutOfScope(V))
4182 auto *
I = cast<Instruction>(V);
4183 auto UsersAreMemAccesses =
4185 return isVectorizedMemAccessUse(cast<Instruction>(U), V);
4187 if (UsersAreMemAccesses)
4188 addToWorklistIfAllowed(
I);
4195 while (idx != Worklist.
size()) {
4198 for (
auto *OV :
I->operand_values()) {
4200 if (isOutOfScope(OV))
4204 auto *
OP = dyn_cast<PHINode>(OV);
4209 auto *OI = cast<Instruction>(OV);
4211 auto *J = cast<Instruction>(U);
4212 return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
4214 addToWorklistIfAllowed(OI);
4226 auto *Ind = Induction.first;
4227 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4232 auto *I = cast<Instruction>(U);
4233 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4234 isVectorizedMemAccessUse(I, Ind);
4241 auto UniformIndUpdate =
4243 auto *I = cast<Instruction>(U);
4244 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4245 isVectorizedMemAccessUse(I, IndUpdate);
4247 if (!UniformIndUpdate)
4251 addToWorklistIfAllowed(Ind);
4252 addToWorklistIfAllowed(IndUpdate);
4263 "runtime pointer checks needed. Enable vectorization of this "
4264 "loop with '#pragma clang loop vectorize(enable)' when "
4265 "compiling with -Os/-Oz",
4266 "CantVersionLoopWithOptForSize",
ORE,
TheLoop);
4272 "runtime SCEV checks needed. Enable vectorization of this "
4273 "loop with '#pragma clang loop vectorize(enable)' when "
4274 "compiling with -Os/-Oz",
4275 "CantVersionLoopWithOptForSize",
ORE,
TheLoop);
4282 "runtime stride == 1 checks needed. Enable vectorization of "
4283 "this loop without such check by compiling with -Os/-Oz",
4284 "CantVersionLoopWithOptForSize",
ORE,
TheLoop);
4292LoopVectorizationCostModel::getMaxLegalScalableVF(
unsigned MaxSafeElements) {
4298 "ScalableVectorizationDisabled",
ORE,
TheLoop);
4302 LLVM_DEBUG(
dbgs() <<
"LV: Scalable vectorization is available\n");
4305 std::numeric_limits<ElementCount::ScalarTy>::max());
4316 "Scalable vectorization not supported for the reduction "
4317 "operations found in this loop.",
4329 "for all element types found in this loop.",
4335 return MaxScalableVF;
4345 "Max legal vector width too small, scalable vectorization "
4349 return MaxScalableVF;
4353 unsigned MaxTripCount,
ElementCount UserVF,
bool FoldTailByMasking) {
4355 unsigned SmallestType, WidestType;
4362 unsigned MaxSafeElements =
4366 auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
4368 LLVM_DEBUG(
dbgs() <<
"LV: The max safe fixed VF is: " << MaxSafeFixedVF
4370 LLVM_DEBUG(
dbgs() <<
"LV: The max safe scalable VF is: " << MaxSafeScalableVF
4375 auto MaxSafeUserVF =
4376 UserVF.
isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
4393 <<
" is unsafe, clamping to max safe VF="
4394 << MaxSafeFixedVF <<
".\n");
4399 <<
"User-specified vectorization factor "
4400 <<
ore::NV(
"UserVectorizationFactor", UserVF)
4401 <<
" is unsafe, clamping to maximum safe vectorization factor "
4402 <<
ore::NV(
"VectorizationFactor", MaxSafeFixedVF);
4404 return MaxSafeFixedVF;
4409 <<
" is ignored because scalable vectors are not "
4415 <<
"User-specified vectorization factor "
4416 <<
ore::NV(
"UserVectorizationFactor", UserVF)
4417 <<
" is ignored because the target does not support scalable "
4418 "vectors. The compiler will pick a more suitable value.";
4422 <<
" is unsafe. Ignoring scalable UserVF.\n");
4427 <<
"User-specified vectorization factor "
4428 <<
ore::NV(
"UserVectorizationFactor", UserVF)
4429 <<
" is unsafe. Ignoring the hint to let the compiler pick a "
4430 "more suitable value.";
4435 LLVM_DEBUG(
dbgs() <<
"LV: The Smallest and Widest types: " << SmallestType
4436 <<
" / " << WidestType <<
" bits.\n");
4441 getMaximizedVFForTarget(MaxTripCount, SmallestType, WidestType,
4442 MaxSafeFixedVF, FoldTailByMasking))
4446 getMaximizedVFForTarget(MaxTripCount, SmallestType, WidestType,
4447 MaxSafeScalableVF, FoldTailByMasking))
4448 if (MaxVF.isScalable()) {
4449 Result.ScalableVF = MaxVF;
4450 LLVM_DEBUG(
dbgs() <<
"LV: Found feasible scalable VF = " << MaxVF
4463 "Not inserting runtime ptr check for divergent target",
4464 "runtime pointer checks needed. Not enabled for divergent target",
4465 "CantVersionLoopWithDivergentTarget",
ORE,
TheLoop);
4474 "loop trip count is one, irrelevant for vectorization",
4479 switch (ScalarEpilogueStatus) {
4481 return computeFeasibleMaxVF(MaxTC, UserVF,
false);
4486 dbgs() <<
"LV: vector predicate hint/switch found.\n"
4487 <<
"LV: Not allowing scalar epilogue, creating predicated "
4488 <<
"vector loop.\n");
4495 dbgs() <<
"LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
4497 LLVM_DEBUG(
dbgs() <<
"LV: Not allowing scalar epilogue due to low trip "
4516 LLVM_DEBUG(
dbgs() <<
"LV: Cannot fold tail by masking: vectorize with a "
4517 "scalar epilogue instead.\n");
4519 return computeFeasibleMaxVF(MaxTC, UserVF,
false);
4530 "No decisions should have been taken at this point");
4540 std::optional<unsigned> MaxPowerOf2RuntimeVF =
4545 MaxPowerOf2RuntimeVF = std::max<unsigned>(
4546 *MaxPowerOf2RuntimeVF,
4549 MaxPowerOf2RuntimeVF = std::nullopt;
4552 if (MaxPowerOf2RuntimeVF && *MaxPowerOf2RuntimeVF > 0) {
4554 "MaxFixedVF must be a power of 2");
4555 unsigned MaxVFtimesIC =
4556 UserIC ? *MaxPowerOf2RuntimeVF * UserIC : *MaxPowerOf2RuntimeVF;
4560 BackedgeTakenCount, SE->
getOne(BackedgeTakenCount->
getType()));
4566 LLVM_DEBUG(
dbgs() <<
"LV: No tail will remain for any chosen VF.\n");
4580 <<
"LV: tail is folded with EVL, forcing unroll factor to be 1. Will "
4581 "try to generate VP Intrinsics with scalable vector "
4587 "Expected scalable vector factor.");
4597 LLVM_DEBUG(
dbgs() <<
"LV: Cannot fold tail by masking: vectorize with a "
4598 "scalar epilogue instead.\n");
4604 LLVM_DEBUG(
dbgs() <<
"LV: Can't fold tail by masking: don't vectorize\n");
4610 "Unable to calculate the loop count due to complex control flow",
4611 "unable to calculate the loop count due to complex control flow",
4617 "Cannot optimize for size and vectorize at the same time.",
4618 "cannot optimize for size and vectorize at the same time. "
4619 "Enable vectorization of this loop with '#pragma clang loop "
4620 "vectorize(enable)' when compiling with -Os/-Oz",
4625ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
4626 unsigned MaxTripCount,
unsigned SmallestType,
unsigned WidestType,
4628 bool ComputeScalableMaxVF = MaxSafeVF.
isScalable();
4636 "Scalable flags must match");
4644 ComputeScalableMaxVF);
4645 MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
4647 << (MaxVectorElementCount * WidestType) <<
" bits.\n");
4649 if (!MaxVectorElementCount) {
4651 << (ComputeScalableMaxVF ?
"scalable" :
"fixed")
4652 <<
" vector registers.\n");
4656 unsigned WidestRegisterMinEC = MaxVectorElementCount.getKnownMinValue();
4657 if (MaxVectorElementCount.isScalable() &&
4661 WidestRegisterMinEC *= Min;
4670 if (MaxTripCount && MaxTripCount <= WidestRegisterMinEC &&
4678 LLVM_DEBUG(
dbgs() <<
"LV: Clamping the MaxVF to maximum power of two not "
4679 "exceeding the constant trip count: "
4680 << ClampedUpperTripCount <<
"\n");
4682 ClampedUpperTripCount,
4683 FoldTailByMasking ? MaxVectorElementCount.isScalable() :
false);
4696 ComputeScalableMaxVF);
4697 MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
4711 for (
int i = RUs.size() - 1; i >= 0; --i) {
4712 bool Selected =
true;
4713 for (
auto &pair : RUs[i].MaxLocalUsers) {
4715 if (pair.second > TargetNumRegisters)
4727 <<
") with target's minimum: " << MinVF <<
'\n');
4743static std::optional<unsigned>
4745 const Function *Fn = L->getHeader()->getParent();
4749 auto Max = Attr.getVScaleRangeMax();
4750 if (Max && Min == Max)
4757bool LoopVectorizationPlanner::isMoreProfitable(
4765 unsigned EstimatedWidthA =
A.Width.getKnownMinValue();
4766 unsigned EstimatedWidthB =
B.Width.getKnownMinValue();
4768 if (
A.Width.isScalable())
4769 EstimatedWidthA *= *VScale;
4770 if (
B.Width.isScalable())
4771 EstimatedWidthB *= *VScale;
4777 bool PreferScalable =
A.Width.isScalable() && !
B.Width.isScalable();
4787 return CmpFn(CostA * EstimatedWidthB, CostB * EstimatedWidthA);
4789 auto GetCostForTC = [MaxTripCount,
this](
unsigned VF,
4801 return VectorCost *
divideCeil(MaxTripCount, VF);
4802 return VectorCost * (MaxTripCount / VF) + ScalarCost * (MaxTripCount % VF);
4805 auto RTCostA = GetCostForTC(EstimatedWidthA, CostA,
A.ScalarCost);
4806 auto RTCostB = GetCostForTC(EstimatedWidthB, CostB,
B.ScalarCost);
4807 return CmpFn(RTCostA, RTCostB);
4813 if (InvalidCosts.
empty())
4820 std::map<Instruction *, unsigned> Numbering;
4822 for (
auto &Pair : InvalidCosts)
4823 if (!Numbering.count(Pair.first))
4824 Numbering[Pair.first] =
I++;
4828 if (Numbering[
A.first] != Numbering[
B.first])
4829 return Numbering[
A.first] < Numbering[
B.first];
4830 const auto &
LHS =
A.second;
4831 const auto &
RHS =
B.second;
4832 return std::make_tuple(
LHS.isScalable(),
LHS.getKnownMinValue()) <
4833 std::make_tuple(
RHS.isScalable(),
RHS.getKnownMinValue());
4845 Subset =
Tail.take_front(1);
4854 if (Subset ==
Tail ||
Tail[Subset.size()].first !=
I) {
4855 std::string OutString;
4857 assert(!Subset.empty() &&
"Unexpected empty range");
4858 OS <<
"Instruction with invalid costs prevented vectorization at VF=(";
4859 for (
const auto &Pair : Subset)
4860 OS << (Pair.second == Subset.front().second ?
"" :
", ") << Pair.second;
4862 if (
auto *CI = dyn_cast<CallInst>(
I))
4863 OS <<
" call to " << CI->getCalledFunction()->getName();
4865 OS <<
" " <<
I->getOpcodeName();
4868 Tail =
Tail.drop_front(Subset.size());
4872 Subset =
Tail.take_front(Subset.size() + 1);
4873 }
while (!
Tail.empty());
4879 LLVM_DEBUG(
dbgs() <<
"LV: Scalar loop costs: " << ExpectedCost <<
".\n");
4880 assert(ExpectedCost.
isValid() &&
"Unexpected invalid cost for scalar loop");
4882 [](std::unique_ptr<VPlan> &
P) {
4885 "Expected Scalar VF to be a candidate");
4892 if (ForceVectorization &&
4893 (VPlans.
size() > 1 || !VPlans[0]->hasScalarVFOnly())) {
4901 for (
auto &
P : VPlans) {
4912 unsigned AssumedMinimumVscale =
4915 Candidate.Width.isScalable()
4916 ? Candidate.Width.getKnownMinValue() * AssumedMinimumVscale
4917 : Candidate.Width.getFixedValue();
4919 <<
" costs: " << (Candidate.Cost / Width));
4920 if (VF.isScalable())
4922 << AssumedMinimumVscale <<
")");
4926 if (!
C.second && !ForceVectorization) {
4929 <<
"LV: Not considering vector loop of width " << VF
4930 <<
" because it will not generate any vector instructions.\n");
4935 if (isMoreProfitable(Candidate, ScalarCost))
4936 ProfitableVFs.push_back(Candidate);
4938 if (isMoreProfitable(Candidate, ChosenFactor))
4939 ChosenFactor = Candidate;
4947 "There are conditional stores.",
4948 "store that is conditionally executed prevents vectorization",
4949 "ConditionalStore", ORE, OrigLoop);
4950 ChosenFactor = ScalarCost;
4954 !isMoreProfitable(ChosenFactor, ScalarCost))
dbgs()
4955 <<
"LV: Vectorization seems to be not beneficial, "
4956 <<
"but was forced by a user.\n");
4958 return ChosenFactor;
4961bool LoopVectorizationPlanner::isCandidateForEpilogueVectorization(
4966 [&](
PHINode &Phi) { return Legal->isFixedOrderRecurrence(&Phi); }))
4976 if (!OrigLoop->
contains(cast<Instruction>(U)))
4980 if (!OrigLoop->
contains(cast<Instruction>(U)))
5009 unsigned Multiplier = 1;
5021 LLVM_DEBUG(
dbgs() <<
"LEV: Epilogue vectorization is disabled.\n");
5026 LLVM_DEBUG(
dbgs() <<
"LEV: Unable to vectorize epilogue because no "
5027 "epilogue is allowed.\n");
5033 if (!isCandidateForEpilogueVectorization(MainLoopVF)) {
5034 LLVM_DEBUG(
dbgs() <<
"LEV: Unable to vectorize epilogue because the loop "
5035 "is not a supported candidate.\n");
5040 LLVM_DEBUG(
dbgs() <<
"LEV: Epilogue vectorization factor is forced.\n");
5043 return {ForcedEC, 0, 0};
5045 LLVM_DEBUG(
dbgs() <<
"LEV: Epilogue vectorization forced factor is not "
5054 dbgs() <<
"LEV: Epilogue vectorization skipped due to opt for size.\n");
5059 LLVM_DEBUG(
dbgs() <<
"LEV: Epilogue vectorization is not profitable for "
5071 EstimatedRuntimeVF *= *VScale;
5076 const SCEV *RemainingIterations =
nullptr;
5077 for (
auto &NextVF : ProfitableVFs) {
5084 if ((!NextVF.Width.isScalable() && MainLoopVF.
isScalable() &&
5091 if (!MainLoopVF.
isScalable() && !NextVF.Width.isScalable()) {
5093 if (!RemainingIterations) {
5100 SE.
getConstant(TCType, NextVF.Width.getKnownMinValue()),
5101 RemainingIterations))
5105 if (Result.Width.isScalar() || isMoreProfitable(NextVF, Result))
5111 << Result.Width <<
"\n");
5115std::pair<unsigned, unsigned>
5117 unsigned MinWidth = -1U;
5118 unsigned MaxWidth = 8;
5131 MaxWidth = std::min<unsigned>(
5132 MaxWidth, std::min<unsigned>(
5138 MinWidth = std::min<unsigned>(
5139 MinWidth,
DL.getTypeSizeInBits(
T->getScalarType()).getFixedValue());
5140 MaxWidth = std::max<unsigned>(
5141 MaxWidth,
DL.getTypeSizeInBits(
T->getScalarType()).getFixedValue());
5144 return {MinWidth, MaxWidth};
5152 for (
Instruction &
I : BB->instructionsWithoutDebug()) {
5160 if (!isa<LoadInst>(
I) && !isa<StoreInst>(
I) && !isa<PHINode>(
I))
5165 if (
auto *PN = dyn_cast<PHINode>(&
I)) {
5179 if (
auto *ST = dyn_cast<StoreInst>(&
I))
5180 T = ST->getValueOperand()->getType();
5183 "Expected the load/store/recurrence type to be sized");
5212 LLVM_DEBUG(
dbgs() <<
"LV: Preference for VP intrinsics indicated. "
5213 "Unroll factor forced to be 1.\n");
5226 if (LoopCost == 0) {
5228 assert(LoopCost.
isValid() &&
"Expected to have chosen a VF with valid cost");
5238 for (
auto& pair : R.MaxLocalUsers) {
5239 pair.second = std::max(pair.second, 1U);
5253 unsigned IC = UINT_MAX;
5255 for (
auto& pair : R.MaxLocalUsers) {
5267 unsigned MaxLocalUsers = pair.second;
5268 unsigned LoopInvariantRegs = 0;
5269 if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
5270 LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
5272 unsigned TmpIC =
llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs) /
5276 TmpIC =
llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs - 1) /
5277 std::max(1U, (MaxLocalUsers - 1)));
5280 IC = std::min(IC, TmpIC);
5298 EstimatedVF *= *VScale;
5300 assert(EstimatedVF >= 1 &&
"Estimated VF shouldn't be less than 1");
5306 unsigned AvailableTC =
5318 std::max(1u, std::min(AvailableTC / EstimatedVF, MaxInterleaveCount)));
5319 unsigned InterleaveCountLB =
bit_floor(std::max(
5320 1u, std::min(AvailableTC / (EstimatedVF * 2), MaxInterleaveCount)));
5321 MaxInterleaveCount = InterleaveCountLB;
5323 if (InterleaveCountUB != InterleaveCountLB) {
5324 unsigned TailTripCountUB =
5325 (AvailableTC % (EstimatedVF * InterleaveCountUB));
5326 unsigned TailTripCountLB =
5327 (AvailableTC % (EstimatedVF * InterleaveCountLB));
5330 if (TailTripCountUB == TailTripCountLB)
5331 MaxInterleaveCount = InterleaveCountUB;
5333 }
else if (BestKnownTC && *BestKnownTC > 0) {
5337 ? (*BestKnownTC) - 1
5345 MaxInterleaveCount =
bit_floor(std::max(
5346 1u, std::min(AvailableTC / (EstimatedVF * 2), MaxInterleaveCount)));
5349 assert(MaxInterleaveCount > 0 &&
5350 "Maximum interleave count must be greater than 0");
5354 if (IC > MaxInterleaveCount)
5355 IC = MaxInterleaveCount;
5358 IC = std::max(1u, IC);
5360 assert(IC > 0 &&
"Interleave count must be greater than 0.");
5364 if (VF.
isVector() && HasReductions) {
5365 LLVM_DEBUG(
dbgs() <<
"LV: Interleaving because of reductions.\n");
5373 bool ScalarInterleavingRequiresPredication =
5375 return Legal->blockNeedsPredication(BB);
5377 bool ScalarInterleavingRequiresRuntimePointerCheck =
5383 <<
"LV: IC is " << IC <<
'\n'
5384 <<
"LV: VF is " << VF <<
'\n');
5385 const bool AggressivelyInterleaveReductions =
5387 if (!ScalarInterleavingRequiresRuntimePointerCheck &&
5388 !ScalarInterleavingRequiresPredication && LoopCost <
SmallLoopCost) {
5392 unsigned SmallIC = std::min(IC, (
unsigned)llvm::bit_floor<uint64_t>(
5399 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5400 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5406 bool HasSelectCmpReductions =
5409 const RecurrenceDescriptor &RdxDesc = Reduction.second;
5410 return RecurrenceDescriptor::isAnyOfRecurrenceKind(
5411 RdxDesc.getRecurrenceKind());
5413 if (HasSelectCmpReductions) {
5414 LLVM_DEBUG(
dbgs() <<
"LV: Not interleaving select-cmp reductions.\n");
5424 bool HasOrderedReductions =
5426 const RecurrenceDescriptor &RdxDesc = Reduction.second;
5427 return RdxDesc.isOrdered();
5429 if (HasOrderedReductions) {
5431 dbgs() <<
"LV: Not interleaving scalar ordered reductions.\n");
5436 SmallIC = std::min(SmallIC,
F);
5437 StoresIC = std::min(StoresIC,
F);
5438 LoadsIC = std::min(LoadsIC,
F);
5442 std::max(StoresIC, LoadsIC) > SmallIC) {
5444 dbgs() <<
"LV: Interleaving to saturate store or load ports.\n");
5445 return std::max(StoresIC, LoadsIC);
5450 if (VF.
isScalar() && AggressivelyInterleaveReductions) {
5454 return std::max(IC / 2, SmallIC);
5456 LLVM_DEBUG(
dbgs() <<
"LV: Interleaving to reduce branch cost.\n");
5463 if (AggressivelyInterleaveReductions) {
5513 for (
Instruction &
I : BB->instructionsWithoutDebug()) {
5517 for (
Value *U :
I.operands()) {
5518 auto *Instr = dyn_cast<Instruction>(U);
5529 LoopInvariants.
insert(Instr);
5534 EndPoint[Instr] = IdxToInstr.
size();
5552 LLVM_DEBUG(
dbgs() <<
"LV(REG): Calculating max register usage:\n");
5554 const auto &TTICapture =
TTI;
5561 for (
unsigned int i = 0, s = IdxToInstr.
size(); i < s; ++i) {
5565 InstrList &
List = TransposeEnds[i];
5580 for (
unsigned j = 0, e = VFs.
size(); j < e; ++j) {
5588 if (VFs[j].isScalar()) {
5589 for (
auto *Inst : OpenIntervals) {
5598 for (
auto *Inst : OpenIntervals) {
5611 RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
5617 auto &Entry = MaxUsages[j][pair.first];
5618 Entry = std::max(Entry, pair.second);
5623 << OpenIntervals.
size() <<
'\n');
5629 for (
unsigned i = 0, e = VFs.
size(); i < e; ++i) {
5635 for (
auto *Inst : LoopInvariants) {
5638 bool IsScalar =
all_of(Inst->users(), [&](
User *U) {
5639 auto *I = cast<Instruction>(U);
5640 return TheLoop != LI->getLoopFor(I->getParent()) ||
5641 isScalarAfterVectorization(I, VFs[i]);
5647 Invariant[ClassID] += GetRegUsage(Inst->getType(), VF);
5651 dbgs() <<
"LV(REG): VF = " << VFs[i] <<
'\n';
5652 dbgs() <<
"LV(REG): Found max usage: " << MaxUsages[i].
size()
5654 for (
const auto &pair : MaxUsages[i]) {
5655 dbgs() <<
"LV(REG): RegisterClass: "
5659 dbgs() <<
"LV(REG): Found invariant usage: " << Invariant.
size()
5661 for (
const auto &pair : Invariant) {
5662 dbgs() <<
"LV(REG): RegisterClass: "
5676bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(
Instruction *
I,
5687 "Expecting a scalar emulated instruction");
5688 return isa<LoadInst>(
I) ||
5689 (isa<StoreInst>(
I) &&
5706 PredicatedBBsAfterVectorization[VF].
clear();
5723 !useEmulatedMaskMemRefHack(&
I, VF) &&
5724 computePredInstDiscount(&
I, ScalarCosts, VF) >= 0)
5727 PredicatedBBsAfterVectorization[VF].
insert(BB);
5729 if (Pred->getSingleSuccessor() == BB)
5730 PredicatedBBsAfterVectorization[VF].
insert(Pred);
5739 "Instruction marked uniform-after-vectorization will be predicated");
5757 if (!
I->hasOneUse() || PredInst->
getParent() !=
I->getParent() ||
5776 for (
Use &U :
I->operands())
5777 if (
auto *J = dyn_cast<Instruction>(U.get()))
5789 while (!Worklist.
empty()) {
5793 if (ScalarCosts.contains(
I))
5824 for (
Use &U :
I->operands())
5825 if (
auto *J = dyn_cast<Instruction>(
U.get())) {
5827 "Instruction has non-scalar type");
5828 if (canBeScalarized(J))
5830 else if (needsExtract(J, VF)) {
5832 cast<VectorType>(
ToVectorTy(J->getType(), VF)),
5843 Discount += VectorCost - ScalarCost;
5844 ScalarCosts[
I] = ScalarCost;
5860 for (
Instruction &
I : BB->instructionsWithoutDebug()) {
5869 if (
C.first.isValid() &&
5877 BlockCost.first +=
C.first;
5878 BlockCost.second |=
C.second;
5880 <<
" for VF " << VF <<
" For instruction: " <<
I
5894 Cost.first += BlockCost.first;
5895 Cost.second |= BlockCost.second;
5910 const Loop *TheLoop) {
5912 auto *Gep = dyn_cast<GetElementPtrInst>(
Ptr);
5918 auto SE = PSE.
getSE();
5919 unsigned NumOperands = Gep->getNumOperands();
5920 for (
unsigned i = 1; i < NumOperands; ++i) {
5921 Value *Opd = Gep->getOperand(i);
5923 !
Legal->isInductionVariable(Opd))
5932LoopVectorizationCostModel::getMemInstScalarizationCost(
Instruction *
I,
5935 "Scalarization cost of instruction implies vectorization.");
5982 if (useEmulatedMaskMemRefHack(
I, VF))
5992LoopVectorizationCostModel::getConsecutiveMemOpCost(
Instruction *
I,
5995 auto *VectorTy = cast<VectorType>(
ToVectorTy(ValTy, VF));
6001 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6002 "Stride should be 1 or -1 for consecutive memory access");
6014 bool Reverse = ConsecutiveStride < 0;
6022LoopVectorizationCostModel::getUniformMemOpCost(
Instruction *
I,
6027 auto *VectorTy = cast<VectorType>(
ToVectorTy(ValTy, VF));
6031 if (isa<LoadInst>(
I)) {
6043 (isLoopInvariantStoreValue
6050LoopVectorizationCostModel::getGatherScatterCost(
Instruction *
I,
6053 auto *VectorTy = cast<VectorType>(
ToVectorTy(ValTy, VF));
6064LoopVectorizationCostModel::getInterleaveGroupCost(
Instruction *
I,
6067 auto *VectorTy = cast<VectorType>(
ToVectorTy(ValTy, VF));
6072 assert(Group &&
"Fail to get an interleaved access group.");
6074 unsigned InterleaveFactor = Group->getFactor();
6079 for (
unsigned IF = 0;
IF < InterleaveFactor;
IF++)
6080 if (Group->getMember(IF))
6084 bool UseMaskForGaps =
6086 (isa<StoreInst>(
I) && (Group->getNumMembers() < Group->getFactor()));
6088 I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
6091 if (Group->isReverse()) {
6094 "Reverse masked interleaved access not supported.");
6095 Cost += Group->getNumMembers() *
6102std::optional<InstructionCost>
6103LoopVectorizationCostModel::getReductionPatternCost(
6108 if (InLoopReductions.
empty() || VF.
isScalar() || !isa<VectorType>(Ty))
6109 return std::nullopt;
6110 auto *VectorTy = cast<VectorType>(Ty);
6127 return std::nullopt;
6138 if (!InLoopReductionImmediateChains.
count(RetI))
6139 return std::nullopt;
6143 Instruction *LastChain = InLoopReductionImmediateChains.
at(RetI);
6145 while (!isa<PHINode>(ReductionPhi))
6146 ReductionPhi = InLoopReductionImmediateChains.
at(ReductionPhi);
6175 if (RedOp && RdxDesc.
getOpcode() == Instruction::Add &&
6188 bool IsUnsigned = isa<ZExtInst>(Op0);
6205 RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
6206 return I == RetI ? RedCost : 0;
6210 bool IsUnsigned = isa<ZExtInst>(RedOp);
6219 if (RedCost.
isValid() && RedCost < BaseCost + ExtCost)
6220 return I == RetI ? RedCost : 0;
6221 }
else if (RedOp && RdxDesc.
getOpcode() == Instruction::Add &&
6226 bool IsUnsigned = isa<ZExtInst>(Op0);
6249 if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
6250 Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
6258 (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
6259 return I == RetI ? RedCost : 0;
6268 if (RedCost.
isValid() && RedCost < MulCost + BaseCost)
6269 return I == RetI ? RedCost : 0;
6273 return I == RetI ? std::optional<InstructionCost>(BaseCost) :
std::nullopt;
6277LoopVectorizationCostModel::getMemoryInstructionCost(
Instruction *
I,
6295LoopVectorizationCostModel::getInstructionCost(
Instruction *
I,
6306 auto ForcedScalar = ForcedScalars.
find(VF);
6307 if (VF.
isVector() && ForcedScalar != ForcedScalars.
end()) {
6308 auto InstSet = ForcedScalar->second;
6309 if (InstSet.count(
I))
6319 bool TypeNotScalarized =
false;
6350 if (!
RetTy->isVoidTy() &&
6372 for (
auto *V : filterExtractingOperands(Ops, VF))
6375 filterExtractingOperands(Ops, VF), Tys,
CostKind);
6397 auto isLegalToScalarize = [&]() {
6411 if (isa<LoadInst>(
I))
6416 auto &SI = cast<StoreInst>(
I);
6434 if (GatherScatterCost < ScalarizationCost)
6446 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6447 "Expected consecutive stride.");
6456 unsigned NumAccesses = 1;
6459 assert(Group &&
"Fail to get an interleaved access group.");
6465 NumAccesses = Group->getNumMembers();
6467 InterleaveCost = getInterleaveGroupCost(&
I, VF);
6472 ? getGatherScatterCost(&
I, VF) * NumAccesses
6476 getMemInstScalarizationCost(&
I, VF) * NumAccesses;
6482 if (InterleaveCost <= GatherScatterCost &&
6483 InterleaveCost < ScalarizationCost) {
6485 Cost = InterleaveCost;
6486 }
else if (GatherScatterCost < ScalarizationCost) {
6488 Cost = GatherScatterCost;
6491 Cost = ScalarizationCost;
6525 while (!Worklist.
empty()) {
6527 for (
auto &
Op :
I->operands())
6528 if (
auto *InstOp = dyn_cast<Instruction>(
Op))
6529 if ((InstOp->getParent() ==
I->getParent()) && !isa<PHINode>(InstOp) &&
6530 AddrDefs.
insert(InstOp).second)
6534 for (
auto *
I : AddrDefs) {
6535 if (isa<LoadInst>(
I)) {
6549 for (
unsigned I = 0;
I < Group->getFactor(); ++
I) {
6566 "Trying to set a vectorization decision for a scalar VF");
6585 for (
auto &ArgOp : CI->
args())
6590 for (
Type *ScalarTy : ScalarTys)
6596 if (
auto RedCost = getReductionPatternCost(CI, VF,
RetTy,
CostKind)) {
6599 std::nullopt, *RedCost);
6613 getScalarizationOverhead(CI, VF,
CostKind);
6619 bool UsesMask =
false;
6625 if (
Info.Shape.VF != VF)
6629 if (MaskRequired && !
Info.isMasked())
6633 bool ParamsOk =
true;
6635 switch (Param.ParamKind) {
6654 dyn_cast<SCEVAddRecExpr>(SE->
getSCEV(ScalarParam));
6656 if (!SAR || SAR->getLoop() !=
TheLoop) {
6662 dyn_cast<SCEVConstant>(SAR->getStepRecurrence(*SE));
6690 if (VecFunc && UsesMask && !MaskRequired)
6710 if (VectorCost <=
Cost) {
6715 if (IntrinsicCost <=
Cost) {
6716 Cost = IntrinsicCost;
6735 auto hasSingleCopyAfterVectorization = [
this](
Instruction *
I,
6740 auto Scalarized = InstsToScalarize.
find(VF);
6741 assert(Scalarized != InstsToScalarize.
end() &&
6742 "VF not yet analyzed for scalarization profitability");
6743 return !Scalarized->second.count(
I) &&
6745 auto *UI = cast<Instruction>(U);
6746 return !Scalarized->second.count(UI);
6749 (void) hasSingleCopyAfterVectorization;
6757 assert(
I->getOpcode() == Instruction::GetElementPtr ||
6758 I->getOpcode() == Instruction::PHI ||
6759 (
I->getOpcode() == Instruction::BitCast &&
6760 I->getType()->isPointerTy()) ||
6761 hasSingleCopyAfterVectorization(
I, VF));
6767 switch (
I->getOpcode()) {
6768 case Instruction::GetElementPtr:
6774 case Instruction::Br: {
6781 bool ScalarPredicatedBB =
false;
6784 (PredicatedBBsAfterVectorization[VF].count(BI->
getSuccessor(0)) ||
6785 PredicatedBBsAfterVectorization[VF].count(BI->
getSuccessor(1))) &&
6787 ScalarPredicatedBB =
true;
6789 if (ScalarPredicatedBB) {
6811 case Instruction::PHI: {
6812 auto *
Phi = cast<PHINode>(
I);
6819 cast<VectorType>(VectorTy), Mask,
CostKind,
6827 return (
Phi->getNumIncomingValues() - 1) *
6835 case Instruction::UDiv:
6836 case Instruction::SDiv:
6837 case Instruction::URem:
6838 case Instruction::SRem:
6842 ScalarCost : SafeDivisorCost;
6846 case Instruction::Add:
6847 case Instruction::FAdd:
6848 case Instruction::Sub:
6849 case Instruction::FSub:
6850 case Instruction::Mul:
6851 case Instruction::FMul:
6852 case Instruction::FDiv:
6853 case Instruction::FRem:
6854 case Instruction::Shl:
6855 case Instruction::LShr:
6856 case Instruction::AShr:
6857 case Instruction::And:
6858 case Instruction::Or:
6859 case Instruction::Xor: {
6863 if (
I->getOpcode() == Instruction::Mul &&
6869 if (
auto RedCost = getReductionPatternCost(
I, VF, VectorTy,
CostKind))
6874 Value *Op2 =
I->getOperand(1);
6883 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6886 case Instruction::FNeg: {
6889 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6890 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6891 I->getOperand(0),
I);
6893 case Instruction::Select: {
6898 const Value *Op0, *Op1;
6915 Type *CondTy =
SI->getCondition()->getType();
6920 if (
auto *Cmp = dyn_cast<CmpInst>(
SI->getCondition()))
6921 Pred =
Cmp->getPredicate();
6925 case Instruction::ICmp:
6926 case Instruction::FCmp: {
6927 Type *ValTy =
I->getOperand(0)->getType();
6928 Instruction *Op0AsInstruction = dyn_cast<Instruction>(
I->getOperand(0));
6933 cast<CmpInst>(
I)->getPredicate(),
CostKind,
6936 case Instruction::Store:
6937 case Instruction::Load: {
6942 "CM decision should be taken at this point");
6949 return getMemoryInstructionCost(
I, VF);
6951 case Instruction::BitCast:
6952 if (
I->getType()->isPointerTy())
6955 case Instruction::ZExt:
6956 case Instruction::SExt:
6957 case Instruction::FPToUI:
6958 case Instruction::FPToSI:
6959 case Instruction::FPExt:
6960 case Instruction::PtrToInt:
6961 case Instruction::IntToPtr:
6962 case Instruction::SIToFP:
6963 case Instruction::UIToFP:
6964 case Instruction::Trunc:
6965 case Instruction::FPTrunc: {
6968 assert((isa<LoadInst>(
I) || isa<StoreInst>(
I)) &&
6969 "Expected a load or a store!");
6995 unsigned Opcode =
I->getOpcode();
6998 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7000 if (
StoreInst *Store = dyn_cast<StoreInst>(*
I->user_begin()))
7001 CCH = ComputeCCH(Store);
7004 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7005 Opcode == Instruction::FPExt) {
7006 if (
LoadInst *Load = dyn_cast<LoadInst>(
I->getOperand(0)))
7007 CCH = ComputeCCH(Load);
7014 auto *Trunc = cast<TruncInst>(
I);
7016 Trunc->getSrcTy(), CCH,
CostKind, Trunc);
7020 if (
auto RedCost = getReductionPatternCost(
I, VF, VectorTy,
CostKind))
7023 Type *SrcScalarTy =
I->getOperand(0)->getType();
7024 Instruction *Op0AsInstruction = dyn_cast<Instruction>(
I->getOperand(0));
7033 case Instruction::Call:
7035 case Instruction::ExtractValue:
7037 case Instruction::Alloca:
7059 if ((SI = dyn_cast<StoreInst>(&
I)) &&
7068 if (Group->getInsertPos() == &
I)
7071 DeadInterleavePointerOps.
insert(PointerOp);
7077 for (
unsigned I = 0;
I != DeadInterleavePointerOps.
size(); ++
I) {
7078 auto *
Op = dyn_cast<Instruction>(DeadInterleavePointerOps[
I]);
7080 Instruction *UI = cast<Instruction>(U);
7081 return !VecValuesToIgnore.contains(U) &&
7082 (!isAccessInterleaved(UI) ||
7083 getInterleavedAccessGroup(UI)->getInsertPos() == UI);
7087 DeadInterleavePointerOps.
insert(
Op->op_begin(),
Op->op_end());
7128 bool InLoop = !ReductionOperations.
empty();
7131 InLoopReductions.
insert(Phi);
7134 for (
auto *
I : ReductionOperations) {
7135 InLoopReductionImmediateChains[
I] = LastChain;
7139 LLVM_DEBUG(
dbgs() <<
"LV: Using " << (InLoop ?
"inloop" :
"out of loop")
7140 <<
" reduction for phi: " << *Phi <<
"\n");
7148 return tryInsertInstruction(
7161 unsigned WidestType;
7170 unsigned N =
RegSize.getKnownMinValue() / WidestType;
7191 <<
"overriding computed VF.\n");
7196 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing. Scalable VF requested, but "
7197 <<
"not supported by the target.\n");
7199 "Scalable vectorization requested but not supported by the target",
7200 "the scalable user-specified vectorization width for outer-loop "
7201 "vectorization cannot be used because the target does not support "
7202 "scalable vectors.",
7203 "ScalableVFUnfeasible", ORE, OrigLoop);
7208 "VF needs to be a power of two");
7210 <<
"VF " << VF <<
" to build VPlans.\n");
7217 return {VF, 0 , 0 };
7221 dbgs() <<
"LV: Not vectorizing. Inner loops aren't supported in the "
7222 "VPlan-native path.\n");
7226std::optional<VectorizationFactor>
7234 return std::nullopt;
7241 <<
"LV: Invalidate all interleaved groups due to fold-tail by masking "
7242 "which requires masked-interleaved support.\n");
7253 if (!UserVF.
isZero() && UserVFIsLegal) {
7255 "VF needs to be a power of two");
7261 buildVPlansWithVPRecipes(UserVF, UserVF);
7263 LLVM_DEBUG(
dbgs() <<
"LV: No VPlan could be built for " << UserVF
7265 return std::nullopt;
7269 return {{UserVF, 0, 0}};
7272 "InvalidCost", ORE, OrigLoop);
7285 for (
const auto &VF : VFCandidates) {
7300 return std::nullopt;
7302 [](std::unique_ptr<VPlan> &
P) {
return P->hasScalarVFOnly(); }))
7311 return std::nullopt;
7318 [VF](
const VPlanPtr &Plan) {
return Plan->hasVF(VF); }) ==
7320 "Best VF has not a single VPlan.");
7322 for (
const VPlanPtr &Plan : VPlans) {
7323 if (Plan->hasVF(VF))
7333 bool IsUnrollMetadata =
false;
7334 MDNode *LoopID = L->getLoopID();
7337 for (
unsigned i = 1, ie = LoopID->
getNumOperands(); i < ie; ++i) {
7338 auto *MD = dyn_cast<MDNode>(LoopID->
getOperand(i));
7340 const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7342 S && S->getString().starts_with(
"llvm.loop.unroll.disable");
7348 if (!IsUnrollMetadata) {
7350 LLVMContext &Context = L->getHeader()->getContext();
7353 MDString::get(Context,
"llvm.loop.unroll.runtime.disable"));
7359 L->setLoopID(NewLoopID);
7369 bool VectorizingEpilogue) {
7374 auto *PhiR = cast<VPReductionPHIRecipe>(RedResult->
getOperand(0));
7380 dyn_cast<PHINode>(PhiR->getStartValue()->getUnderlyingValue());
7383 auto *Cmp = cast<ICmpInst>(PhiR->getStartValue()->getUnderlyingValue());
7386 ResumePhi = cast<PHINode>(Cmp->getOperand(0));
7388 assert((!VectorizingEpilogue || ResumePhi) &&
7389 "when vectorizing the epilogue loop, we need a resume phi from main "
7406 BCBlockPhi->addIncoming(FinalValue,
Incoming);
7408 BCBlockPhi->addIncoming(ResumePhi->getIncomingValueForBlock(
Incoming),
7414 auto *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
7418 int IncomingEdgeBlockIdx =
7420 assert(IncomingEdgeBlockIdx >= 0 &&
"Invalid block index");
7422 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
7423 OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
7425 OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
7427 ReductionResumeValues[&RdxDesc] = BCBlockPhi;
7430std::pair<DenseMap<const SCEV *, Value *>,
7437 "Trying to execute plan with unsupported VF");
7439 "Trying to execute plan with unsupported UF");
7441 (IsEpilogueVectorization || !ExpandedSCEVs) &&
7442 "expanded SCEVs to reuse can only be used during epilogue vectorization");
7443 (void)IsEpilogueVectorization;
7448 <<
", UF=" << BestUF <<
'\n');
7449 BestVPlan.
setName(
"Final VPlan");
7466 assert(IsEpilogueVectorization &&
"should only re-use the existing trip "
7467 "count during epilogue vectorization");
7471 Value *CanonicalIVStartValue;
7472 std::tie(State.
CFG.
PrevBB, CanonicalIVStartValue) =
7479 std::unique_ptr<LoopVersioning> LVer =
nullptr;
7487 LVer = std::make_unique<LoopVersioning>(
7490 State.
LVer = &*LVer;
7507 CanonicalIVStartValue, State);
7517 dyn_cast<VPInstruction>(&R), ReductionResumeValues, State, OrigLoop,
7526 std::optional<MDNode *> VectorizedLoopID =
7533 if (VectorizedLoopID)
7534 L->setLoopID(*VectorizedLoopID);
7558#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
7560 for (
const auto &Plan : VPlans)
7574std::pair<BasicBlock *, Value *>
7576 const SCEV2ValueTy &ExpandedSCEVs) {
7616 dbgs() <<
"Create Skeleton for epilogue vectorized loop (first pass)\n"
7626 dbgs() <<
"intermediate fn:\n"
7634 assert(Bypass &&
"Expected valid bypass basic block.");
7655 TCCheckBlock->
setName(
"vector.main.loop.iter.check");
7659 DT,
LI,
nullptr,
"vector.ph");
7664 "TC check is expected to dominate Bypass");
7688 return TCCheckBlock;
7697std::pair<BasicBlock *, Value *>
7699 const SCEV2ValueTy &ExpandedSCEVs) {
7707 nullptr,
"vec.epilog.iter.check",
true);
7709 VecEpilogueIterationCountCheck);
7714 "expected this to be saved from the previous pass.");
7732 VecEpilogueIterationCountCheck,
7756 for (
PHINode &Phi : VecEpilogueIterationCountCheck->
phis())
7759 for (
PHINode *Phi : PhisInBlock) {
7761 Phi->replaceIncomingBlockWith(
7763 VecEpilogueIterationCountCheck);
7770 return EPI.EpilogueIterationCountCheck == IncB;
7782 Type *IdxTy =
Legal->getWidestInductionType();
7786 EPResumeVal->
addIncoming(ConstantInt::get(IdxTy, 0),
7797 {VecEpilogueIterationCountCheck,
7808 "Expected trip count to have been safed in the first pass.");
7812 "saved trip count does not dominate insertion point.");
7823 Value *CheckMinIters =
7827 "min.epilog.iters.check");
7833 unsigned EpilogueLoopStep =
7839 unsigned EstimatedSkipCount = std::min(MainLoopStep, EpilogueLoopStep);
7840 const uint32_t Weights[] = {EstimatedSkipCount,
7841 MainLoopStep - EstimatedSkipCount};
7852 dbgs() <<
"Create Skeleton for epilogue vectorized loop (second pass)\n"
7866 assert(!
Range.isEmpty() &&
"Trying to test an empty VF range.");
7867 bool PredicateAtRangeStart = Predicate(
Range.Start);
7870 if (Predicate(TmpVF) != PredicateAtRangeStart) {
7875 return PredicateAtRangeStart;
7885 auto MaxVFTimes2 = MaxVF * 2;
7887 VFRange SubRange = {VF, MaxVFTimes2};
7888 VPlans.push_back(buildVPlan(SubRange));
7896 if (
auto *
I = dyn_cast<Instruction>(
Op)) {
7897 if (
auto *R = Ingredient2Recipe.lookup(
I))
7898 return R->getVPSingleValue();
7900 return Plan.getOrAddLiveIn(
Op);
7909 std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
7911 if (ECEntryIt != EdgeMaskCache.
end())
7912 return ECEntryIt->second;
7917 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
7918 assert(BI &&
"Unexpected terminator found");
7921 return EdgeMaskCache[Edge] = SrcMask;
7927 return EdgeMaskCache[Edge] = SrcMask;
7930 assert(EdgeMask &&
"No Edge Mask found for condition");
7942 return EdgeMaskCache[Edge] = EdgeMask;
7949 std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
7951 assert(ECEntryIt != EdgeMaskCache.
end() &&
7952 "looking up mask for edge which has not been created");
7953 return ECEntryIt->second;
7961 BlockMaskCache[Header] =
nullptr;
7973 HeaderVPBB->
insert(
IV, NewInsertionPoint);
7980 BlockMaskCache[Header] = BlockMask;
7986 assert(BCEntryIt != BlockMaskCache.
end() &&
7987 "Trying to access mask for block without one.");
7988 return BCEntryIt->second;
7992 assert(OrigLoop->
contains(BB) &&
"Block is not a part of a loop");
7993 assert(BlockMaskCache.
count(BB) == 0 &&
"Mask for block already computed");
7995 "Loop header must have cached block mask");
8004 BlockMaskCache[BB] = EdgeMask;
8009 BlockMask = EdgeMask;
8013 BlockMask = Builder.
createOr(BlockMask, EdgeMask, {});
8016 BlockMaskCache[BB] = BlockMask;
8022 assert((isa<LoadInst>(
I) || isa<StoreInst>(
I)) &&
8023 "Must be called with either a load or store");
8029 "CM decision should be taken at this point.");
8055 auto *
GEP = dyn_cast<GetElementPtrInst>(
8056 Ptr->getUnderlyingValue()->stripPointerCasts());
8063 if (
LoadInst *Load = dyn_cast<LoadInst>(
I))
8081 "step must be loop invariant");
8085 if (
auto *TruncI = dyn_cast<TruncInst>(PhiOrTrunc)) {
8088 assert(isa<PHINode>(PhiOrTrunc) &&
"must be a phi node here");
8099 *PSE.
getSE(), *OrigLoop);
8125 auto isOptimizableIVTruncate =
8133 isOptimizableIVTruncate(
I),
Range)) {
8135 auto *
Phi = cast<PHINode>(
I->getOperand(0));
8146 unsigned NumIncoming =
Phi->getNumIncomingValues();
8157 for (
unsigned In = 0;
In < NumIncoming;
In++) {
8162 assert(In == 0 &&
"Both null and non-null edge masks found");
8164 "Distinct incoming values with one having a full mask");
8187 if (
ID && (
ID == Intrinsic::assume ||
ID == Intrinsic::lifetime_end ||
8188 ID == Intrinsic::lifetime_start ||
ID == Intrinsic::sideeffect ||
8189 ID == Intrinsic::pseudoprobe ||
8190 ID == Intrinsic::experimental_noalias_scope_decl))
8197 bool ShouldUseVectorIntrinsic =
8204 if (ShouldUseVectorIntrinsic)
8209 std::optional<unsigned> MaskPos;
8231 Variant = Decision.Variant;
8232 MaskPos = Decision.MaskPos;
8239 if (ShouldUseVectorCall) {
8240 if (MaskPos.has_value()) {
8255 Ops.insert(Ops.
begin() + *MaskPos, Mask);
8267 assert(!isa<BranchInst>(
I) && !isa<PHINode>(
I) && !isa<LoadInst>(
I) &&
8268 !isa<StoreInst>(
I) &&
"Instruction should have been handled earlier");
8283 switch (
I->getOpcode()) {
8286 case Instruction::SDiv:
8287 case Instruction::UDiv:
8288 case Instruction::SRem:
8289 case Instruction::URem: {
8297 auto *SafeRHS = Builder.
createSelect(Mask, Ops[1], One,
I->getDebugLoc());
8303 case Instruction::Add:
8304 case Instruction::And:
8305 case Instruction::AShr:
8306 case Instruction::FAdd:
8307 case Instruction::FCmp:
8308 case Instruction::FDiv:
8309 case Instruction::FMul:
8310 case Instruction::FNeg:
8311 case Instruction::FRem:
8312 case Instruction::FSub:
8313 case Instruction::ICmp:
8314 case Instruction::LShr:
8315 case Instruction::Mul:
8316 case Instruction::Or:
8317 case Instruction::Select:
8318 case Instruction::Shl:
8319 case Instruction::Sub:
8320 case Instruction::Xor:
8321 case Instruction::Freeze:
8329 auto *PN = cast<PHINode>(R->getUnderlyingValue());
8331 getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8348 if (!IsUniform &&
Range.Start.isScalable() && isa<IntrinsicInst>(
I)) {
8350 case Intrinsic::assume:
8351 case Intrinsic::lifetime_start:
8352 case Intrinsic::lifetime_end:
8374 VPValue *BlockInMask =
nullptr;
8375 if (!IsPredicated) {
8379 LLVM_DEBUG(
dbgs() <<
"LV: Scalarizing and predicating:" << *
I <<
"\n");
8388 IsUniform, BlockInMask);
8399 if (
auto Phi = dyn_cast<PHINode>(Instr)) {
8400 if (Phi->getParent() != OrigLoop->
getHeader())
8403 if ((Recipe = tryToOptimizeInductionPHI(Phi,
Operands,
Range)))
8409 "can only widen reductions and fixed-order recurrences here");
8427 PhisToFix.push_back(PhiRecipe);
8431 if (isa<TruncInst>(Instr) && (Recipe = tryToOptimizeInductionTruncate(
8440 if (
auto *CI = dyn_cast<CallInst>(Instr))
8443 if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8446 if (!shouldWiden(Instr,
Range))
8449 if (
auto GEP = dyn_cast<GetElementPtrInst>(Instr))
8453 if (
auto *SI = dyn_cast<SelectInst>(Instr)) {
8458 if (
auto *CI = dyn_cast<CastInst>(Instr)) {
8463 return tryToWiden(Instr,
Operands, VPBB);
8466void LoopVectorizationPlanner::buildVPlansWithVPRecipes(
ElementCount MinVF,
8470 auto MaxVFTimes2 = MaxVF * 2;
8472 VFRange SubRange = {VF, MaxVFTimes2};
8473 if (
auto Plan = tryToBuildVPlanWithVPRecipes(SubRange)) {
8485 VPlans.push_back(std::move(Plan));
8495 Value *StartIdx = ConstantInt::get(IdxTy, 0);
8502 Header->insert(CanonicalIVPHI, Header->begin());
8507 Instruction::Add, {CanonicalIVPHI, &Plan.
getVFxUF()}, {HasNUW,
false},
DL,
8509 CanonicalIVPHI->
addOperand(CanonicalIVIncrement);
8528 Value *IncomingValue =
8529 ExitPhi.getIncomingValueForBlock(ExitingBB);
8536LoopVectorizationPlanner::tryToBuildVPlanWithVPRecipes(
VFRange &
Range) {
8556 Plan->getVectorLoopRegion()->setEntry(HeaderVPBB);
8557 Plan->getVectorLoopRegion()->setExiting(LatchVPBB);
8563 bool IVUpdateMayOverflow =
false;
8574 VPRecipeBuilder RecipeBuilder(*Plan, OrigLoop, TLI, Legal, CM, PSE, Builder);
8594 "Unsupported interleave factor for scalable vectors");
8599 InterleaveGroups.
insert(IG);
8616 bool NeedsBlends = BB != HeaderBB && !BB->phis().empty();
8617 return Legal->blockNeedsPredication(BB) || NeedsBlends;
8622 if (VPBB != HeaderVPBB)
8626 if (VPBB == HeaderVPBB)
8627 RecipeBuilder.createHeaderMask();
8628 else if (NeedsMasks)
8629 RecipeBuilder.createBlockInMask(BB);
8636 auto *
Phi = dyn_cast<PHINode>(Instr);
8637 if (Phi &&
Phi->getParent() == HeaderBB) {
8638 Operands.push_back(Plan->getOrAddLiveIn(
8641 auto OpRange = RecipeBuilder.mapToVPValues(
Instr->operands());
8642 Operands = {OpRange.begin(), OpRange.end()};
8648 if ((SI = dyn_cast<StoreInst>(&
I)) &&
8653 RecipeBuilder.tryToCreateWidenRecipe(Instr,
Operands,
Range, VPBB);
8655 Recipe = RecipeBuilder.handleReplication(Instr,
Range);
8657 RecipeBuilder.setRecipe(Instr, Recipe);
8658 if (isa<VPHeaderPHIRecipe>(Recipe)) {
8669 "unexpected recipe needs moving");
8689 assert(isa<VPRegionBlock>(Plan->getVectorLoopRegion()) &&
8690 !Plan->getVectorLoopRegion()->getEntryBasicBlock()->empty() &&
8691 "entry block must be set to a VPRegionBlock having a non-empty entry "
8693 RecipeBuilder.fixHeaderPhis();
8701 adjustRecipesForReductions(LatchVPBB, Plan, RecipeBuilder,
Range.Start);
8706 for (
const auto *IG : InterleaveGroups) {
8708 cast<VPWidenMemoryRecipe>(RecipeBuilder.getRecipe(IG->getInsertPos()));
8710 for (
unsigned i = 0; i < IG->getFactor(); ++i)
8711 if (
auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
8712 auto *StoreR = cast<VPWidenStoreRecipe>(RecipeBuilder.getRecipe(SI));
8713 StoredValues.
push_back(StoreR->getStoredValue());
8716 bool NeedsMaskForGaps =
8719 Recipe->getMask(), NeedsMaskForGaps);
8720 VPIG->insertBefore(Recipe);
8722 for (
unsigned i = 0; i < IG->getFactor(); ++i)
8724 VPRecipeBase *MemberR = RecipeBuilder.getRecipe(Member);
8725 if (!
Member->getType()->isVoidTy()) {
8736 Plan->setName(
"Initial VPlan");
8741 auto *StrideV = cast<SCEVUnknown>(Stride)->getValue();
8742 auto *ScevStride = dyn_cast<SCEVConstant>(PSE.
getSCEV(StrideV));
8747 auto *CI = Plan->getOrAddLiveIn(
8748 ConstantInt::get(Stride->getType(), ScevStride->getAPInt()));
8749 if (
VPValue *StrideVPV = Plan->getLiveIn(StrideV))
8755 if (!isa<SExtInst, ZExtInst>(U))
8757 VPValue *StrideVPV = Plan->getLiveIn(U);
8760 unsigned BW =
U->getType()->getScalarSizeInBits();
8761 APInt C = isa<SExtInst>(U) ? ScevStride->getAPInt().sext(BW)
8762 : ScevStride->getAPInt().zext(BW);
8763 VPValue *CI = Plan->getOrAddLiveIn(ConstantInt::get(
U->getType(),
C));
8781 bool WithoutRuntimeCheck =
8784 WithoutRuntimeCheck);
8804 HCFGBuilder.buildHierarchicalCFG();
8812 *PSE.
getSE(), *TLI);
8817 Plan->getVectorLoopRegion()->getExitingBasicBlock()->getTerminator();
8818 Term->eraseFromParent();
8842void LoopVectorizationPlanner::adjustRecipesForReductions(
8845 VPRegionBlock *VectorLoopRegion = Plan->getVectorLoopRegion();
8852 if (
auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R))
8855 bool HasIntermediateStore =
false;
8860 auto *IS2 =
R2->getRecurrenceDescriptor().IntermediateStore;
8861 HasIntermediateStore |= IS1 || IS2;
8882 if (HasIntermediateStore && ReductionPHIList.
size() > 1)
8884 R->moveBefore(*Header, Header->getFirstNonPhi());
8887 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
8888 if (!PhiR || !PhiR->isInLoop() || (MinVF.
isScalar() && !PhiR->isOrdered()))
8894 "AnyOf reductions are not allowed for in-loop reductions");
8899 for (
unsigned I = 0;
I != Worklist.
size(); ++
I) {
8902 auto *UserRecipe = dyn_cast<VPSingleDefRecipe>(U);
8904 assert(isa<VPLiveOut>(U) &&
8905 "U must either be a VPSingleDef or VPLiveOut");
8908 Worklist.
insert(UserRecipe);
8921 Instruction *CurrentLinkI = CurrentLink->getUnderlyingInstr();
8924 unsigned IndexOfFirstOperand;
8932 "Expected instruction to be a call to the llvm.fmuladd intrinsic");
8933 assert(((MinVF.
isScalar() && isa<VPReplicateRecipe>(CurrentLink)) ||
8934 isa<VPWidenCallRecipe>(CurrentLink)) &&
8935 CurrentLink->getOperand(2) == PreviousLink &&
8936 "expected a call where the previous link is the added operand");
8944 {CurrentLink->getOperand(0), CurrentLink->getOperand(1)},
8946 LinkVPBB->
insert(FMulRecipe, CurrentLink->getIterator());
8949 auto *Blend = dyn_cast<VPBlendRecipe>(CurrentLink);
8950 if (PhiR->isInLoop() && Blend) {
8951 assert(Blend->getNumIncomingValues() == 2 &&
8952 "Blend must have 2 incoming values");
8953 if (Blend->getIncomingValue(0) == PhiR)
8954 Blend->replaceAllUsesWith(Blend->getIncomingValue(1));
8956 assert(Blend->getIncomingValue(1) == PhiR &&
8957 "PhiR must be an operand of the blend");
8958 Blend->replaceAllUsesWith(Blend->getIncomingValue(0));
8964 if (isa<VPWidenRecipe>(CurrentLink)) {
8965 assert(isa<CmpInst>(CurrentLinkI) &&
8966 "need to have the compare of the select");
8969 assert(isa<VPWidenSelectRecipe>(CurrentLink) &&
8970 "must be a select recipe");
8971 IndexOfFirstOperand = 1;
8974 "Expected to replace a VPWidenSC");
8975 IndexOfFirstOperand = 0;
8980 CurrentLink->getOperand(IndexOfFirstOperand) == PreviousLink
8981 ? IndexOfFirstOperand + 1
8982 : IndexOfFirstOperand;
8983 VecOp = CurrentLink->getOperand(VecOpId);
8984 assert(VecOp != PreviousLink &&
8985 CurrentLink->getOperand(CurrentLink->getNumOperands() - 1 -
8986 (VecOpId - IndexOfFirstOperand)) ==
8988 "PreviousLink must be the operand other than VecOp");
9004 CurrentLink->replaceAllUsesWith(RedRecipe);
9005 PreviousLink = RedRecipe;
9010 Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
9023 return isa<VPWidenSelectRecipe>(U) ||
9024 (isa<VPReplicateRecipe>(U) &&
9025 cast<VPReplicateRecipe>(U)->getUnderlyingInstr()->getOpcode() ==
9026 Instruction::Select);
9032 for (
unsigned I = 0;
I != CmpR->getNumOperands(); ++
I)
9033 if (CmpR->getOperand(
I) == PhiR)
9041 if (
Select->getOperand(1) == PhiR)
9044 Select->getVPSingleValue()->replaceAllUsesWith(
Or);
9058 assert(OrigExitingVPV->getDefiningRecipe()->getParent() != LatchVPBB &&
9059 "reduction recipe must be defined before latch");
9061 std::optional<FastMathFlags> FMFs =
9068 return isa<VPInstruction>(&U) &&
9069 cast<VPInstruction>(&U)->getOpcode() ==
9086 assert(!PhiR->
isInLoop() &&
"Unexpected truncated inloop reduction!");
9095 Trunc->
insertAfter(NewExitingVPV->getDefiningRecipe());
9096 Extnd->insertAfter(Trunc);
9098 PhiR->
setOperand(1, Extnd->getVPSingleValue());
9099 NewExitingVPV = Extnd;
9118 ->appendRecipe(FinalReductionResult);
9120 FinalReductionResult,
9127#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9130 O << Indent <<
"INTERLEAVE-GROUP with factor " << IG->getFactor() <<
" at ";
9131 IG->getInsertPos()->printAsOperand(O,
false);
9141 for (
unsigned i = 0; i < IG->getFactor(); ++i) {
9142 if (!IG->getMember(i))
9145 O <<
"\n" << Indent <<
" store ";
9147 O <<
" to index " << i;
9149 O <<
"\n" << Indent <<
" ";
9151 O <<
" = load from index " << i;
9160 "Not a pointer induction according to InductionDescriptor!");
9162 "Unexpected type.");
9164 "Recipe should have been replaced");
9167 PHINode *CanonicalIV = cast<PHINode>(State.
get(IVR, 0,
true));
9172 Type *ScStValueType = ScalarStartValue->
getType();
9177 NewPointerPhi->
addIncoming(ScalarStartValue, VectorPH);
9184 Value *NumUnrolledElems =
9195 NewPointerPhi->
addIncoming(InductionGEP, VectorPH);
9200 for (
unsigned Part = 0; Part < State.
UF; ++Part) {
9202 Value *StartOffsetScalar =
9204 Value *StartOffset =
9211 "scalar step must be the same across all parts");
9218 State.
set(
this,
GEP, Part);
9223 assert(!State.
Instance &&
"VPDerivedIVRecipe being replicated.");
9234 Kind, cast_if_present<BinaryOperator>(FPBinOp));
9235 DerivedIV->
setName(
"offset.idx");
9236 assert(DerivedIV != CanonicalIV &&
"IV didn't need transforming?");
9256 if (State.
Instance->Lane.isFirstLane()) {
9270 if ((isa<LoadInst>(UI) || isa<StoreInst>(UI)) &&
9272 return Op->isDefinedOutsideVectorRegions();
9276 for (
unsigned Part = 1; Part < State.
UF; ++Part)
9285 for (
unsigned Part = 0; Part < State.
UF; ++Part)
9292 if (isa<StoreInst>(UI) &&
9303 for (
unsigned Part = 0; Part < State.
UF; ++Part)
9304 for (
unsigned Lane = 0; Lane < EndLane; ++Lane)
9316 auto &Builder = State.
Builder;
9318 for (
unsigned Part = 0; Part < State.
UF; ++Part) {
9320 Value *Mask =
nullptr;
9321 if (
auto *VPMask =
getMask()) {
9324 Mask = State.
get(VPMask, Part);
9326 Mask = Builder.CreateVectorReverse(Mask,
"reverse");
9331 NewLI = Builder.CreateMaskedGather(DataTy,
Addr, Alignment, Mask,
nullptr,
9332 "wide.masked.gather");
9334 NewLI = Builder.CreateMaskedLoad(DataTy,
Addr, Alignment, Mask,
9336 "wide.masked.load");
9338 NewLI = Builder.CreateAlignedLoad(DataTy,
Addr, Alignment,
"wide.load");
9343 NewLI = Builder.CreateVectorReverse(NewLI,
"reverse");
9344 State.
set(
this, NewLI, Part);
9353 Value *AllTrueMask =
9355 return Builder.
CreateIntrinsic(ValTy, Intrinsic::experimental_vp_reverse,
9356 {Operand, AllTrueMask, EVL},
nullptr,
Name);
9360 assert(State.
UF == 1 &&
"Expected only UF == 1 when vectorizing with "
9361 "explicit vector length.");
9369 auto &Builder = State.
Builder;
9374 Value *Mask =
nullptr;
9376 Mask = State.
get(VPMask, 0);
9380 Mask = Builder.CreateVectorSplat(State.
VF, Builder.getTrue());
9385 Builder.CreateIntrinsic(DataTy, Intrinsic::vp_gather, {
Addr, Mask, EVL},
9386 nullptr,
"wide.masked.gather");
9391 Instruction::Load, DataTy,
Addr,
"vp.op.load"));
9399 State.
set(
this, Res, 0);
9409 auto &Builder = State.
Builder;
9412 for (
unsigned Part = 0; Part < State.
UF; ++Part) {
9414 Value *Mask =
nullptr;
9415 if (
auto *VPMask =
getMask()) {
9418 Mask = State.
get(VPMask, Part);
9420 Mask = Builder.CreateVectorReverse(Mask,
"reverse");
9423 Value *StoredVal = State.
get(StoredVPValue, Part);
9427 StoredVal = Builder.CreateVectorReverse(StoredVal,
"reverse");
9433 NewSI = Builder.CreateMaskedScatter(StoredVal,
Addr, Alignment, Mask);
9435 NewSI = Builder.CreateMaskedStore(StoredVal,
Addr, Alignment, Mask);
9437 NewSI = Builder.CreateAlignedStore(StoredVal,
Addr, Alignment);
9443 assert(State.
UF == 1 &&
"Expected only UF == 1 when vectorizing with "
9444 "explicit vector length.");
9451 auto &Builder = State.
Builder;
9455 Value *StoredVal = State.
get(StoredValue, 0);
9459 Value *Mask =
nullptr;
9461 Mask = State.
get(VPMask, 0);
9465 Mask = Builder.CreateVectorSplat(State.
VF, Builder.getTrue());
9468 if (CreateScatter) {
9470 Intrinsic::vp_scatter,
9471 {StoredVal, Addr, Mask, EVL});
9477 {StoredVal, Addr}));
9546 LLVM_DEBUG(
dbgs() <<
"LV: cannot compute the outer-loop trip count\n");
9550 Function *
F = L->getHeader()->getParent();
9556 LoopVectorizationCostModel CM(
SEL, L, PSE, LI, LVL, *
TTI, TLI, DB, AC, ORE,
F,
9561 LoopVectorizationPlanner LVP(L, LI, DT, TLI, *
TTI, LVL, CM, IAI, PSE, Hints,
9581 bool AddBranchWeights =
9583 GeneratedRTChecks Checks(*PSE.
getSE(), DT, LI,
TTI,
9584 F->getDataLayout(), AddBranchWeights);
9586 VF.
Width, 1, LVL, &CM, BFI, PSI, Checks);
9588 << L->getHeader()->getParent()->getName() <<
"\"\n");
9608 if (
auto *S = dyn_cast<StoreInst>(&Inst)) {
9609 if (S->getValueOperand()->getType()->isFloatTy())
9619 while (!Worklist.
empty()) {
9621 if (!L->contains(
I))
9623 if (!Visited.
insert(
I).second)
9630 if (isa<FPExtInst>(
I) && EmittedRemark.
insert(
I).second)
9633 I->getDebugLoc(), L->getHeader())
9634 <<
"floating point conversion changes vector width. "
9635 <<
"Mixed floating point precision requires an up/down "
9636 <<
"cast that will negatively impact performance.";
9639 for (
Use &
Op :
I->operands())
9640 if (
auto *OpI = dyn_cast<Instruction>(
Op))
9647 std::optional<unsigned> VScale,
Loop *L,
9660 <<
"LV: Interleaving only is not profitable due to runtime checks\n");
9701 unsigned AssumedMinimumVscale = 1;
9703 AssumedMinimumVscale = *VScale;
9704 IntVF *= AssumedMinimumVscale;
9722 uint64_t MinTC = std::max(MinTC1, MinTC2);
9724 MinTC =
alignTo(MinTC, IntVF);
9728 dbgs() <<
"LV: Minimum required TC for runtime checks to be profitable:"
9736 LLVM_DEBUG(
dbgs() <<
"LV: Vectorization is not beneficial: expected "
9737 "trip count < minimum profitable VF ("
9748 : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
9750 VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
9755 "VPlan-native path is not enabled. Only process inner loops.");
9758 << L->getHeader()->getParent()->getName() <<
"' from "
9759 << L->getLocStr() <<
"\n");
9764 dbgs() <<
"LV: Loop hints:"
9775 Function *
F = L->getHeader()->getParent();
9797 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: Cannot prove legality.\n");
9807 if (!L->isInnermost())
9811 assert(L->isInnermost() &&
"Inner loop expected.");
9833 LLVM_DEBUG(
dbgs() <<
"LV: Found a loop with a very small trip count. "
9834 <<
"This loop is worth vectorizing only if no scalar "
9835 <<
"iteration overheads are incurred.");
9837 LLVM_DEBUG(
dbgs() <<
" But vectorizing was explicitly forced.\n");
9850 LLVM_DEBUG(
dbgs() <<
" But the target considers the trip count too "
9851 "small to consider vectorizing.\n");
9853 "The trip count is below the minial threshold value.",
9854 "loop trip count is too low, avoiding vectorization",
9855 "LowTripCount",
ORE, L);
9864 if (
F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9866 "Can't vectorize when the NoImplicitFloat attribute is used",
9867 "loop not vectorized due to NoImplicitFloat attribute",
9868 "NoImplicitFloat",
ORE, L);
9880 "Potentially unsafe FP op prevents vectorization",
9881 "loop not vectorized due to unsafe FP support.",
9882 "UnsafeFP",
ORE, L);
9887 bool AllowOrderedReductions;
9897 ExactFPMathInst->getDebugLoc(),
9898 ExactFPMathInst->getParent())
9899 <<
"loop not vectorized: cannot prove it is safe to reorder "
9900 "floating-point operations";
9902 LLVM_DEBUG(
dbgs() <<
"LV: loop not vectorized: cannot prove it is safe to "
9903 "reorder floating-point operations\n");
9909 LoopVectorizationCostModel CM(
SEL, L, PSE,
LI, &LVL, *
TTI,
TLI,
DB,
AC,
ORE,
9912 LoopVectorizationPlanner LVP(L,
LI,
DT,
TLI, *
TTI, &LVL, CM, IAI, PSE, Hints,
9920 std::optional<VectorizationFactor> MaybeVF = LVP.
plan(UserVF, UserIC);
9925 bool AddBranchWeights =
9928 F->getDataLayout(), AddBranchWeights);
9934 unsigned SelectedIC = std::max(IC, UserIC);
9941 bool ForceVectorization =
9943 if (!ForceVectorization &&
9945 *PSE.
getSE(),
SEL)) {
9948 DEBUG_TYPE,
"CantReorderMemOps", L->getStartLoc(),
9950 <<
"loop not vectorized: cannot prove it is safe to reorder "
9951 "memory operations";
9960 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
9961 bool VectorizeLoop =
true, InterleaveLoop =
true;
9963 LLVM_DEBUG(
dbgs() <<
"LV: Vectorization is possible but not beneficial.\n");
9964 VecDiagMsg = std::make_pair(
9965 "VectorizationNotBeneficial",
9966 "the cost-model indicates that vectorization is not beneficial");
9967 VectorizeLoop =
false;
9970 if (!MaybeVF && UserIC > 1) {
9973 LLVM_DEBUG(
dbgs() <<
"LV: Ignoring UserIC, because vectorization and "
9974 "interleaving should be avoided up front\n");
9975 IntDiagMsg = std::make_pair(
9976 "InterleavingAvoided",
9977 "Ignoring UserIC, because interleaving was avoided up front");
9978 InterleaveLoop =
false;
9979 }
else if (IC == 1 && UserIC <= 1) {
9982 IntDiagMsg = std::make_pair(
9983 "InterleavingNotBeneficial",
9984 "the cost-model indicates that interleaving is not beneficial");
9985 InterleaveLoop =
false;
9987 IntDiagMsg.first =
"InterleavingNotBeneficialAndDisabled";
9988 IntDiagMsg.second +=
9989 " and is explicitly disabled or interleave count is set to 1";
9991 }
else if (IC > 1 && UserIC == 1) {
9994 dbgs() <<
"LV: Interleaving is beneficial but is explicitly disabled.");
9995 IntDiagMsg = std::make_pair(
9996 "InterleavingBeneficialButDisabled",
9997 "the cost-model indicates that interleaving is beneficial "
9998 "but is explicitly disabled or interleave count is set to 1");
9999 InterleaveLoop =
false;
10003 IC = UserIC > 0 ? UserIC : IC;
10007 if (!VectorizeLoop && !InterleaveLoop) {
10011 L->getStartLoc(), L->getHeader())
10012 << VecDiagMsg.second;
10016 L->getStartLoc(), L->getHeader())
10017 << IntDiagMsg.second;
10020 }
else if (!VectorizeLoop && InterleaveLoop) {
10024 L->getStartLoc(), L->getHeader())
10025 << VecDiagMsg.second;
10027 }
else if (VectorizeLoop && !InterleaveLoop) {
10029 <<
") in " << L->getLocStr() <<
'\n');
10032 L->getStartLoc(), L->getHeader())
10033 << IntDiagMsg.second;
10035 }
else if (VectorizeLoop && InterleaveLoop) {
10037 <<
") in " << L->getLocStr() <<
'\n');
10041 bool DisableRuntimeUnroll =
false;
10042 MDNode *OrigLoopID = L->getLoopID();
10044 using namespace ore;
10045 if (!VectorizeLoop) {
10046 assert(IC > 1 &&
"interleave count should not be 1 or 0");
10049 InnerLoopUnroller Unroller(L, PSE,
LI,
DT,
TLI,
TTI,
AC,
ORE, IC, &LVL,
10058 <<
"interleaved loop (interleaved count: "
10059 << NV(
"InterleaveCount", IC) <<
")";
10074 EPI, &LVL, &CM,
BFI,
PSI, Checks);
10076 std::unique_ptr<VPlan> BestMainPlan(
10078 const auto &[ExpandedSCEVs, ReductionResumeValues] = LVP.
executePlan(
10093 Header->setName(
"vec.epilog.vector.body");
10103 auto *ExpandR = cast<VPExpandSCEVRecipe>(&R);
10105 ExpandedSCEVs.find(ExpandR->getSCEV())->second);
10109 ExpandR->eraseFromParent();
10116 if (isa<VPCanonicalIVPHIRecipe>(&R))
10119 Value *ResumeV =
nullptr;
10121 if (
auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
10123 ReductionPhi->getRecurrenceDescriptor();
10125 ResumeV = ReductionResumeValues.find(&RdxDesc)->second;
10131 cast<Instruction>(ResumeV)->
getParent()->getFirstNonPHI());
10141 if (
auto *Ind = dyn_cast<VPWidenPointerInductionRecipe>(&R)) {
10142 IndPhi = cast<PHINode>(Ind->getUnderlyingValue());
10143 ID = &Ind->getInductionDescriptor();
10145 auto *WidenInd = cast<VPWidenIntOrFpInductionRecipe>(&R);
10146 IndPhi = WidenInd->getPHINode();
10147 ID = &WidenInd->getInductionDescriptor();
10154 assert(ResumeV &&
"Must have a resume value");
10156 cast<VPHeaderPHIRecipe>(&R)->setStartValue(StartVal);
10160 DT,
true, &ExpandedSCEVs);
10161 ++LoopsEpilogueVectorized;
10164 DisableRuntimeUnroll =
true;
10178 DisableRuntimeUnroll =
true;
10188 std::optional<MDNode *> RemainderLoopID =
10191 if (RemainderLoopID) {
10192 L->setLoopID(*RemainderLoopID);
10194 if (DisableRuntimeUnroll)
10233 bool Changed =
false, CFGChanged =
false;
10240 for (
const auto &L : *
LI)
10241 Changed |= CFGChanged |=
10252 LoopsAnalyzed += Worklist.
size();
10255 while (!Worklist.
empty()) {
10301 runImpl(
F,
SE,
LI,
TTI,
DT,
BFI, &
TLI,
DB,
AC,
LAIs,
ORE,
PSI);
10302 if (!Result.MadeAnyChange)
10315 if (Result.MadeCFGChange) {
10331 OS, MapClassName2PassName);
10334 OS << (InterleaveOnlyWhenForced ?
"" :
"no-") <<
"interleave-forced-only;";
10335 OS << (VectorizeOnlyWhenForced ?
"" :
"no-") <<
"vectorize-forced-only;";
static unsigned getIntrinsicID(const SDNode *N)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
AMDGPU Lower Kernel Arguments
amdgpu AMDGPU Register Bank Select
This file implements a class to represent arbitrary precision integral constant values and operations...
ReachingDefAnalysis InstSet & ToRemove
static bool isEqual(const Function &Caller, const Function &Callee)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
This is the interface for LLVM's primary stateless and local alias analysis.
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...
static cl::opt< TargetTransformInfo::TargetCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(TargetTransformInfo::TCK_RecipThroughput), cl::values(clEnumValN(TargetTransformInfo::TCK_RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(TargetTransformInfo::TCK_Latency, "latency", "Instruction latency"), clEnumValN(TargetTransformInfo::TCK_CodeSize, "code-size", "Code size"), clEnumValN(TargetTransformInfo::TCK_SizeAndLatency, "size-latency", "Code size and latency")))
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, X)
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...
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
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 > 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 ElementCount determineVPlanVF(const TargetTransformInfo &TTI, LoopVectorizationCostModel &CM)
static void createAndCollectMergePhiForReduction(VPInstruction *RedResult, DenseMap< const RecurrenceDescriptor *, Value * > &ReductionResumeValues, VPTransformState &State, Loop *OrigLoop, BasicBlock *LoopMiddleBlock, bool VectorizingEpilogue)
static std::optional< unsigned > getSmallBestKnownTC(ScalarEvolution &SE, Loop *L)
Returns "best known" trip count for the specified loop L as defined by the following procedure: 1) Re...
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 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 Instruction * createReverseEVL(IRBuilderBase &Builder, Value *Operand, Value *EVL, const Twine &Name)
Use all-true mask for reverse rather than actual mask, as it avoids a dependence w/o affecting the re...
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 Value * interleaveVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vals, const Twine &Name)
Return a vector containing interleaved elements from multiple smaller input vectors.
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 it's operands.
static void emitInvalidCostRemarks(SmallVector< InstructionVFPair > InvalidCosts, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
static void addUsersInExitBlock(VPBasicBlock *HeaderVPBB, Loop *OrigLoop, VPRecipeBuilder &Builder, VPlan &Plan)
const char LLVMLoopVectorizeFollowupAll[]
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 std::optional< unsigned > getVScaleForTuning(const Loop *L, const TargetTransformInfo &TTI)
Convenience function that returns the value of vscale_range iff vscale_range.min == vscale_range....
static bool useActiveLaneMaskForControlFlow(TailFoldingStyle Style)
static constexpr uint32_t MemCheckBypassWeights[]
static Type * MaybeVectorizeType(Type *Elt, ElementCount VF)
static 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 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 areRuntimeChecksProfitable(GeneratedRTChecks &Checks, VectorizationFactor &VF, std::optional< unsigned > VScale, Loop *L, ScalarEvolution &SE, ScalarEpilogueLowering SEL)
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 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 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 OptimizationRemarkAnalysis createLVAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop, Instruction *I)
Create an analysis remark that explains why vectorization failed.
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."))
static cl::opt< unsigned > EpilogueVectorizationMinVF("epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden, cl::desc("Only loops with vectorization factor equal to or larger than " "the specified value are considered for epilogue vectorization."))
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 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 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 unsigned getReciprocalPredBlockProb()
A helper function that returns the reciprocal of the block probability of predicated blocks.
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 void AddRuntimeUnrollDisableMetaData(Loop *L)
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 cl::opt< bool > PrintVPlansInDotFormat("vplan-print-in-dot-format", cl::Hidden, cl::desc("Use dot format instead of plain text when dumping VPlans"))
static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE)
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."))
mir Rename Register Operands
This file implements a map that provides insertion order iteration.
std::pair< uint64_t, uint64_t > Interval
Module.h This file contains the declarations for the Module class.
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())
separate const offset from gep
This file defines the SmallPtrSet class.
This file defines the SmallSet 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)
static SymbolRef::Type getType(const Symbol *Sym)
This defines the Use class.
This file defines the VPlanHCFGBuilder class which contains the public interface (buildHierarchicalCF...
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.
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.
static Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
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
Iterator returning form of getFirstNonPHI.
const Instruction * getFirstNonPHI() const
Returns a pointer 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.
InstListType::iterator iterator
Instruction iterators...
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.
void setCondition(Value *V)
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
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
static bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
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
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)
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)
void printDebugTracesAtStart() override
Allow subclasses to override and print debug traces before/after vplan execution, when trace informat...
std::pair< BasicBlock *, Value * > 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...
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)
void printDebugTracesAtEnd() override
std::pair< BasicBlock *, Value * > createEpilogueVectorizedLoopSkeleton(const SCEV2ValueTy &ExpandedSCEVs) final
Implements the interface for creating a vectorized skeleton using the main loop strategy (ie the firs...
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.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Common base class shared among various IRBuilders.
Value * CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 2 operands which is mangled on the first type.
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
ConstantInt * getTrue()
Get the constant value for i1 true.
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
CallInst * CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Load intrinsic.
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
BasicBlock::iterator GetInsertPoint() const
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Value * CreateVectorReverse(Value *V, const Twine &Name="")
Return a vector value that contains the vector V reversed.
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNSW=false)
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
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 * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
CallInst * CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment, Value *Mask)
Create a call to Masked Store intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
ConstantInt * getFalse()
Get the constant value for i1 false.
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Value * CreateURem(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateStepVector(Type *DstType, const Twine &Name="")
Creates a vector of type DstType with the linear sequence <0, 1, ...>
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
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.
InductionKind getKind() const
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)
virtual std::pair< BasicBlock *, Value * > createEpilogueVectorizedLoopSkeleton(const SCEV2ValueTy &ExpandedSCEVs)=0
The interface for creating a vectorized skeleton using one of two different strategies,...
std::pair< BasicBlock *, Value * > createVectorizedLoopSkeleton(const SCEV2ValueTy &ExpandedSCEVs) final
Create a new empty loop that will contain vectorized instructions later on, while the old loop will b...
EpilogueLoopVectorizationInfo & EPI
Holds and updates state information required to vectorize the main loop and its epilogue in two separ...
InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, const TargetTransformInfo *TTI, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, unsigned UnrollFactor, LoopVectorizationLegality *LVL, LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
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...
PHINode * createInductionResumeValue(PHINode *OrigPhi, const InductionDescriptor &ID, Value *Step, ArrayRef< BasicBlock * > BypassBlocks, std::pair< BasicBlock *, Value * > AdditionalBypass={nullptr, nullptr})
Create a new phi node for the induction variable OrigPhi to resume iteration count in the scalar epil...
void scalarizeInstruction(const Instruction *Instr, VPReplicateRecipe *RepRecipe, const VPIteration &Instance, VPTransformState &State)
A helper function to scalarize a single Instruction in the innermost loop.
BasicBlock * LoopScalarBody
The scalar loop body.
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.
DenseMap< PHINode *, Value * > IVEndValues
ElementCount MinProfitableTripCount
Value * createBitOrPointerCast(Value *V, VectorType *DstVTy, const DataLayout &DL)
Returns a bitcasted value to the requested vector type.
const TargetTransformInfo * TTI
Target Transform Info.
Value * VectorTripCount
Trip count of the widened loop (TripCount - TripCount % (VF*UF))
bool areSafetyChecksAdded()
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)
BasicBlock * emitSCEVChecks(BasicBlock *Bypass)
Emit a bypass check to see if all of the SCEV assumptions we've had to make are correct.
LoopVectorizationCostModel * Cost
The profitablity analysis.
SmallMapVector< const RecurrenceDescriptor *, PHINode *, 4 > ReductionResumeValues
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.
SmallVector< Instruction *, 4 > PredicatedInstructions
Store instructions that were predicated.
void createVectorLoopSkeleton(StringRef Prefix)
Emit basic blocks (prefixed with Prefix) for the iteration check, vector loop preheader,...
BasicBlock * completeLoopSkeleton()
Complete the loop skeleton by adding debug MDs, creating appropriate conditional branches in the midd...
BasicBlock * emitMemRuntimeChecks(BasicBlock *Bypass)
Emit bypass checks to check any memory assumptions we may have made.
BasicBlock * LoopScalarPreHeader
The scalar-loop preheader.
LoopVectorizationLegality * Legal
The legality analysis.
void fixFixedOrderRecurrence(VPLiveOut *LO, VPTransformState &State)
Create the phi node for the resume value of first order recurrences in the scalar preheader and updat...
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.
void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II, Value *VectorTripCount, Value *EndValue, BasicBlock *MiddleBlock, BasicBlock *VectorHeader, VPlan &Plan, VPTransformState &State)
Set up the values of the IVs correctly when exiting the vector loop.
void createInductionResumeValues(const SCEV2ValueTy &ExpandedSCEVs, std::pair< BasicBlock *, Value * > AdditionalBypass={nullptr, nullptr})
Create new phi nodes for the induction variables to resume iteration count in the scalar epilogue,...
void fixNonInductionPHIs(VPlan &Plan, VPTransformState &State)
Fix the non-induction PHIs in Plan.
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
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 vectorizeInterleaveGroup(const InterleaveGroup< Instruction > *Group, ArrayRef< VPValue * > VPDefs, VPTransformState &State, VPValue *Addr, ArrayRef< VPValue * > StoredValues, VPValue *BlockInMask, bool NeedsMaskForGaps)
Try to vectorize interleaved access group Group with the base address given in Addr,...
virtual std::pair< BasicBlock *, Value * > createVectorizedLoopSkeleton(const SCEV2ValueTy &ExpandedSCEVs)
Create a new empty loop that will contain vectorized instructions later on, while the old loop will b...
unsigned UF
The vectorization unroll factor to use.
void fixVectorizedLoop(VPTransformState &State, VPlan &Plan)
Fix the vectorized code, taking care of header phi's, live-outs, and more.
BasicBlock * LoopExitBlock
The unique ExitBlock of the scalar loop if one exists.
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...
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
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...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
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.
uint32_t getIndex(const InstTy *Instr) const
Get the index for the given member.
InstTy * getInsertPos() const
void addMetadata(InstTy *NewInst) const
Add metadata (e.g.
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.
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.
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.
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop.
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
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 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.
PredicatedScalarEvolution & PSE
Predicated scalar evolution analysis.
const LoopVectorizeHints * Hints
Loop Vectorize Hint.
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::pair< InstructionCost, bool > VectorizationCostTy
The vectorization cost is a combination of the cost itself and a boolean indicating whether any of th...
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.
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.
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.
VectorizationCostTy expectedCost(ElementCount VF, SmallVectorImpl< InstructionVFPair > *Invalid=nullptr)
Returns the expected execution cost.
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 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...
bool isEpilogueVectorizationProfitable(const ElementCount VF) const
Returns true if epilogue vectorization is considered profitable, and false otherwise.
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...
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 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
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.
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 InductionList & getInductionVars() const
Returns the induction variables found in the loop.
bool isInvariant(Value *V) const
Returns true if value V is uniform across VF lanes, when VF is provided, and otherwise if V is invari...
const ReductionList & getReductionVars() const
Returns the reduction variables found in the loop.
bool isSafeForAnyVectorWidth() const
unsigned getNumLoads() const
Type * getWidestInductionType()
Returns the widest induction type.
const LoopAccessInfo * getLAI() const
bool prepareToFoldTailByMasking()
Return true if we can vectorize this loop while folding its tail by masking, and mark all respective ...
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,...
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.
std::optional< VectorizationFactor > plan(ElementCount UserVF, unsigned UserIC)
Plan how to best vectorize, return the best VF and its cost, or std::nullopt if vectorization and int...
VectorizationFactor selectEpilogueVectorizationFactor(const ElementCount MaxVF, unsigned IC)
VectorizationFactor planInVPlanNativePath(ElementCount UserVF)
Use the VPlan-native path to plan how to best vectorize, return the best VF and its cost.
std::pair< DenseMap< const SCEV *, Value * >, DenseMap< const RecurrenceDescriptor *, Value * > > executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan, InnerLoopVectorizer &LB, DominatorTree *DT, bool IsEpilogueVectorization, const DenseMap< const SCEV *, Value * > *ExpandedSCEVs=nullptr)
Generate the IR code for the vectorized loop captured in VPlan BestPlan according to the best selecte...
void buildVPlans(ElementCount MinVF, ElementCount MaxVF)
Build VPlans for power-of-2 VF's between MinVF and MaxVF inclusive, according to the information gath...
VPlan & getBestPlanFor(ElementCount VF) const
Return the best VPlan for VF.
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)
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)
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.
void setIncomingValueForBlock(const BasicBlock *BB, Value *V)
Set every incoming value(s) for block BB to V.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
static unsigned getIncomingValueNumForOperand(unsigned i)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
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
const SCEV * getBackedgeTakenCount()
Get the (predicated) 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,...
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.
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 * getConstant(ConstantInt *V)
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
unsigned getSmallConstantMaxTripCount(const Loop *L)
Returns the upper bound of the loop trip count as a normal unsigned value.
const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
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 isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
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.
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.
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.
LLVMContext & getContext() const
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()
This class provides computation of slot numbers for LLVM Assembly writing.
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.
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.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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...
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.
bool isPointerTy() const
True if this is an instance of PointerType.
static IntegerType * getInt1Ty(LLVMContext &C)
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
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.
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPBasicBlock,...
iterator begin()
Recipe iterator methods.
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.
VPRegionBlock * getParent()
const VPBasicBlock * getExitingBasicBlock() const
void setName(const Twine &newName)
const VPBasicBlock * getEntryBasicBlock() const
VPBlockBase * getSingleSuccessor() const
static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBase NewBlock after BlockPtr.
RAII object that stores the current insertion point and restores it when the object is destroyed.
VPlan-based builder utility analogous to IRBuilder.
VPValue * createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL={}, const Twine &Name="")
VPBasicBlock * getInsertBlock() const
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.
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.
ArrayRef< VPValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I 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
This is a concrete Recipe that models a single VPlan-level instruction.
unsigned getOpcode() const
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
VPValue * getAddr() const
Return the address accessed by this recipe.
VPValue * getMask() const
Return the mask used by this recipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
unsigned getNumStoreOperands() const
Returns the number of stored operands of this interleave group.
static VPLane getLastLaneForVF(const ElementCount &VF)
static VPLane getFirstLane()
A value that is used outside the VPlan.
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.
VPValue * getVPValueOrAddLiveIn(Value *V, VPlan &Plan)
VPValue * createEdgeMask(BasicBlock *Src, BasicBlock *Dst)
A helper function that computes the predicate of the edge between SRC and DST.
VPReplicateRecipe * handleReplication(Instruction *I, VFRange &Range)
Build a VPReplicationRecipe for I.
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.
VPRecipeBase * tryToCreateWidenRecipe(Instruction *Instr, ArrayRef< VPValue * > Operands, VFRange &Range, VPBasicBlock *VPBB)
Create and return a widened recipe for I if one can be created within the given VF Range.
void createHeaderMask()
Create the mask for the vector loop header block.
void createBlockInMask(BasicBlock *BB)
A helper function that computes the predicate of the block BB, assuming that the header block of the ...
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...
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.
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.
This class can be used to assign names to 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)
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
void replaceAllUsesWith(VPValue *New)
user_iterator user_begin()
Value * getLiveInIRValue()
Returns the underlying IR value, if this VPValue is defined outside the scope of VPlan.
bool isLiveIn() const
Returns true if this VPValue is a live-in, i.e. defined outside the 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 for all parts.
A recipe for widening Call instructions.
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.
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
A common base class for widening memory operations.
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
VPValue * getMask() const
Return the mask used by this recipe.
VPValue * getAddr() const
Return the address accessed by this recipe.
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
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.
bool onlyScalarsGenerated(bool IsScalable)
Returns true if only scalar values will be generated.
void execute(VPTransformState &State) override
Generate vector values for the pointer induction.
VPWidenRecipe is a recipe for producing a copy of vector type its ingredient.
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...
void prepareToExecute(Value *TripCount, Value *VectorTripCount, Value *CanonicalIVStartValue, VPTransformState &State)
Prepare the plan for execution, setting up the required live-in values.
VPBasicBlock * getEntry()
VPValue & getVectorTripCount()
The vector trip count.
void setName(const Twine &newName)
VPValue & getVFxUF()
Returns VF * UF 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.
void removeLiveOut(PHINode *PN)
void addLiveOut(PHINode *PN, VPValue *V)
VPBasicBlock * getPreheader()
VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
bool hasVF(ElementCount VF)
bool hasUF(unsigned UF) const
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
VPValue * getOrAddLiveIn(Value *V)
Gets the live-in VPValue for V or adds a new live-in (if none exists yet) for V.
LLVM_DUMP_METHOD void dump() const
Dump the plan to stderr (for debugging).
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
VPCanonicalIVPHIRecipe * getCanonicalIV()
Returns the canonical induction recipe of the vector loop.
const MapVector< PHINode *, VPLiveOut * > & getLiveOuts() const
VPValue * getSCEVExpansion(const SCEV *S) const
static VPlanPtr createInitialVPlan(const SCEV *TripCount, ScalarEvolution &PSE, BasicBlock *PH)
Create initial VPlan skeleton, having an "entry" VPBasicBlock (wrapping original scalar pre-header PH...
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()
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
LLVMContext & getContext() const
All values hold a context through their type.
StringRef getName() const
Return a constant reference to the value's name.
VectorBuilder & setEVL(Value *NewExplicitVectorLength)
VectorBuilder & setMask(Value *NewMask)
Value * createVectorInstruction(unsigned Opcode, Type *ReturnTy, ArrayRef< Value * > VecOpArray, const Twine &Name=Twine())
Base class of all SIMD vector types.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
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 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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ 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.
std::variant< std::monostate, Loc::Single, Loc::Multi, Loc::MMI, Loc::EntryValue > Variant
Alias for the std::variant specialization base class of DbgVariable.
bool match(Val *V, const Pattern &P)
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
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.
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, Style style=Style::native)
Get begin iterator over path.
const_iterator end(StringRef path)
Get end iterator over path.
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, ScalarEvolution &SE)
Get or create a VPValue that corresponds to the expansion of Expr.
bool isUniformAfterVectorization(VPValue *VPV)
Returns true if VPV is uniform after vectorization.
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.
void stable_sort(R &&Range)
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.
Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator)
Returns the integer ceil(Numerator / Denominator).
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are are tuples (A,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
unsigned getLoadStoreAddressSpace(Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
const SCEV * createTripCountSCEV(Type *IdxTy, PredicatedScalarEvolution &PSE, Loop *OrigLoop)
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...
Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
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.
Constant * createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF, const InterleaveGroup< Instruction > &Group)
Create a mask that filters the members of an interleave group where there are gaps.
llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
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)
llvm::SmallVector< int, 16 > createReplicatedMask(unsigned ReplicationFactor, unsigned VF)
Create a mask with replicated elements.
std::unique_ptr< VPlan > VPlanPtr
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isPointerTy(const Type *T)
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
Align getLoadStoreAlignment(Value *I)
A helper function that returns the alignment of load or store instruction.
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
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.
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Type * ToVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
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).
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...
@ CM_ScalarEpilogueNotAllowedLowTripLoop
@ CM_ScalarEpilogueNotNeededUsePredicate
@ CM_ScalarEpilogueNotAllowedOptSize
@ CM_ScalarEpilogueAllowed
@ CM_ScalarEpilogueNotAllowedUsePredicate
bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
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...
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.
void reportVectorizationInfo(const StringRef OREMsg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I=nullptr)
Reports an informative message: print Msg for debugging purposes as well as an optimization remark.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
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...
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 * getLoadStoreType(Value *I)
A helper function that returns the type of a load or store instruction.
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.
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
BasicBlock * MemSafetyCheck
BasicBlock * MainLoopIterationCountCheck
EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF, ElementCount EVF, unsigned EUF)
BasicBlock * EpilogueIterationCountCheck
A class that represents two vectorization factors (initialized with 0 by default).
static FixedScalableVFPair getNone()
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
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.
bool processLoop(Loop *L)
LoopAccessInfoManager * LAIs
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LoopVectorizePass(LoopVectorizeOptions Opts={})
LoopVectorizeResult runImpl(Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_, DominatorTree &DT_, BlockFrequencyInfo *BFI_, TargetLibraryInfo *TLI_, DemandedBits &DB_, AssumptionCache &AC_, LoopAccessInfoManager &LAIs_, OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
OptimizationRemarkEmitter * ORE
Storage for information about made changes.
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.
A recipe for handling first-order recurrence phis.
VPIteration represents a single point in the iteration space of the output (vectorized and/or unrolle...
bool isFirstIteration() const
void execute(VPTransformState &State) override
Generate the wide load or gather.
VPValue * getEVL() const
Return the EVL operand.
A recipe for widening load operations, using the address to load from and an optional mask.
void execute(VPTransformState &State) override
Generate a wide load or gather.
A recipe for widening select instructions.
VPValue * getStoredValue() const
Return the address accessed by this recipe.
void execute(VPTransformState &State) override
Generate the wide store or scatter.
VPValue * getEVL() const
Return the EVL operand.
A recipe for widening store operations, using the stored value, the address to store to and an option...
void execute(VPTransformState &State) override
Generate a wide store or scatter.
VPValue * getStoredValue() const
Return the value stored by this recipe.
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