140 #include <functional> 149 using namespace llvm;
151 #define LV_NAME "loop-vectorize" 152 #define DEBUG_TYPE LV_NAME 154 STATISTIC(LoopsVectorized,
"Number of loops vectorized");
155 STATISTIC(LoopsAnalyzed,
"Number of loops analyzed for vectorization");
161 cl::desc(
"Loops with a constant trip count that is smaller than this " 162 "value are vectorized only if no scalar iteration overheads " 167 cl::desc(
"Maximize bandwidth when selecting vectorization factor which " 168 "will be determined by the smallest type in loop."));
172 cl::desc(
"Enable vectorization on interleaved memory accesses in a loop"));
177 cl::desc(
"Maximum factor for an interleaved access group (default = 8)"),
186 cl::desc(
"A flag that overrides the target's number of scalar registers."));
190 cl::desc(
"A flag that overrides the target's number of vector registers."));
194 cl::desc(
"A flag that overrides the target's max interleave factor for " 199 cl::desc(
"A flag that overrides the target's max interleave factor for " 200 "vectorized loops."));
204 cl::desc(
"A flag that overrides the target's expected cost for " 205 "an instruction to a single constant value. Mostly " 206 "useful for getting consistent testing."));
211 "The cost of a loop that is considered 'small' by the interleaver."));
215 cl::desc(
"Enable the use of the block frequency analysis to access PGO " 216 "heuristics minimizing code growth in cold regions and being more " 217 "aggressive in hot regions."));
223 "Enable runtime interleaving until load/store ports are saturated"));
228 cl::desc(
"Max number of stores to be predicated behind an if."));
232 cl::desc(
"Count the induction variable only once when interleaving"));
236 cl::desc(
"Enable if predication of stores during vectorization."));
240 cl::desc(
"The maximum interleave count to use when interleaving a scalar " 241 "reduction in a nested loop."));
245 cl::desc(
"Enable VPlan-native vectorization path with " 246 "support for outer loop vectorization."));
255 "Build VPlan for every supported loop nest in the function and bail " 256 "out right after the build (stress test the VPlan H-CFG construction " 257 "in the VPlan-native vectorization path)."));
274 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
275 "Expected Load or Store instruction");
276 if (
auto *LI = dyn_cast<LoadInst>(I))
277 return LI->getType();
278 return cast<StoreInst>(
I)->getValueOperand()->getType();
283 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
284 "Expected Load or Store instruction");
285 if (
auto *LI = dyn_cast<LoadInst>(I))
286 return LI->getAlignment();
293 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
294 "Expected Load or Store instruction");
295 if (
auto *LI = dyn_cast<LoadInst>(I))
296 return LI->getPointerAddressSpace();
297 return cast<StoreInst>(
I)->getPointerAddressSpace();
326 if (isa<FPMathOperator>(V)) {
329 cast<Instruction>(V)->setFastMathFlags(Flags);
366 : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
367 AC(AC), ORE(ORE),
VF(VecWidth),
UF(UnrollFactor),
368 Builder(PSE.getSE()->getContext()),
400 bool IfPredicateInstr);
513 Instruction::BinaryOpsEnd);
558 Value *VectorLoopValue,
560 unsigned Lane = UINT_MAX);
639 std::unique_ptr<LoopVersioning>
LVer;
720 UnrollFactor, LVL, CM) {}
726 Instruction::BinaryOpsEnd)
override;
743 if (
Instruction *OpInst = dyn_cast<Instruction>(*OI))
744 if (OpInst->getDebugLoc() !=
Empty)
752 if (
const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
754 if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
755 !isa<DbgInfoIntrinsic>(Inst))
770 LoopDbgLoc.print(OS);
784 if (
LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
785 LVer->annotateInstWithNoAlias(To, Orig);
796 for (
Value *V : To) {
833 : Align(Align), InsertPos(Instr) {
834 assert(Align &&
"The alignment should be non-zero");
837 assert(Factor > 1 &&
"Invalid interleave factor");
839 Reverse = Stride < 0;
854 assert(NewAlign &&
"The new member's alignment should be non-zero");
856 int Key = Index + SmallestKey;
859 if (Members.count(Key))
862 if (Key > LargestKey) {
864 if (Index >= static_cast<int>(Factor))
868 }
else if (Key < SmallestKey) {
870 if (LargestKey - Key >= static_cast<int>(Factor))
878 Members[
Key] = Instr;
887 if (!Members.count(Key))
890 return Members.find(Key)->second;
896 for (
auto I : Members)
897 if (
I.second == Instr)
898 return I.first - SmallestKey;
914 std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
915 [](std::pair<int, Instruction *> p) {
return p.second; });
952 class InterleavedAccessInfo {
957 :
PSE(PSE), TheLoop(L),
DT(DT),
LI(LI), LAI(LAI) {}
959 ~InterleavedAccessInfo() {
962 for (
auto &
I : InterleaveGroupMap)
964 for (
auto *
Ptr : DelSet)
970 void analyzeInterleaving();
974 return InterleaveGroupMap.count(Instr);
981 if (InterleaveGroupMap.count(Instr))
982 return InterleaveGroupMap.find(Instr)->second;
988 bool requiresScalarEpilogue()
const {
return RequiresScalarEpilogue; }
1005 bool RequiresScalarEpilogue =
false;
1015 struct StrideDescriptor {
1016 StrideDescriptor() =
default;
1017 StrideDescriptor(int64_t Stride,
const SCEV *Scev, uint64_t
Size,
1019 : Stride(Stride), Scev(Scev),
Size(Size),
Align(Align) {}
1025 const SCEV *Scev =
nullptr;
1035 using StrideEntry = std::pair<Instruction *, StrideDescriptor>;
1044 "Already in an interleaved access group");
1045 InterleaveGroupMap[Instr] =
new InterleaveGroup(Instr, Stride, Align);
1046 return InterleaveGroupMap[Instr];
1051 for (
unsigned i = 0; i < Group->
getFactor(); i++)
1053 InterleaveGroupMap.
erase(Member);
1059 void collectConstStrideAccesses(
1064 static bool isStrided(
int Stride) {
1065 unsigned Factor =
std::abs(Stride);
1075 bool areDependencesValid()
const {
1084 bool canReorderMemAccessesForInterleavedGroups(StrideEntry *A,
1085 StrideEntry *
B)
const {
1101 auto *Src = A->first;
1102 auto SrcDes = A->second;
1105 auto *
Sink = B->first;
1106 auto SinkDes = B->second;
1110 if (!Src->mayWriteToMemory())
1114 if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride))
1119 if (!areDependencesValid())
1124 return !Dependences.
count(Src) || !Dependences.
lookup(Src).count(
Sink);
1131 void collectDependences() {
1132 if (!areDependencesValid())
1135 for (
auto Dep : *Deps)
1136 Dependences[Dep.getSource(*LAI)].
insert(Dep.getDestination(*LAI));
1152 <<
"loop not vectorized: " 1153 <<
"failed explicitly specified loop vectorization");
1158 <<
"loop not interleaved: " 1159 <<
"failed explicitly specified loop interleaving");
1181 InterleavedAccessInfo &IAI)
1182 : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
1183 AC(AC), ORE(ORE), TheFunction(F), Hints(Hints), InterleaveInfo(IAI) {}
1197 collectUniformsAndScalars(UserVF);
1198 collectInstsToScalarize(UserVF);
1204 std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1210 unsigned selectInterleaveCount(
bool OptForSize,
unsigned VF,
1220 void setCostBasedWideningDecision(
unsigned VF);
1237 void collectValuesToIgnore();
1249 assert(VF > 1 &&
"Profitable to scalarize relevant only for VF > 1.");
1250 auto Scalars = InstsToScalarize.find(VF);
1251 assert(Scalars != InstsToScalarize.end() &&
1252 "VF not yet analyzed for scalarization profitability");
1253 return Scalars->second.count(I);
1260 assert(Uniforms.count(VF) &&
"VF not yet analyzed for uniformity");
1261 auto UniformsPerVF = Uniforms.find(VF);
1262 return UniformsPerVF->second.count(I);
1269 assert(Scalars.count(VF) &&
"Scalar values are not calculated for VF");
1270 auto ScalarsPerVF = Scalars.find(VF);
1271 return ScalarsPerVF->second.count(I);
1277 return VF > 1 && MinBWs.count(I) && !isProfitableToScalarize(I, VF) &&
1278 !isScalarAfterVectorization(I, VF);
1295 assert(VF >= 2 &&
"Expected VF >=2");
1296 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1303 assert(VF >= 2 &&
"Expected VF >=2");
1306 for (
unsigned i = 0; i < Grp->
getFactor(); ++i) {
1309 WideningDecisions[std::make_pair(
I, VF)] = std::make_pair(W, Cost);
1311 WideningDecisions[std::make_pair(
I, VF)] = std::make_pair(W, 0);
1320 assert(VF >= 2 &&
"Expected VF >=2");
1321 std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1322 auto Itr = WideningDecisions.find(InstOnVF);
1323 if (Itr == WideningDecisions.end())
1325 return Itr->second.first;
1331 assert(VF >= 2 &&
"Expected VF >=2");
1332 std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1333 assert(WideningDecisions.count(InstOnVF) &&
"The cost is not calculated");
1334 return WideningDecisions[InstOnVF].second;
1355 Value *
Op = Trunc->getOperand(0);
1365 void collectInstsToScalarize(
unsigned VF);
1372 if (VF == 1 || Uniforms.count(VF))
1374 setCostBasedWideningDecision(VF);
1375 collectLoopUniforms(VF);
1376 collectLoopScalars(VF);
1406 bool LI = isa<LoadInst>(V);
1407 bool SI = isa<StoreInst>(V);
1411 return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty));
1421 bool memoryInstructionCanBeWidened(
Instruction *I,
unsigned VF = 1);
1425 return InterleaveInfo.isInterleaved(Instr);
1430 return InterleaveInfo.getInterleaveGroup(Instr);
1436 return InterleaveInfo.requiresScalarEpilogue();
1440 unsigned NumPredStores = 0;
1444 unsigned computeFeasibleMaxVF(
bool OptForSize,
unsigned ConstTripCount);
1453 using VectorizationCostTy = std::pair<unsigned, bool>;
1459 VectorizationCostTy expectedCost(
unsigned VF);
1463 VectorizationCostTy getInstructionCost(
Instruction *I,
unsigned VF);
1467 unsigned getInstructionCost(
Instruction *I,
unsigned VF,
Type *&VectorTy);
1470 unsigned getMemoryInstructionCost(
Instruction *I,
unsigned VF);
1473 unsigned getMemInstScalarizationCost(
Instruction *I,
unsigned VF);
1476 unsigned getInterleaveGroupCost(
Instruction *I,
unsigned VF);
1479 unsigned getGatherScatterCost(
Instruction *I,
unsigned VF);
1483 unsigned getConsecutiveMemOpCost(
Instruction *I,
unsigned VF);
1487 unsigned getUniformMemOpCost(
Instruction *I,
unsigned VF);
1503 RemarkName, TheLoop);
1555 void collectLoopUniforms(
unsigned VF);
1562 void collectLoopScalars(
unsigned VF);
1567 std::pair<InstWidening, unsigned>>;
1633 assert(!OuterLp->
empty() &&
"This is not an outer loop");
1642 if (!Hints.allowVectorization(Fn, OuterLp,
false )) {
1643 LLVM_DEBUG(
dbgs() <<
"LV: Loop hints prevent outer loop vectorization.\n");
1647 if (!Hints.getWidth()) {
1648 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: No user vector width.\n");
1653 if (Hints.getInterleave() > 1) {
1655 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: Interleave is not supported for " 1675 if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
1685 for (
Loop *InnerL : L)
1698 explicit LoopVectorize(
bool NoUnrolling =
false,
bool AlwaysVectorize =
true)
1706 if (skipFunction(F))
1709 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1710 auto *
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1711 auto *
TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1712 auto *
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1713 auto *
BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1714 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1715 auto *
TLI = TLIP ? &TLIP->getTLI() :
nullptr;
1716 auto *
AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1717 auto *
AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1718 auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
1719 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
1720 auto *
ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1722 std::function<const LoopAccessInfo &(Loop &)> GetLAA =
1725 return Impl.
runImpl(F, *SE, *
LI, *
TTI, *
DT, *
BFI, TLI, *DB, *
AA, *
AC,
1775 assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
1776 "Expected either an induction phi-node or a truncate of it!");
1782 if (isa<TruncInst>(EntryVal)) {
1784 "Truncation requires an integer type");
1785 auto *TruncType = cast<IntegerType>(EntryVal->
getType());
1790 Value *SteppedStart =
1799 MulOp = Instruction::Mul;
1802 MulOp = Instruction::FMul;
1815 Value *SplatVF = isa<Constant>(Mul)
1826 for (
unsigned Part = 0; Part <
UF; ++Part) {
1829 if (isa<TruncInst>(EntryVal))
1841 auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
1842 auto *ICmp = cast<Instruction>(Br->getCondition());
1844 LastInduction->
setName(
"vec.ind.next");
1847 VecInd->
addIncoming(LastInduction, LoopVectorLatch);
1858 auto isScalarInst = [&](
User *U) ->
bool {
1859 auto *
I = cast<Instruction>(U);
1867 Value *VectorLoopVal,
unsigned Part,
unsigned Lane) {
1868 assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
1869 "Expected either an induction phi-node or a truncate of it!");
1877 if (isa<TruncInst>(EntryVal))
1887 if (Lane < UINT_MAX)
1895 "Primary induction variable must have an integer type");
1900 auto ID = II->second;
1901 assert(IV->
getType() == ID.getStartValue()->getType() &&
"Types must match");
1905 Value *ScalarIV =
nullptr;
1909 Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
1912 auto VectorizedIV =
false;
1922 "Induction step should be loop invariant");
1924 Value *Step =
nullptr;
1927 Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
1930 Step = cast<SCEVUnknown>(ID.getStep())->getValue();
1938 VectorizedIV =
true;
1946 if (!VectorizedIV || NeedsScalarIV) {
1954 ScalarIV->
setName(
"offset.idx");
1957 auto *TruncType = cast<IntegerType>(Trunc->
getType());
1959 "Truncation requires an integer step");
1968 if (!VectorizedIV) {
1970 for (
unsigned Part = 0; Part <
UF; ++Part) {
1998 "Induction Step must be an integer or FP");
2005 for (
int i = 0; i < VLen; ++i)
2012 assert(Step->getType() == Val->
getType() &&
"Invalid step vec");
2020 assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2021 "Binary Opcode should be specified for FP induction");
2023 for (
int i = 0; i < VLen; ++i)
2036 if (isa<Instruction>(MulOp))
2038 cast<Instruction>(MulOp)->setFastMathFlags(Flags);
2041 if (isa<Instruction>(BOp))
2042 cast<Instruction>(BOp)->setFastMathFlags(Flags);
2050 assert(
VF > 1 &&
"VF should be greater than one");
2055 "Val and Step should have the same type");
2063 MulOp = Instruction::Mul;
2066 MulOp = Instruction::FMul;
2076 for (
unsigned Part = 0; Part <
UF; ++Part) {
2077 for (
unsigned Lane = 0; Lane < Lanes; ++Lane) {
2088 assert(V !=
Induction &&
"The new induction variable should not be used.");
2107 auto *
I = cast<Instruction>(V);
2121 auto *LastInst = cast<Instruction>(
2136 Value *VectorValue =
nullptr;
2144 for (
unsigned Lane = 0; Lane <
VF; ++Lane)
2169 :
true &&
"Uniform values only have lane zero");
2182 if (!U->getType()->isVectorTy()) {
2183 assert(
VF == 1 &&
"Value not scalarized has non-vector type");
2195 assert(V !=
Induction &&
"The new induction variable should not be used.");
2209 for (
unsigned i = 0; i <
VF; ++i)
2247 assert(Group &&
"Fail to get an interleaved access group.");
2258 unsigned InterleaveFactor = Group->
getFactor();
2276 bool InBounds =
false;
2278 InBounds =
gep->isInBounds();
2280 for (
unsigned Part = 0; Part <
UF; Part++) {
2296 cast<GetElementPtrInst>(NewPtr)->setIsInBounds(
true);
2306 if (isa<LoadInst>(Instr)) {
2309 for (
unsigned Part = 0; Part <
UF; Part++) {
2318 for (
unsigned I = 0;
I < InterleaveFactor; ++
I) {
2326 for (
unsigned Part = 0; Part <
UF; Part++) {
2328 NewLoads[Part], UndefVec, StrideMask,
"strided.vec");
2331 if (Member->
getType() != ScalarTy) {
2349 for (
unsigned Part = 0; Part <
UF; Part++) {
2352 for (
unsigned i = 0; i < InterleaveFactor; i++) {
2355 assert(Member &&
"Fail to get a member from an interleaved store group");
2358 cast<StoreInst>(Member)->getValueOperand(), Part);
2364 if (StoredVec->
getType() != SubVT)
2391 assert((LI || SI) &&
"Invalid Load/Store instruction");
2396 "CM decision should be taken at this point");
2414 bool ConsecutiveStride =
2416 bool CreateGatherScatter =
2421 assert((ConsecutiveStride || CreateGatherScatter) &&
2422 "The instruction should be scalarized");
2425 if (ConsecutiveStride)
2429 bool isMaskRequired = BlockInMask;
2431 Mask = *BlockInMask;
2433 bool InBounds =
false;
2434 if (
auto *
gep = dyn_cast<GetElementPtrInst>(
2436 InBounds =
gep->isInBounds();
2438 const auto CreateVecPtr = [&](
unsigned Part,
Value *Ptr) ->
Value * {
2445 PartPtr = cast<GetElementPtrInst>(
2448 PartPtr = cast<GetElementPtrInst>(
2454 PartPtr = cast<GetElementPtrInst>(
2466 for (
unsigned Part = 0; Part <
UF; ++Part) {
2469 if (CreateGatherScatter) {
2470 Value *MaskPart = isMaskRequired ? Mask[Part] :
nullptr;
2482 auto *VecPtr = CreateVecPtr(Part, Ptr);
2495 assert(LI &&
"Must have a load instruction");
2497 for (
unsigned Part = 0; Part <
UF; ++Part) {
2499 if (CreateGatherScatter) {
2500 Value *MaskPart = isMaskRequired ? Mask[Part] :
nullptr;
2503 nullptr,
"wide.masked.gather");
2506 auto *VecPtr = CreateVecPtr(Part, Ptr);
2510 "wide.masked.load");
2525 bool IfPredicateInstr) {
2552 if (
auto *II = dyn_cast<IntrinsicInst>(Cloned))
2553 if (II->getIntrinsicID() == Intrinsic::assume)
2557 if (IfPredicateInstr)
2601 assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
2602 "Invalid loop count");
2612 IdxTy->getPrimitiveSizeInBits())
2613 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2614 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2617 const SCEV *ExitCount = SE->getAddExpr(
2618 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->
getType()));
2679 "Vector elements must have same size");
2690 "Only one type should be a pointer type");
2692 "Only one type should be a floating point type");
2739 if (
auto *
C = dyn_cast<ConstantInt>(SCEVCheck))
2744 BB->
setName(
"vector.scevcheck");
2766 std::tie(FirstCheckInst, MemRuntimeCheck) =
2768 if (!MemRuntimeCheck)
2772 BB->
setName(
"vector.memcheck");
2789 LVer->prepareNoAliasMetadata();
2828 assert(VectorPH &&
"Invalid loop structure");
2829 assert(ExitBlock &&
"Must have an exit block");
2910 for (
auto &InductionEntry : *List) {
2911 PHINode *OrigPhi = InductionEntry.first;
2922 EndValue = CountRoundDown;
2928 Value *CRD =
B.CreateCast(CastOp, CountRoundDown, StepType,
"cast.crd");
3002 assert(isa<PHINode>(UI) &&
"Expected LCSSA form");
3003 MissingVals[UI] = EndValue;
3011 auto *UI = cast<Instruction>(U);
3015 assert(isa<PHINode>(UI) &&
"Expected LCSSA form");
3018 Value *CountMinusOne =
B.CreateSub(
3022 ?
B.CreateCast(Instruction::SIToFP, CountMinusOne,
3027 Escape->
setName(
"ind.escape");
3028 MissingVals[UI] = Escape;
3032 for (
auto &
I : MissingVals) {
3033 PHINode *PHI = cast<PHINode>(
I.first);
3046 struct CSEDenseMapInfo {
3048 return isa<InsertElementInst>(
I) || isa<ExtractElementInst>(I) ||
3049 isa<ShuffleVectorInst>(
I) || isa<GetElementPtrInst>(I);
3060 static unsigned getHashValue(
const Instruction *I) {
3061 assert(canHandle(I) &&
"Unknown instruction!");
3067 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3068 LHS == getTombstoneKey() || RHS == getTombstoneKey())
3083 if (!CSEDenseMapInfo::canHandle(In))
3108 (!isa<LoadInst>(
I) ||
3112 if (
CallInst *CI = dyn_cast<CallInst>(I)) {
3116 else if (!isa<StoreInst>(I) ||
3132 bool &NeedToScalarize) {
3146 return ScalarCallCost;
3150 for (
Type *ScalarTy : ScalarTys)
3157 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3161 NeedToScalarize =
true;
3167 if (VectorCallCost < Cost) {
3168 NeedToScalarize =
false;
3169 return VectorCallCost;
3181 assert(ID &&
"Expected intrinsic call!");
3184 if (
auto *FPMO = dyn_cast<FPMathOperator>(CI))
3185 FMF = FPMO->getFastMathFlags();
3194 return I1->getBitWidth() < I2->getBitWidth() ?
T1 : T2;
3199 return I1->getBitWidth() > I2->getBitWidth() ?
T1 : T2;
3213 for (
unsigned Part = 0; Part <
UF; ++Part) {
3218 Type *ScalarTruncatedTy =
3222 if (TruncatedTy == OriginalTy)
3226 auto ShrinkOperand = [&](
Value *V) ->
Value * {
3227 if (
auto *ZI = dyn_cast<ZExtInst>(V))
3228 if (ZI->getSrcTy() == TruncatedTy)
3229 return ZI->getOperand(0);
3235 Value *NewI =
nullptr;
3236 if (
auto *BO = dyn_cast<BinaryOperator>(I)) {
3237 NewI = B.
CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3238 ShrinkOperand(BO->getOperand(1)));
3243 cast<BinaryOperator>(NewI)->copyIRFlags(I,
false);
3244 }
else if (
auto *CI = dyn_cast<ICmpInst>(I)) {
3246 B.
CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3247 ShrinkOperand(CI->getOperand(1)));
3248 }
else if (
auto *
SI = dyn_cast<SelectInst>(I)) {
3250 ShrinkOperand(
SI->getTrueValue()),
3251 ShrinkOperand(
SI->getFalseValue()));
3252 }
else if (
auto *CI = dyn_cast<CastInst>(I)) {
3253 switch (CI->getOpcode()) {
3256 case Instruction::Trunc:
3257 NewI = ShrinkOperand(CI->getOperand(0));
3259 case Instruction::SExt:
3264 case Instruction::ZExt:
3270 }
else if (
auto *
SI = dyn_cast<ShuffleVectorInst>(I)) {
3271 auto Elements0 =
SI->getOperand(0)->getType()->getVectorNumElements();
3274 auto Elements1 =
SI->getOperand(1)->getType()->getVectorNumElements();
3279 }
else if (isa<LoadInst>(I) || isa<PHINode>(
I)) {
3282 }
else if (
auto *
IE = dyn_cast<InsertElementInst>(I)) {
3283 auto Elements =
IE->getOperand(0)->getType()->getVectorNumElements();
3288 }
else if (
auto *EE = dyn_cast<ExtractElementInst>(I)) {
3299 NewI->
takeName(cast<Instruction>(I));
3302 cast<Instruction>(
I)->eraseFromParent();
3315 for (
unsigned Part = 0; Part <
UF; ++Part) {
3438 auto *VectorInit = ScalarInit;
3453 auto *VecPhi =
Builder.
CreatePHI(VectorInit->getType(), 2,
"vector.recur");
3466 isa<PHINode>(PreviousLastPart))
3476 for (
unsigned I = 1;
I <
VF; ++
I)
3481 Value *Incoming = VecPhi;
3484 for (
unsigned Part = 0; Part <
UF; ++Part) {
3492 cast<Instruction>(PhiPart)->eraseFromParent();
3494 Incoming = PreviousPart;
3502 auto *ExtractForScalar = Incoming;
3513 Value *ExtractForPhiUsedOutsideLoop =
nullptr;
3528 auto *Incoming = BB ==
LoopMiddleBlock ? ExtractForScalar : ScalarInit;
3529 Start->addIncoming(Incoming, BB);
3541 if (LCSSAPhi.getIncomingValue(0) == Phi) {
3552 "Unable to find the reduction variable");
3557 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3559 RdxDesc.getMinMaxRecurrenceKind();
3579 VectorStart = Identity = ReductionStartValue;
3581 VectorStart = Identity =
3592 VectorStart = ReductionStartValue;
3609 for (
unsigned Part = 0; Part <
UF; ++Part) {
3614 Value *StartVal = (Part == 0) ? VectorStart : Identity;
3616 cast<PHINode>(VecRdxPhi)
3631 if (
VF > 1 && Phi->
getType() != RdxDesc.getRecurrenceType()) {
3636 for (
unsigned Part = 0; Part <
UF; ++Part) {
3642 UI != RdxParts[Part]->user_end();)
3644 (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
3645 RdxParts[Part] = Extnd;
3651 for (
unsigned Part = 0; Part <
UF; ++Part) {
3661 for (
unsigned Part = 1; Part <
UF; ++Part) {
3663 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3667 ReducedPartRdx,
"bin.rdx"));
3670 Builder, MinMaxKind, ReducedPartRdx, RdxPart);
3679 if (Phi->
getType() != RdxDesc.getRecurrenceType())
3701 assert(LCSSAPhi.getNumIncomingValues() < 3 &&
"Invalid LCSSA PHI");
3705 if (LCSSAPhi.getIncomingValue(0) == LoopExitInst)
3711 int IncomingEdgeBlockIdx =
3713 assert(IncomingEdgeBlockIdx >= 0 &&
"Invalid block index");
3715 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3722 if (LCSSAPhi.getNumIncomingValues() == 1) {
3724 "Incoming value isn't loop invariant");
3744 auto isBlockOfUsePredicated = [&](
Use &U) ->
bool {
3745 auto *
I = cast<Instruction>(U.getUser());
3747 if (
auto *Phi = dyn_cast<PHINode>(
I))
3748 BB = Phi->getIncomingBlock(
3750 return BB == PredBB;
3761 Worklist.insert(InstsToReanalyze.
begin(), InstsToReanalyze.
end());
3762 InstsToReanalyze.
clear();
3765 while (!Worklist.empty()) {
3770 if (!
I || isa<PHINode>(
I) ||
I->getParent() == PredBB ||
3771 !VectorLoop->contains(
I) ||
I->mayHaveSideEffects())
3778 InstsToReanalyze.push_back(
I);
3784 I->moveBefore(&*PredBB->getFirstInsertionPt());
3785 Worklist.insert(
I->op_begin(),
I->op_end());
3797 "Non-header phis should have been handled elsewhere");
3805 for (
unsigned Part = 0; Part <
UF; ++Part) {
3827 switch (II.getKind()) {
3835 assert(P->getType()->isPointerTy() &&
"Unexpected type.");
3845 for (
unsigned Part = 0; Part <
UF; ++Part) {
3846 for (
unsigned Lane = 0; Lane < Lanes; ++Lane) {
3871 "Unexpected instruction");
3874 return !CInt || CInt->
isZero();
3879 case Instruction::Br:
3880 case Instruction::PHI:
3882 case Instruction::GetElementPtr: {
3888 auto *
GEP = cast<GetElementPtrInst>(&
I);
3904 for (
unsigned Part = 0; Part <
UF; ++Part) {
3917 for (
unsigned Part = 0; Part <
UF; ++Part) {
3922 ?
GEP->getPointerOperand()
3937 auto *NewGEP =
GEP->isInBounds()
3940 assert((
VF == 1 || NewGEP->getType()->isVectorTy()) &&
3941 "NewGEP is not a pointer vector");
3949 case Instruction::UDiv:
3950 case Instruction::SDiv:
3951 case Instruction::SRem:
3952 case Instruction::URem:
3954 case Instruction::FAdd:
3955 case Instruction::Sub:
3956 case Instruction::FSub:
3957 case Instruction::Mul:
3958 case Instruction::FMul:
3959 case Instruction::FDiv:
3960 case Instruction::FRem:
3961 case Instruction::Shl:
3962 case Instruction::LShr:
3963 case Instruction::AShr:
3964 case Instruction::And:
3965 case Instruction::Or:
3966 case Instruction::Xor: {
3968 auto *BinOp = cast<BinaryOperator>(&
I);
3971 for (
unsigned Part = 0; Part <
UF; ++Part) {
3977 VecOp->copyIRFlags(BinOp);
3991 bool InvariantCond =
4002 for (
unsigned Part = 0; Part <
UF; ++Part) {
4015 case Instruction::ICmp:
4016 case Instruction::FCmp: {
4018 bool FCmp = (I.
getOpcode() == Instruction::FCmp);
4021 for (
unsigned Part = 0; Part <
UF; ++Part) {
4040 case Instruction::ZExt:
4041 case Instruction::SExt:
4042 case Instruction::FPToUI:
4043 case Instruction::FPToSI:
4044 case Instruction::FPExt:
4045 case Instruction::PtrToInt:
4046 case Instruction::IntToPtr:
4047 case Instruction::SIToFP:
4048 case Instruction::UIToFP:
4049 case Instruction::Trunc:
4050 case Instruction::FPTrunc:
4051 case Instruction::BitCast: {
4059 for (
unsigned Part = 0; Part <
UF; ++Part) {
4070 if (isa<DbgInfoIntrinsic>(I))
4075 auto *CI = cast<CallInst>(&
I);
4077 StringRef FnName = CI->getCalledFunction()->getName();
4081 for (
Value *ArgOperand : CI->arg_operands())
4089 bool NeedToScalarize;
4091 bool UseVectorIntrinsic =
4093 assert((UseVectorIntrinsic || !NeedToScalarize) &&
4094 "Instruction should be scalarized elsewhere.");
4096 for (
unsigned Part = 0; Part <
UF; ++Part) {
4098 for (
unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
4108 if (UseVectorIntrinsic) {
4110 Type *TysForDecl[] = {CI->getType()};
4117 assert(!VFnName.
empty() &&
"Vector function name is empty.");
4124 VectorF->copyAttributesFrom(F);
4127 assert(VectorF &&
"Can't create vector function.");
4130 CI->getOperandBundlesAsDefs(OpBundles);
4133 if (isa<FPMathOperator>(V))
4145 LLVM_DEBUG(
dbgs() <<
"LV: Found an unhandled instruction: " << I);
4156 "Entry does not dominate exit.");
4166 void LoopVectorizationCostModel::collectLoopScalars(
unsigned VF) {
4170 assert(VF >= 2 && !Scalars.count(VF) &&
4171 "This function should not be visited twice for the same VF");
4185 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4186 assert(WideningDecision != CM_Unknown &&
4187 "Widening decision should be ready at this moment");
4188 if (
auto *
Store = dyn_cast<StoreInst>(MemAccess))
4189 if (
Ptr ==
Store->getValueOperand())
4190 return WideningDecision == CM_Scalarize;
4192 "Ptr is neither a value or pointer operand");
4193 return WideningDecision != CM_GatherScatter;
4198 auto isLoopVaryingBitCastOrGEP = [&](
Value *V) {
4199 return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4200 isa<GetElementPtrInst>(V)) &&
4201 !TheLoop->isLoopInvariant(V);
4211 if (!isLoopVaryingBitCastOrGEP(
Ptr))
4216 auto *
I = cast<Instruction>(
Ptr);
4217 if (Worklist.count(
I))
4224 return isa<LoadInst>(U) || isa<StoreInst>(U);
4228 PossibleNonScalarPtrs.
insert(
I);
4239 Worklist.insert(Uniforms[VF].
begin(), Uniforms[VF].
end());
4246 for (
auto *BB : TheLoop->blocks())
4247 for (
auto &
I : *BB) {
4248 if (
auto *
Load = dyn_cast<LoadInst>(&
I)) {
4249 evaluatePtrUse(
Load,
Load->getPointerOperand());
4250 }
else if (
auto *
Store = dyn_cast<StoreInst>(&
I)) {
4251 evaluatePtrUse(
Store,
Store->getPointerOperand());
4252 evaluatePtrUse(
Store,
Store->getValueOperand());
4255 for (
auto *
I : ScalarPtrs)
4256 if (!PossibleNonScalarPtrs.
count(
I)) {
4266 auto *Latch = TheLoop->getLoopLatch();
4269 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4272 Worklist.insert(Ind);
4273 Worklist.insert(IndUpdate);
4274 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Ind <<
"\n");
4275 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *IndUpdate
4282 if (ForcedScalars.count(VF))
4283 for (
auto *
I : ForcedScalars.find(VF)->second)
4291 while (Idx != Worklist.size()) {
4293 if (!isLoopVaryingBitCastOrGEP(Dst->
getOperand(0)))
4295 auto *Src = cast<Instruction>(Dst->
getOperand(0));
4297 auto *J = cast<Instruction>(U);
4298 return !TheLoop->contains(J) || Worklist.count(J) ||
4299 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4300 isScalarUse(J, Src));
4302 Worklist.insert(Src);
4303 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Src <<
"\n");
4311 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4324 auto *
I = cast<Instruction>(U);
4325 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
4332 auto ScalarIndUpdate =
4334 auto *
I = cast<Instruction>(U);
4335 return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
4337 if (!ScalarIndUpdate)
4341 Worklist.insert(Ind);
4342 Worklist.insert(IndUpdate);
4343 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *Ind <<
"\n");
4344 LLVM_DEBUG(
dbgs() <<
"LV: Found scalar instruction: " << *IndUpdate
4348 Scalars[
VF].insert(Worklist.begin(), Worklist.end());
4363 return isa<LoadInst>(
I) ?
4364 !(isLegalMaskedLoad(Ty,
Ptr) || isLegalMaskedGather(Ty))
4365 : !(isLegalMaskedStore(Ty,
Ptr) || isLegalMaskedScatter(Ty));
4367 case Instruction::UDiv:
4368 case Instruction::SDiv:
4369 case Instruction::SRem:
4370 case Instruction::URem:
4381 assert((LI || SI) &&
"Invalid memory instruction");
4391 if (isScalarWithPredication(I))
4397 auto *ScalarTy = LI ? LI->
getType() : SI->getValueOperand()->getType();
4404 void LoopVectorizationCostModel::collectLoopUniforms(
unsigned VF) {
4410 assert(VF >= 2 && !Uniforms.count(VF) &&
4411 "This function should not be visited twice for the same VF");
4415 Uniforms[
VF].clear();
4423 auto isOutOfScope = [&](
Value *V) ->
bool {
4425 return (!I || !TheLoop->contains(I));
4435 if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) {
4437 LLVM_DEBUG(
dbgs() <<
"LV: Found uniform instruction: " << *Cmp <<
"\n");
4450 InstWidening WideningDecision = getWideningDecision(I, VF);
4451 assert(WideningDecision != CM_Unknown &&
4452 "Widening decision should be ready at this moment");
4454 return (WideningDecision == CM_Widen ||
4455 WideningDecision == CM_Widen_Reverse ||
4456 WideningDecision == CM_Interleave);
4466 for (
auto *BB : TheLoop->blocks())
4467 for (
auto &I : *BB) {
4475 auto UsersAreMemAccesses =
4484 if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
4496 for (
auto *V : ConsecutiveLikePtrs)
4497 if (!PossibleNonUniformPtrs.
count(V)) {
4498 LLVM_DEBUG(
dbgs() <<
"LV: Found uniform instruction: " << *V <<
"\n");
4507 while (idx != Worklist.
size()) {
4511 if (isOutOfScope(OV))
4513 auto *OI = cast<Instruction>(OV);
4515 auto *J = cast<Instruction>(U);
4516 return !TheLoop->contains(J) || Worklist.
count(J) ||
4518 isUniformDecision(J, VF));
4521 LLVM_DEBUG(
dbgs() <<
"LV: Found uniform instruction: " << *OI <<
"\n");
4540 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4545 auto *I = cast<Instruction>(U);
4546 return I == IndUpdate || !TheLoop->contains(I) || Worklist.
count(I) ||
4547 isVectorizedMemAccessUse(I, Ind);
4554 auto UniformIndUpdate =
4556 auto *I = cast<Instruction>(U);
4557 return I == Ind || !TheLoop->contains(I) || Worklist.
count(I) ||
4558 isVectorizedMemAccessUse(I, IndUpdate);
4560 if (!UniformIndUpdate)
4565 Worklist.
insert(IndUpdate);
4566 LLVM_DEBUG(
dbgs() <<
"LV: Found uniform instruction: " << *Ind <<
"\n");
4567 LLVM_DEBUG(
dbgs() <<
"LV: Found uniform instruction: " << *IndUpdate
4571 Uniforms[
VF].insert(Worklist.
begin(), Worklist.
end());
4574 void InterleavedAccessInfo::collectConstStrideAccesses(
4577 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
4588 for (
auto &
I : *BB) {
4614 AccessStrideInfo[&
I] = StrideDescriptor(Stride, Scev, Size, Align);
4654 void InterleavedAccessInfo::analyzeInterleaving() {
4660 collectConstStrideAccesses(AccessStrideInfo, Strides);
4662 if (AccessStrideInfo.
empty())
4666 collectDependences();
4685 for (
auto BI = AccessStrideInfo.
rbegin(),
E = AccessStrideInfo.
rend();
4688 StrideDescriptor DesB = BI->second;
4694 if (isStrided(DesB.Stride)) {
4695 Group = getInterleaveGroup(B);
4697 LLVM_DEBUG(
dbgs() <<
"LV: Creating an interleave group with:" << *B
4699 Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
4702 StoreGroups.
insert(Group);
4704 LoadGroups.
insert(Group);
4707 for (
auto AI = std::next(BI); AI !=
E; ++AI) {
4709 StrideDescriptor DesA = AI->second;
4730 if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
4736 if (isInterleaved(A)) {
4738 StoreGroups.
remove(StoreGroup);
4739 releaseGroup(StoreGroup);
4752 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
4767 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
4784 if (DistanceToB % static_cast<int64_t>(DesB.Size))
4797 Group->
getIndex(B) + DistanceToB /
static_cast<int64_t
>(DesB.Size);
4802 <<
" into the interleave group with" << *B
4804 InterleaveGroupMap[A] = Group;
4815 if (Group->getNumMembers() != Group->getFactor()) {
4817 dbgs() <<
"LV: Invalidate candidate interleaved store group due " 4819 releaseGroup(Group);
4839 if (Group->getNumMembers() == Group->getFactor())
4851 dbgs() <<
"LV: Invalidate candidate interleaved group due to " 4852 "first group member potentially pointer-wrapping.\n");
4853 releaseGroup(Group);
4856 Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
4862 dbgs() <<
"LV: Invalidate candidate interleaved group due to " 4863 "last group member potentially pointer-wrapping.\n");
4864 releaseGroup(Group);
4872 if (Group->isReverse()) {
4874 dbgs() <<
"LV: Invalidate candidate interleaved group due to " 4875 "a reverse access with gaps.\n");
4876 releaseGroup(Group);
4880 dbgs() <<
"LV: Interleaved group requires epilogue iteration.\n");
4881 RequiresScalarEpilogue =
true;
4891 dbgs() <<
"LV: Not inserting runtime ptr check for divergent target");
4894 createMissedAnalysis(
"CantVersionLoopWithDivergentTarget")
4895 <<
"runtime pointer checks needed. Not enabled for divergent target");
4902 return computeFeasibleMaxVF(OptForSize, TC);
4905 ORE->
emit(createMissedAnalysis(
"CantVersionLoopWithOptForSize")
4906 <<
"runtime pointer checks needed. Enable vectorization of this " 4907 "loop with '#pragma clang loop vectorize(enable)' when " 4908 "compiling with -Os/-Oz");
4911 <<
"LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
4921 createMissedAnalysis(
"UnknownLoopCountComplexCFG")
4922 <<
"unable to calculate the loop count due to complex control flow");
4924 dbgs() <<
"LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4928 unsigned MaxVF = computeFeasibleMaxVF(OptForSize, TC);
4930 if (TC % MaxVF != 0) {
4937 ORE->
emit(createMissedAnalysis(
"NoTailLoopWithOptForSize")
4938 <<
"cannot optimize for size and vectorize at the " 4939 "same time. Enable vectorization of this loop " 4940 "with '#pragma clang loop vectorize(enable)' " 4941 "when compiling with -Os/-Oz");
4943 dbgs() <<
"LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4951 LoopVectorizationCostModel::computeFeasibleMaxVF(
bool OptForSize,
4952 unsigned ConstTripCount) {
4954 unsigned SmallestType, WidestType;
4955 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
4964 WidestRegister = std::min(WidestRegister, MaxSafeRegisterWidth);
4966 unsigned MaxVectorSize = WidestRegister / WidestType;
4968 LLVM_DEBUG(
dbgs() <<
"LV: The Smallest and Widest types: " << SmallestType
4969 <<
" / " << WidestType <<
" bits.\n");
4971 << WidestRegister <<
" bits.\n");
4973 assert(MaxVectorSize <= 256 &&
"Did not expect to pack so many elements" 4974 " into one vector!");
4975 if (MaxVectorSize == 0) {
4976 LLVM_DEBUG(
dbgs() <<
"LV: The target has no vector registers.\n");
4978 return MaxVectorSize;
4979 }
else if (ConstTripCount && ConstTripCount < MaxVectorSize &&
4983 LLVM_DEBUG(
dbgs() <<
"LV: Clamping the MaxVF to the constant trip count: " 4984 << ConstTripCount <<
"\n");
4985 MaxVectorSize = ConstTripCount;
4986 return MaxVectorSize;
4989 unsigned MaxVF = MaxVectorSize;
4995 unsigned NewMaxVectorSize = WidestRegister / SmallestType;
4996 for (
unsigned VS = MaxVectorSize * 2;
VS <= NewMaxVectorSize;
VS *= 2)
5000 auto RUs = calculateRegisterUsage(VFs);
5005 for (
int i = RUs.size() - 1; i >= 0; --i) {
5006 if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
5012 if (MaxVF < MinVF) {
5014 <<
") with target's minimum: " << MinVF <<
'\n');
5024 float Cost = expectedCost(1).first;
5025 const float ScalarCost =
Cost;
5027 LLVM_DEBUG(
dbgs() <<
"LV: Scalar loop costs: " << (
int)ScalarCost <<
".\n");
5030 if (ForceVectorization && MaxVF > 1) {
5037 for (
unsigned i = 2; i <= MaxVF; i *= 2) {
5041 VectorizationCostTy
C = expectedCost(i);
5042 float VectorCost = C.first / (float)i;
5044 <<
" costs: " << (
int)VectorCost <<
".\n");
5045 if (!C.second && !ForceVectorization) {
5047 dbgs() <<
"LV: Not considering vector loop of width " << i
5048 <<
" because it will not generate any vector instructions.\n");
5051 if (VectorCost < Cost) {
5058 ORE->
emit(createMissedAnalysis(
"ConditionalStore")
5059 <<
"store that is conditionally executed prevents vectorization");
5061 dbgs() <<
"LV: No vectorization. There are conditional stores.\n");
5066 LLVM_DEBUG(
if (ForceVectorization && Width > 1 && Cost >= ScalarCost)
dbgs()
5067 <<
"LV: Vectorization seems to be not beneficial, " 5068 <<
"but was forced by a user.\n");
5074 std::pair<unsigned, unsigned>
5076 unsigned MinWidth = -1U;
5077 unsigned MaxWidth = 8;
5078 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5087 if (ValuesToIgnore.count(&
I))
5091 if (!isa<LoadInst>(
I) && !isa<StoreInst>(
I) && !isa<PHINode>(
I))
5096 if (
auto *PN = dyn_cast<PHINode>(&
I)) {
5104 if (
auto *
ST = dyn_cast<StoreInst>(&
I))
5105 T =
ST->getValueOperand()->getType();
5116 if (T->
isPointerTy() && !isConsecutiveLoadOrStore(&
I) &&
5117 !isAccessInterleaved(&
I) && !isLegalGatherOrScatter(&
I))
5120 MinWidth = std::min(MinWidth,
5127 return {MinWidth, MaxWidth};
5132 unsigned LoopCost) {
5157 if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
5208 LoopCost = expectedCost(VF).first;
5212 if (IC > MaxInterleaveCount)
5213 IC = MaxInterleaveCount;
5220 LLVM_DEBUG(
dbgs() <<
"LV: Interleaving because of reductions.\n");
5226 bool InterleavingRequiresRuntimePointerCheck =
5232 if (!InterleavingRequiresRuntimePointerCheck && LoopCost <
SmallLoopCost) {
5243 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5244 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5252 SmallIC = std::min(SmallIC, F);
5253 StoresIC = std::min(StoresIC, F);
5254 LoadsIC = std::min(LoadsIC, F);
5258 std::max(StoresIC, LoadsIC) > SmallIC) {
5260 dbgs() <<
"LV: Interleaving to saturate store or load ports.\n");
5261 return std::max(StoresIC, LoadsIC);
5264 LLVM_DEBUG(
dbgs() <<
"LV: Interleaving to reduce branch cost.\n");
5322 IdxToInstr[Index++] = &
I;
5325 for (
Value *U :
I.operands()) {
5333 if (!TheLoop->contains(Instr)) {
5334 LoopInvariants.
insert(Instr);
5339 EndPoint[Instr] =
Index;
5356 unsigned MaxSafeDepDist = -1U;
5359 unsigned WidestRegister =
5361 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5366 LLVM_DEBUG(
dbgs() <<
"LV(REG): Calculating max register usage:\n");
5369 auto GetRegUsage = [&DL, WidestRegister](
Type *Ty,
unsigned VF) {
5370 if (Ty->isTokenTy())
5372 unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
5373 return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
5376 for (
unsigned int i = 0; i <
Index; ++i) {
5380 InstrList &
List = TransposeEnds[i];
5382 OpenIntervals.
erase(ToRemove);
5389 if (ValuesToIgnore.count(I))
5393 for (
unsigned j = 0, e = VFs.
size(); j < e; ++j) {
5395 MaxUsages[j] =
std::max(MaxUsages[j], OpenIntervals.
size());
5398 collectUniformsAndScalars(VFs[j]);
5401 for (
auto Inst : OpenIntervals) {
5403 if (VecValuesToIgnore.count(Inst) ||
5404 isScalarAfterVectorization(Inst, VFs[j]))
5406 RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
5408 MaxUsages[j] =
std::max(MaxUsages[j], RegUsage);
5412 << OpenIntervals.
size() <<
'\n');
5418 for (
unsigned i = 0, e = VFs.
size(); i < e; ++i) {
5419 unsigned Invariant = 0;
5421 Invariant = LoopInvariants.
size();
5423 for (
auto Inst : LoopInvariants)
5424 Invariant += GetRegUsage(Inst->getType(), VFs[i]);
5428 LLVM_DEBUG(
dbgs() <<
"LV(REG): Found max usage: " << MaxUsages[i] <<
'\n');
5429 LLVM_DEBUG(
dbgs() <<
"LV(REG): Found invariant usage: " << Invariant
5440 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(
Instruction *
I){
5449 assert(isScalarWithPredication(I) &&
5450 "Expecting a scalar emulated instruction");
5451 return isa<LoadInst>(
I) ||
5452 (isa<StoreInst>(I) &&
5461 if (VF < 2 || InstsToScalarize.count(VF))
5476 if (isScalarWithPredication(&I)) {
5480 if (!useEmulatedMaskMemRefHack(&I) &&
5481 computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
5484 PredicatedBBsAfterVectorization.insert(BB);
5489 int LoopVectorizationCostModel::computePredInstDiscount(
5492 assert(!isUniformAfterVectorization(PredInst, VF) &&
5493 "Instruction marked uniform-after-vectorization will be predicated");
5512 isScalarAfterVectorization(I, VF))
5517 if (isScalarWithPredication(I))
5531 if (
auto *J = dyn_cast<Instruction>(U.get()))
5532 if (isUniformAfterVectorization(J, VF))
5545 return TheLoop->contains(I) && !isScalarAfterVectorization(I, VF);
5552 while (!Worklist.
empty()) {
5556 if (ScalarCosts.
count(I))
5561 unsigned VectorCost = getInstructionCost(I, VF).first;
5567 unsigned ScalarCost = VF * getInstructionCost(I, 1).first;
5582 if (
auto *J = dyn_cast<Instruction>(U.get())) {
5584 "Instruction has non-scalar type");
5585 if (canBeScalarized(J))
5587 else if (needsExtract(J))
5597 Discount += VectorCost - ScalarCost;
5598 ScalarCosts[
I] = ScalarCost;
5604 LoopVectorizationCostModel::VectorizationCostTy
5605 LoopVectorizationCostModel::expectedCost(
unsigned VF) {
5606 VectorizationCostTy
Cost;
5610 VectorizationCostTy BlockCost;
5613 for (
Instruction &I : BB->instructionsWithoutDebug()) {
5615 if (ValuesToIgnore.count(&I) ||
5616 (VF > 1 && VecValuesToIgnore.count(&I)))
5619 VectorizationCostTy
C = getInstructionCost(&I, VF);
5625 BlockCost.first += C.first;
5626 BlockCost.second |= C.second;
5627 LLVM_DEBUG(
dbgs() <<
"LV: Found an estimated cost of " << C.first
5628 <<
" for VF " << VF <<
" For instruction: " << I
5641 Cost.first += BlockCost.first;
5642 Cost.second |= BlockCost.second;
5657 const Loop *TheLoop) {
5665 auto SE = PSE.
getSE();
5666 unsigned NumOperands = Gep->getNumOperands();
5667 for (
unsigned i = 1; i < NumOperands; ++i) {
5668 Value *Opd = Gep->getOperand(i);
5669 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5683 unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(
Instruction *I,
5711 if (isScalarWithPredication(I)) {
5714 if (useEmulatedMaskMemRefHack(I))
5723 unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(
Instruction *I,
5732 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
5733 "Stride should be 1 or -1 for consecutive memory access");
5740 bool Reverse = ConsecutiveStride < 0;
5746 unsigned LoopVectorizationCostModel::getUniformMemOpCost(
Instruction *I,
5759 unsigned LoopVectorizationCostModel::getGatherScatterCost(
Instruction *I,
5771 unsigned LoopVectorizationCostModel::getInterleaveGroupCost(
Instruction *I,
5777 auto Group = getInterleavedAccessGroup(I);
5778 assert(Group &&
"Fail to get an interleaved access group.");
5780 unsigned InterleaveFactor = Group->getFactor();
5786 if (isa<LoadInst>(I)) {
5787 for (
unsigned i = 0; i < InterleaveFactor; i++)
5788 if (Group->getMember(i))
5794 Group->getFactor(), Indices,
5795 Group->getAlignment(),
AS);
5797 if (Group->isReverse())
5798 Cost += Group->getNumMembers() *
5803 unsigned LoopVectorizationCostModel::getMemoryInstructionCost(
Instruction *I,
5815 return getWideningCost(I, VF);
5818 LoopVectorizationCostModel::VectorizationCostTy
5819 LoopVectorizationCostModel::getInstructionCost(
Instruction *I,
unsigned VF) {
5822 if (isUniformAfterVectorization(I, VF))
5825 if (VF > 1 && isProfitableToScalarize(I, VF))
5826 return VectorizationCostTy(InstsToScalarize[VF][I],
false);
5829 if (VF > 1 && ForcedScalars.count(VF) &&
5830 ForcedScalars.find(VF)->second.count(I))
5831 return VectorizationCostTy((getInstructionCost(I, 1).
first * VF),
false);
5834 unsigned C = getInstructionCost(I, VF, VectorTy);
5836 bool TypeNotScalarized =
5838 return VectorizationCostTy(C, TypeNotScalarized);
5852 if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
5856 unsigned Cost = getUniformMemOpCost(&I, VF);
5857 setWideningDecision(&I, VF, CM_Scalarize, Cost);
5862 if (memoryInstructionCanBeWidened(&I, VF)) {
5863 unsigned Cost = getConsecutiveMemOpCost(&I, VF);
5864 int ConsecutiveStride =
5866 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
5867 "Expected consecutive stride.");
5869 ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
5870 setWideningDecision(&I, VF, Decision, Cost);
5876 unsigned NumAccesses = 1;
5877 if (isAccessInterleaved(&I)) {
5878 auto Group = getInterleavedAccessGroup(&I);
5879 assert(Group &&
"Fail to get an interleaved access group.");
5882 if (getWideningDecision(&I, VF) != CM_Unknown)
5885 NumAccesses = Group->getNumMembers();
5886 InterleaveCost = getInterleaveGroupCost(&I, VF);
5889 unsigned GatherScatterCost =
5890 isLegalGatherOrScatter(&I)
5891 ? getGatherScatterCost(&I, VF) * NumAccesses
5894 unsigned ScalarizationCost =
5895 getMemInstScalarizationCost(&I, VF) * NumAccesses;
5901 if (InterleaveCost <= GatherScatterCost &&
5902 InterleaveCost < ScalarizationCost) {
5903 Decision = CM_Interleave;
5904 Cost = InterleaveCost;
5905 }
else if (GatherScatterCost < ScalarizationCost) {
5906 Decision = CM_GatherScatter;
5907 Cost = GatherScatterCost;
5909 Decision = CM_Scalarize;
5910 Cost = ScalarizationCost;
5915 if (
auto Group = getInterleavedAccessGroup(&I))
5916 setWideningDecision(Group, VF, Decision, Cost);
5918 setWideningDecision(&I, VF, Decision, Cost);
5936 if (PtrDef && TheLoop->contains(PtrDef) &&
5937 getWideningDecision(&I, VF) != CM_GatherScatter)
5943 for (
auto *I : AddrDefs)
5945 while (!Worklist.
empty()) {
5948 if (
auto *InstOp = dyn_cast<Instruction>(
Op))
5949 if ((InstOp->getParent() == I->
getParent()) && !isa<PHINode>(InstOp) &&
5950 AddrDefs.insert(InstOp).second)
5954 for (
auto *I : AddrDefs) {
5955 if (isa<LoadInst>(I)) {
5961 if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
5963 setWideningDecision(I, VF, CM_Scalarize,
5964 (VF * getMemoryInstructionCost(I, 1)));
5965 else if (
auto Group = getInterleavedAccessGroup(I)) {
5967 for (
unsigned I = 0; I < Group->getFactor(); ++
I) {
5969 setWideningDecision(Member, VF, CM_Scalarize,
5970 (VF * getMemoryInstructionCost(Member, 1)));
5976 ForcedScalars[
VF].insert(I);
5980 unsigned LoopVectorizationCostModel::getInstructionCost(
Instruction *I,
5984 if (canTruncateToMinimalBitwidth(I, VF))
5986 VectorTy = isScalarAfterVectorization(I, VF) ? RetTy :
ToVectorTy(RetTy, VF);
5991 case Instruction::GetElementPtr:
5997 case Instruction::Br: {
6001 bool ScalarPredicatedBB =
false;
6004 (PredicatedBBsAfterVectorization.count(BI->
getSuccessor(0)) ||
6005 PredicatedBBsAfterVectorization.count(BI->
getSuccessor(1))))
6006 ScalarPredicatedBB =
true;
6008 if (ScalarPredicatedBB) {
6014 }
else if (I->
getParent() == TheLoop->getLoopLatch() || VF == 1)
6024 case Instruction::PHI: {
6025 auto *Phi = cast<PHINode>(
I);
6030 VectorTy, VF - 1, VectorTy);
6035 if (VF > 1 && Phi->getParent() != TheLoop->getHeader())
6036 return (Phi->getNumIncomingValues() - 1) *
6043 case Instruction::UDiv:
6044 case Instruction::SDiv:
6045 case Instruction::URem:
6046 case Instruction::SRem:
6051 if (VF > 1 && isScalarWithPredication(I)) {
6074 case Instruction::FAdd:
6075 case Instruction::Sub:
6076 case Instruction::FSub:
6077 case Instruction::Mul:
6078 case Instruction::FMul:
6079 case Instruction::FDiv:
6080 case Instruction::FRem:
6081 case Instruction::Shl:
6082 case Instruction::LShr:
6083 case Instruction::AShr:
6084 case Instruction::And:
6085 case Instruction::Or:
6086 case Instruction::Xor: {
6103 if (isa<ConstantInt>(Op2)) {
6108 }
else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
6121 unsigned N = isScalarAfterVectorization(I, VF) ?
VF : 1;
6123 Op2VK, Op1VP, Op2VP, Operands);
6128 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
6135 case Instruction::ICmp:
6136 case Instruction::FCmp: {
6139 if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
6146 unsigned Width =
VF;
6149 assert(Decision != CM_Unknown &&
6150 "CM decision should be taken at this point");
6151 if (Decision == CM_Scalarize)
6155 return getMemoryInstructionCost(I, VF);
6157 case Instruction::ZExt:
6158 case Instruction::SExt:
6159 case Instruction::FPToUI:
6160 case Instruction::FPToSI:
6161 case Instruction::FPExt:
6162 case Instruction::PtrToInt:
6163 case Instruction::IntToPtr:
6164 case Instruction::SIToFP:
6165 case Instruction::UIToFP:
6166 case Instruction::Trunc:
6167 case Instruction::FPTrunc:
6168 case Instruction::BitCast: {
6172 if (isOptimizableIVTruncate(I, VF)) {
6173 auto *Trunc = cast<TruncInst>(
I);
6175 Trunc->getSrcTy(), Trunc);
6181 if (canTruncateToMinimalBitwidth(I, VF)) {
6187 Type *MinVecTy = VectorTy;
6188 if (I->
getOpcode() == Instruction::Trunc) {
6192 }
else if (I->
getOpcode() == Instruction::ZExt ||
6200 unsigned N = isScalarAfterVectorization(I, VF) ?
VF : 1;
6204 bool NeedToScalarize;
6221 static const char lv_name[] =
"Loop Vectorization";
6241 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
6246 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(
Instruction *Inst) {
6263 VecValuesToIgnore.insert(Casts.
begin(), Casts.
end());
6270 VecValuesToIgnore.insert(Casts.
begin(), Casts.
end());
6292 assert(UserVF &&
"Expected UserVF for outer loop vectorization.");
6295 buildVPlans(UserVF, UserVF);
6299 return NoVectorization;
6305 dbgs() <<
"LV: Not vectorizing. Inner loops aren't supported in the " 6306 "VPlan-native path.\n");
6307 return NoVectorization;
6317 return NoVectorization;
6324 CM.selectUserVectorizationFactor(UserVF);
6325 buildVPlansWithVPRecipes(UserVF, UserVF);
6330 unsigned MaxVF = MaybeMaxVF.
getValue();
6331 assert(MaxVF != 0 &&
"MaxVF is zero.");
6333 for (
unsigned VF = 1; VF <= MaxVF; VF *= 2) {
6335 CM.collectUniformsAndScalars(VF);
6340 CM.collectInstsToScalarize(VF);
6343 buildVPlansWithVPRecipes(1, MaxVF);
6346 return NoVectorization;
6349 return CM.selectVectorizationFactor(MaxVF);
6353 LLVM_DEBUG(
dbgs() <<
"Setting best plan to VF=" << VF <<
", UF=" << UF
6358 erase_if(VPlans, [VF](
const VPlanPtr &Plan) {
6359 return !Plan->hasVF(VF);
6361 assert(VPlans.size() == 1 &&
"Best VF has not a single VPlan.");
6369 VPCallbackILV CallbackILV(ILV);
6385 assert(VPlans.size() == 1 &&
"Not a single VPlan to execute.");
6386 VPlans.front()->execute(&State);
6401 if (Cmp && Cmp->hasOneUse())
6402 DeadInstructions.
insert(Cmp);
6411 return U == Ind || DeadInstructions.
count(cast<Instruction>(U));
6413 DeadInstructions.
insert(IndUpdate);
6429 Value *InnerLoopUnroller::reverseVector(
Value *Vec) {
return Vec; }
6431 Value *InnerLoopUnroller::getBroadcastInstrs(
Value *V) {
return V; }
6433 Value *InnerLoopUnroller::getStepVector(
Value *Val,
int StartIdx,
Value *Step,
6454 bool IsUnrollMetadata =
false;
6458 for (
unsigned i = 1, ie = LoopID->
getNumOperands(); i < ie; ++i) {
6463 S && S->getString().startswith(
"llvm.loop.unroll.disable");
6469 if (!IsUnrollMetadata) {
6474 MDString::get(Context,
"llvm.loop.unroll.runtime.disable"));
6486 assert(Range.
End > Range.
Start &&
"Trying to test an empty VF range.");
6489 for (
unsigned TmpVF = Range.
Start * 2; TmpVF < Range.
End; TmpVF *= 2)
6490 if (
Predicate(TmpVF) != PredicateAtRangeStart) {
6495 return PredicateAtRangeStart;
6504 for (
unsigned VF = MinVF; VF < MaxVF + 1;) {
6506 VPlans.push_back(buildVPlan(SubRange));
6516 std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
6518 if (ECEntryIt != EdgeMaskCache.end())
6519 return ECEntryIt->second;
6521 VPValue *SrcMask = createBlockInMask(Src, Plan);
6525 assert(BI &&
"Unexpected terminator found");
6528 return EdgeMaskCache[Edge] = SrcMask;
6531 assert(EdgeMask &&
"No Edge Mask found for condition");
6534 EdgeMask =
Builder.createNot(EdgeMask);
6537 EdgeMask =
Builder.createAnd(EdgeMask, SrcMask);
6539 return EdgeMaskCache[Edge] = EdgeMask;
6547 if (BCEntryIt != BlockMaskCache.end())
6548 return BCEntryIt->second;
6556 return BlockMaskCache[BB] = BlockMask;
6560 VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
6562 return BlockMaskCache[BB] = EdgeMask;
6565 BlockMask = EdgeMask;
6569 BlockMask =
Builder.createOr(BlockMask, EdgeMask);
6572 return BlockMaskCache[BB] = BlockMask;
6583 return [=](
unsigned VF) ->
bool {
6585 CM.getWideningDecision(I, VF) ==
6596 "Generating a recipe for an adjunct member of an interleave group");
6604 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
6607 auto willWiden = [&](
unsigned VF) ->
bool {
6610 if (CM.isScalarAfterVectorization(I, VF) ||
6611 CM.isProfitableToScalarize(I, VF))
6614 CM.getWideningDecision(I, VF);
6616 "CM decision should be taken at this point.");
6618 "Interleave memory opportunity should be caught earlier.");
6627 Mask = createBlockInMask(I->
getParent(), Plan);
6634 if (
PHINode *Phi = dyn_cast<PHINode>(I)) {
6652 auto isOptimizableIVTruncate =
6655 [=](
unsigned VF) ->
bool {
return CM.isOptimizableIVTruncate(K, VF); };
6659 isOptimizableIVTruncate(I), Range))
6661 cast<TruncInst>(I));
6678 for (
unsigned In = 0;
In < NumIncoming;
In++) {
6681 assert((EdgeMask || NumIncoming == 1) &&
6682 "Multiple predecessors with one having a full mask");
6691 if (CM.isScalarWithPredication(I))
6694 auto IsVectorizableOpcode = [](
unsigned Opcode) {
6697 case Instruction::And:
6698 case Instruction::AShr:
6699 case Instruction::BitCast:
6700 case Instruction::Br:
6702 case Instruction::FAdd:
6703 case Instruction::FCmp:
6704 case Instruction::FDiv:
6705 case Instruction::FMul:
6706 case Instruction::FPExt:
6707 case Instruction::FPToSI:
6708 case Instruction::FPToUI:
6709 case Instruction::FPTrunc:
6710 case Instruction::FRem:
6711 case Instruction::FSub:
6712 case Instruction::GetElementPtr:
6713 case Instruction::ICmp:
6714 case Instruction::IntToPtr:
6716 case Instruction::LShr:
6717 case Instruction::Mul:
6718 case Instruction::Or:
6719 case Instruction::PHI:
6720 case Instruction::PtrToInt:
6721 case Instruction::SDiv:
6723 case Instruction::SExt:
6724 case Instruction::Shl:
6725 case Instruction::SIToFP:
6726 case Instruction::SRem:
6728 case Instruction::Sub:
6729 case Instruction::Trunc:
6730 case Instruction::UDiv:
6731 case Instruction::UIToFP:
6732 case Instruction::URem:
6733 case Instruction::Xor:
6734 case Instruction::ZExt:
6740 if (!IsVectorizableOpcode(I->
getOpcode()))
6743 if (
CallInst *CI = dyn_cast<CallInst>(I)) {
6745 if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
6746 ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect))
6750 auto willWiden = [&](
unsigned VF) ->
bool {
6751 if (!isa<PHINode>(I) && (CM.isScalarAfterVectorization(I, VF) ||
6752 CM.isProfitableToScalarize(I, VF)))
6754 if (
CallInst *CI = dyn_cast<CallInst>(I)) {
6760 bool NeedToScalarize;
6762 bool UseVectorIntrinsic =
6764 return UseVectorIntrinsic || !NeedToScalarize;
6766 if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
6767 assert(CM.getWideningDecision(I, VF) ==
6769 "Memory widening decisions should have been taken care by now");
6780 if (!VPBB->
empty()) {
6795 [&](
unsigned VF) {
return CM.isUniformAfterVectorization(I, VF); },
6798 bool IsPredicated = CM.isScalarWithPredication(I);
6805 if (
auto *PredInst = dyn_cast<Instruction>(
Op))
6806 if (PredInst2Recipe.
find(PredInst) != PredInst2Recipe.
end())
6807 PredInst2Recipe[PredInst]->setAlsoPack(
false);
6810 if (!IsPredicated) {
6815 LLVM_DEBUG(
dbgs() <<
"LV: Scalarizing and predicating:" << *I <<
"\n");
6817 "VPBB has successors when handling predicated replication.");
6819 PredInst2Recipe[
I] = Recipe;
6838 assert(Instr->
getParent() &&
"Predicated instruction not in any basic block");
6860 if ((Recipe = tryToInterleaveMemory(Instr, Range))) {
6866 if ((Recipe = tryToWidenMemory(Instr, Range, Plan))) {
6872 if ((Recipe = tryToOptimizeInduction(Instr, Range))) {
6876 if ((Recipe = tryToBlend(Instr, Plan))) {
6880 if (
PHINode *Phi = dyn_cast<PHINode>(Instr)) {
6888 if (tryToWiden(Instr, VPBB, Range))
6894 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(
unsigned MinVF,
6918 collectTriviallyDeadInstructions(DeadInstructions);
6920 for (
unsigned VF = MinVF; VF < MaxVF + 1;) {
6923 buildVPlanWithVPRecipes(SubRange, NeedDef, DeadInstructions));
6928 LoopVectorizationPlanner::VPlanPtr
6929 LoopVectorizationPlanner::buildVPlanWithVPRecipes(
6942 auto Plan = llvm::make_unique<VPlan>(VPBB);
6946 for (
Value *V : NeedDef)
6947 Plan->addVPValue(V);
6957 unsigned VPBBsForBB = 0;
6958 auto *FirstVPBBForBB =
new VPBasicBlock(BB->getName());
6960 VPBB = FirstVPBBForBB;
6963 std::vector<Instruction *> Ingredients;
6967 for (
Instruction &I : BB->instructionsWithoutDebug()) {
6972 if (isa<BranchInst>(Instr) || DeadInstructions.
count(Instr))
6980 CM.getWideningDecision(Instr, Range.
Start) ==
6982 if (SinkAfterInverse.
count(Instr))
6983 Ingredients.push_back(SinkAfterInverse.
find(Instr)->second);
6990 auto SAIt = SinkAfter.
find(Instr);
6991 if (SAIt != SinkAfter.
end()) {
6994 <<
" to vectorize a 1st order recurrence.\n");
6995 SinkAfterInverse[SAIt->second] = Instr;
6999 Ingredients.push_back(Instr);
7003 auto SAInvIt = SinkAfterInverse.
find(Instr);
7004 if (SAInvIt != SinkAfterInverse.
end())
7005 Ingredients.push_back(SAInvIt->second);
7010 if (RecipeBuilder.tryToCreateRecipe(Instr, Range, Plan, VPBB))
7015 VPBasicBlock *NextVPBB = RecipeBuilder.handleReplication(
7016 Instr, Range, VPBB, PredInst2Recipe, Plan);
7017 if (NextVPBB != VPBB) {
7019 VPBB->
setName(BB->hasName() ? BB->getName() +
"." +
Twine(VPBBsForBB++)
7028 VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
7029 assert(PreEntry->
empty() &&
"Expecting empty pre-entry block.");
7034 std::string PlanName;
7036 unsigned VF = Range.
Start;
7038 RSO <<
"Initial VPlan for VF={" <<
VF;
7039 for (VF *= 2; VF < Range.
End; VF *= 2) {
7045 Plan->setName(PlanName);
7050 LoopVectorizationPlanner::VPlanPtr
7051 LoopVectorizationPlanner::buildVPlan(
VFRange &Range) {
7060 auto Plan = llvm::make_unique<VPlan>();
7064 HCFGBuilder.buildHierarchicalCFG();
7069 Value* LoopVectorizationPlanner::VPCallbackILV::
7070 getOrCreateVectorValues(
Value *V,
unsigned Part) {
7071 return ILV.getOrCreateVectorValue(V, Part);
7076 << Indent <<
"\"INTERLEAVE-GROUP with factor " << IG->getFactor() <<
" at ";
7077 IG->getInsertPos()->printAsOperand(O,
false);
7079 for (
unsigned i = 0; i < IG->getFactor(); ++i)
7091 assert(!State.
Instance &&
"Int or FP induction being replicated.");
7108 unsigned NumIncoming = Phi->getNumIncomingValues();
7111 "Multiple predecessors with predecessors having a full mask");
7117 for (
unsigned In = 0;
In < NumIncoming; ++
In) {
7118 for (
unsigned Part = 0; Part < State.
UF; ++Part) {
7134 for (
unsigned Part = 0; Part < State.
UF; ++Part)
7147 if (AlsoPack && State.
VF > 1) {
7162 unsigned EndLane = IsUniform ? 1 : State.
VF;
7163 for (
unsigned Part = 0; Part < State.
UF; ++Part)
7164 for (
unsigned Lane = 0; Lane < EndLane; ++Lane)
7169 assert(State.
Instance &&
"Branch on Mask works only on single instance.");
7171 unsigned Part = State.
Instance->Part;
7172 unsigned Lane = State.
Instance->Lane;
7174 Value *ConditionBit =
nullptr;
7179 ConditionBit = State.
get(BlockInMask, Part);
7188 assert(isa<UnreachableInst>(CurrentTerminator) &&
7189 "Expected to replace unreachable terminator with conditional branch.");
7191 CondBr->setSuccessor(0,
nullptr);
7196 assert(State.
Instance &&
"Predicated instruction PHI works per instance.");
7201 assert(PredicatingBB &&
"Predicated block has no single predecessor.");
7209 unsigned Part = State.
Instance->Part;
7215 VPhi->addIncoming(IEI, PredicatedBB);
7233 for (
unsigned Part = 0; Part < State.
UF; ++Part)
7234 MaskValues[Part] = State.
get(Mask, Part);
7250 InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->
getLAI());
7251 LoopVectorizationCostModel CM(L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
7259 unsigned UserVF = Hints.
getWidth();
7276 "VPlan-native path is not enabled. Only process inner loops.");
7284 << DebugLocStr <<
"\n");
7289 dbgs() <<
"LV: Loop hints:" 7296 <<
" width=" << Hints.getWidth()
7297 <<
" unroll=" << Hints.getInterleave() <<
"\n");
7310 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
7320 &Requirements, &Hints, DB,
AC);
7322 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: Cannot prove legality.\n");
7345 unsigned ExpectedTC = 0;
7346 bool HasExpectedTC =
false;
7348 dyn_cast<SCEVConstant>(SE->getBackedgeTakenCount(L))) {
7349 const APInt &ExitsCount = ConstExits->getAPInt();
7353 ExpectedTC =
static_cast<unsigned>(ExitsCount.
getZExtValue()) + 1;
7354 HasExpectedTC =
true;
7362 ExpectedTC = *EstimatedTC;
7363 HasExpectedTC =
true;
7366 if (!HasExpectedTC) {
7367 ExpectedTC = SE->getSmallConstantMaxTripCount(L);
7368 HasExpectedTC = (ExpectedTC > 0);
7372 LLVM_DEBUG(
dbgs() <<
"LV: Found a loop with a very small trip count. " 7373 <<
"This loop is worth vectorizing only if no scalar " 7374 <<
"iteration overheads are incurred.");
7376 LLVM_DEBUG(
dbgs() <<
" But vectorizing was explicitly forced.\n");
7390 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
7391 LLVM_DEBUG(
dbgs() <<
"LV: Can't vectorize when the NoImplicitFloat" 7392 "attribute is used.\n");
7394 "NoImplicitFloat", L)
7395 <<
"loop not vectorized due to NoImplicitFloat attribute");
7404 if (Hints.isPotentiallyUnsafe() &&
7407 dbgs() <<
"LV: Potentially unsafe FP op prevents vectorization.\n");
7410 <<
"loop not vectorized due to unsafe FP support.");
7416 InterleavedAccessInfo IAI(PSE, L,
DT,
LI, LVL.
getLAI());
7423 if (UseInterleaved) {
7424 IAI.analyzeInterleaving();
7428 LoopVectorizationCostModel CM(L, PSE,
LI, &LVL, *
TTI,
TLI, DB,
AC,
ORE, F,
7436 unsigned UserVF = Hints.getWidth();
7445 unsigned UserIC = Hints.getInterleave();
7448 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
7449 bool VectorizeLoop =
true, InterleaveLoop =
true;
7451 LLVM_DEBUG(
dbgs() <<
"LV: Not vectorizing: loop did not meet vectorization " 7457 if (VF.
Width == 1) {
7458 LLVM_DEBUG(
dbgs() <<
"LV: Vectorization is possible but not beneficial.\n");
7459 VecDiagMsg = std::make_pair(
7460 "VectorizationNotBeneficial",
7461 "the cost-model indicates that vectorization is not beneficial");
7462 VectorizeLoop =
false;
7465 if (IC == 1 && UserIC <= 1) {
7468 IntDiagMsg = std::make_pair(
7469 "InterleavingNotBeneficial",
7470 "the cost-model indicates that interleaving is not beneficial");
7471 InterleaveLoop =
false;
7473 IntDiagMsg.first =
"InterleavingNotBeneficialAndDisabled";
7474 IntDiagMsg.second +=
7475 " and is explicitly disabled or interleave count is set to 1";
7477 }
else if (IC > 1 && UserIC == 1) {
7480 dbgs() <<
"LV: Interleaving is beneficial but is explicitly disabled.");
7481 IntDiagMsg = std::make_pair(
7482 "InterleavingBeneficialButDisabled",
7483 "the cost-model indicates that interleaving is beneficial " 7484 "but is explicitly disabled or interleave count is set to 1");
7485 InterleaveLoop =
false;
7489 IC = UserIC > 0 ? UserIC : IC;
7492 const char *VAPassName = Hints.vectorizeAnalysisPassName();
7493 if (!VectorizeLoop && !InterleaveLoop) {
7498 << VecDiagMsg.second;
7503 << IntDiagMsg.second;
7506 }
else if (!VectorizeLoop && InterleaveLoop) {
7511 << VecDiagMsg.second;
7513 }
else if (VectorizeLoop && !InterleaveLoop) {
7515 <<
") in " << DebugLocStr <<
'\n');
7519 << IntDiagMsg.second;
7521 }
else if (VectorizeLoop && InterleaveLoop) {
7523 <<
") in " << DebugLocStr <<
'\n');
7529 using namespace ore;
7531 if (!VectorizeLoop) {
7532 assert(IC > 1 &&
"interleave count should not be 1 or 0");
7535 InnerLoopUnroller Unroller(L, PSE,
LI,
DT,
TLI,
TTI,
AC,
ORE, IC, &LVL,
7542 <<
"interleaved loop (interleaved count: " 7543 <<
NV(
"InterleaveCount", IC) <<
")";
7547 InnerLoopVectorizer LB(L, PSE,
LI,
DT,
TLI,
TTI,
AC,
ORE, VF.
Width, IC,
7562 <<
"vectorized loop (vectorization width: " 7563 <<
NV(
"VectorizationFactor", VF.
Width)
7564 <<
", interleaved count: " <<
NV(
"InterleaveCount", IC) <<
")";
7569 Hints.setAlreadyVectorized();
7603 bool Changed =
false;
7621 LoopsAnalyzed += Worklist.
size();
7624 while (!Worklist.
empty()) {
7631 Changed |= processLoop(L);
7652 std::function<const LoopAccessInfo &(Loop &)> GetLAA =
7658 runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE);
Legacy wrapper pass to provide the GlobalsAAResult object.
Pass interface - Implemented by all 'passes'.
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)...
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Type * getVectorElementType() const
unsigned getSmallConstantTripCount(const Loop *L)
Returns the maximum trip count of the loop if it is a single-exit loop and we can compute a small max...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Value * getOrCreateScalarValue(Value *V, const VPIteration &Instance)
Return a value in the new loop corresponding to V from the original loop at unroll and vector indices...
Main class to build the VPlan H-CFG for an incoming IR.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
const_iterator end(StringRef path)
Get end iterator over path.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction, which must be an operator which supports these flags.
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
OptimizationRemarkEmitter * ORE
Interface to emit optimization remarks.
Type * getWidestInductionType()
Returns the widest induction type.
bool processLoop(Loop *L)
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
This class is the base class for the comparison instructions.
bool appendInstruction(Instruction *Instr)
Augment the recipe to include Instr, if it lies at its End.
unsigned getWidth() const
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
const MemoryDepChecker & getDepChecker() const
the Memory Dependence Checker which can determine the loop-independent and loop-carried dependences b...
DemandedBits * DB
Demanded bits analysis.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static IntegerType * getInt1Ty(LLVMContext &C)
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."))
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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."))
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
InstWidening
Decision that was taken during cost calculation for memory instruction.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
uint64_t getZExtValue() const
Get zero extended value.
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
bool isLegalMaskedScatter(Type *DataType)
Returns true if the target machine supports masked scatter operation for the given DataType...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
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.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF=1)
Returns true if I is a memory instruction with consecutive memory access that can be widened...
DiagnosticInfoOptimizationBase::Argument NV
void setFast(bool B=true)
bool isMaskRequired(const Instruction *I)
Returns true if vector representation of the instruction I requires mask.
void execute(VPTransformState &State) override
Generate the wide load/store.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
void addNewMetadata(Instruction *To, const Instruction *Orig)
Add additional metadata to To that was not present on Orig.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void collectValuesToIgnore()
Collect values we want to ignore in the cost model.
Compute iterated dominance frontiers using a linear time algorithm.
InnerLoopVectorizer vectorizes loops which contain only one basic block to a specified vectorization ...
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."))
const LoopVectorizeHints * Hints
Loop Vectorize Hint.
size_type size() const
Determine the number of elements in the SetVector.
This is the interface for a simple mod/ref and alias analysis over globals.
VPInterleaveRecipe * tryToInterleaveMemory(Instruction *I, VFRange &Range)
Check if belongs to an Interleave Group within the given VF Range,.
A Module instance is used to store all the information related to an LLVM module. ...
void scalarizeInstruction(Instruction *Instr, const VPIteration &Instance, bool IfPredicateInstr)
A helper function to scalarize a single Instruction in the innermost loop.
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
std::unique_ptr< LoopVersioning > LVer
LoopVersioning.
void emitSCEVChecks(Loop *L, BasicBlock *Bypass)
Emit a bypass check to see if all of the SCEV assumptions we've had to make are correct.
static MDString * get(LLVMContext &Context, StringRef Str)
const Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
Interval Class - An Interval is a set of nodes defined such that every node in the interval has all o...
VectorizationFactor planInVPlanNativePath(bool OptForSize, unsigned UserVF)
Use the VPlan-native path to plan how to best vectorize, return the best VF and its cost...
Min/max implemented in terms of select(cmp()).
This class represents zero extension of integer types.
Value * getScalarValue(Value *Key, const VPIteration &Instance)
Retrieve the existing scalar value that corresponds to Key and Instance.
Instruction::BinaryOps getInductionOpcode() const
Returns binary opcode of the induction operator.
Value * createBitOrPointerCast(Value *V, VectorType *DstVTy, const DataLayout &DL)
Returns a bitcasted value to the requested vector type.
static unsigned getScalarizationOverhead(Instruction *I, unsigned VF, const TargetTransformInfo &TTI)
Estimate the overhead of scalarizing an instruction.
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
value_op_iterator value_op_begin()
Instruction * propagateMetadata(Instruction *I, ArrayRef< Value *> VL)
Specifically, let Kinds = [MD_tbaa, MD_alias_scope, MD_noalias, MD_fpmath, MD_nontemporal].
static void AddRuntimeUnrollDisableMetaData(Loop *L)
The main scalar evolution driver.
bool isUniform(Value *V)
Returns true if the value V is uniform within the loop.
TODO: The following VectorizationFactor was pulled out of LoopVectorizationCostModel class...
static std::string getDebugLocString(const Loop *L)
bool insertMember(Instruction *Instr, int Index, unsigned NewAlign)
Try to insert a new member Instr with index Index and alignment NewAlign.
This is a helper struct for maintaining vectorization state.
This class represents a function call, abstracting a target machine's calling convention.
int64_t getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr, const Loop *Lp, const ValueToValueMap &StridesMap=ValueToValueMap(), bool Assume=false, bool ShouldCheckWrap=true)
If the pointer has a constant stride return it in units of its element size.
void widenPHIInstruction(Instruction *PN, unsigned UF, unsigned VF)
Vectorize a single PHINode in a block.
DominatorTree * DT
Dominator Tree.
void collectTriviallyDeadInstructions(SmallPtrSetImpl< Instruction *> &DeadInstructions)
Collect the instructions from the original loop that would be trivially dead in the vectorized loop i...
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
An immutable pass that tracks lazily created AssumptionCache objects.
VPWidenMemoryInstructionRecipe * tryToWidenMemory(Instruction *I, VFRange &Range, VPlanPtr &Plan)
Check if is a memory instruction to be widened for Range.Start and potentially masked.
static Type * largestIntegerVectorType(Type *T1, Type *T2)
void fixLCSSAPHIs()
The Loop exit block may have single value PHI nodes with some incoming value.
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
Helper class to create VPRecipies from IR instructions.
A cache of @llvm.assume calls within a function.
Analysis pass providing the TargetTransformInfo.
LoopVectorizationLegality checks if it is legal to vectorize a loop, and to what vectorization factor...
void createVectorIntOrFpInductionPHI(const InductionDescriptor &II, Value *Step, Instruction *EntryVal)
Create a vector induction phi node based on an existing scalar one.
Externally visible function.
Loop * TheLoop
The loop that we evaluate.
BasicBlock * LoopScalarPreHeader
The scalar-loop preheader.
bool tryToCreateRecipe(Instruction *Instr, VFRange &Range, VPlanPtr &Plan, VPBasicBlock *VPBB)
Check if a recipe can be create for I withing the given VF Range.
LLVMContext & getContext() const
All values hold a context through their type.
void initializeLoopVectorizePass(PassRegistry &)
static void collectSupportedLoops(Loop &L, LoopInfo *LI, OptimizationRemarkEmitter *ORE, SmallVectorImpl< Loop *> &V)
A Recipe for widening load/store operations.
Value * TripCount
Trip count of the original loop.
void recordVectorLoopValueForInductionCast(const InductionDescriptor &ID, const Instruction *EntryVal, Value *VectorLoopValue, unsigned Part, unsigned Lane=UINT_MAX)
If there is a cast involved in the induction variable ID, which should be ignored in the vectorized l...
This class implements a map that also provides access to all stored values in a deterministic order...
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
value_op_iterator value_op_end()
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
BasicBlock * getSuccessor(unsigned i) const
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
InductionKind getKind() const
STATISTIC(NumFunctions, "Total number of functions")
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
Analysis pass which computes a DominatorTree.
const MDOperand & getOperand(unsigned I) const
An instruction for reading from memory.
Value * getCondition() const
bool isVectorTy() const
True if this is an instance of VectorType.
bool hasAnyScalarValue(Value *Key) const
virtual Value * getStepVector(Value *Val, int StartIdx, Value *Step, Instruction::BinaryOps Opcode=Instruction::BinaryOpsEnd)
This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...) to each vector element of Val...
This defines the Use class.
VPBlockBase * getSingleSuccessor() const
Value * getStartValue() const
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.
const TargetLibraryInfo * TLI
Target Library Info.
bool AlwaysVectorize
If true, consider all loops for vectorization.
iterator end()
Get an iterator to the end of the SetVector.
LLVMContext & getContext() const
Get the context in which this basic block lives.
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
VPValue * createBlockInMask(BasicBlock *BB, VPlanPtr &Plan)
A helper function that computes the predicate of the block BB, assuming that the header block of the ...
void setWideningDecision(const InterleaveGroup *Grp, unsigned VF, InstWidening W, unsigned Cost)
Save vectorization decision W and Cost taken by the cost model for interleaving group Grp and vector ...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
const DILocation * cloneWithDuplicationFactor(unsigned DF) const
Returns a new DILocation with duplication factor DF encoded in the discriminator. ...
SmallVector< Instruction *, 4 > PredicatedInstructions
Store instructions that were predicated.
Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, const TargetTransformInfo *TTI, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, unsigned VecWidth, unsigned UnrollFactor, LoopVectorizationLegality *LVL, LoopVectorizationCostModel *CM)
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...
iterator begin()
Instruction iterator methods.
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align, bool isVolatile=false)
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
const MapVector< Instruction *, uint64_t > & getMinimalBitwidths() const
bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
bool hasAnyVectorValue(Value *Key) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
virtual ~InnerLoopVectorizer()=default
VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when control converges back from ...
AnalysisUsage & addRequired()
PredicatedScalarEvolution & PSE
A wrapper around ScalarEvolution used to add runtime SCEV checks.
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
void setInsertPos(Instruction *Inst)
#define INITIALIZE_PASS_DEPENDENCY(depName)
void print(raw_ostream &O, const Twine &Indent) const override
Print the recipe.
static uint32_t getAlignment(const MCSectionCOFF &Sec)
static unsigned getMemInstAlignment(Value *I)
A helper function that returns the alignment of load or store instruction.
bool tryToWiden(Instruction *I, VPBasicBlock *VPBB, VFRange &Range)
Check if I can be widened within the given VF Range.
This file defines the LoopVectorizationLegality class.
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal)
This is the base class for all instructions that perform data casts.
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBase NewBlock after BlockPtr.
A Use represents the edge between a Value definition and its users.
Diagnostic information for optimization failures.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
static cl::opt< unsigned > MaxInterleaveGroupFactor("max-interleave-group-factor", cl::Hidden, cl::desc("Maximum factor for an interleaved access group (default = 8)"), cl::init(8))
Maximum factor for an interleaved memory access.
bool hasVectorValue(Value *Key, unsigned Part) const
void setIsInBounds(bool b=true)
Set or clear the inbounds flag on this GEP instruction.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
const TargetLibraryInfo * TLI
Target Library Info.
bool isIntegerTy() const
True if this is an instance of IntegerType.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
const Function * TheFunction
An analysis that produces DemandedBits for a function.
unsigned getIndex(Instruction *Instr) const
Get the index for the given member.
This file contains the simple types necessary to represent the attributes associated with functions a...
A recipe for handling all phi nodes except for integer and FP inductions.
Legacy analysis pass which computes BlockFrequencyInfo.
void setName(const Twine &newName)
static void emitMissedWarning(Function *F, Loop *L, const LoopVectorizeHints &LH, OptimizationRemarkEmitter *ORE)
void setWideningDecision(Instruction *I, unsigned VF, InstWidening W, unsigned Cost)
Save vectorization decision W and Cost taken by the cost model for instruction I and vector width VF...
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void setName(const Twine &Name)
Change the name of the value.
Analysis pass that exposes the LoopInfo for a function.
RPOIterator endRPO() const
bool isOptimizableIVTruncate(Instruction *I, unsigned VF)
Return True if instruction I is an optimizable truncate whose operand is an induction variable...
uint64_t getNumElements() const
BasicBlock * LoopExitBlock
The ExitBlock of the scalar loop.
static void cse(BasicBlock *BB)
Perform cse of induction variable instructions.
bool remove(const value_type &X)
Remove an item from the set vector.
Value * getOrCreateVectorTripCount(Loop *NewLoop)
Returns (and creates if needed) the trip count of the widened loop.
CallInst * CreateMaskedGather(Value *Ptrs, unsigned Align, Value *Mask=nullptr, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Gather intrinsic.
static const unsigned TinyTripCountInterleaveThreshold
We don't interleave loops with a known constant trip count below this number.
virtual Value * reverseVector(Value *Vec)
Generate a shuffle sequence that will reverse the vector Vec.
This file implements a class to represent arbitrary precision integral constant values and operations...
const APInt & getAPInt() const
BlockT * getHeader() const
VPBlendRecipe * tryToBlend(Instruction *I, VPlanPtr &Plan)
Handle non-loop phi nodes.
int isConsecutivePtr(Value *Ptr)
Check if this pointer is consecutive when vectorizing.
void sinkScalarOperands(Instruction *PredInst)
Iteratively sink the scalarized operands of a predicated instruction into the block that was created ...
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
Class to represent function types.
const InterleaveGroup * getInterleavedAccessGroup(Instruction *Instr)
Get the interleaved access group that Instr belongs to.
static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF, const TargetTransformInfo &TTI, const TargetLibraryInfo *TLI)
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
int64_t getSExtValue() const
Get sign extended value.
Type * getType() const
All values are typed, get the type of this value.
Value * CreateSExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a SExt or Trunc from the integer value V to DestTy.
VPRegionBlock * createReplicateRegion(Instruction *I, VPRecipeBase *PredRecipe, VPlanPtr &Plan)
Create a replicating region for instruction I that requires predication.
bool insert(const value_type &X)
Insert a new element into the SetVector.
bool isInductionVariable(const Value *V)
Returns True if V can be considered as an induction variable in this loop.
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 bool isEqual(const Function &Caller, const Function &Callee)
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
LoopVectorizationCostModel(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)
This file provides a LoopVectorizationPlanner class.
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
const T & getValue() const LLVM_LVALUE_FUNCTION
void widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc=nullptr)
Widen an integer or floating-point induction variable IV.
Pass * createLoopVectorizePass(bool NoUnrolling=false, bool AlwaysVectorize=true)
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
SmallVector< RegisterUsage, 8 > calculateRegisterUsage(ArrayRef< unsigned > VFs)
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
iterator begin()
Get an iterator to the beginning of the SetVector.
static Type * smallestIntegerVectorType(Type *T1, Type *T2)
The group of interleaved loads/stores sharing the same stride and close to each other.
This header provides classes for managing per-loop analyses.
static CmpInst * Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, const Twine &Name="", Instruction *InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
ReductionList * getReductionVars()
Returns the reduction variables found in the loop.
const APInt & getValue() const
Return the constant as an APInt value reference.
PHINode * getPrimaryInduction()
Returns the primary induction variable.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
A struct that represents some properties of the register usage of a loop.
Not an induction variable.
Value * getOrCreateTripCount(Loop *NewLoop)
Returns (and creates if needed) the original loop trip count.
Value * getLoadStorePointerOperand(Value *V)
A helper function that returns the pointer operand of a load or store instruction.
An instruction for storing to memory.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
SmallPtrSet< const Value *, 16 > VecValuesToIgnore
Values to ignore in the cost model when VF > 1.
bool blockNeedsPredication(BasicBlock *BB)
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
bool isLegalGatherOrScatter(Value *V)
Returns true if the target machine can represent V as a masked gather or scatter operation.
void takeName(Value *V)
Transfer the name from V to this value.
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Value * getOrCreateVectorValue(Value *V, unsigned Part)
getOrCreateVectorValue and getOrCreateScalarValue coordinate to generate a vector or scalar value on-...
iterator find(const KeyT &Key)
void truncateToMinimalBitwidths()
Shrinks vector element sizes to the smallest bitwidth they can be legally represented as...
VectorType * getType() const
Overload to return most specific vector type.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
BasicBlock * createVectorizedLoopSkeleton()
Create a new empty loop.
void execute(VPTransformState &State) override
Produce widened copies of all Ingredients.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass)
Emit a bypass check to see if the vector trip count is zero, including if it overflows.
This class represents a truncation of integer types.
void resetScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar)
Reset the scalar value associated with Key for Part and Lane.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Value * getOperand(unsigned i) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
bool runImpl(Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_, DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_, DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_, std::function< const LoopAccessInfo &(Loop &)> &GetLAA_, OptimizationRemarkEmitter &ORE)
Class to represent pointers.
Pointer induction var. Step = C / sizeof(elem).
const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
void execute(VPTransformState &State) override
Generates phi nodes for live-outs as needed to retain SSA form.
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
iterator find(const_arg_type_t< KeyT > Val)
void widenInstruction(Instruction &I)
Widen a single instruction within the innermost loop.
Value * CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
BasicBlock * LoopMiddleBlock
Middle Block between the vector and the scalar.
std::pair< Instruction *, Instruction * > addRuntimeChecks(Instruction *Loc) const
Add code that checks at runtime if the accessed arrays overlap.
bool isVoidTy() const
Return true if this is 'void'.
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe...
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
void setBestPlan(unsigned VF, unsigned UF)
Finalize the best decision and dispose of all other VPlans.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
static bool runOnFunction(Function &F, bool PostInlining)
enum ForceKind getForce() const
initializer< Ty > init(const Ty &Val)
bool erase(const KeyT &Val)
void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II, Value *CountRoundDown, Value *EndValue, BasicBlock *MiddleBlock)
Set up the values of the IVs correctly when exiting the vector loop.
This instruction inserts a single (scalar) element into a VectorType value.
void restoreIP(InsertPoint IP)
Sets the current insert point to a previously-saved location.
static cl::opt< bool > EnableCondStoresVectorization("enable-cond-stores-vec", cl::init(true), cl::Hidden, cl::desc("Enable if predication of stores during vectorization."))
Integer induction variable. Step = C.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Value * CreateFMul(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
A set of analyses that are preserved following a run of a transformation pass.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
OptimizationRemarkEmitter * ORE
Interface to emit optimization remarks.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
static bool hasIrregularType(Type *Ty, const DataLayout &DL, unsigned VF)
A helper function that returns true if the given type is irregular.
Value * concatenateVectors(IRBuilder<> &Builder, ArrayRef< Value *> Vecs)
Concatenate a list of vectors.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
bool isProfitableToScalarize(Instruction *I, unsigned VF) const
This is an important class for using LLVM in a threaded context.
void fixVectorizedLoop()
Fix the vectorized code, taking care of header phi's, live-outs, and more.
ConstantInt * getTrue()
Get the constant value for i1 true.
Conditional or Unconditional Branch instruction.
Min/max implemented in terms of select(cmp()).
Value handle that tracks a Value across RAUW.
BasicBlock * LoopScalarBody
The scalar loop body.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
bool ult(const APInt &RHS) const
Unsigned less than comparison.
size_t size() const
size - Get the array size.
const char * getOpcodeName() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static Instruction * getDebugLocFromInstOrOperands(Instruction *I)
Look for a meaningful debug location on the instruction or it's operands.
This is an important base class in LLVM.
bool hasScalarValue(Value *Key, const VPIteration &Instance) const
This analysis provides dependence information for the memory accesses of a loop.
PredicatedScalarEvolution & PSE
Predicated scalar evolution analysis.
InsertPoint saveIP() const
Returns the current insert point.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr)
Set the debug location in the builder using the debug location in the instruction.
const SCEV * getStep() const
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool getDecisionAndClampRange(const std::function< bool(unsigned)> &Predicate, VFRange &Range)
Test a Predicate on a Range of VF's.
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
bool isPointerTy() const
True if this is an instance of PointerType.
static Value * addFastMathFlag(Value *V)
A helper function that adds a 'fast' flag to floating-point operations.
A manager for alias analyses.
unsigned selectInterleaveCount(bool OptForSize, unsigned VF, unsigned LoopCost)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
InterleavedAccessInfo & InterleaveInfo
The interleave access information contains groups of interleaved accesses with the same stride and cl...
std::unique_ptr< VPlan > VPlanPtr
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."))
Represent the analysis usage information of a pass.
PHINode * Induction
The new Induction variable which was added to the new block.
OptimizationRemarkAnalysis createLVMissedAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop, Instruction *I=nullptr)
Create an analysis remark that explains why vectorization failed.
unsigned getNumLoads() const
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
bool hasFunNoNaNAttr() const
bool optForSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
bool isReductionVariable(PHINode *PN)
Returns True if PN is a reduction variable in this loop.
Analysis pass providing a never-invalidated alias analysis result.
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
void fixCrossIterationPHIs()
Handle all cross-iteration phis in the header.
void fixFirstOrderRecurrence(PHINode *Phi)
Fix a first-order recurrence.
FunctionPass class - This class is used to implement most global optimizations.
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
const SCEV * replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE, const ValueToValueMap &PtrToStride, Value *Ptr, Value *OrigPtr=nullptr)
Return the SCEV corresponding to a pointer with the symbolic stride replaced with constant one...
VectorizationFactor selectVectorizationFactor(unsigned MaxVF)
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
unsigned UF
The vectorization unroll factor to use.
Optional< unsigned > getLoopEstimatedTripCount(Loop *L)
Get a loop's estimated trip count based on branch weight metadata.
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."))
const RuntimePointerChecking * getRuntimePointerChecking() const
Returns the information that we collected about runtime memory check.
static CastInst * CreatePointerCast(Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
void execute(VPTransformState &State) override
Generate the extraction of the appropriate bit from the block mask and the conditional branch...
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
unsigned LoopInvariantRegs
Holds the number of loop invariant values that are used in the loop.
const Value * getCondition() const
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
AssumptionCache * AC
Assumption cache.
unsigned getInterleave() const
bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
AssumptionCache * AC
Assumption Cache.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
iterator_range< User::op_iterator > arg_operands()
Iteration adapter for range-for loops.
static void connectBlocks(VPBlockBase *From, VPBlockBase *To)
Connect VPBlockBases From and To bi-directionally.
static unsigned getIncomingValueNumForOperand(unsigned i)
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
RecurrenceKind getRecurrenceKind()
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar)
Set a scalar value associated with Key and Instance.
bool requiresScalarEpilogue() const
Returns true if an interleaved group requires a scalar iteration to handle accesses with gaps...
static unsigned getRecurrenceBinOp(RecurrenceKind Kind)
Returns the opcode of binary operation corresponding to the RecurrenceKind.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Instruction * getMember(unsigned Index) const
Get the member with the given index Index.
void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass)
Emit bypass checks to check any memory assumptions we may have made.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
BasicBlock * LoopVectorBody
The vector loop body.
unsigned getNumMembers() const
void fixReduction(PHINode *Phi)
Fix a reduction cross-iteration phi.
void executePlan(InnerLoopVectorizer &LB, DominatorTree *DT)
Generate the IR code for the body of the vectorized loop according to the best selected VPlan...
Planner drives the vectorization process after having passed Legality checks.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
A function analysis which provides an AssumptionCache.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Value * transform(IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL) const
Compute the transformed value of Index at offset StartValue using step StepValue. ...
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
bool isLegalMaskedGather(Type *DataType)
Returns true if the target machine supports masked gather operation for the given DataType...
const SmallVectorImpl< Dependence > * getDependences() const
Returns the memory dependences.
const VPRecipeBase & back() const
A SetVector that performs no allocations if smaller than a certain size.
Analysis pass which computes BlockFrequencyInfo.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
This file defines the VPlanHCFGBuilder class which contains the public interface (buildHierarchicalCF...
static bool mayDivideByZero(Instruction &I)
A helper function for checking whether an integer division-related instruction may divide by zero (in...
LoopVectorizationLegality * Legal
Vectorization legality.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse, VPValue *Condition, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBases IfTrue and IfFalse after BlockPtr.
This is the shared class of boolean and integer constants.
const SCEVUnionPredicate & getUnionPredicate() const
Type * getType() const
Return the LLVM type of this SCEV expression.
A struct for saving information about induction variables.
unsigned getAlignment() const
A range of powers-of-2 vectorization factors with fixed start and adjustable end. ...
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
unsigned MaxLocalUsers
Holds the maximum number of concurrent live intervals in the loop.
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
BasicBlock * LoopVectorPreHeader
The vector-loop preheader.
bool isFunctionVectorizable(StringRef F, unsigned VF) const
This holds vectorization requirements that must be verified late in the process.
static cl::opt< bool > EnableVPlanNativePath("enable-vplan-native-path", cl::init(false), cl::Hidden, cl::desc("Enable VPlan-native vectorization path with " "support for outer loop vectorization."))
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"))
bool isAccessInterleaved(Instruction *Instr)
Check if Instr belongs to any interleaved access group.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
SmallPtrSet< const Value *, 16 > ValuesToIgnore
Values to ignore in the cost model.
Module.h This file contains the declarations for the Module class.
Value * CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx, const Twine &Name="")
Provides information about what library functions are available for the current target.
void buildVPlans(unsigned MinVF, unsigned MaxVF)
Build VPlans for power-of-2 VF's between MinVF and MaxVF inclusive, according to the information gath...
VPValue * createEdgeMask(BasicBlock *Src, BasicBlock *Dst, VPlanPtr &Plan)
A helper function that computes the predicate of the edge between SRC and DST.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
size_type count(const KeyT &Key) const
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
bool isAggregateType() const
Return true if the type is an aggregate type.
bool isFirstOrderRecurrence(const PHINode *Phi)
Returns True if Phi is a first-order recurrence in this loop.
LoopT * AllocateLoop(ArgsTy &&... Args)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal, const InductionDescriptor &ID)
Compute scalar induction steps.
CallInst * CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align, Value *Mask)
Create a call to Masked Store intrinsic.
LLVM_NODISCARD T pop_back_val()
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
unsigned getMaxSafeDepDistBytes()
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...
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Drive the analysis of memory accesses in the loop.
static Constant * getSignedIntOrFpConstant(Type *Ty, int64_t C)
A helper function that returns an integer or floating-point constant with value C.
VectorizationFactor plan(bool OptForSize, unsigned UserVF)
Plan how to best vectorize, return the best VF and its cost.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
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"))
reverse_iterator rbegin()
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
pred_range predecessors(BasicBlock *BB)
const VPBlocksTy & getSuccessors() const
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
CallInst * CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Load intrinsic.
bool hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, unsigned ScalarOpdIdx)
Identifies if the intrinsic has a scalar operand.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Value * CreateURem(Value *LHS, Value *RHS, const Twine &Name="")
StringRef getVectorizedFunction(StringRef F, unsigned VF) const
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
void setOperand(unsigned i, Value *Val)
Value * createTargetReduction(IRBuilder<> &B, const TargetTransformInfo *TTI, RecurrenceDescriptor &Desc, Value *Src, bool NoNaN=false)
Create a generic target reduction using a recurrence descriptor Desc The target is queried to determi...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
unsigned getVectorNumElements() const
static Constant * getRecurrenceIdentity(RecurrenceKind K, Type *Tp)
Returns identity corresponding to the RecurrenceKind.
Store the result of a depth first search within basic blocks contained by a single loop...
void clear()
Completely clear the SetVector.
DenseMap< PHINode *, Value * > IVEndValues
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Class to represent vector types.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class for arbitrary precision integers.
bool isInductionPhi(const Value *V)
Returns True if V is a Phi node of an induction variable in this loop.
void collectUniformsAndScalars(unsigned VF)
Collect Uniform and Scalar values for the given VF.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
void addMetadata(Instruction *To, Instruction *From)
Add metadata from one instruction to another.
const LoopAccessInfo * getLAI() const
void resetVectorValue(Value *Key, unsigned Part, Value *Vector)
Reset the vector value associated with Key for the given Part.
LoopInfo * LI
Loop Info analysis.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
iterator_range< user_iterator > users()
static Value * createMinMaxOp(IRBuilder<> &Builder, MinMaxRecurrenceKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
static const char lv_name[]
This class uses information about analyze scalars to rewrite expressions in canonical form...
static bool processLoopInVPlanNativePath(Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, LoopVectorizationLegality *LVL, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, LoopVectorizeHints &Hints)
bool isPredicated(MCInstrInfo const &MCII, MCInst const &MCI)
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
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."))
Value * VectorTripCount
Trip count of the widened loop (TripCount - TripCount % (VF*UF))
void vectorizeMemoryInstruction(Instruction *Instr, VectorParts *BlockInMask=nullptr)
Vectorize Load and Store instructions, optionally masking the vector operations if BlockInMask is non...
loop Loop Strength Reduction
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)."))
ValueT lookup(const KeyT &Key) const
const TargetTransformInfo & TTI
Vector target information.
amdgpu Simplify well known AMD library false Value Value * Arg
const SmallVectorImpl< Instruction * > & getCastInsts() const
Returns a reference to the type cast instructions in the induction update chain, that are redundant w...
LoopVectorizationCostModel * Cost
The profitablity analysis.
Analysis pass that exposes the ScalarEvolution for a function.
Constant * createStrideMask(IRBuilder<> &Builder, unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
PHINode * OldInduction
The induction variable of the old basic block.
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
LoopT * getParentLoop() const
static unsigned getReciprocalPredBlockProb()
A helper function that returns the reciprocal of the block probability of predicated blocks...
Analysis pass providing a never-invalidated alias analysis result.
const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
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...
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
This analysis provides dependence information for the memory accesses of a loop.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
uint64_t getMaxSafeRegisterWidth() const
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
static Type * getMemInstValueType(Value *I)
A helper function that returns the type of loaded or stored value.
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
void packScalarIntoVectorValue(Value *V, const VPIteration &Instance)
Construct the vector value of a scalarized value V one lane at a time.
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 areSafetyChecksAdded()
static unsigned getVectorCallCost(CallInst *CI, unsigned VF, const TargetTransformInfo &TTI, const TargetLibraryInfo *TLI, bool &NeedToScalarize)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
This class represents an analyzed expression in the program.
Value * getVectorValue(Value *Key, unsigned Part)
Retrieve the existing vector value that corresponds to Key and Part.
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"))
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
LLVM_NODISCARD bool empty() const
bool canTruncateToMinimalBitwidth(Instruction *I, unsigned VF) const
Floating point induction variable.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
Represents a single loop in the control flow graph.
VPBasicBlock * handleReplication(Instruction *I, VFRange &Range, VPBasicBlock *VPBB, DenseMap< Instruction *, VPReplicateRecipe *> &PredInst2Recipe, VPlanPtr &Plan)
Build a VPReplicationRecipe for I and enclose it within a Region if it is predicated.
InductionList * getInductionVars()
Returns the induction variables found in the loop.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
bool isUniformAfterVectorization(Instruction *I, unsigned VF) const
Returns true if I is known to be uniform after vectorization.
void collectInstsToScalarize(unsigned VF)
Collects the instructions to scalarize for each predicated instruction in the loop.
static Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
user_iterator_impl< User > user_iterator
APFloat abs(APFloat X)
Returns the absolute value of the argument.
bool mayReadFromMemory() const
Return true if this instruction may read memory.
bool isLegalMaskedStore(Type *DataType, Value *Ptr)
Returns true if the target machine supports masked store operation for the given DataType and kind of...
void execute(VPTransformState &State) override
Generate the vectorized and scalarized versions of the phi node as needed by their users...
PHINode * createInductionVariable(Loop *L, Value *Start, Value *End, Value *Step, Instruction *DL)
Create a new induction variable inside L.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
Optional< unsigned > computeMaxVF(bool OptForSize)
iterator_range< value_op_iterator > operand_values()
Loop * OrigLoop
The original loop.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
unsigned getWideningCost(Instruction *I, unsigned VF)
Return the vectorization cost for the given instruction I and vector width VF.
InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
bool isScalarWithPredication(Instruction *I)
Returns true if I is an instruction that will be scalarized with predication.
void preserve()
Mark an analysis as preserved.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector and ...
bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
InstWidening getWideningDecision(Instruction *I, unsigned VF)
Return the cost model decision for the given instruction I and vector width VF.
LLVM_NODISCARD bool empty() const
void setVectorValue(Value *Key, unsigned Part, Value *Vector)
Set a vector value associated with Key and Part.
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...
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
void updateAnalysis()
Insert the new loop to the loop hierarchy and pass manager and update the analysis passes...
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void vectorizeInterleaveGroup(Instruction *Instr)
Try to vectorize the interleaved access group that Instr belongs to.
void addMetadata(Instruction *NewInst) const
Add metadata (e.g.
Instruction * getInsertPos() const
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Analysis pass providing the TargetLibraryInfo.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
AliasAnalysis * AA
Alias Analysis.
LoopVectorizationLegality * Legal
The legality analysis.
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
separate const offset from gep
void setAlreadyVectorized()
Mark the loop L as already vectorized by setting the width to 1.
Constant * createInterleaveMask(IRBuilder<> &Builder, unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isExplicitVecOuterLoop(Loop *OuterLp, OptimizationRemarkEmitter *ORE)
SmallPtrSet< Instruction *, 8 > & getCastInsts()
Returns a reference to the instructions used for type-promoting the recurrence.
unsigned VF
The vectorization SIMD factor to use.
CallInst * CreateMaskedScatter(Value *Val, Value *Ptrs, unsigned Align, Value *Mask=nullptr)
Create a call to Masked Scatter intrinsic.
LoadInst * CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name)
Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")' correctly, instead of converting the strin...
A raw_ostream that writes to an std::string.
LoopVectorizationCostModel - estimates the expected speedups due to vectorization.
VPWidenRecipe is a recipe for producing a copy of vector type for each Instruction in its ingredients...
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
IRBuilder Builder
The builder that we use.
uint64_t PowerOf2Floor(uint64_t A)
Returns the power of two which is less than or equal to the given value.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
virtual Value * getBroadcastInstrs(Value *V)
Create a broadcast instruction.
A recipe for generating conditional branches on the bits of a mask.
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
bool isLegalMaskedLoad(Type *DataType, Value *Ptr)
Returns true if the target machine supports masked load operation for the given DataType and kind of ...
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop, DominatorTree *DT)
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
unsigned getFactor() const
This class implements an extremely fast bulk output stream that can only output to a stream...
uint64_t getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
Type * getElementType() const
The legacy pass manager's analysis pass to compute loop information.
print Print MemDeps of function
SmallVector< BasicBlock *, 4 > LoopBypassBlocks
A list of all bypass blocks. The first block is the entry of the loop.
static Type * ToVectorTy(Type *Scalar, unsigned VF)
A helper function for converting Scalar types to vector types.
const TargetTransformInfo * TTI
Target Transform Info.
bool hasOneUse() const
Return true if there is exactly one user of this value.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Convenience struct for specifying and reasoning about fast-math flags.
StringRef - Represent a constant reference to a string, i.e.
This is the interface for LLVM's primary stateless and local alias analysis.
A recipe for vectorizing a phi-node as a sequence of mask-based select instructions.
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
A container for analyses that lazily runs them and caches their results.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
VectorizerValueMap VectorLoopValueMap
Maps values from the original loop to their corresponding values in the vectorized loop...
Legacy analysis pass which computes a DominatorTree.
void selectUserVectorizationFactor(unsigned UserVF)
Setup cost-based decisions for user vectorization factor.
bool shouldScalarizeInstruction(Instruction *I) const
Returns true if an instruction I should be scalarized instead of vectorized for the chosen vectorizat...
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void setIncomingValue(unsigned i, Value *V)
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
unsigned getNumOperands() const
Return number of MDNode operands.
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."))
unsigned getNumStores() const
iterator_range< block_iterator > blocks() const
VPWidenIntOrFpInductionRecipe * tryToOptimizeInduction(Instruction *I, VFRange &Range)
Check if an induction recipe should be constructed for within the given VF Range.
void setCostBasedWideningDecision(unsigned VF)
Memory access instruction may be vectorized in more than one way.
bool isScalarAfterVectorization(Instruction *I, unsigned VF) const
Returns true if I is known to be scalar after vectorization.
static Constant * get(ArrayRef< Constant *> V)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
DenseMap< Instruction *, Instruction * > & getSinkAfter()
Return the set of instructions to sink to handle first-order recurrences.
Type * getElementType() const
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."))
void emitRemarkWithHints() const
Dumps all the hint information.
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
static unsigned getMemInstAddressSpace(Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction...
RecurrenceKind
This enum represents the kinds of recurrences that we support.
const BasicBlock * getParent() const
This class represents a constant integer value.
bool needsScalarInduction(Instruction *IV) const
Returns true if we should generate a scalar version of IV.
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)
Legacy wrapper pass to provide the BasicAAResult object.
bool Need
This flag indicates if we need to add the runtime check.
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Type * getRecurrenceType()
Returns the type of the recurrence.
std::pair< unsigned, unsigned > getSmallestAndWidestTypes()
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.