IVUsers.cpp 14 KB

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