LCSSA.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. //===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
  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 transforms loops by placing phi nodes at the end of the loops for
  11. // all values that are live across the loop boundary. For example, it turns
  12. // the left into the right code:
  13. //
  14. // for (...) for (...)
  15. // if (c) if (c)
  16. // X1 = ... X1 = ...
  17. // else else
  18. // X2 = ... X2 = ...
  19. // X3 = phi(X1, X2) X3 = phi(X1, X2)
  20. // ... = X3 + 4 X4 = phi(X3)
  21. // ... = X4 + 4
  22. //
  23. // This is still valid LLVM; the extra phi nodes are purely redundant, and will
  24. // be trivially eliminated by InstCombine. The major benefit of this
  25. // transformation is that it makes many other loop optimizations, such as
  26. // LoopUnswitching, simpler.
  27. //
  28. //===----------------------------------------------------------------------===//
  29. #include "llvm/Transforms/Scalar.h"
  30. #include "llvm/ADT/STLExtras.h"
  31. #include "llvm/ADT/Statistic.h"
  32. #include "llvm/Analysis/AliasAnalysis.h"
  33. #include "llvm/Analysis/LoopPass.h"
  34. #include "llvm/Analysis/ScalarEvolution.h"
  35. #include "llvm/IR/Constants.h"
  36. #include "llvm/IR/Dominators.h"
  37. #include "llvm/IR/Function.h"
  38. #include "llvm/IR/Instructions.h"
  39. #include "llvm/IR/PredIteratorCache.h"
  40. #include "llvm/Pass.h"
  41. #include "llvm/Transforms/Utils/LoopUtils.h"
  42. #include "llvm/Transforms/Utils/SSAUpdater.h"
  43. using namespace llvm;
  44. #define DEBUG_TYPE "lcssa"
  45. STATISTIC(NumLCSSA, "Number of live out of a loop variables");
  46. /// Return true if the specified block is in the list.
  47. static bool isExitBlock(BasicBlock *BB,
  48. const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
  49. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
  50. if (ExitBlocks[i] == BB)
  51. return true;
  52. return false;
  53. }
  54. /// Given an instruction in the loop, check to see if it has any uses that are
  55. /// outside the current loop. If so, insert LCSSA PHI nodes and rewrite the
  56. /// uses.
  57. static bool processInstruction(Loop &L, Instruction &Inst, DominatorTree &DT,
  58. const SmallVectorImpl<BasicBlock *> &ExitBlocks,
  59. PredIteratorCache &PredCache, LoopInfo *LI) {
  60. SmallVector<Use *, 16> UsesToRewrite;
  61. BasicBlock *InstBB = Inst.getParent();
  62. for (Use &U : Inst.uses()) {
  63. Instruction *User = cast<Instruction>(U.getUser());
  64. BasicBlock *UserBB = User->getParent();
  65. if (PHINode *PN = dyn_cast<PHINode>(User))
  66. UserBB = PN->getIncomingBlock(U);
  67. if (InstBB != UserBB && !L.contains(UserBB))
  68. UsesToRewrite.push_back(&U);
  69. }
  70. // If there are no uses outside the loop, exit with no change.
  71. if (UsesToRewrite.empty())
  72. return false;
  73. ++NumLCSSA; // We are applying the transformation
  74. // Invoke instructions are special in that their result value is not available
  75. // along their unwind edge. The code below tests to see whether DomBB
  76. // dominates
  77. // the value, so adjust DomBB to the normal destination block, which is
  78. // effectively where the value is first usable.
  79. BasicBlock *DomBB = Inst.getParent();
  80. if (InvokeInst *Inv = dyn_cast<InvokeInst>(&Inst))
  81. DomBB = Inv->getNormalDest();
  82. DomTreeNode *DomNode = DT.getNode(DomBB);
  83. SmallVector<PHINode *, 16> AddedPHIs;
  84. SmallVector<PHINode *, 8> PostProcessPHIs;
  85. SSAUpdater SSAUpdate;
  86. SSAUpdate.Initialize(Inst.getType(), Inst.getName());
  87. // Insert the LCSSA phi's into all of the exit blocks dominated by the
  88. // value, and add them to the Phi's map.
  89. for (SmallVectorImpl<BasicBlock *>::const_iterator BBI = ExitBlocks.begin(),
  90. BBE = ExitBlocks.end();
  91. BBI != BBE; ++BBI) {
  92. BasicBlock *ExitBB = *BBI;
  93. if (!DT.dominates(DomNode, DT.getNode(ExitBB)))
  94. continue;
  95. // If we already inserted something for this BB, don't reprocess it.
  96. if (SSAUpdate.HasValueForBlock(ExitBB))
  97. continue;
  98. PHINode *PN = PHINode::Create(Inst.getType(), PredCache.size(ExitBB),
  99. Inst.getName() + ".lcssa", ExitBB->begin());
  100. // Add inputs from inside the loop for this PHI.
  101. for (BasicBlock *Pred : PredCache.get(ExitBB)) {
  102. PN->addIncoming(&Inst, Pred);
  103. // If the exit block has a predecessor not within the loop, arrange for
  104. // the incoming value use corresponding to that predecessor to be
  105. // rewritten in terms of a different LCSSA PHI.
  106. if (!L.contains(Pred))
  107. UsesToRewrite.push_back(
  108. &PN->getOperandUse(PN->getOperandNumForIncomingValue(
  109. PN->getNumIncomingValues() - 1)));
  110. }
  111. AddedPHIs.push_back(PN);
  112. // Remember that this phi makes the value alive in this block.
  113. SSAUpdate.AddAvailableValue(ExitBB, PN);
  114. // LoopSimplify might fail to simplify some loops (e.g. when indirect
  115. // branches are involved). In such situations, it might happen that an exit
  116. // for Loop L1 is the header of a disjoint Loop L2. Thus, when we create
  117. // PHIs in such an exit block, we are also inserting PHIs into L2's header.
  118. // This could break LCSSA form for L2 because these inserted PHIs can also
  119. // have uses outside of L2. Remember all PHIs in such situation as to
  120. // revisit than later on. FIXME: Remove this if indirectbr support into
  121. // LoopSimplify gets improved.
  122. if (auto *OtherLoop = LI->getLoopFor(ExitBB))
  123. if (!L.contains(OtherLoop))
  124. PostProcessPHIs.push_back(PN);
  125. }
  126. // Rewrite all uses outside the loop in terms of the new PHIs we just
  127. // inserted.
  128. for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) {
  129. // If this use is in an exit block, rewrite to use the newly inserted PHI.
  130. // This is required for correctness because SSAUpdate doesn't handle uses in
  131. // the same block. It assumes the PHI we inserted is at the end of the
  132. // block.
  133. Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser());
  134. BasicBlock *UserBB = User->getParent();
  135. if (PHINode *PN = dyn_cast<PHINode>(User))
  136. UserBB = PN->getIncomingBlock(*UsesToRewrite[i]);
  137. if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) {
  138. // Tell the VHs that the uses changed. This updates SCEV's caches.
  139. if (UsesToRewrite[i]->get()->hasValueHandle())
  140. ValueHandleBase::ValueIsRAUWd(*UsesToRewrite[i], UserBB->begin());
  141. UsesToRewrite[i]->set(UserBB->begin());
  142. continue;
  143. }
  144. // Otherwise, do full PHI insertion.
  145. SSAUpdate.RewriteUse(*UsesToRewrite[i]);
  146. }
  147. // Post process PHI instructions that were inserted into another disjoint loop
  148. // and update their exits properly.
  149. for (auto *I : PostProcessPHIs) {
  150. if (I->use_empty())
  151. continue;
  152. BasicBlock *PHIBB = I->getParent();
  153. Loop *OtherLoop = LI->getLoopFor(PHIBB);
  154. SmallVector<BasicBlock *, 8> EBs;
  155. OtherLoop->getExitBlocks(EBs);
  156. if (EBs.empty())
  157. continue;
  158. // Recurse and re-process each PHI instruction. FIXME: we should really
  159. // convert this entire thing to a worklist approach where we process a
  160. // vector of instructions...
  161. processInstruction(*OtherLoop, *I, DT, EBs, PredCache, LI);
  162. }
  163. // Remove PHI nodes that did not have any uses rewritten.
  164. for (unsigned i = 0, e = AddedPHIs.size(); i != e; ++i) {
  165. if (AddedPHIs[i]->use_empty())
  166. AddedPHIs[i]->eraseFromParent();
  167. }
  168. return true;
  169. }
  170. /// Return true if the specified block dominates at least
  171. /// one of the blocks in the specified list.
  172. static bool
  173. blockDominatesAnExit(BasicBlock *BB,
  174. DominatorTree &DT,
  175. const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
  176. DomTreeNode *DomNode = DT.getNode(BB);
  177. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
  178. if (DT.dominates(DomNode, DT.getNode(ExitBlocks[i])))
  179. return true;
  180. return false;
  181. }
  182. bool llvm::formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI,
  183. ScalarEvolution *SE) {
  184. bool Changed = false;
  185. // Get the set of exiting blocks.
  186. SmallVector<BasicBlock *, 8> ExitBlocks;
  187. L.getExitBlocks(ExitBlocks);
  188. if (ExitBlocks.empty())
  189. return false;
  190. PredIteratorCache PredCache;
  191. // Look at all the instructions in the loop, checking to see if they have uses
  192. // outside the loop. If so, rewrite those uses.
  193. for (Loop::block_iterator BBI = L.block_begin(), BBE = L.block_end();
  194. BBI != BBE; ++BBI) {
  195. BasicBlock *BB = *BBI;
  196. // For large loops, avoid use-scanning by using dominance information: In
  197. // particular, if a block does not dominate any of the loop exits, then none
  198. // of the values defined in the block could be used outside the loop.
  199. if (!blockDominatesAnExit(BB, DT, ExitBlocks))
  200. continue;
  201. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  202. // Reject two common cases fast: instructions with no uses (like stores)
  203. // and instructions with one use that is in the same block as this.
  204. if (I->use_empty() ||
  205. (I->hasOneUse() && I->user_back()->getParent() == BB &&
  206. !isa<PHINode>(I->user_back())))
  207. continue;
  208. Changed |= processInstruction(L, *I, DT, ExitBlocks, PredCache, LI);
  209. }
  210. }
  211. // If we modified the code, remove any caches about the loop from SCEV to
  212. // avoid dangling entries.
  213. // FIXME: This is a big hammer, can we clear the cache more selectively?
  214. if (SE && Changed)
  215. SE->forgetLoop(&L);
  216. assert(L.isLCSSAForm(DT));
  217. return Changed;
  218. }
  219. /// Process a loop nest depth first.
  220. bool llvm::formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI,
  221. ScalarEvolution *SE) {
  222. bool Changed = false;
  223. // Recurse depth-first through inner loops.
  224. for (Loop::iterator I = L.begin(), E = L.end(); I != E; ++I)
  225. Changed |= formLCSSARecursively(**I, DT, LI, SE);
  226. Changed |= formLCSSA(L, DT, LI, SE);
  227. return Changed;
  228. }
  229. namespace {
  230. struct LCSSA : public FunctionPass {
  231. static char ID; // Pass identification, replacement for typeid
  232. LCSSA() : FunctionPass(ID) {
  233. initializeLCSSAPass(*PassRegistry::getPassRegistry());
  234. }
  235. // Cached analysis information for the current function.
  236. DominatorTree *DT;
  237. LoopInfo *LI;
  238. ScalarEvolution *SE;
  239. bool runOnFunction(Function &F) override;
  240. /// This transformation requires natural loop information & requires that
  241. /// loop preheaders be inserted into the CFG. It maintains both of these,
  242. /// as well as the CFG. It also requires dominator information.
  243. void getAnalysisUsage(AnalysisUsage &AU) const override {
  244. AU.setPreservesCFG();
  245. AU.addRequired<DominatorTreeWrapperPass>();
  246. AU.addRequired<LoopInfoWrapperPass>();
  247. AU.addPreservedID(LoopSimplifyID);
  248. AU.addPreserved<AliasAnalysis>();
  249. AU.addPreserved<ScalarEvolution>();
  250. }
  251. };
  252. }
  253. char LCSSA::ID = 0;
  254. INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
  255. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  256. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  257. INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
  258. Pass *llvm::createLCSSAPass() { return new LCSSA(); }
  259. char &llvm::LCSSAID = LCSSA::ID;
  260. /// Process all loops in the function, inner-most out.
  261. bool LCSSA::runOnFunction(Function &F) {
  262. bool Changed = false;
  263. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  264. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  265. SE = getAnalysisIfAvailable<ScalarEvolution>();
  266. // Simplify each loop nest in the function.
  267. for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
  268. Changed |= formLCSSARecursively(**I, *DT, LI, SE);
  269. return Changed;
  270. }