73 #define DEBUG_TYPE "loop-unroll" 77 cl::desc(
"Forget everything in SCEV when doing LoopUnroll, instead of just" 78 " the current top-most loop. This is somtimes preferred to reduce" 83 cl::desc(
"The cost threshold for loop unrolling"));
87 cl::desc(
"The cost threshold for partial loop unrolling"));
91 cl::desc(
"The maximum 'boost' (represented as a percentage >= 100) applied " 92 "to the threshold when aggressively unrolling a loop due to the " 93 "dynamic cost savings. If completely unrolling a loop will reduce " 94 "the total runtime from X to Y, we boost the loop unroll " 95 "threshold to DefaultThreshold*std::min(MaxPercentThresholdBoost, " 96 "X/Y). This limit avoids excessive code bloat."));
100 cl::desc(
"Don't allow loop unrolling to simulate more than this number of" 101 "iterations when checking full unroll profitability"));
105 cl::desc(
"Use this unroll count for all loops including those with " 106 "unroll_count pragma values, for testing purposes"));
110 cl::desc(
"Set the max unroll count for partial and runtime unrolling, for" 111 "testing purposes"));
116 "Set the max unroll count for full unrolling, for testing purposes"));
120 cl::desc(
"Set the unroll peeling count, for testing purposes"));
124 cl::desc(
"Allows loops to be partially unrolled until " 125 "-unroll-threshold loop size is reached."));
129 cl::desc(
"Allow generation of a loop remainder (extra iterations) " 130 "when unrolling a loop."));
134 cl::desc(
"Unroll loops with run-time trip counts"));
139 "The max of trip count upper bound that is considered in unrolling"));
143 cl::desc(
"Unrolled size limit for loops with an unroll(full) or " 144 "unroll_count pragma."));
148 cl::desc(
"If the runtime tripcount for the loop is lower than the " 149 "threshold, the loop is considered as flat and will be less " 150 "aggressively unrolled."));
154 cl::desc(
"Allows loops to be peeled when the dynamic " 155 "trip count is known to be low."));
159 cl::desc(
"Allow the loop remainder to be unrolled."));
166 cl::desc(
"Enqueue and re-visit child loops in the loop PM after unrolling. " 167 "This shouldn't typically be needed as child loops (or their " 168 "clones) were already visited."));
256 UP.
Count = *UserCount;
258 UP.
Partial = *UserAllowPartial;
281 struct UnrolledInstState {
285 unsigned IsCounted : 1;
289 struct UnrolledInstStateKeyInfo {
293 static inline UnrolledInstState getEmptyKey() {
294 return {PtrInfo::getEmptyKey(), 0, 0, 0};
297 static inline UnrolledInstState getTombstoneKey() {
298 return {PtrInfo::getTombstoneKey(), 0, 0, 0};
301 static inline unsigned getHashValue(
const UnrolledInstState &S) {
302 return PairInfo::getHashValue({S.I, S.Iteration});
305 static inline bool isEqual(
const UnrolledInstState &LHS,
306 const UnrolledInstState &RHS) {
311 struct EstimatedUnrollCost {
313 unsigned UnrolledCost;
317 unsigned RolledDynamicCost;
344 "The unroll iterations max is too large!");
363 unsigned UnrolledCost = 0;
370 unsigned RolledDynamicCost = 0;
386 auto AddCostRecursively = [&](
Instruction &RootI,
int Iteration) {
387 assert(Iteration >= 0 &&
"Cannot have a negative iteration!");
388 assert(CostWorklist.
empty() &&
"Must start with an empty cost list");
389 assert(PHIUsedList.
empty() &&
"Must start with an empty phi used list");
391 for (;; --Iteration) {
397 auto CostIter = InstCostMap.
find({
I, Iteration, 0, 0});
398 if (CostIter == InstCostMap.
end())
403 auto &Cost = *CostIter;
409 Cost.IsCounted =
true;
412 if (
auto *PhiI = dyn_cast<PHINode>(I))
413 if (PhiI->getParent() == L->
getHeader()) {
414 assert(Cost.IsFree &&
"Loop PHIs shouldn't be evaluated as they " 415 "inherently simplify during unrolling.");
422 if (
auto *OpI = dyn_cast<Instruction>(
433 << Iteration <<
"): ");
450 }
while (!CostWorklist.
empty());
452 if (PHIUsedList.
empty())
457 "Cannot track PHI-used values past the first iteration!");
467 "Must have loops in LCSSA form to track live-out values.");
469 LLVM_DEBUG(
dbgs() <<
"Starting LoopUnroll profitability analysis...\n");
475 for (
unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
476 LLVM_DEBUG(
dbgs() <<
" Analyzing iteration " << Iteration <<
"\n");
488 PHI->getNumIncomingValues() == 2 &&
489 "Must have an incoming value only for the preheader and the latch.");
491 Value *V = PHI->getIncomingValueForBlock(
494 if (Iteration != 0 && !C)
495 C = SimplifiedValues.
lookup(V);
497 SimplifiedInputValues.
push_back({PHI, C});
501 SimplifiedValues.
clear();
502 while (!SimplifiedInputValues.
empty())
510 for (
unsigned Idx = 0; Idx != BBWorklist.
size(); ++Idx) {
519 if (isa<DbgInfoIntrinsic>(
I) || EphValues.
count(&
I))
529 bool IsFree = Analyzer.
visit(
I);
530 bool Inserted = InstCostMap.
insert({&
I, (int)Iteration,
534 assert(Inserted &&
"Cannot have a state for an unvisited instruction!");
541 if (
auto *CI = dyn_cast<CallInst>(&
I)) {
551 if (
I.mayHaveSideEffects())
552 AddCostRecursively(
I, Iteration);
555 if (UnrolledCost > MaxUnrolledLoopSize) {
557 <<
" UnrolledCost: " << UnrolledCost
558 <<
", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
569 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
570 if (BI->isConditional()) {
572 SimplifiedValues.
lookup(BI->getCondition())) {
574 if (isa<UndefValue>(SimpleCond))
575 KnownSucc = BI->getSuccessor(0);
577 dyn_cast<ConstantInt>(SimpleCond))
578 KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0);
583 SimplifiedValues.
lookup(
SI->getCondition())) {
585 if (isa<UndefValue>(SimpleCond))
586 KnownSucc =
SI->getSuccessor(0);
588 dyn_cast<ConstantInt>(SimpleCond))
589 KnownSucc =
SI->findCaseValue(SimpleCondVal)->getCaseSuccessor();
594 BBWorklist.
insert(KnownSucc);
596 ExitWorklist.
insert({BB, KnownSucc});
605 ExitWorklist.
insert({BB, Succ});
606 AddCostRecursively(*TI, Iteration);
611 if (UnrolledCost == RolledDynamicCost) {
613 <<
" UnrolledCost: " << UnrolledCost <<
"\n");
618 while (!ExitWorklist.
empty()) {
620 std::tie(ExitingBB, ExitBB) = ExitWorklist.
pop_back_val();
627 Value *
Op = PN->getIncomingValueForBlock(ExitingBB);
628 if (
auto *OpI = dyn_cast<Instruction>(Op))
630 AddCostRecursively(*OpI, TripCount - 1);
635 <<
"UnrolledCost: " << UnrolledCost <<
", " 636 <<
"RolledDynamicCost: " << RolledDynamicCost <<
"\n");
637 return {{UnrolledCost, RolledDynamicCost}};
642 const Loop *L,
unsigned &NumCalls,
bool &NotDuplicatable,
bool &
Convergent,
652 unsigned LoopSize = Metrics.
NumInsts;
660 LoopSize =
std::max(LoopSize, BEInsns + 1);
696 "Unroll count hint metadata should have two operands.");
698 mdconst::extract<ConstantInt>(MD->
getOperand(1))->getZExtValue();
699 assert(Count >= 1 &&
"Unroll count must be positive.");
711 unsigned MaxPercentThresholdBoost) {
714 else if (Cost.UnrolledCost != 0)
716 return std::min(100 * Cost.RolledDynamicCost / Cost.UnrolledCost,
717 MaxPercentThresholdBoost);
719 return MaxPercentThresholdBoost;
726 assert(LoopSize >= UP.
BEInsns &&
"LoopSize should not be less than BEInsns!");
742 bool MaxOrZero,
unsigned &TripMultiple,
unsigned LoopSize,
747 bool UserUnrollCount =
UnrollCount.getNumOccurrences() > 0;
748 if (UserUnrollCount) {
758 if (PragmaCount > 0) {
759 UP.
Count = PragmaCount;
768 if (PragmaFullUnroll && TripCount != 0) {
769 UP.
Count = TripCount;
775 bool ExplicitUnroll = PragmaCount > 0 || PragmaFullUnroll ||
776 PragmaEnableUnroll || UserUnrollCount;
778 if (ExplicitUnroll && TripCount != 0) {
802 unsigned FullUnrollMaxTripCount = MaxTripCount;
805 FullUnrollMaxTripCount = 0;
809 unsigned ExactTripCount = TripCount;
810 assert((ExactTripCount == 0 || FullUnrollMaxTripCount == 0) &&
811 "ExtractTripCount and UnrollByMaxCount cannot both be non zero.");
813 unsigned FullUnrollTripCount =
814 ExactTripCount ? ExactTripCount : FullUnrollMaxTripCount;
815 UP.
Count = FullUnrollTripCount;
820 UseUpperBound = (FullUnrollMaxTripCount == FullUnrollTripCount);
821 TripCount = FullUnrollTripCount;
822 TripMultiple = UP.
UpperBound ? 1 : TripMultiple;
823 return ExplicitUnroll;
829 L, FullUnrollTripCount, DT, SE, EphValues, TTI,
833 if (Cost->UnrolledCost < UP.
Threshold * Boost / 100) {
834 UseUpperBound = (FullUnrollMaxTripCount == FullUnrollTripCount);
835 TripCount = FullUnrollTripCount;
836 TripMultiple = UP.
UpperBound ? 1 : TripMultiple;
837 return ExplicitUnroll;
848 return ExplicitUnroll;
857 <<
"-unroll-allow-partial not given\n");
862 UP.
Count = TripCount;
871 while (UP.
Count != 0 && TripCount % UP.
Count != 0)
879 while (UP.
Count != 0 &&
884 if (PragmaEnableUnroll)
887 "UnrollAsDirectedTooLarge",
889 <<
"Unable to unroll loop as directed by unroll(enable) " 891 "because unrolled size is too large.";
896 UP.
Count = TripCount;
900 if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
901 UP.
Count != TripCount)
903 return OptimizationRemarkMissed(DEBUG_TYPE,
904 "FullUnrollAsDirectedTooLarge",
905 L->getStartLoc(), L->getHeader())
906 <<
"Unable to fully unroll loop as directed by unroll pragma " 908 "unrolled size is too large.";
912 return ExplicitUnroll;
915 "All cases when TripCount is constant should be covered here.");
916 if (PragmaFullUnroll)
919 DEBUG_TYPE,
"CantFullUnrollAsDirectedRuntimeTripCount",
921 <<
"Unable to fully unroll loop as directed by unroll(full) " 923 "because loop has a runtime trip count.";
950 UP.
Runtime |= PragmaEnableUnroll || PragmaCount > 0 || UserUnrollCount;
953 dbgs() <<
" will not try to unroll loop with runtime trip count " 954 <<
"-unroll-runtime not given\n");
963 while (UP.
Count != 0 &&
968 unsigned OrigCount = UP.
Count;
972 while (UP.
Count != 0 && TripMultiple % UP.
Count != 0)
975 dbgs() <<
"Remainder loop is restricted (that could architecture " 976 "specific or because the loop contains a convergent " 977 "instruction), so unroll count must divide the trip " 979 << TripMultiple <<
". Reducing unroll count from " << OrigCount
980 <<
" to " << UP.
Count <<
".\n");
987 "DifferentUnrollCountFromDirected",
989 <<
"Unable to unroll loop the number of times directed by " 990 "unroll_count pragma because remainder loop is restricted " 991 "(that could architecture specific or because the loop " 992 "contains a convergent instruction) and so must have an " 994 "count that divides the loop trip multiple of " 995 <<
NV(
"TripMultiple", TripMultiple) <<
". Unrolling instead " 996 <<
NV(
"UnrollCount", UP.
Count) <<
" time(s).";
1003 if (MaxTripCount && UP.
Count > MaxTripCount)
1004 UP.
Count = MaxTripCount;
1010 return ExplicitUnroll;
1032 dbgs() <<
" Not unrolling loop which is not in loop-simplify form.\n");
1038 if (OnlyWhenForced && !(TM &
TM_Enable))
1042 unsigned NumInlineCandidates;
1043 bool NotDuplicatable;
1046 L, SE, TTI, BFI, PSI, OptLevel, ProvidedThreshold, ProvidedCount,
1047 ProvidedAllowPartial, ProvidedRuntime, ProvidedUpperBound,
1048 ProvidedAllowPeeling, ProvidedAllowProfileBasedPeeling,
1049 ProvidedFullUnrollMaxCount);
1064 if (NotDuplicatable) {
1065 LLVM_DEBUG(
dbgs() <<
" Not unrolling loop which contains non-duplicatable" 1066 <<
" instructions.\n");
1075 if (NumInlineCandidates != 0) {
1076 LLVM_DEBUG(
dbgs() <<
" Not unrolling loop with inlinable calls.\n");
1081 unsigned TripCount = 0;
1082 unsigned TripMultiple = 1;
1111 unsigned MaxTripCount = 0;
1112 bool MaxOrZero =
false;
1120 bool UseUpperBound =
false;
1122 L, TTI, DT, LI, SE, EphValues, &ORE, TripCount, MaxTripCount, MaxOrZero,
1123 TripMultiple, LoopSize, UP, UseUpperBound);
1127 if (TripCount && UP.
Count > TripCount)
1128 UP.
Count = TripCount;
1134 Loop *RemainderLoop =
nullptr;
1140 LI, &SE, &DT, &AC, &ORE, PreserveLCSSA, &RemainderLoop);
1144 if (RemainderLoop) {
1161 return UnrollResult;
1173 return UnrollResult;
1178 class LoopUnroll :
public LoopPass {
1187 bool OnlyWhenForced;
1203 LoopUnroll(
int OptLevel = 2,
bool OnlyWhenForced =
false,
1211 :
LoopPass(ID), OptLevel(OptLevel), OnlyWhenForced(OnlyWhenForced),
1212 ForgetAllSCEV(ForgetAllSCEV), ProvidedCount(std::move(Count)),
1213 ProvidedThreshold(
Threshold), ProvidedAllowPartial(AllowPartial),
1214 ProvidedRuntime(Runtime), ProvidedUpperBound(UpperBound),
1215 ProvidedAllowPeeling(AllowPeeling),
1216 ProvidedAllowProfileBasedPeeling(AllowProfileBasedPeeling),
1217 ProvidedFullUnrollMaxCount(ProvidedFullUnrollMaxCount) {
1227 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1228 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1229 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1231 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1232 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1237 bool PreserveLCSSA = mustPreserveAnalysisID(
LCSSAID);
1240 L, DT, LI, SE, TTI, AC, ORE,
nullptr,
nullptr, PreserveLCSSA, OptLevel,
1241 OnlyWhenForced, ForgetAllSCEV, ProvidedCount, ProvidedThreshold,
1242 ProvidedAllowPartial, ProvidedRuntime, ProvidedUpperBound,
1243 ProvidedAllowPeeling, ProvidedAllowProfileBasedPeeling,
1244 ProvidedFullUnrollMaxCount);
1274 bool ForgetAllSCEV,
int Threshold,
int Count,
1275 int AllowPartial,
int Runtime,
int UpperBound,
1280 return new LoopUnroll(
1281 OptLevel, OnlyWhenForced, ForgetAllSCEV,
1291 bool ForgetAllSCEV) {
1301 Function *
F = L.getHeader()->getParent();
1307 "LoopFullUnrollPass: OptimizationRemarkEmitterAnalysis not " 1308 "cached at a higher level");
1312 Loop *ParentL = L.getParentLoop();
1319 std::string LoopName = L.getName();
1324 OnlyWhenForced, ForgetSCEV,
None,
1356 bool IsCurrentLoopValid =
false;
1363 if (SibLoop == &L) {
1364 IsCurrentLoopValid =
true;
1369 return OldLoops.
count(SibLoop) != 0;
1373 if (!IsCurrentLoopValid) {
1387 template <
typename RangeT>
1395 assert(PreOrderLoops.
empty() &&
"Must start with an empty preorder walk.");
1397 "Must start with an empty preorder walk worklist.");
1403 }
while (!PreOrderWorklist.
empty());
1406 PreOrderLoops.
clear();
1422 LAM = &LAMProxy->getManager();
1431 bool Changed =
false;
1438 for (
auto &L : LI) {
1446 while (!Worklist.
empty()) {
1461 LocalAllowPeeling =
false;
1462 std::string LoopName = L.
getName();
1466 &L, DT, &LI, SE, TTI, AC, ORE, BFI, PSI,
1467 true, UnrollOpts.OptLevel, UnrollOpts.OnlyWhenForced,
1468 UnrollOpts.ForgetSCEV,
None,
1469 None, UnrollOpts.AllowPartial, UnrollOpts.AllowRuntime,
1470 UnrollOpts.AllowUpperBound, LocalAllowPeeling,
1471 UnrollOpts.AllowProfileBasedPeeling, UnrollOpts.FullUnrollMaxCount);
1482 LAM->clear(L, LoopName);
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)...
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...
Pass * createSimpleLoopUnrollPass(int OptLevel=2, bool OnlyWhenForced=false, bool ForgetAllSCEV=false)
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
unsigned getSmallConstantTripMultiple(const Loop *L)
Returns the largest constant divisor of the trip count of the loop if it is a single-exit loop and we...
DiagnosticInfoOptimizationBase::Argument NV
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM_NODISCARD T pop_back_val()
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
size_type size() const
Determine the number of elements in the SetVector.
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
cl::opt< bool > ForgetSCEVInLoopUnroll
bool convergent
True if this function contains a call to a convergent function.
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static bool HasUnrollEnablePragma(const Loop *L)
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
Implements a dense probed hash-table based set.
void push_back(const T &Elt)
Analysis providing profile information.
The main scalar evolution driver.
static unsigned getFullUnrollBoostingFactor(const EstimatedUnrollCost &Cost, unsigned MaxPercentThresholdBoost)
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
Analysis pass providing the TargetTransformInfo.
unsigned NumInlineCandidates
The number of calls to internal functions with a single caller.
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
bool notDuplicatable
True if this function cannot be duplicated.
static cl::opt< unsigned > UnrollFullMaxCount("unroll-full-max-count", cl::Hidden, cl::desc("Set the max unroll count for full unrolling, for testing purposes"))
unsigned getSmallConstantMaxTripCount(const Loop *L)
Returns the upper bound of the loop trip count as a normal unsigned value.
const char *const LLVMLoopUnrollFollowupUnrolled
void addChildLoops(ArrayRef< Loop *> NewChildLoops)
Loop passes should use this method to indicate they have added new child loops of the current loop...
static cl::opt< unsigned > UnrollPartialThreshold("unroll-partial-threshold", cl::Hidden, cl::desc("The cost threshold for partial loop unrolling"))
bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
void dump() const
Support for debugging, callable in GDB: V->dump()
static cl::opt< bool > UnrollRevisitChildLoops("unroll-revisit-child-loops", cl::Hidden, cl::desc("Enqueue and re-visit child loops in the loop PM after unrolling. " "This shouldn't typically be needed as child loops (or their " "clones) were already visited."))
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
static cl::opt< unsigned > FlatLoopTripCountThreshold("flat-loop-tripcount-threshold", cl::init(5), cl::Hidden, cl::desc("If the runtime tripcount for the loop is lower than the " "threshold, the loop is considered as flat and will be less " "aggressively unrolled."))
static bool HasUnrollFullPragma(const Loop *L)
TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences(Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, int OptLevel, Optional< unsigned > UserThreshold, Optional< unsigned > UserCount, Optional< bool > UserAllowPartial, Optional< bool > UserRuntime, Optional< bool > UserUpperBound, Optional< bool > UserAllowPeeling, Optional< bool > UserAllowProfileBasedPeeling, Optional< unsigned > UserFullUnrollMaxCount)
Gather the various unrolling parameters based on the defaults, compiler flags, TTI overrides and user...
static cl::opt< unsigned > UnrollCount("unroll-count", cl::Hidden, cl::desc("Use this unroll count for all loops including those with " "unroll_count pragma values, for testing purposes"))
Analysis pass that exposes the LoopInfo for a function.
static cl::opt< bool > UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden, cl::desc("Unroll loops with run-time trip counts"))
static Optional< EstimatedUnrollCost > analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE, const SmallPtrSetImpl< const Value *> &EphValues, const TargetTransformInfo &TTI, unsigned MaxUnrolledLoopSize)
Figure out if the loop is worth full unrolling.
BlockT * getHeader() const
static MDNode * GetUnrollMetadataForLoop(const Loop *L, StringRef Name)
The transformation should be applied without considering a cost model.
void computePeelCount(Loop *L, unsigned LoopSize, TargetTransformInfo::UnrollingPreferences &UP, unsigned &TripCount, ScalarEvolution &SE)
void visit(Iterator Start, Iterator End)
bool insert(const value_type &X)
Insert a new element into the SetVector.
static cl::opt< unsigned > UnrollMaxUpperBound("unroll-max-upperbound", cl::init(8), cl::Hidden, cl::desc("The max of trip count upper bound that is considered in unrolling"))
static bool isEqual(const Function &Caller, const Function &Callee)
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
const T & getValue() const LLVM_LVALUE_FUNCTION
const char *const LLVMLoopUnrollFollowupRemainder
This header provides classes for managing per-loop analyses.
static cl::opt< bool > UnrollAllowRemainder("unroll-allow-remainder", cl::Hidden, cl::desc("Allow generation of a loop remainder (extra iterations) " "when unrolling a loop."))
bool computeUnrollCount(Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, LoopInfo *LI, ScalarEvolution &SE, const SmallPtrSetImpl< const Value *> &EphValues, OptimizationRemarkEmitter *ORE, unsigned &TripCount, unsigned MaxTripCount, bool MaxOrZero, unsigned &TripMultiple, unsigned LoopSize, TargetTransformInfo::UnrollingPreferences &UP, bool &UseUpperBound)
static cl::opt< unsigned > UnrollMaxPercentThresholdBoost("unroll-max-percent-threshold-boost", cl::init(400), cl::Hidden, cl::desc("The maximum 'boost' (represented as a percentage >= 100) applied " "to the threshold when aggressively unrolling a loop due to the " "dynamic cost savings. If completely unrolling a loop will reduce " "the total runtime from X to Y, we boost the loop unroll " "threshold to DefaultThreshold*std::min(MaxPercentThresholdBoost, " "X/Y). This limit avoids excessive code bloat."))
void initializeLoopUnrollPass(PassRegistry &)
static LoopUnrollResult tryToUnrollLoop(Loop *L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution &SE, const TargetTransformInfo &TTI, AssumptionCache &AC, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, bool PreserveLCSSA, int OptLevel, bool OnlyWhenForced, bool ForgetAllSCEV, Optional< unsigned > ProvidedCount, Optional< unsigned > ProvidedThreshold, Optional< bool > ProvidedAllowPartial, Optional< bool > ProvidedRuntime, Optional< bool > ProvidedUpperBound, Optional< bool > ProvidedAllowPeeling, Optional< bool > ProvidedAllowProfileBasedPeeling, Optional< unsigned > ProvidedFullUnrollMaxCount)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
bool hasProfileSummary()
Returns true if profile summary is available.
The loop was fully unrolled into straight-line code.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
initializer< Ty > init(const Ty &Val)
static cl::opt< bool > UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden, cl::desc("Allows loops to be peeled when the dynamic " "trip count is known to be low."))
A set of analyses that are preserved following a run of a transformation pass.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
LLVM Basic Block Representation.
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop...
Conditional or Unconditional Branch instruction.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
This is an important base class in LLVM.
static cl::opt< unsigned > UnrollMaxCount("unroll-max-count", cl::Hidden, cl::desc("Set the max unroll count for partial and runtime unrolling, for" "testing purposes"))
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void setLoopAlreadyUnrolled()
Add llvm.loop.unroll.disable to this loop's loop id metadata.
std::pair< iterator, bool > insert(const ValueT &V)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Represent the analysis usage information of a pass.
void analyzeBasicBlock(const BasicBlock *BB, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value *> &EphValues)
Add information about a block to the current state.
static cl::opt< unsigned > UnrollThreshold("unroll-threshold", cl::Hidden, cl::desc("The cost threshold for loop unrolling"))
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Optional< unsigned > getLoopEstimatedTripCount(Loop *L)
Get a loop's estimated trip count based on branch weight metadata.
bool hasProfileData(bool IncludeSynthetic=false) const
Return true if the function is annotated with profile data.
static cl::opt< unsigned > UnrollPeelCount("unroll-peel-count", cl::Hidden, cl::desc("Set the unroll peeling count, for testing purposes"))
void addSiblingLoops(ArrayRef< Loop *> NewSibLoops)
Loop passes should use this method to indicate they have added new sibling loops to the current loop...
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
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.
void markLoopAsDeleted(Loop &L, llvm::StringRef Name)
Loop passes should use this method to indicate they have deleted a loop from the nest.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
TargetTransformInfo & TTI
const char *const LLVMLoopUnrollFollowupAll
The transformation should not be applied.
A function analysis which provides an AssumptionCache.
unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls, bool &NotDuplicatable, bool &Convergent, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value *> &EphValues, unsigned BEInsns)
ApproximateLoopSize - Approximate the size of the loop.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
A SetVector that performs no allocations if smaller than a certain size.
Analysis pass which computes BlockFrequencyInfo.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
Align max(MaybeAlign Lhs, Align Rhs)
static cl::opt< bool > UnrollAllowPartial("unroll-allow-partial", cl::Hidden, cl::desc("Allows loops to be partially unrolled until " "-unroll-threshold loop size is reached."))
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
static cl::opt< unsigned > PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 *1024), cl::Hidden, cl::desc("Unrolled size limit for loops with an unroll(full) or " "unroll_count pragma."))
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Utility to calculate the size and a few similar metrics for a set of basic blocks.
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static unsigned UnrollCountPragmaValue(const Loop *L)
LLVM_NODISCARD T pop_back_val()
void markLoopAsDeleted(Loop &L)
static uint64_t getUnrolledLoopSize(unsigned LoopSize, TargetTransformInfo::UnrollingPreferences &UP)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Optional< MDNode * > makeFollowupLoopID(MDNode *OrigLoopID, ArrayRef< StringRef > FollowupAttrs, const char *InheritOptionsAttrsPrefix="", bool AlwaysNew=false)
Create a new loop identifier for a loop created from a loop transformation.
void clear()
Completely clear the SetVector.
amdgpu Simplify well known AMD library false FunctionCallee Callee
bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile...
static cl::opt< bool > UnrollUnrollRemainder("unroll-remainder", cl::Hidden, cl::desc("Allow the loop remainder to be unrolled."))
static cl::opt< unsigned > Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), cl::init(100), cl::Hidden)
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
MDNode * GetUnrollMetadata(MDNode *LoopID, StringRef Name)
Given an llvm.loop loop id metadata node, returns the loop hint metadata node with the given name (fo...
Analysis pass that exposes the ScalarEvolution for a function.
static const unsigned NoThreshold
A magic value for use with the Threshold parameter to indicate that the loop unroll should be perform...
LoopT * getParentLoop() const
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
bool empty() const
Determine if the SetVector is empty or not.
LoopUnrollResult UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, bool PreserveLCSSA, Loop **RemainderLoop=nullptr)
Unroll the given loop by Count.
iterator find(const_arg_type_t< ValueT > V)
TransformationMode hasUnrollTransformation(Loop *L)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
TransformationMode
The mode sets how eager a transformation should be applied.
static SmallVector< Loop *, 8 > appendLoopsToWorklist(RangeT &&Loops)
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...
Pass * createLoopUnrollPass(int OptLevel=2, bool OnlyWhenForced=false, bool ForgetAllSCEV=false, int Threshold=-1, int Count=-1, int AllowPartial=-1, int Runtime=-1, int UpperBound=-1, int AllowPeeling=-1)
static bool HasRuntimeUnrollDisablePragma(const Loop *L)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool hasHugeWorkingSetSize()
Returns true if the working set size of the code is considered huge.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
succ_range successors(Instruction *I)
The loop was not modified.
static cl::opt< unsigned > UnrollMaxIterationsCountToAnalyze("unroll-max-iteration-count-to-analyze", cl::init(10), cl::Hidden, cl::desc("Don't allow loop unrolling to simulate more than this number of" "iterations when checking full unroll profitability"))
bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
void verifyLoop() const
Verify loop structure.
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
This header defines various interfaces for pass management in LLVM.
unsigned getNumOperands() const
Return number of MDNode operands.
unsigned NumInsts
Number of instructions in the analyzed blocks.
iterator_range< block_iterator > blocks() const
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
LoopUnrollResult
Represents the result of a UnrollLoop invocation.