UnifyLoopExits.cpp 9.2 KB

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