LoopUnrollPass.cpp 37 KB

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