FixIrreducible.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. //===- FixIrreducible.cpp - Convert irreducible control-flow into loops ---===//
  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. // An irreducible SCC is one which has multiple "header" blocks, i.e., blocks
  10. // with control-flow edges incident from outside the SCC. This pass converts a
  11. // irreducible SCC into a natural loop by applying the following transformation:
  12. //
  13. // 1. Collect the set of headers H of the SCC.
  14. // 2. Collect the set of predecessors P of these headers. These may be inside as
  15. // well as outside the SCC.
  16. // 3. Create block N and redirect every edge from set P to set H through N.
  17. //
  18. // This converts the SCC into a natural loop with N as the header: N is the only
  19. // block with edges incident from outside the SCC, and all backedges in the SCC
  20. // are incident on N, i.e., for every backedge, the head now dominates the tail.
  21. //
  22. // INPUT CFG: The blocks A and B form an irreducible loop with two headers.
  23. //
  24. // Entry
  25. // / \
  26. // v v
  27. // A ----> B
  28. // ^ /|
  29. // `----' |
  30. // v
  31. // Exit
  32. //
  33. // OUTPUT CFG: Edges incident on A and B are now redirected through a
  34. // new block N, forming a natural loop consisting of N, A and B.
  35. //
  36. // Entry
  37. // |
  38. // v
  39. // .---> N <---.
  40. // / / \ \
  41. // | / \ |
  42. // \ v v /
  43. // `-- A B --'
  44. // |
  45. // v
  46. // Exit
  47. //
  48. // The transformation is applied to every maximal SCC that is not already
  49. // recognized as a loop. The pass operates on all maximal SCCs found in the
  50. // function body outside of any loop, as well as those found inside each loop,
  51. // including inside any newly created loops. This ensures that any SCC hidden
  52. // inside a maximal SCC is also transformed.
  53. //
  54. // The actual transformation is handled by function CreateControlFlowHub, which
  55. // takes a set of incoming blocks (the predecessors) and outgoing blocks (the
  56. // headers). The function also moves every PHINode in an outgoing block to the
  57. // hub. Since the hub dominates all the outgoing blocks, each such PHINode
  58. // continues to dominate its uses. Since every header in an SCC has at least two
  59. // predecessors, every value used in the header (or later) but defined in a
  60. // predecessor (or earlier) is represented by a PHINode in a header. Hence the
  61. // above handling of PHINodes is sufficient and no further processing is
  62. // required to restore SSA.
  63. //
  64. // Limitation: The pass cannot handle switch statements and indirect
  65. // branches. Both must be lowered to plain branches first.
  66. //
  67. //===----------------------------------------------------------------------===//
  68. #include "llvm/Transforms/Utils/FixIrreducible.h"
  69. #include "llvm/ADT/SCCIterator.h"
  70. #include "llvm/Analysis/LoopIterator.h"
  71. #include "llvm/InitializePasses.h"
  72. #include "llvm/Pass.h"
  73. #include "llvm/Transforms/Utils.h"
  74. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  75. #define DEBUG_TYPE "fix-irreducible"
  76. using namespace llvm;
  77. namespace {
  78. struct FixIrreducible : public FunctionPass {
  79. static char ID;
  80. FixIrreducible() : FunctionPass(ID) {
  81. initializeFixIrreduciblePass(*PassRegistry::getPassRegistry());
  82. }
  83. void getAnalysisUsage(AnalysisUsage &AU) const override {
  84. AU.addRequiredID(LowerSwitchID);
  85. AU.addRequired<DominatorTreeWrapperPass>();
  86. AU.addRequired<LoopInfoWrapperPass>();
  87. AU.addPreservedID(LowerSwitchID);
  88. AU.addPreserved<DominatorTreeWrapperPass>();
  89. AU.addPreserved<LoopInfoWrapperPass>();
  90. }
  91. bool runOnFunction(Function &F) override;
  92. };
  93. } // namespace
  94. char FixIrreducible::ID = 0;
  95. FunctionPass *llvm::createFixIrreduciblePass() { return new FixIrreducible(); }
  96. INITIALIZE_PASS_BEGIN(FixIrreducible, "fix-irreducible",
  97. "Convert irreducible control-flow into natural loops",
  98. false /* Only looks at CFG */, false /* Analysis Pass */)
  99. INITIALIZE_PASS_DEPENDENCY(LowerSwitchLegacyPass)
  100. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  101. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  102. INITIALIZE_PASS_END(FixIrreducible, "fix-irreducible",
  103. "Convert irreducible control-flow into natural loops",
  104. false /* Only looks at CFG */, false /* Analysis Pass */)
  105. // When a new loop is created, existing children of the parent loop may now be
  106. // fully inside the new loop. Reconnect these as children of the new loop.
  107. static void reconnectChildLoops(LoopInfo &LI, Loop *ParentLoop, Loop *NewLoop,
  108. SetVector<BasicBlock *> &Blocks,
  109. SetVector<BasicBlock *> &Headers) {
  110. auto &CandidateLoops = ParentLoop ? ParentLoop->getSubLoopsVector()
  111. : LI.getTopLevelLoopsVector();
  112. // The new loop cannot be its own child, and any candidate is a
  113. // child iff its header is owned by the new loop. Move all the
  114. // children to a new vector.
  115. auto FirstChild = std::partition(
  116. CandidateLoops.begin(), CandidateLoops.end(), [&](Loop *L) {
  117. return L == NewLoop || !Blocks.contains(L->getHeader());
  118. });
  119. SmallVector<Loop *, 8> ChildLoops(FirstChild, CandidateLoops.end());
  120. CandidateLoops.erase(FirstChild, CandidateLoops.end());
  121. for (Loop *Child : ChildLoops) {
  122. LLVM_DEBUG(dbgs() << "child loop: " << Child->getHeader()->getName()
  123. << "\n");
  124. // TODO: A child loop whose header is also a header in the current
  125. // SCC gets destroyed since its backedges are removed. That may
  126. // not be necessary if we can retain such backedges.
  127. if (Headers.count(Child->getHeader())) {
  128. for (auto BB : Child->blocks()) {
  129. LI.changeLoopFor(BB, NewLoop);
  130. LLVM_DEBUG(dbgs() << "moved block from child: " << BB->getName()
  131. << "\n");
  132. }
  133. LI.destroy(Child);
  134. LLVM_DEBUG(dbgs() << "subsumed child loop (common header)\n");
  135. continue;
  136. }
  137. Child->setParentLoop(nullptr);
  138. NewLoop->addChildLoop(Child);
  139. LLVM_DEBUG(dbgs() << "added child loop to new loop\n");
  140. }
  141. }
  142. // Given a set of blocks and headers in an irreducible SCC, convert it into a
  143. // natural loop. Also insert this new loop at its appropriate place in the
  144. // hierarchy of loops.
  145. static void createNaturalLoopInternal(LoopInfo &LI, DominatorTree &DT,
  146. Loop *ParentLoop,
  147. SetVector<BasicBlock *> &Blocks,
  148. SetVector<BasicBlock *> &Headers) {
  149. #ifndef NDEBUG
  150. // All headers are part of the SCC
  151. for (auto H : Headers) {
  152. assert(Blocks.count(H));
  153. }
  154. #endif
  155. SetVector<BasicBlock *> Predecessors;
  156. for (auto H : Headers) {
  157. for (auto P : predecessors(H)) {
  158. Predecessors.insert(P);
  159. }
  160. }
  161. LLVM_DEBUG(
  162. dbgs() << "Found predecessors:";
  163. for (auto P : Predecessors) {
  164. dbgs() << " " << P->getName();
  165. }
  166. dbgs() << "\n");
  167. // Redirect all the backedges through a "hub" consisting of a series
  168. // of guard blocks that manage the flow of control from the
  169. // predecessors to the headers.
  170. SmallVector<BasicBlock *, 8> GuardBlocks;
  171. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  172. CreateControlFlowHub(&DTU, GuardBlocks, Predecessors, Headers, "irr");
  173. #if defined(EXPENSIVE_CHECKS)
  174. assert(DT.verify(DominatorTree::VerificationLevel::Full));
  175. #else
  176. assert(DT.verify(DominatorTree::VerificationLevel::Fast));
  177. #endif
  178. // Create a new loop from the now-transformed cycle
  179. auto NewLoop = LI.AllocateLoop();
  180. if (ParentLoop) {
  181. ParentLoop->addChildLoop(NewLoop);
  182. } else {
  183. LI.addTopLevelLoop(NewLoop);
  184. }
  185. // Add the guard blocks to the new loop. The first guard block is
  186. // the head of all the backedges, and it is the first to be inserted
  187. // in the loop. This ensures that it is recognized as the
  188. // header. Since the new loop is already in LoopInfo, the new blocks
  189. // are also propagated up the chain of parent loops.
  190. for (auto G : GuardBlocks) {
  191. LLVM_DEBUG(dbgs() << "added guard block: " << G->getName() << "\n");
  192. NewLoop->addBasicBlockToLoop(G, LI);
  193. }
  194. // Add the SCC blocks to the new loop.
  195. for (auto BB : Blocks) {
  196. NewLoop->addBlockEntry(BB);
  197. if (LI.getLoopFor(BB) == ParentLoop) {
  198. LLVM_DEBUG(dbgs() << "moved block from parent: " << BB->getName()
  199. << "\n");
  200. LI.changeLoopFor(BB, NewLoop);
  201. } else {
  202. LLVM_DEBUG(dbgs() << "added block from child: " << BB->getName() << "\n");
  203. }
  204. }
  205. LLVM_DEBUG(dbgs() << "header for new loop: "
  206. << NewLoop->getHeader()->getName() << "\n");
  207. reconnectChildLoops(LI, ParentLoop, NewLoop, Blocks, Headers);
  208. NewLoop->verifyLoop();
  209. if (ParentLoop) {
  210. ParentLoop->verifyLoop();
  211. }
  212. #if defined(EXPENSIVE_CHECKS)
  213. LI.verify(DT);
  214. #endif // EXPENSIVE_CHECKS
  215. }
  216. namespace llvm {
  217. // Enable the graph traits required for traversing a Loop body.
  218. template <> struct GraphTraits<Loop> : LoopBodyTraits {};
  219. } // namespace llvm
  220. // Overloaded wrappers to go with the function template below.
  221. static BasicBlock *unwrapBlock(BasicBlock *B) { return B; }
  222. static BasicBlock *unwrapBlock(LoopBodyTraits::NodeRef &N) { return N.second; }
  223. static void createNaturalLoop(LoopInfo &LI, DominatorTree &DT, Function *F,
  224. SetVector<BasicBlock *> &Blocks,
  225. SetVector<BasicBlock *> &Headers) {
  226. createNaturalLoopInternal(LI, DT, nullptr, Blocks, Headers);
  227. }
  228. static void createNaturalLoop(LoopInfo &LI, DominatorTree &DT, Loop &L,
  229. SetVector<BasicBlock *> &Blocks,
  230. SetVector<BasicBlock *> &Headers) {
  231. createNaturalLoopInternal(LI, DT, &L, Blocks, Headers);
  232. }
  233. // Convert irreducible SCCs; Graph G may be a Function* or a Loop&.
  234. template <class Graph>
  235. static bool makeReducible(LoopInfo &LI, DominatorTree &DT, Graph &&G) {
  236. bool Changed = false;
  237. for (auto Scc = scc_begin(G); !Scc.isAtEnd(); ++Scc) {
  238. if (Scc->size() < 2)
  239. continue;
  240. SetVector<BasicBlock *> Blocks;
  241. LLVM_DEBUG(dbgs() << "Found SCC:");
  242. for (auto N : *Scc) {
  243. auto BB = unwrapBlock(N);
  244. LLVM_DEBUG(dbgs() << " " << BB->getName());
  245. Blocks.insert(BB);
  246. }
  247. LLVM_DEBUG(dbgs() << "\n");
  248. // Minor optimization: The SCC blocks are usually discovered in an order
  249. // that is the opposite of the order in which these blocks appear as branch
  250. // targets. This results in a lot of condition inversions in the control
  251. // flow out of the new ControlFlowHub, which can be mitigated if the orders
  252. // match. So we discover the headers using the reverse of the block order.
  253. SetVector<BasicBlock *> Headers;
  254. LLVM_DEBUG(dbgs() << "Found headers:");
  255. for (auto BB : reverse(Blocks)) {
  256. for (const auto P : predecessors(BB)) {
  257. // Skip unreachable predecessors.
  258. if (!DT.isReachableFromEntry(P))
  259. continue;
  260. if (!Blocks.count(P)) {
  261. LLVM_DEBUG(dbgs() << " " << BB->getName());
  262. Headers.insert(BB);
  263. break;
  264. }
  265. }
  266. }
  267. LLVM_DEBUG(dbgs() << "\n");
  268. if (Headers.size() == 1) {
  269. assert(LI.isLoopHeader(Headers.front()));
  270. LLVM_DEBUG(dbgs() << "Natural loop with a single header: skipped\n");
  271. continue;
  272. }
  273. createNaturalLoop(LI, DT, G, Blocks, Headers);
  274. Changed = true;
  275. }
  276. return Changed;
  277. }
  278. static bool FixIrreducibleImpl(Function &F, LoopInfo &LI, DominatorTree &DT) {
  279. LLVM_DEBUG(dbgs() << "===== Fix irreducible control-flow in function: "
  280. << F.getName() << "\n");
  281. bool Changed = false;
  282. SmallVector<Loop *, 8> WorkList;
  283. LLVM_DEBUG(dbgs() << "visiting top-level\n");
  284. Changed |= makeReducible(LI, DT, &F);
  285. // Any SCCs reduced are now already in the list of top-level loops, so simply
  286. // add them all to the worklist.
  287. append_range(WorkList, LI);
  288. while (!WorkList.empty()) {
  289. auto L = WorkList.pop_back_val();
  290. LLVM_DEBUG(dbgs() << "visiting loop with header "
  291. << L->getHeader()->getName() << "\n");
  292. Changed |= makeReducible(LI, DT, *L);
  293. // Any SCCs reduced are now already in the list of child loops, so simply
  294. // add them all to the worklist.
  295. WorkList.append(L->begin(), L->end());
  296. }
  297. return Changed;
  298. }
  299. bool FixIrreducible::runOnFunction(Function &F) {
  300. auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  301. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  302. return FixIrreducibleImpl(F, LI, DT);
  303. }
  304. PreservedAnalyses FixIrreduciblePass::run(Function &F,
  305. FunctionAnalysisManager &AM) {
  306. auto &LI = AM.getResult<LoopAnalysis>(F);
  307. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  308. if (!FixIrreducibleImpl(F, LI, DT))
  309. return PreservedAnalyses::all();
  310. PreservedAnalyses PA;
  311. PA.preserve<LoopAnalysis>();
  312. PA.preserve<DominatorTreeAnalysis>();
  313. return PA;
  314. }