IVUsers.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. //===- IVUsers.cpp - Induction Variable Users -------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements bookkeeping for "interesting" users of expressions
  10. // computed from induction variables.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Analysis/IVUsers.h"
  14. #include "llvm/Analysis/AssumptionCache.h"
  15. #include "llvm/Analysis/CodeMetrics.h"
  16. #include "llvm/Analysis/LoopAnalysisManager.h"
  17. #include "llvm/Analysis/LoopInfo.h"
  18. #include "llvm/Analysis/LoopPass.h"
  19. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/Config/llvm-config.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/Dominators.h"
  24. #include "llvm/IR/Instructions.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/InitializePasses.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. using namespace llvm;
  30. #define DEBUG_TYPE "iv-users"
  31. AnalysisKey IVUsersAnalysis::Key;
  32. IVUsers IVUsersAnalysis::run(Loop &L, LoopAnalysisManager &AM,
  33. LoopStandardAnalysisResults &AR) {
  34. return IVUsers(&L, &AR.AC, &AR.LI, &AR.DT, &AR.SE);
  35. }
  36. char IVUsersWrapperPass::ID = 0;
  37. INITIALIZE_PASS_BEGIN(IVUsersWrapperPass, "iv-users",
  38. "Induction Variable Users", false, true)
  39. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  40. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  41. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  42. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  43. INITIALIZE_PASS_END(IVUsersWrapperPass, "iv-users", "Induction Variable Users",
  44. false, true)
  45. Pass *llvm::createIVUsersPass() { return new IVUsersWrapperPass(); }
  46. /// isInteresting - Test whether the given expression is "interesting" when
  47. /// used by the given expression, within the context of analyzing the
  48. /// given loop.
  49. static bool isInteresting(const SCEV *S, const Instruction *I, const Loop *L,
  50. ScalarEvolution *SE, LoopInfo *LI) {
  51. // An addrec is interesting if it's affine or if it has an interesting start.
  52. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  53. // Keep things simple. Don't touch loop-variant strides unless they're
  54. // only used outside the loop and we can simplify them.
  55. if (AR->getLoop() == L)
  56. return AR->isAffine() ||
  57. (!L->contains(I) &&
  58. SE->getSCEVAtScope(AR, LI->getLoopFor(I->getParent())) != AR);
  59. // Otherwise recurse to see if the start value is interesting, and that
  60. // the step value is not interesting, since we don't yet know how to
  61. // do effective SCEV expansions for addrecs with interesting steps.
  62. return isInteresting(AR->getStart(), I, L, SE, LI) &&
  63. !isInteresting(AR->getStepRecurrence(*SE), I, L, SE, LI);
  64. }
  65. // An add is interesting if exactly one of its operands is interesting.
  66. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
  67. bool AnyInterestingYet = false;
  68. for (const auto *Op : Add->operands())
  69. if (isInteresting(Op, I, L, SE, LI)) {
  70. if (AnyInterestingYet)
  71. return false;
  72. AnyInterestingYet = true;
  73. }
  74. return AnyInterestingYet;
  75. }
  76. // Nothing else is interesting here.
  77. return false;
  78. }
  79. /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
  80. /// and now we need to decide whether the user should use the preinc or post-inc
  81. /// value. If this user should use the post-inc version of the IV, return true.
  82. ///
  83. /// Choosing wrong here can break dominance properties (if we choose to use the
  84. /// post-inc value when we cannot) or it can end up adding extra live-ranges to
  85. /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
  86. /// should use the post-inc value).
  87. static bool IVUseShouldUsePostIncValue(Instruction *User, Value *Operand,
  88. const Loop *L, DominatorTree *DT) {
  89. // If the user is in the loop, use the preinc value.
  90. if (L->contains(User))
  91. return false;
  92. BasicBlock *LatchBlock = L->getLoopLatch();
  93. if (!LatchBlock)
  94. return false;
  95. // Ok, the user is outside of the loop. If it is dominated by the latch
  96. // block, use the post-inc value.
  97. if (DT->dominates(LatchBlock, User->getParent()))
  98. return true;
  99. // There is one case we have to be careful of: PHI nodes. These little guys
  100. // can live in blocks that are not dominated by the latch block, but (since
  101. // their uses occur in the predecessor block, not the block the PHI lives in)
  102. // should still use the post-inc value. Check for this case now.
  103. PHINode *PN = dyn_cast<PHINode>(User);
  104. if (!PN || !Operand)
  105. return false; // not a phi, not dominated by latch block.
  106. // Look at all of the uses of Operand by the PHI node. If any use corresponds
  107. // to a block that is not dominated by the latch block, give up and use the
  108. // preincremented value.
  109. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  110. if (PN->getIncomingValue(i) == Operand &&
  111. !DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
  112. return false;
  113. // Okay, all uses of Operand by PN are in predecessor blocks that really are
  114. // dominated by the latch block. Use the post-incremented value.
  115. return true;
  116. }
  117. /// Inspect the specified instruction. If it is a reducible SCEV, recursively
  118. /// add its users to the IVUsesByStride set and return true. Otherwise, return
  119. /// false.
  120. bool IVUsers::AddUsersIfInteresting(Instruction *I) {
  121. const DataLayout &DL = I->getModule()->getDataLayout();
  122. // Add this IV user to the Processed set before returning false to ensure that
  123. // all IV users are members of the set. See IVUsers::isIVUserOrOperand.
  124. if (!Processed.insert(I).second)
  125. return true; // Instruction already handled.
  126. if (!SE->isSCEVable(I->getType()))
  127. return false; // Void and FP expressions cannot be reduced.
  128. // IVUsers is used by LSR which assumes that all SCEV expressions are safe to
  129. // pass to SCEVExpander. Expressions are not safe to expand if they represent
  130. // operations that are not safe to speculate, namely integer division.
  131. if (!isa<PHINode>(I) && !isSafeToSpeculativelyExecute(I))
  132. return false;
  133. // LSR is not APInt clean, do not touch integers bigger than 64-bits.
  134. // Also avoid creating IVs of non-native types. For example, we don't want a
  135. // 64-bit IV in 32-bit code just because the loop has one 64-bit cast.
  136. uint64_t Width = SE->getTypeSizeInBits(I->getType());
  137. if (Width > 64 || !DL.isLegalInteger(Width))
  138. return false;
  139. // Don't attempt to promote ephemeral values to indvars. They will be removed
  140. // later anyway.
  141. if (EphValues.count(I))
  142. return false;
  143. // Get the symbolic expression for this instruction.
  144. const SCEV *ISE = SE->getSCEV(I);
  145. // If we've come to an uninteresting expression, stop the traversal and
  146. // call this a user.
  147. if (!isInteresting(ISE, I, L, SE, LI))
  148. return false;
  149. SmallPtrSet<Instruction *, 4> UniqueUsers;
  150. for (Use &U : I->uses()) {
  151. Instruction *User = cast<Instruction>(U.getUser());
  152. if (!UniqueUsers.insert(User).second)
  153. continue;
  154. // Do not infinitely recurse on PHI nodes.
  155. if (isa<PHINode>(User) && Processed.count(User))
  156. continue;
  157. // Descend recursively, but not into PHI nodes outside the current loop.
  158. // It's important to see the entire expression outside the loop to get
  159. // choices that depend on addressing mode use right, although we won't
  160. // consider references outside the loop in all cases.
  161. // If User is already in Processed, we don't want to recurse into it again,
  162. // but do want to record a second reference in the same instruction.
  163. bool AddUserToIVUsers = false;
  164. if (LI->getLoopFor(User->getParent()) != L) {
  165. if (isa<PHINode>(User) || Processed.count(User) ||
  166. !AddUsersIfInteresting(User)) {
  167. LLVM_DEBUG(dbgs() << "FOUND USER in other loop: " << *User << '\n'
  168. << " OF SCEV: " << *ISE << '\n');
  169. AddUserToIVUsers = true;
  170. }
  171. } else if (Processed.count(User) || !AddUsersIfInteresting(User)) {
  172. LLVM_DEBUG(dbgs() << "FOUND USER: " << *User << '\n'
  173. << " OF SCEV: " << *ISE << '\n');
  174. AddUserToIVUsers = true;
  175. }
  176. if (AddUserToIVUsers) {
  177. // Okay, we found a user that we cannot reduce.
  178. IVStrideUse &NewUse = AddUser(User, I);
  179. // Autodetect the post-inc loop set, populating NewUse.PostIncLoops.
  180. // The regular return value here is discarded; instead of recording
  181. // it, we just recompute it when we need it.
  182. const SCEV *OriginalISE = ISE;
  183. auto NormalizePred = [&](const SCEVAddRecExpr *AR) {
  184. auto *L = AR->getLoop();
  185. bool Result = IVUseShouldUsePostIncValue(User, I, L, DT);
  186. if (Result)
  187. NewUse.PostIncLoops.insert(L);
  188. return Result;
  189. };
  190. ISE = normalizeForPostIncUseIf(ISE, NormalizePred, *SE);
  191. // PostIncNormalization effectively simplifies the expression under
  192. // pre-increment assumptions. Those assumptions (no wrapping) might not
  193. // hold for the post-inc value. Catch such cases by making sure the
  194. // transformation is invertible.
  195. if (OriginalISE != ISE) {
  196. const SCEV *DenormalizedISE =
  197. denormalizeForPostIncUse(ISE, NewUse.PostIncLoops, *SE);
  198. // If we normalized the expression, but denormalization doesn't give the
  199. // original one, discard this user.
  200. if (OriginalISE != DenormalizedISE) {
  201. LLVM_DEBUG(dbgs()
  202. << " DISCARDING (NORMALIZATION ISN'T INVERTIBLE): "
  203. << *ISE << '\n');
  204. IVUses.pop_back();
  205. return false;
  206. }
  207. }
  208. LLVM_DEBUG(if (SE->getSCEV(I) != ISE) dbgs()
  209. << " NORMALIZED TO: " << *ISE << '\n');
  210. }
  211. }
  212. return true;
  213. }
  214. IVStrideUse &IVUsers::AddUser(Instruction *User, Value *Operand) {
  215. IVUses.push_back(new IVStrideUse(this, User, Operand));
  216. return IVUses.back();
  217. }
  218. IVUsers::IVUsers(Loop *L, AssumptionCache *AC, LoopInfo *LI, DominatorTree *DT,
  219. ScalarEvolution *SE)
  220. : L(L), AC(AC), LI(LI), DT(DT), SE(SE) {
  221. // Collect ephemeral values so that AddUsersIfInteresting skips them.
  222. EphValues.clear();
  223. CodeMetrics::collectEphemeralValues(L, AC, EphValues);
  224. // Find all uses of induction variables in this loop, and categorize
  225. // them by stride. Start by finding all of the PHI nodes in the header for
  226. // this loop. If they are induction variables, inspect their uses.
  227. for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
  228. (void)AddUsersIfInteresting(&*I);
  229. }
  230. void IVUsers::print(raw_ostream &OS, const Module *M) const {
  231. OS << "IV Users for loop ";
  232. L->getHeader()->printAsOperand(OS, false);
  233. if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
  234. OS << " with backedge-taken count " << *SE->getBackedgeTakenCount(L);
  235. }
  236. OS << ":\n";
  237. for (const IVStrideUse &IVUse : IVUses) {
  238. OS << " ";
  239. IVUse.getOperandValToReplace()->printAsOperand(OS, false);
  240. OS << " = " << *getReplacementExpr(IVUse);
  241. for (const auto *PostIncLoop : IVUse.PostIncLoops) {
  242. OS << " (post-inc with loop ";
  243. PostIncLoop->getHeader()->printAsOperand(OS, false);
  244. OS << ")";
  245. }
  246. OS << " in ";
  247. if (IVUse.getUser())
  248. IVUse.getUser()->print(OS);
  249. else
  250. OS << "Printing <null> User";
  251. OS << '\n';
  252. }
  253. }
  254. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  255. LLVM_DUMP_METHOD void IVUsers::dump() const { print(dbgs()); }
  256. #endif
  257. void IVUsers::releaseMemory() {
  258. Processed.clear();
  259. IVUses.clear();
  260. }
  261. IVUsersWrapperPass::IVUsersWrapperPass() : LoopPass(ID) {
  262. initializeIVUsersWrapperPassPass(*PassRegistry::getPassRegistry());
  263. }
  264. void IVUsersWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
  265. AU.addRequired<AssumptionCacheTracker>();
  266. AU.addRequired<LoopInfoWrapperPass>();
  267. AU.addRequired<DominatorTreeWrapperPass>();
  268. AU.addRequired<ScalarEvolutionWrapperPass>();
  269. AU.setPreservesAll();
  270. }
  271. bool IVUsersWrapperPass::runOnLoop(Loop *L, LPPassManager &LPM) {
  272. auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
  273. *L->getHeader()->getParent());
  274. auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  275. auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  276. auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  277. IU.reset(new IVUsers(L, AC, LI, DT, SE));
  278. return false;
  279. }
  280. void IVUsersWrapperPass::print(raw_ostream &OS, const Module *M) const {
  281. IU->print(OS, M);
  282. }
  283. void IVUsersWrapperPass::releaseMemory() { IU->releaseMemory(); }
  284. /// getReplacementExpr - Return a SCEV expression which computes the
  285. /// value of the OperandValToReplace.
  286. const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &IU) const {
  287. return SE->getSCEV(IU.getOperandValToReplace());
  288. }
  289. /// getExpr - Return the expression for the use.
  290. const SCEV *IVUsers::getExpr(const IVStrideUse &IU) const {
  291. return normalizeForPostIncUse(getReplacementExpr(IU), IU.getPostIncLoops(),
  292. *SE);
  293. }
  294. static const SCEVAddRecExpr *findAddRecForLoop(const SCEV *S, const Loop *L) {
  295. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  296. if (AR->getLoop() == L)
  297. return AR;
  298. return findAddRecForLoop(AR->getStart(), L);
  299. }
  300. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
  301. for (const auto *Op : Add->operands())
  302. if (const SCEVAddRecExpr *AR = findAddRecForLoop(Op, L))
  303. return AR;
  304. return nullptr;
  305. }
  306. return nullptr;
  307. }
  308. const SCEV *IVUsers::getStride(const IVStrideUse &IU, const Loop *L) const {
  309. if (const SCEVAddRecExpr *AR = findAddRecForLoop(getExpr(IU), L))
  310. return AR->getStepRecurrence(*SE);
  311. return nullptr;
  312. }
  313. void IVStrideUse::transformToPostInc(const Loop *L) {
  314. PostIncLoops.insert(L);
  315. }
  316. void IVStrideUse::deleted() {
  317. // Remove this user from the list.
  318. Parent->Processed.erase(this->getUser());
  319. Parent->IVUses.erase(this);
  320. // this now dangles!
  321. }