LoopUnrollPass.cpp 38 KB

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