LoopUnrollPass.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass implements a simple loop unroller. It works best when loops have
  11. // been canonicalized by the -indvars pass, allowing it to determine the trip
  12. // counts of loops easily.
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Scalar.h"
  15. #include "llvm/ADT/SetVector.h"
  16. #include "llvm/Analysis/AssumptionCache.h"
  17. #include "llvm/Analysis/CodeMetrics.h"
  18. #include "llvm/Analysis/InstructionSimplify.h"
  19. #include "llvm/Analysis/LoopPass.h"
  20. #include "llvm/Analysis/ScalarEvolution.h"
  21. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  22. #include "llvm/Analysis/TargetTransformInfo.h"
  23. #include "llvm/IR/DataLayout.h"
  24. #include "llvm/IR/DiagnosticInfo.h"
  25. #include "llvm/IR/Dominators.h"
  26. #include "llvm/IR/InstVisitor.h"
  27. #include "llvm/IR/IntrinsicInst.h"
  28. #include "llvm/IR/Metadata.h"
  29. #include "llvm/Support/CommandLine.h"
  30. #include "llvm/Support/Debug.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include "llvm/Transforms/Utils/UnrollLoop.h"
  33. #include <climits>
  34. using namespace llvm;
  35. #define DEBUG_TYPE "loop-unroll"
  36. static cl::opt<unsigned>
  37. UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
  38. cl::desc("The baseline cost threshold for loop unrolling"));
  39. static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold(
  40. "unroll-percent-dynamic-cost-saved-threshold", cl::init(20), cl::Hidden,
  41. cl::desc("The percentage of estimated dynamic cost which must be saved by "
  42. "unrolling to allow unrolling up to the max threshold."));
  43. static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount(
  44. "unroll-dynamic-cost-savings-discount", cl::init(2000), cl::Hidden,
  45. cl::desc("This is the amount discounted from the total unroll cost when "
  46. "the unrolled form has a high dynamic cost savings (triggered by "
  47. "the '-unroll-perecent-dynamic-cost-saved-threshold' flag)."));
  48. static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
  49. "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden,
  50. cl::desc("Don't allow loop unrolling to simulate more than this number of"
  51. "iterations when checking full unroll profitability"));
  52. static cl::opt<unsigned>
  53. UnrollCount("unroll-count", cl::init(0), cl::Hidden,
  54. cl::desc("Use this unroll count for all loops including those with "
  55. "unroll_count pragma values, for testing purposes"));
  56. static cl::opt<bool>
  57. UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
  58. cl::desc("Allows loops to be partially unrolled until "
  59. "-unroll-threshold loop size is reached."));
  60. static cl::opt<bool>
  61. UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden,
  62. cl::desc("Unroll loops with run-time trip counts"));
  63. static cl::opt<unsigned>
  64. PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
  65. cl::desc("Unrolled size limit for loops with an unroll(full) or "
  66. "unroll_count pragma."));
  67. namespace {
  68. class LoopUnroll : public LoopPass {
  69. public:
  70. static char ID; // Pass ID, replacement for typeid
  71. LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) {
  72. CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
  73. CurrentPercentDynamicCostSavedThreshold =
  74. UnrollPercentDynamicCostSavedThreshold;
  75. CurrentDynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount;
  76. CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
  77. CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
  78. CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R;
  79. UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
  80. UserPercentDynamicCostSavedThreshold =
  81. (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0);
  82. UserDynamicCostSavingsDiscount =
  83. (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0);
  84. UserAllowPartial = (P != -1) ||
  85. (UnrollAllowPartial.getNumOccurrences() > 0);
  86. UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0);
  87. UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0);
  88. initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
  89. }
  90. /// A magic value for use with the Threshold parameter to indicate
  91. /// that the loop unroll should be performed regardless of how much
  92. /// code expansion would result.
  93. static const unsigned NoThreshold = UINT_MAX;
  94. // Threshold to use when optsize is specified (and there is no
  95. // explicit -unroll-threshold).
  96. static const unsigned OptSizeUnrollThreshold = 50;
  97. // Default unroll count for loops with run-time trip count if
  98. // -unroll-count is not set
  99. static const unsigned UnrollRuntimeCount = 8;
  100. unsigned CurrentCount;
  101. unsigned CurrentThreshold;
  102. unsigned CurrentPercentDynamicCostSavedThreshold;
  103. unsigned CurrentDynamicCostSavingsDiscount;
  104. bool CurrentAllowPartial;
  105. bool CurrentRuntime;
  106. // Flags for whether the 'current' settings are user-specified.
  107. bool UserCount;
  108. bool UserThreshold;
  109. bool UserPercentDynamicCostSavedThreshold;
  110. bool UserDynamicCostSavingsDiscount;
  111. bool UserAllowPartial;
  112. bool UserRuntime;
  113. bool runOnLoop(Loop *L, LPPassManager &LPM) override;
  114. /// This transformation requires natural loop information & requires that
  115. /// loop preheaders be inserted into the CFG...
  116. ///
  117. void getAnalysisUsage(AnalysisUsage &AU) const override {
  118. AU.addRequired<AssumptionCacheTracker>();
  119. AU.addRequired<LoopInfoWrapperPass>();
  120. AU.addPreserved<LoopInfoWrapperPass>();
  121. AU.addRequiredID(LoopSimplifyID);
  122. AU.addPreservedID(LoopSimplifyID);
  123. AU.addRequiredID(LCSSAID);
  124. AU.addPreservedID(LCSSAID);
  125. AU.addRequired<ScalarEvolution>();
  126. AU.addPreserved<ScalarEvolution>();
  127. AU.addRequired<TargetTransformInfoWrapperPass>();
  128. // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
  129. // If loop unroll does not preserve dom info then LCSSA pass on next
  130. // loop will receive invalid dom info.
  131. // For now, recreate dom info, if loop is unrolled.
  132. AU.addPreserved<DominatorTreeWrapperPass>();
  133. }
  134. // Fill in the UnrollingPreferences parameter with values from the
  135. // TargetTransformationInfo.
  136. void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI,
  137. TargetTransformInfo::UnrollingPreferences &UP) {
  138. UP.Threshold = CurrentThreshold;
  139. UP.PercentDynamicCostSavedThreshold =
  140. CurrentPercentDynamicCostSavedThreshold;
  141. UP.DynamicCostSavingsDiscount = CurrentDynamicCostSavingsDiscount;
  142. UP.OptSizeThreshold = OptSizeUnrollThreshold;
  143. UP.PartialThreshold = CurrentThreshold;
  144. UP.PartialOptSizeThreshold = OptSizeUnrollThreshold;
  145. UP.Count = CurrentCount;
  146. UP.MaxCount = UINT_MAX;
  147. UP.Partial = CurrentAllowPartial;
  148. UP.Runtime = CurrentRuntime;
  149. UP.AllowExpensiveTripCount = false;
  150. TTI.getUnrollingPreferences(L, UP);
  151. }
  152. // Select and return an unroll count based on parameters from
  153. // user, unroll preferences, unroll pragmas, or a heuristic.
  154. // SetExplicitly is set to true if the unroll count is is set by
  155. // the user or a pragma rather than selected heuristically.
  156. unsigned
  157. selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
  158. unsigned PragmaCount,
  159. const TargetTransformInfo::UnrollingPreferences &UP,
  160. bool &SetExplicitly);
  161. // Select threshold values used to limit unrolling based on a
  162. // total unrolled size. Parameters Threshold and PartialThreshold
  163. // are set to the maximum unrolled size for fully and partially
  164. // unrolled loops respectively.
  165. void selectThresholds(const Loop *L, bool HasPragma,
  166. const TargetTransformInfo::UnrollingPreferences &UP,
  167. unsigned &Threshold, unsigned &PartialThreshold,
  168. unsigned &PercentDynamicCostSavedThreshold,
  169. unsigned &DynamicCostSavingsDiscount) {
  170. // Determine the current unrolling threshold. While this is
  171. // normally set from UnrollThreshold, it is overridden to a
  172. // smaller value if the current function is marked as
  173. // optimize-for-size, and the unroll threshold was not user
  174. // specified.
  175. Threshold = UserThreshold ? CurrentThreshold : UP.Threshold;
  176. PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold;
  177. PercentDynamicCostSavedThreshold =
  178. UserPercentDynamicCostSavedThreshold
  179. ? CurrentPercentDynamicCostSavedThreshold
  180. : UP.PercentDynamicCostSavedThreshold;
  181. DynamicCostSavingsDiscount = UserDynamicCostSavingsDiscount
  182. ? CurrentDynamicCostSavingsDiscount
  183. : UP.DynamicCostSavingsDiscount;
  184. if (!UserThreshold &&
  185. L->getHeader()->getParent()->hasFnAttribute(
  186. Attribute::OptimizeForSize)) {
  187. Threshold = UP.OptSizeThreshold;
  188. PartialThreshold = UP.PartialOptSizeThreshold;
  189. }
  190. if (HasPragma) {
  191. // If the loop has an unrolling pragma, we want to be more
  192. // aggressive with unrolling limits. Set thresholds to at
  193. // least the PragmaTheshold value which is larger than the
  194. // default limits.
  195. if (Threshold != NoThreshold)
  196. Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold);
  197. if (PartialThreshold != NoThreshold)
  198. PartialThreshold =
  199. std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold);
  200. }
  201. }
  202. bool canUnrollCompletely(Loop *L, unsigned Threshold,
  203. unsigned PercentDynamicCostSavedThreshold,
  204. unsigned DynamicCostSavingsDiscount,
  205. uint64_t UnrolledCost, uint64_t RolledDynamicCost);
  206. };
  207. }
  208. char LoopUnroll::ID = 0;
  209. INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
  210. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  211. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  212. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  213. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  214. INITIALIZE_PASS_DEPENDENCY(LCSSA)
  215. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  216. INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
  217. Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
  218. int Runtime) {
  219. return new LoopUnroll(Threshold, Count, AllowPartial, Runtime);
  220. }
  221. Pass *llvm::createSimpleLoopUnrollPass() {
  222. return llvm::createLoopUnrollPass(-1, -1, 0, 0);
  223. }
  224. namespace {
  225. // This class is used to get an estimate of the optimization effects that we
  226. // could get from complete loop unrolling. It comes from the fact that some
  227. // loads might be replaced with concrete constant values and that could trigger
  228. // a chain of instruction simplifications.
  229. //
  230. // E.g. we might have:
  231. // int a[] = {0, 1, 0};
  232. // v = 0;
  233. // for (i = 0; i < 3; i ++)
  234. // v += b[i]*a[i];
  235. // If we completely unroll the loop, we would get:
  236. // v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2]
  237. // Which then will be simplified to:
  238. // v = b[0]* 0 + b[1]* 1 + b[2]* 0
  239. // And finally:
  240. // v = b[1]
  241. class UnrolledInstAnalyzer : private InstVisitor<UnrolledInstAnalyzer, bool> {
  242. typedef InstVisitor<UnrolledInstAnalyzer, bool> Base;
  243. friend class InstVisitor<UnrolledInstAnalyzer, bool>;
  244. struct SimplifiedAddress {
  245. Value *Base = nullptr;
  246. ConstantInt *Offset = nullptr;
  247. };
  248. public:
  249. UnrolledInstAnalyzer(unsigned Iteration,
  250. DenseMap<Value *, Constant *> &SimplifiedValues,
  251. const Loop *L, ScalarEvolution &SE)
  252. : Iteration(Iteration), SimplifiedValues(SimplifiedValues), L(L), SE(SE) {
  253. IterationNumber = SE.getConstant(APInt(64, Iteration));
  254. }
  255. // Allow access to the initial visit method.
  256. using Base::visit;
  257. private:
  258. /// \brief A cache of pointer bases and constant-folded offsets corresponding
  259. /// to GEP (or derived from GEP) instructions.
  260. ///
  261. /// In order to find the base pointer one needs to perform non-trivial
  262. /// traversal of the corresponding SCEV expression, so it's good to have the
  263. /// results saved.
  264. DenseMap<Value *, SimplifiedAddress> SimplifiedAddresses;
  265. /// \brief Number of currently simulated iteration.
  266. ///
  267. /// If an expression is ConstAddress+Constant, then the Constant is
  268. /// Start + Iteration*Step, where Start and Step could be obtained from
  269. /// SCEVGEPCache.
  270. unsigned Iteration;
  271. /// \brief SCEV expression corresponding to number of currently simulated
  272. /// iteration.
  273. const SCEV *IterationNumber;
  274. /// \brief A Value->Constant map for keeping values that we managed to
  275. /// constant-fold on the given iteration.
  276. ///
  277. /// While we walk the loop instructions, we build up and maintain a mapping
  278. /// of simplified values specific to this iteration. The idea is to propagate
  279. /// any special information we have about loads that can be replaced with
  280. /// constants after complete unrolling, and account for likely simplifications
  281. /// post-unrolling.
  282. DenseMap<Value *, Constant *> &SimplifiedValues;
  283. const Loop *L;
  284. ScalarEvolution &SE;
  285. /// \brief Try to simplify instruction \param I using its SCEV expression.
  286. ///
  287. /// The idea is that some AddRec expressions become constants, which then
  288. /// could trigger folding of other instructions. However, that only happens
  289. /// for expressions whose start value is also constant, which isn't always the
  290. /// case. In another common and important case the start value is just some
  291. /// address (i.e. SCEVUnknown) - in this case we compute the offset and save
  292. /// it along with the base address instead.
  293. bool simplifyInstWithSCEV(Instruction *I) {
  294. if (!SE.isSCEVable(I->getType()))
  295. return false;
  296. const SCEV *S = SE.getSCEV(I);
  297. if (auto *SC = dyn_cast<SCEVConstant>(S)) {
  298. SimplifiedValues[I] = SC->getValue();
  299. return true;
  300. }
  301. auto *AR = dyn_cast<SCEVAddRecExpr>(S);
  302. if (!AR)
  303. return false;
  304. const SCEV *ValueAtIteration = AR->evaluateAtIteration(IterationNumber, SE);
  305. // Check if the AddRec expression becomes a constant.
  306. if (auto *SC = dyn_cast<SCEVConstant>(ValueAtIteration)) {
  307. SimplifiedValues[I] = SC->getValue();
  308. return true;
  309. }
  310. // Check if the offset from the base address becomes a constant.
  311. auto *Base = dyn_cast<SCEVUnknown>(SE.getPointerBase(S));
  312. if (!Base)
  313. return false;
  314. auto *Offset =
  315. dyn_cast<SCEVConstant>(SE.getMinusSCEV(ValueAtIteration, Base));
  316. if (!Offset)
  317. return false;
  318. SimplifiedAddress Address;
  319. Address.Base = Base->getValue();
  320. Address.Offset = Offset->getValue();
  321. SimplifiedAddresses[I] = Address;
  322. return true;
  323. }
  324. /// Base case for the instruction visitor.
  325. bool visitInstruction(Instruction &I) {
  326. return simplifyInstWithSCEV(&I);
  327. }
  328. /// TODO: Add visitors for other instruction types, e.g. ZExt, SExt.
  329. /// Try to simplify binary operator I.
  330. ///
  331. /// TODO: Probaly it's worth to hoist the code for estimating the
  332. /// simplifications effects to a separate class, since we have a very similar
  333. /// code in InlineCost already.
  334. bool visitBinaryOperator(BinaryOperator &I) {
  335. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  336. if (!isa<Constant>(LHS))
  337. if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
  338. LHS = SimpleLHS;
  339. if (!isa<Constant>(RHS))
  340. if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
  341. RHS = SimpleRHS;
  342. Value *SimpleV = nullptr;
  343. const DataLayout &DL = I.getModule()->getDataLayout();
  344. if (auto FI = dyn_cast<FPMathOperator>(&I))
  345. SimpleV =
  346. SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
  347. else
  348. SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
  349. if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
  350. SimplifiedValues[&I] = C;
  351. if (SimpleV)
  352. return true;
  353. return Base::visitBinaryOperator(I);
  354. }
  355. /// Try to fold load I.
  356. bool visitLoad(LoadInst &I) {
  357. Value *AddrOp = I.getPointerOperand();
  358. auto AddressIt = SimplifiedAddresses.find(AddrOp);
  359. if (AddressIt == SimplifiedAddresses.end())
  360. return false;
  361. ConstantInt *SimplifiedAddrOp = AddressIt->second.Offset;
  362. auto *GV = dyn_cast<GlobalVariable>(AddressIt->second.Base);
  363. // We're only interested in loads that can be completely folded to a
  364. // constant.
  365. if (!GV || !GV->hasInitializer())
  366. return false;
  367. ConstantDataSequential *CDS =
  368. dyn_cast<ConstantDataSequential>(GV->getInitializer());
  369. if (!CDS)
  370. return false;
  371. int ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
  372. assert(SimplifiedAddrOp->getValue().getActiveBits() < 64 &&
  373. "Unexpectedly large index value.");
  374. int64_t Index = SimplifiedAddrOp->getSExtValue() / ElemSize;
  375. if (Index >= CDS->getNumElements()) {
  376. // FIXME: For now we conservatively ignore out of bound accesses, but
  377. // we're allowed to perform the optimization in this case.
  378. return false;
  379. }
  380. Constant *CV = CDS->getElementAsConstant(Index);
  381. assert(CV && "Constant expected.");
  382. SimplifiedValues[&I] = CV;
  383. return true;
  384. }
  385. };
  386. } // namespace
  387. namespace {
  388. struct EstimatedUnrollCost {
  389. /// \brief The estimated cost after unrolling.
  390. unsigned UnrolledCost;
  391. /// \brief The estimated dynamic cost of executing the instructions in the
  392. /// rolled form.
  393. unsigned RolledDynamicCost;
  394. };
  395. }
  396. /// \brief Figure out if the loop is worth full unrolling.
  397. ///
  398. /// Complete loop unrolling can make some loads constant, and we need to know
  399. /// if that would expose any further optimization opportunities. This routine
  400. /// estimates this optimization. It computes cost of unrolled loop
  401. /// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
  402. /// dynamic cost we mean that we won't count costs of blocks that are known not
  403. /// to be executed (i.e. if we have a branch in the loop and we know that at the
  404. /// given iteration its condition would be resolved to true, we won't add up the
  405. /// cost of the 'false'-block).
  406. /// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
  407. /// the analysis failed (no benefits expected from the unrolling, or the loop is
  408. /// too big to analyze), the returned value is None.
  409. Optional<EstimatedUnrollCost>
  410. analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, ScalarEvolution &SE,
  411. const TargetTransformInfo &TTI,
  412. unsigned MaxUnrolledLoopSize) {
  413. // We want to be able to scale offsets by the trip count and add more offsets
  414. // to them without checking for overflows, and we already don't want to
  415. // analyze *massive* trip counts, so we force the max to be reasonably small.
  416. assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
  417. "The unroll iterations max is too large!");
  418. // Don't simulate loops with a big or unknown tripcount
  419. if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
  420. TripCount > UnrollMaxIterationsCountToAnalyze)
  421. return None;
  422. SmallSetVector<BasicBlock *, 16> BBWorklist;
  423. DenseMap<Value *, Constant *> SimplifiedValues;
  424. // The estimated cost of the unrolled form of the loop. We try to estimate
  425. // this by simplifying as much as we can while computing the estimate.
  426. unsigned UnrolledCost = 0;
  427. // We also track the estimated dynamic (that is, actually executed) cost in
  428. // the rolled form. This helps identify cases when the savings from unrolling
  429. // aren't just exposing dead control flows, but actual reduced dynamic
  430. // instructions due to the simplifications which we expect to occur after
  431. // unrolling.
  432. unsigned RolledDynamicCost = 0;
  433. // Simulate execution of each iteration of the loop counting instructions,
  434. // which would be simplified.
  435. // Since the same load will take different values on different iterations,
  436. // we literally have to go through all loop's iterations.
  437. for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
  438. SimplifiedValues.clear();
  439. UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, L, SE);
  440. BBWorklist.clear();
  441. BBWorklist.insert(L->getHeader());
  442. // Note that we *must not* cache the size, this loop grows the worklist.
  443. for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
  444. BasicBlock *BB = BBWorklist[Idx];
  445. // Visit all instructions in the given basic block and try to simplify
  446. // it. We don't change the actual IR, just count optimization
  447. // opportunities.
  448. for (Instruction &I : *BB) {
  449. unsigned InstCost = TTI.getUserCost(&I);
  450. // Visit the instruction to analyze its loop cost after unrolling,
  451. // and if the visitor returns false, include this instruction in the
  452. // unrolled cost.
  453. if (!Analyzer.visit(I))
  454. UnrolledCost += InstCost;
  455. // Also track this instructions expected cost when executing the rolled
  456. // loop form.
  457. RolledDynamicCost += InstCost;
  458. // If unrolled body turns out to be too big, bail out.
  459. if (UnrolledCost > MaxUnrolledLoopSize)
  460. return None;
  461. }
  462. // Add BB's successors to the worklist.
  463. for (BasicBlock *Succ : successors(BB))
  464. if (L->contains(Succ))
  465. BBWorklist.insert(Succ);
  466. }
  467. // If we found no optimization opportunities on the first iteration, we
  468. // won't find them on later ones too.
  469. if (UnrolledCost == RolledDynamicCost)
  470. return None;
  471. }
  472. return {{UnrolledCost, RolledDynamicCost}};
  473. }
  474. /// ApproximateLoopSize - Approximate the size of the loop.
  475. static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
  476. bool &NotDuplicatable,
  477. const TargetTransformInfo &TTI,
  478. AssumptionCache *AC) {
  479. SmallPtrSet<const Value *, 32> EphValues;
  480. CodeMetrics::collectEphemeralValues(L, AC, EphValues);
  481. CodeMetrics Metrics;
  482. for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
  483. I != E; ++I)
  484. Metrics.analyzeBasicBlock(*I, TTI, EphValues);
  485. NumCalls = Metrics.NumInlineCandidates;
  486. NotDuplicatable = Metrics.notDuplicatable;
  487. unsigned LoopSize = Metrics.NumInsts;
  488. // Don't allow an estimate of size zero. This would allows unrolling of loops
  489. // with huge iteration counts, which is a compile time problem even if it's
  490. // not a problem for code quality. Also, the code using this size may assume
  491. // that each loop has at least three instructions (likely a conditional
  492. // branch, a comparison feeding that branch, and some kind of loop increment
  493. // feeding that comparison instruction).
  494. LoopSize = std::max(LoopSize, 3u);
  495. return LoopSize;
  496. }
  497. // Returns the loop hint metadata node with the given name (for example,
  498. // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
  499. // returned.
  500. static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
  501. if (MDNode *LoopID = L->getLoopID())
  502. return GetUnrollMetadata(LoopID, Name);
  503. return nullptr;
  504. }
  505. // Returns true if the loop has an unroll(full) pragma.
  506. static bool HasUnrollFullPragma(const Loop *L) {
  507. return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
  508. }
  509. // Returns true if the loop has an unroll(disable) pragma.
  510. static bool HasUnrollDisablePragma(const Loop *L) {
  511. return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
  512. }
  513. // Returns true if the loop has an runtime unroll(disable) pragma.
  514. static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
  515. return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
  516. }
  517. // If loop has an unroll_count pragma return the (necessarily
  518. // positive) value from the pragma. Otherwise return 0.
  519. static unsigned UnrollCountPragmaValue(const Loop *L) {
  520. MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
  521. if (MD) {
  522. assert(MD->getNumOperands() == 2 &&
  523. "Unroll count hint metadata should have two operands.");
  524. unsigned Count =
  525. mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
  526. assert(Count >= 1 && "Unroll count must be positive.");
  527. return Count;
  528. }
  529. return 0;
  530. }
  531. // Remove existing unroll metadata and add unroll disable metadata to
  532. // indicate the loop has already been unrolled. This prevents a loop
  533. // from being unrolled more than is directed by a pragma if the loop
  534. // unrolling pass is run more than once (which it generally is).
  535. static void SetLoopAlreadyUnrolled(Loop *L) {
  536. MDNode *LoopID = L->getLoopID();
  537. if (!LoopID) return;
  538. // First remove any existing loop unrolling metadata.
  539. SmallVector<Metadata *, 4> MDs;
  540. // Reserve first location for self reference to the LoopID metadata node.
  541. MDs.push_back(nullptr);
  542. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  543. bool IsUnrollMetadata = false;
  544. MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  545. if (MD) {
  546. const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
  547. IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
  548. }
  549. if (!IsUnrollMetadata)
  550. MDs.push_back(LoopID->getOperand(i));
  551. }
  552. // Add unroll(disable) metadata to disable future unrolling.
  553. LLVMContext &Context = L->getHeader()->getContext();
  554. SmallVector<Metadata *, 1> DisableOperands;
  555. DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
  556. MDNode *DisableNode = MDNode::get(Context, DisableOperands);
  557. MDs.push_back(DisableNode);
  558. MDNode *NewLoopID = MDNode::get(Context, MDs);
  559. // Set operand 0 to refer to the loop id itself.
  560. NewLoopID->replaceOperandWith(0, NewLoopID);
  561. L->setLoopID(NewLoopID);
  562. }
  563. bool LoopUnroll::canUnrollCompletely(Loop *L, unsigned Threshold,
  564. unsigned PercentDynamicCostSavedThreshold,
  565. unsigned DynamicCostSavingsDiscount,
  566. uint64_t UnrolledCost,
  567. uint64_t RolledDynamicCost) {
  568. if (Threshold == NoThreshold) {
  569. DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n");
  570. return true;
  571. }
  572. if (UnrolledCost <= Threshold) {
  573. DEBUG(dbgs() << " Can fully unroll, because unrolled cost: "
  574. << UnrolledCost << "<" << Threshold << "\n");
  575. return true;
  576. }
  577. assert(UnrolledCost && "UnrolledCost can't be 0 at this point.");
  578. assert(RolledDynamicCost >= UnrolledCost &&
  579. "Cannot have a higher unrolled cost than a rolled cost!");
  580. // Compute the percentage of the dynamic cost in the rolled form that is
  581. // saved when unrolled. If unrolling dramatically reduces the estimated
  582. // dynamic cost of the loop, we use a higher threshold to allow more
  583. // unrolling.
  584. unsigned PercentDynamicCostSaved =
  585. (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost;
  586. if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold &&
  587. (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <=
  588. (int64_t)Threshold) {
  589. DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the "
  590. "expected dynamic cost by " << PercentDynamicCostSaved
  591. << "% (threshold: " << PercentDynamicCostSavedThreshold
  592. << "%)\n"
  593. << " and the unrolled cost (" << UnrolledCost
  594. << ") is less than the max threshold ("
  595. << DynamicCostSavingsDiscount << ").\n");
  596. return true;
  597. }
  598. DEBUG(dbgs() << " Too large to fully unroll:\n");
  599. DEBUG(dbgs() << " Threshold: " << Threshold << "\n");
  600. DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n");
  601. DEBUG(dbgs() << " Percent cost saved threshold: "
  602. << PercentDynamicCostSavedThreshold << "%\n");
  603. DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n");
  604. DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n");
  605. DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved
  606. << "\n");
  607. return false;
  608. }
  609. unsigned LoopUnroll::selectUnrollCount(
  610. const Loop *L, unsigned TripCount, bool PragmaFullUnroll,
  611. unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP,
  612. bool &SetExplicitly) {
  613. SetExplicitly = true;
  614. // User-specified count (either as a command-line option or
  615. // constructor parameter) has highest precedence.
  616. unsigned Count = UserCount ? CurrentCount : 0;
  617. // If there is no user-specified count, unroll pragmas have the next
  618. // highest precendence.
  619. if (Count == 0) {
  620. if (PragmaCount) {
  621. Count = PragmaCount;
  622. } else if (PragmaFullUnroll) {
  623. Count = TripCount;
  624. }
  625. }
  626. if (Count == 0)
  627. Count = UP.Count;
  628. if (Count == 0) {
  629. SetExplicitly = false;
  630. if (TripCount == 0)
  631. // Runtime trip count.
  632. Count = UnrollRuntimeCount;
  633. else
  634. // Conservative heuristic: if we know the trip count, see if we can
  635. // completely unroll (subject to the threshold, checked below); otherwise
  636. // try to find greatest modulo of the trip count which is still under
  637. // threshold value.
  638. Count = TripCount;
  639. }
  640. if (TripCount && Count > TripCount)
  641. return TripCount;
  642. return Count;
  643. }
  644. bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
  645. if (skipOptnoneFunction(L))
  646. return false;
  647. Function &F = *L->getHeader()->getParent();
  648. LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  649. ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
  650. const TargetTransformInfo &TTI =
  651. getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  652. auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  653. BasicBlock *Header = L->getHeader();
  654. DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
  655. << "] Loop %" << Header->getName() << "\n");
  656. if (HasUnrollDisablePragma(L)) {
  657. return false;
  658. }
  659. bool PragmaFullUnroll = HasUnrollFullPragma(L);
  660. unsigned PragmaCount = UnrollCountPragmaValue(L);
  661. bool HasPragma = PragmaFullUnroll || PragmaCount > 0;
  662. TargetTransformInfo::UnrollingPreferences UP;
  663. getUnrollingPreferences(L, TTI, UP);
  664. // Find trip count and trip multiple if count is not available
  665. unsigned TripCount = 0;
  666. unsigned TripMultiple = 1;
  667. // If there are multiple exiting blocks but one of them is the latch, use the
  668. // latch for the trip count estimation. Otherwise insist on a single exiting
  669. // block for the trip count estimation.
  670. BasicBlock *ExitingBlock = L->getLoopLatch();
  671. if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
  672. ExitingBlock = L->getExitingBlock();
  673. if (ExitingBlock) {
  674. TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
  675. TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
  676. }
  677. // Select an initial unroll count. This may be reduced later based
  678. // on size thresholds.
  679. bool CountSetExplicitly;
  680. unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll,
  681. PragmaCount, UP, CountSetExplicitly);
  682. unsigned NumInlineCandidates;
  683. bool notDuplicatable;
  684. unsigned LoopSize =
  685. ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC);
  686. DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
  687. // When computing the unrolled size, note that the conditional branch on the
  688. // backedge and the comparison feeding it are not replicated like the rest of
  689. // the loop body (which is why 2 is subtracted).
  690. uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2;
  691. if (notDuplicatable) {
  692. DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
  693. << " instructions.\n");
  694. return false;
  695. }
  696. if (NumInlineCandidates != 0) {
  697. DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
  698. return false;
  699. }
  700. unsigned Threshold, PartialThreshold;
  701. unsigned PercentDynamicCostSavedThreshold;
  702. unsigned DynamicCostSavingsDiscount;
  703. selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold,
  704. PercentDynamicCostSavedThreshold,
  705. DynamicCostSavingsDiscount);
  706. // Given Count, TripCount and thresholds determine the type of
  707. // unrolling which is to be performed.
  708. enum { Full = 0, Partial = 1, Runtime = 2 };
  709. int Unrolling;
  710. if (TripCount && Count == TripCount) {
  711. Unrolling = Partial;
  712. // If the loop is really small, we don't need to run an expensive analysis.
  713. if (canUnrollCompletely(L, Threshold, 100, DynamicCostSavingsDiscount,
  714. UnrolledSize, UnrolledSize)) {
  715. Unrolling = Full;
  716. } else {
  717. // The loop isn't that small, but we still can fully unroll it if that
  718. // helps to remove a significant number of instructions.
  719. // To check that, run additional analysis on the loop.
  720. if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
  721. L, TripCount, *SE, TTI, Threshold + DynamicCostSavingsDiscount))
  722. if (canUnrollCompletely(L, Threshold, PercentDynamicCostSavedThreshold,
  723. DynamicCostSavingsDiscount, Cost->UnrolledCost,
  724. Cost->RolledDynamicCost)) {
  725. Unrolling = Full;
  726. }
  727. }
  728. } else if (TripCount && Count < TripCount) {
  729. Unrolling = Partial;
  730. } else {
  731. Unrolling = Runtime;
  732. }
  733. // Reduce count based on the type of unrolling and the threshold values.
  734. unsigned OriginalCount = Count;
  735. bool AllowRuntime =
  736. (PragmaCount > 0) || (UserRuntime ? CurrentRuntime : UP.Runtime);
  737. // Don't unroll a runtime trip count loop with unroll full pragma.
  738. if (HasRuntimeUnrollDisablePragma(L) || PragmaFullUnroll) {
  739. AllowRuntime = false;
  740. }
  741. if (Unrolling == Partial) {
  742. bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial;
  743. if (!AllowPartial && !CountSetExplicitly) {
  744. DEBUG(dbgs() << " will not try to unroll partially because "
  745. << "-unroll-allow-partial not given\n");
  746. return false;
  747. }
  748. if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) {
  749. // Reduce unroll count to be modulo of TripCount for partial unrolling.
  750. Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2);
  751. while (Count != 0 && TripCount % Count != 0)
  752. Count--;
  753. }
  754. } else if (Unrolling == Runtime) {
  755. if (!AllowRuntime && !CountSetExplicitly) {
  756. DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
  757. << "-unroll-runtime not given\n");
  758. return false;
  759. }
  760. // Reduce unroll count to be the largest power-of-two factor of
  761. // the original count which satisfies the threshold limit.
  762. while (Count != 0 && UnrolledSize > PartialThreshold) {
  763. Count >>= 1;
  764. UnrolledSize = (LoopSize-2) * Count + 2;
  765. }
  766. if (Count > UP.MaxCount)
  767. Count = UP.MaxCount;
  768. DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n");
  769. }
  770. if (HasPragma) {
  771. if (PragmaCount != 0)
  772. // If loop has an unroll count pragma mark loop as unrolled to prevent
  773. // unrolling beyond that requested by the pragma.
  774. SetLoopAlreadyUnrolled(L);
  775. // Emit optimization remarks if we are unable to unroll the loop
  776. // as directed by a pragma.
  777. DebugLoc LoopLoc = L->getStartLoc();
  778. Function *F = Header->getParent();
  779. LLVMContext &Ctx = F->getContext();
  780. if (PragmaFullUnroll && PragmaCount == 0) {
  781. if (TripCount && Count != TripCount) {
  782. emitOptimizationRemarkMissed(
  783. Ctx, DEBUG_TYPE, *F, LoopLoc,
  784. "Unable to fully unroll loop as directed by unroll(full) pragma "
  785. "because unrolled size is too large.");
  786. } else if (!TripCount) {
  787. emitOptimizationRemarkMissed(
  788. Ctx, DEBUG_TYPE, *F, LoopLoc,
  789. "Unable to fully unroll loop as directed by unroll(full) pragma "
  790. "because loop has a runtime trip count.");
  791. }
  792. } else if (PragmaCount > 0 && Count != OriginalCount) {
  793. emitOptimizationRemarkMissed(
  794. Ctx, DEBUG_TYPE, *F, LoopLoc,
  795. "Unable to unroll loop the number of times directed by "
  796. "unroll_count pragma because unrolled size is too large.");
  797. }
  798. }
  799. if (Unrolling != Full && Count < 2) {
  800. // Partial unrolling by 1 is a nop. For full unrolling, a factor
  801. // of 1 makes sense because loop control can be eliminated.
  802. return false;
  803. }
  804. // Unroll the loop.
  805. if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount,
  806. TripMultiple, LI, this, &LPM, &AC))
  807. return false;
  808. return true;
  809. }