UnifyLoopExits.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. //===- UnifyLoopExits.cpp - Redirect exiting edges to one block -*- 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. // For each natural loop with multiple exit blocks, this pass creates a new
  10. // block N such that all exiting blocks now branch to N, and then control flow
  11. // is redistributed to all the original exit blocks.
  12. //
  13. // Limitation: This assumes that all terminators in the CFG are direct branches
  14. // (the "br" instruction). The presence of any other control flow
  15. // such as indirectbr, switch or callbr will cause an assert.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/Transforms/Utils/UnifyLoopExits.h"
  19. #include "llvm/ADT/MapVector.h"
  20. #include "llvm/Analysis/LoopInfo.h"
  21. #include "llvm/IR/Dominators.h"
  22. #include "llvm/InitializePasses.h"
  23. #include "llvm/Transforms/Utils.h"
  24. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  25. #define DEBUG_TYPE "unify-loop-exits"
  26. using namespace llvm;
  27. namespace {
  28. struct UnifyLoopExitsLegacyPass : public FunctionPass {
  29. static char ID;
  30. UnifyLoopExitsLegacyPass() : FunctionPass(ID) {
  31. initializeUnifyLoopExitsLegacyPassPass(*PassRegistry::getPassRegistry());
  32. }
  33. void getAnalysisUsage(AnalysisUsage &AU) const override {
  34. AU.addRequiredID(LowerSwitchID);
  35. AU.addRequired<LoopInfoWrapperPass>();
  36. AU.addRequired<DominatorTreeWrapperPass>();
  37. AU.addPreservedID(LowerSwitchID);
  38. AU.addPreserved<LoopInfoWrapperPass>();
  39. AU.addPreserved<DominatorTreeWrapperPass>();
  40. }
  41. bool runOnFunction(Function &F) override;
  42. };
  43. } // namespace
  44. char UnifyLoopExitsLegacyPass::ID = 0;
  45. FunctionPass *llvm::createUnifyLoopExitsPass() {
  46. return new UnifyLoopExitsLegacyPass();
  47. }
  48. INITIALIZE_PASS_BEGIN(UnifyLoopExitsLegacyPass, "unify-loop-exits",
  49. "Fixup each natural loop to have a single exit block",
  50. false /* Only looks at CFG */, false /* Analysis Pass */)
  51. INITIALIZE_PASS_DEPENDENCY(LowerSwitchLegacyPass)
  52. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  53. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  54. INITIALIZE_PASS_END(UnifyLoopExitsLegacyPass, "unify-loop-exits",
  55. "Fixup each natural loop to have a single exit block",
  56. false /* Only looks at CFG */, false /* Analysis Pass */)
  57. // The current transform introduces new control flow paths which may break the
  58. // SSA requirement that every def must dominate all its uses. For example,
  59. // consider a value D defined inside the loop that is used by some instruction
  60. // U outside the loop. It follows that D dominates U, since the original
  61. // program has valid SSA form. After merging the exits, all paths from D to U
  62. // now flow through the unified exit block. In addition, there may be other
  63. // paths that do not pass through D, but now reach the unified exit
  64. // block. Thus, D no longer dominates U.
  65. //
  66. // Restore the dominance by creating a phi for each such D at the new unified
  67. // loop exit. But when doing this, ignore any uses U that are in the new unified
  68. // loop exit, since those were introduced specially when the block was created.
  69. //
  70. // The use of SSAUpdater seems like overkill for this operation. The location
  71. // for creating the new PHI is well-known, and also the set of incoming blocks
  72. // to the new PHI.
  73. static void restoreSSA(const DominatorTree &DT, const Loop *L,
  74. const SetVector<BasicBlock *> &Incoming,
  75. BasicBlock *LoopExitBlock) {
  76. using InstVector = SmallVector<Instruction *, 8>;
  77. using IIMap = MapVector<Instruction *, InstVector>;
  78. IIMap ExternalUsers;
  79. for (auto BB : L->blocks()) {
  80. for (auto &I : *BB) {
  81. for (auto &U : I.uses()) {
  82. auto UserInst = cast<Instruction>(U.getUser());
  83. auto UserBlock = UserInst->getParent();
  84. if (UserBlock == LoopExitBlock)
  85. continue;
  86. if (L->contains(UserBlock))
  87. continue;
  88. LLVM_DEBUG(dbgs() << "added ext use for " << I.getName() << "("
  89. << BB->getName() << ")"
  90. << ": " << UserInst->getName() << "("
  91. << UserBlock->getName() << ")"
  92. << "\n");
  93. ExternalUsers[&I].push_back(UserInst);
  94. }
  95. }
  96. }
  97. for (auto II : ExternalUsers) {
  98. // For each Def used outside the loop, create NewPhi in
  99. // LoopExitBlock. NewPhi receives Def only along exiting blocks that
  100. // dominate it, while the remaining values are undefined since those paths
  101. // didn't exist in the original CFG.
  102. auto Def = II.first;
  103. LLVM_DEBUG(dbgs() << "externally used: " << Def->getName() << "\n");
  104. auto NewPhi = PHINode::Create(Def->getType(), Incoming.size(),
  105. Def->getName() + ".moved",
  106. LoopExitBlock->getTerminator());
  107. for (auto In : Incoming) {
  108. LLVM_DEBUG(dbgs() << "predecessor " << In->getName() << ": ");
  109. if (Def->getParent() == In || DT.dominates(Def, In)) {
  110. LLVM_DEBUG(dbgs() << "dominated\n");
  111. NewPhi->addIncoming(Def, In);
  112. } else {
  113. LLVM_DEBUG(dbgs() << "not dominated\n");
  114. NewPhi->addIncoming(UndefValue::get(Def->getType()), In);
  115. }
  116. }
  117. LLVM_DEBUG(dbgs() << "external users:");
  118. for (auto U : II.second) {
  119. LLVM_DEBUG(dbgs() << " " << U->getName());
  120. U->replaceUsesOfWith(Def, NewPhi);
  121. }
  122. LLVM_DEBUG(dbgs() << "\n");
  123. }
  124. }
  125. static bool unifyLoopExits(DominatorTree &DT, LoopInfo &LI, Loop *L) {
  126. // To unify the loop exits, we need a list of the exiting blocks as
  127. // well as exit blocks. The functions for locating these lists both
  128. // traverse the entire loop body. It is more efficient to first
  129. // locate the exiting blocks and then examine their successors to
  130. // locate the exit blocks.
  131. SetVector<BasicBlock *> ExitingBlocks;
  132. SetVector<BasicBlock *> Exits;
  133. // We need SetVectors, but the Loop API takes a vector, so we use a temporary.
  134. SmallVector<BasicBlock *, 8> Temp;
  135. L->getExitingBlocks(Temp);
  136. for (auto BB : Temp) {
  137. ExitingBlocks.insert(BB);
  138. for (auto S : successors(BB)) {
  139. auto SL = LI.getLoopFor(S);
  140. // A successor is not an exit if it is directly or indirectly in the
  141. // current loop.
  142. if (SL == L || L->contains(SL))
  143. continue;
  144. Exits.insert(S);
  145. }
  146. }
  147. LLVM_DEBUG(
  148. dbgs() << "Found exit blocks:";
  149. for (auto Exit : Exits) {
  150. dbgs() << " " << Exit->getName();
  151. }
  152. dbgs() << "\n";
  153. dbgs() << "Found exiting blocks:";
  154. for (auto EB : ExitingBlocks) {
  155. dbgs() << " " << EB->getName();
  156. }
  157. dbgs() << "\n";);
  158. if (Exits.size() <= 1) {
  159. LLVM_DEBUG(dbgs() << "loop does not have multiple exits; nothing to do\n");
  160. return false;
  161. }
  162. SmallVector<BasicBlock *, 8> GuardBlocks;
  163. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  164. auto LoopExitBlock = CreateControlFlowHub(&DTU, GuardBlocks, ExitingBlocks,
  165. Exits, "loop.exit");
  166. restoreSSA(DT, L, ExitingBlocks, LoopExitBlock);
  167. #if defined(EXPENSIVE_CHECKS)
  168. assert(DT.verify(DominatorTree::VerificationLevel::Full));
  169. #else
  170. assert(DT.verify(DominatorTree::VerificationLevel::Fast));
  171. #endif // EXPENSIVE_CHECKS
  172. L->verifyLoop();
  173. // The guard blocks were created outside the loop, so they need to become
  174. // members of the parent loop.
  175. if (auto ParentLoop = L->getParentLoop()) {
  176. for (auto G : GuardBlocks) {
  177. ParentLoop->addBasicBlockToLoop(G, LI);
  178. }
  179. ParentLoop->verifyLoop();
  180. }
  181. #if defined(EXPENSIVE_CHECKS)
  182. LI.verify(DT);
  183. #endif // EXPENSIVE_CHECKS
  184. return true;
  185. }
  186. static bool runImpl(LoopInfo &LI, DominatorTree &DT) {
  187. bool Changed = false;
  188. auto Loops = LI.getLoopsInPreorder();
  189. for (auto L : Loops) {
  190. LLVM_DEBUG(dbgs() << "Loop: " << L->getHeader()->getName() << " (depth: "
  191. << LI.getLoopDepth(L->getHeader()) << ")\n");
  192. Changed |= unifyLoopExits(DT, LI, L);
  193. }
  194. return Changed;
  195. }
  196. bool UnifyLoopExitsLegacyPass::runOnFunction(Function &F) {
  197. LLVM_DEBUG(dbgs() << "===== Unifying loop exits in function " << F.getName()
  198. << "\n");
  199. auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  200. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  201. return runImpl(LI, DT);
  202. }
  203. namespace llvm {
  204. PreservedAnalyses UnifyLoopExitsPass::run(Function &F,
  205. FunctionAnalysisManager &AM) {
  206. auto &LI = AM.getResult<LoopAnalysis>(F);
  207. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  208. if (!runImpl(LI, DT))
  209. return PreservedAnalyses::all();
  210. PreservedAnalyses PA;
  211. PA.preserve<LoopAnalysis>();
  212. PA.preserve<DominatorTreeAnalysis>();
  213. return PA;
  214. }
  215. } // namespace llvm