Fiona Glaser | b417d46 | 2016-01-29 22:35:36 +0000 | [diff] [blame] | 1 | //===--------- LoopSimplifyCFG.cpp - Loop CFG Simplification Pass ---------===// |
| 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 file implements the Loop SimplifyCFG Pass. This pass is responsible for |
| 11 | // basic loop CFG cleanup, primarily to assist other loop passes. If you |
| 12 | // encounter a noncanonical CFG construct that causes another loop pass to |
| 13 | // perform suboptimally, this is the place to fix it up. |
| 14 | // |
| 15 | //===----------------------------------------------------------------------===// |
| 16 | |
Justin Bogner | ab6a513 | 2016-05-03 21:47:32 +0000 | [diff] [blame] | 17 | #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h" |
Fiona Glaser | b417d46 | 2016-01-29 22:35:36 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/SmallVector.h" |
| 19 | #include "llvm/ADT/Statistic.h" |
| 20 | #include "llvm/Analysis/AliasAnalysis.h" |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/AssumptionCache.h" |
Chandler Carruth | 3bab7e1 | 2017-01-11 09:43:56 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/BasicAliasAnalysis.h" |
Fiona Glaser | b417d46 | 2016-01-29 22:35:36 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/DependenceAnalysis.h" |
| 24 | #include "llvm/Analysis/GlobalsModRef.h" |
| 25 | #include "llvm/Analysis/LoopInfo.h" |
| 26 | #include "llvm/Analysis/LoopPass.h" |
Alina Sbirlea | 8b83d68 | 2018-08-22 20:10:21 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/MemorySSA.h" |
| 28 | #include "llvm/Analysis/MemorySSAUpdater.h" |
Fiona Glaser | b417d46 | 2016-01-29 22:35:36 +0000 | [diff] [blame] | 29 | #include "llvm/Analysis/ScalarEvolution.h" |
| 30 | #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" |
| 31 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chijun Sima | 21a8b60 | 2018-08-03 05:08:17 +0000 | [diff] [blame] | 32 | #include "llvm/IR/DomTreeUpdater.h" |
Fiona Glaser | b417d46 | 2016-01-29 22:35:36 +0000 | [diff] [blame] | 33 | #include "llvm/IR/Dominators.h" |
Justin Bogner | ab6a513 | 2016-05-03 21:47:32 +0000 | [diff] [blame] | 34 | #include "llvm/Transforms/Scalar.h" |
Chandler Carruth | 3bab7e1 | 2017-01-11 09:43:56 +0000 | [diff] [blame] | 35 | #include "llvm/Transforms/Scalar/LoopPassManager.h" |
David Blaikie | a373d18 | 2018-03-28 17:44:36 +0000 | [diff] [blame] | 36 | #include "llvm/Transforms/Utils.h" |
Alina Sbirlea | dfd14ad | 2018-06-20 22:01:04 +0000 | [diff] [blame] | 37 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 38 | #include "llvm/Transforms/Utils/Local.h" |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 39 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Fiona Glaser | b417d46 | 2016-01-29 22:35:36 +0000 | [diff] [blame] | 40 | using namespace llvm; |
| 41 | |
| 42 | #define DEBUG_TYPE "loop-simplifycfg" |
| 43 | |
Max Kazantsev | e1c2dc2 | 2018-11-23 09:14:53 +0000 | [diff] [blame] | 44 | static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding", |
Max Kazantsev | 9cf417d | 2018-11-30 10:06:23 +0000 | [diff] [blame] | 45 | cl::init(true)); |
Max Kazantsev | e1c2dc2 | 2018-11-23 09:14:53 +0000 | [diff] [blame] | 46 | |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 47 | STATISTIC(NumTerminatorsFolded, |
| 48 | "Number of terminators folded to unconditional branches"); |
| 49 | |
| 50 | /// If \p BB is a switch or a conditional branch, but only one of its successors |
| 51 | /// can be reached from this block in runtime, return this successor. Otherwise, |
| 52 | /// return nullptr. |
| 53 | static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) { |
| 54 | Instruction *TI = BB->getTerminator(); |
| 55 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| 56 | if (BI->isUnconditional()) |
| 57 | return nullptr; |
| 58 | if (BI->getSuccessor(0) == BI->getSuccessor(1)) |
| 59 | return BI->getSuccessor(0); |
| 60 | ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition()); |
| 61 | if (!Cond) |
| 62 | return nullptr; |
| 63 | return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0); |
| 64 | } |
| 65 | |
| 66 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 67 | auto *CI = dyn_cast<ConstantInt>(SI->getCondition()); |
| 68 | if (!CI) |
| 69 | return nullptr; |
| 70 | for (auto Case : SI->cases()) |
| 71 | if (Case.getCaseValue() == CI) |
| 72 | return Case.getCaseSuccessor(); |
| 73 | return SI->getDefaultDest(); |
| 74 | } |
| 75 | |
| 76 | return nullptr; |
| 77 | } |
| 78 | |
| 79 | /// Helper class that can turn branches and switches with constant conditions |
| 80 | /// into unconditional branches. |
| 81 | class ConstantTerminatorFoldingImpl { |
| 82 | private: |
| 83 | Loop &L; |
| 84 | LoopInfo &LI; |
| 85 | DominatorTree &DT; |
Max Kazantsev | 9cf417d | 2018-11-30 10:06:23 +0000 | [diff] [blame] | 86 | MemorySSAUpdater *MSSAU; |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 87 | |
Max Kazantsev | a523a21 | 2018-12-07 05:44:45 +0000 | [diff] [blame] | 88 | // Whether or not the current loop has irreducible CFG. |
| 89 | bool HasIrreducibleCFG = false; |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 90 | // Whether or not the current loop will still exist after terminator constant |
| 91 | // folding will be done. In theory, there are two ways how it can happen: |
| 92 | // 1. Loop's latch(es) become unreachable from loop header; |
| 93 | // 2. Loop's header becomes unreachable from method entry. |
| 94 | // In practice, the second situation is impossible because we only modify the |
| 95 | // current loop and its preheader and do not affect preheader's reachibility |
| 96 | // from any other block. So this variable set to true means that loop's latch |
| 97 | // has become unreachable from loop header. |
| 98 | bool DeleteCurrentLoop = false; |
| 99 | |
| 100 | // The blocks of the original loop that will still be reachable from entry |
| 101 | // after the constant folding. |
| 102 | SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks; |
| 103 | // The blocks of the original loop that will become unreachable from entry |
| 104 | // after the constant folding. |
| 105 | SmallPtrSet<BasicBlock *, 8> DeadLoopBlocks; |
| 106 | // The exits of the original loop that will still be reachable from entry |
| 107 | // after the constant folding. |
| 108 | SmallPtrSet<BasicBlock *, 8> LiveExitBlocks; |
| 109 | // The exits of the original loop that will become unreachable from entry |
| 110 | // after the constant folding. |
Max Kazantsev | 56a2443 | 2018-11-22 12:33:41 +0000 | [diff] [blame] | 111 | SmallVector<BasicBlock *, 8> DeadExitBlocks; |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 112 | // The blocks that will still be a part of the current loop after folding. |
| 113 | SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding; |
| 114 | // The blocks that have terminators with constant condition that can be |
| 115 | // folded. Note: fold candidates should be in L but not in any of its |
| 116 | // subloops to avoid complex LI updates. |
| 117 | SmallVector<BasicBlock *, 8> FoldCandidates; |
| 118 | |
| 119 | void dump() const { |
| 120 | dbgs() << "Constant terminator folding for loop " << L << "\n"; |
| 121 | dbgs() << "After terminator constant-folding, the loop will"; |
| 122 | if (!DeleteCurrentLoop) |
| 123 | dbgs() << " not"; |
| 124 | dbgs() << " be destroyed\n"; |
Max Kazantsev | 56a2443 | 2018-11-22 12:33:41 +0000 | [diff] [blame] | 125 | auto PrintOutVector = [&](const char *Message, |
| 126 | const SmallVectorImpl<BasicBlock *> &S) { |
| 127 | dbgs() << Message << "\n"; |
| 128 | for (const BasicBlock *BB : S) |
| 129 | dbgs() << "\t" << BB->getName() << "\n"; |
| 130 | }; |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 131 | auto PrintOutSet = [&](const char *Message, |
| 132 | const SmallPtrSetImpl<BasicBlock *> &S) { |
| 133 | dbgs() << Message << "\n"; |
| 134 | for (const BasicBlock *BB : S) |
| 135 | dbgs() << "\t" << BB->getName() << "\n"; |
| 136 | }; |
Max Kazantsev | 56a2443 | 2018-11-22 12:33:41 +0000 | [diff] [blame] | 137 | PrintOutVector("Blocks in which we can constant-fold terminator:", |
| 138 | FoldCandidates); |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 139 | PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks); |
| 140 | PrintOutSet("Dead blocks from the original loop:", DeadLoopBlocks); |
| 141 | PrintOutSet("Live exit blocks:", LiveExitBlocks); |
Max Kazantsev | 56a2443 | 2018-11-22 12:33:41 +0000 | [diff] [blame] | 142 | PrintOutVector("Dead exit blocks:", DeadExitBlocks); |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 143 | if (!DeleteCurrentLoop) |
| 144 | PrintOutSet("The following blocks will still be part of the loop:", |
| 145 | BlocksInLoopAfterFolding); |
| 146 | } |
| 147 | |
Max Kazantsev | a523a21 | 2018-12-07 05:44:45 +0000 | [diff] [blame] | 148 | /// Whether or not the current loop has irreducible CFG. |
| 149 | bool hasIrreducibleCFG(LoopBlocksDFS &DFS) { |
| 150 | assert(DFS.isComplete() && "DFS is expected to be finished"); |
| 151 | // Index of a basic block in RPO traversal. |
| 152 | DenseMap<const BasicBlock *, unsigned> RPO; |
| 153 | unsigned Current = 0; |
| 154 | for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) |
| 155 | RPO[*I] = Current++; |
| 156 | |
| 157 | for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) { |
| 158 | BasicBlock *BB = *I; |
| 159 | for (auto *Succ : successors(BB)) |
| 160 | if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ]) |
| 161 | // If an edge goes from a block with greater order number into a block |
| 162 | // with lesses number, and it is not a loop backedge, then it can only |
| 163 | // be a part of irreducible non-loop cycle. |
| 164 | return true; |
| 165 | } |
| 166 | return false; |
| 167 | } |
| 168 | |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 169 | /// Fill all information about status of blocks and exits of the current loop |
| 170 | /// if constant folding of all branches will be done. |
| 171 | void analyze() { |
| 172 | LoopBlocksDFS DFS(&L); |
| 173 | DFS.perform(&LI); |
| 174 | assert(DFS.isComplete() && "DFS is expected to be finished"); |
| 175 | |
Max Kazantsev | a523a21 | 2018-12-07 05:44:45 +0000 | [diff] [blame] | 176 | // TODO: The algorithm below relies on both RPO and Postorder traversals. |
| 177 | // When the loop has only reducible CFG inside, then the invariant "all |
| 178 | // predecessors of X are processed before X in RPO" is preserved. However |
| 179 | // an irreducible loop can break this invariant (e.g. latch does not have to |
| 180 | // be the last block in the traversal in this case, and the algorithm relies |
| 181 | // on this). We can later decide to support such cases by altering the |
| 182 | // algorithms, but so far we just give up analyzing them. |
| 183 | if (hasIrreducibleCFG(DFS)) { |
| 184 | HasIrreducibleCFG = true; |
| 185 | return; |
| 186 | } |
| 187 | |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 188 | // Collect live and dead loop blocks and exits. |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 189 | LiveLoopBlocks.insert(L.getHeader()); |
| 190 | for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) { |
| 191 | BasicBlock *BB = *I; |
| 192 | |
| 193 | // If a loop block wasn't marked as live so far, then it's dead. |
| 194 | if (!LiveLoopBlocks.count(BB)) { |
| 195 | DeadLoopBlocks.insert(BB); |
| 196 | continue; |
| 197 | } |
| 198 | |
| 199 | BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB); |
| 200 | |
| 201 | // If a block has only one live successor, it's a candidate on constant |
| 202 | // folding. Only handle blocks from current loop: branches in child loops |
| 203 | // are skipped because if they can be folded, they should be folded during |
| 204 | // the processing of child loops. |
| 205 | if (TheOnlySucc && LI.getLoopFor(BB) == &L) |
| 206 | FoldCandidates.push_back(BB); |
| 207 | |
| 208 | // Handle successors. |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 209 | for (BasicBlock *Succ : successors(BB)) |
Max Kazantsev | d9f59f8 | 2018-11-22 10:48:30 +0000 | [diff] [blame] | 210 | if (!TheOnlySucc || TheOnlySucc == Succ) { |
| 211 | if (L.contains(Succ)) |
| 212 | LiveLoopBlocks.insert(Succ); |
| 213 | else |
| 214 | LiveExitBlocks.insert(Succ); |
| 215 | } |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 216 | } |
| 217 | |
| 218 | // Sanity check: amount of dead and live loop blocks should match the total |
| 219 | // number of blocks in loop. |
| 220 | assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() && |
| 221 | "Malformed block sets?"); |
| 222 | |
| 223 | // Now, all exit blocks that are not marked as live are dead. |
Max Kazantsev | d9f59f8 | 2018-11-22 10:48:30 +0000 | [diff] [blame] | 224 | SmallVector<BasicBlock *, 8> ExitBlocks; |
| 225 | L.getExitBlocks(ExitBlocks); |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 226 | for (auto *ExitBlock : ExitBlocks) |
| 227 | if (!LiveExitBlocks.count(ExitBlock)) |
Max Kazantsev | 56a2443 | 2018-11-22 12:33:41 +0000 | [diff] [blame] | 228 | DeadExitBlocks.push_back(ExitBlock); |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 229 | |
| 230 | // Whether or not the edge From->To will still be present in graph after the |
| 231 | // folding. |
| 232 | auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) { |
| 233 | if (!LiveLoopBlocks.count(From)) |
| 234 | return false; |
| 235 | BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From); |
| 236 | return !TheOnlySucc || TheOnlySucc == To; |
| 237 | }; |
| 238 | |
| 239 | // The loop will not be destroyed if its latch is live. |
| 240 | DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader()); |
| 241 | |
| 242 | // If we are going to delete the current loop completely, no extra analysis |
| 243 | // is needed. |
| 244 | if (DeleteCurrentLoop) |
| 245 | return; |
| 246 | |
| 247 | // Otherwise, we should check which blocks will still be a part of the |
| 248 | // current loop after the transform. |
| 249 | BlocksInLoopAfterFolding.insert(L.getLoopLatch()); |
| 250 | // If the loop is live, then we should compute what blocks are still in |
| 251 | // loop after all branch folding has been done. A block is in loop if |
| 252 | // it has a live edge to another block that is in the loop; by definition, |
| 253 | // latch is in the loop. |
| 254 | auto BlockIsInLoop = [&](BasicBlock *BB) { |
| 255 | return any_of(successors(BB), [&](BasicBlock *Succ) { |
| 256 | return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ); |
| 257 | }); |
| 258 | }; |
| 259 | for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) { |
| 260 | BasicBlock *BB = *I; |
| 261 | if (BlockIsInLoop(BB)) |
| 262 | BlocksInLoopAfterFolding.insert(BB); |
| 263 | } |
| 264 | |
| 265 | // Sanity check: header must be in loop. |
| 266 | assert(BlocksInLoopAfterFolding.count(L.getHeader()) && |
| 267 | "Header not in loop?"); |
Max Kazantsev | b565e60 | 2018-11-22 12:43:27 +0000 | [diff] [blame] | 268 | assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() && |
| 269 | "All blocks that stay in loop should be live!"); |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 270 | } |
| 271 | |
| 272 | /// Constant-fold terminators of blocks acculumated in FoldCandidates into the |
| 273 | /// unconditional branches. |
| 274 | void foldTerminators() { |
| 275 | DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); |
| 276 | |
| 277 | for (BasicBlock *BB : FoldCandidates) { |
| 278 | assert(LI.getLoopFor(BB) == &L && "Should be a loop block!"); |
| 279 | BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB); |
| 280 | assert(TheOnlySucc && "Should have one live successor!"); |
| 281 | |
| 282 | LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName() |
| 283 | << " with an unconditional branch to the block " |
| 284 | << TheOnlySucc->getName() << "\n"); |
| 285 | |
| 286 | SmallPtrSet<BasicBlock *, 2> DeadSuccessors; |
| 287 | // Remove all BB's successors except for the live one. |
Max Kazantsev | c4e4d64 | 2018-11-27 06:17:21 +0000 | [diff] [blame] | 288 | unsigned TheOnlySuccDuplicates = 0; |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 289 | for (auto *Succ : successors(BB)) |
| 290 | if (Succ != TheOnlySucc) { |
| 291 | DeadSuccessors.insert(Succ); |
Max Kazantsev | cb8e240 | 2018-11-23 07:56:47 +0000 | [diff] [blame] | 292 | // If our successor lies in a different loop, we don't want to remove |
| 293 | // the one-input Phi because it is a LCSSA Phi. |
| 294 | bool PreserveLCSSAPhi = !L.contains(Succ); |
| 295 | Succ->removePredecessor(BB, PreserveLCSSAPhi); |
Max Kazantsev | 9cf417d | 2018-11-30 10:06:23 +0000 | [diff] [blame] | 296 | if (MSSAU) |
| 297 | MSSAU->removeEdge(BB, Succ); |
Max Kazantsev | c4e4d64 | 2018-11-27 06:17:21 +0000 | [diff] [blame] | 298 | } else |
| 299 | ++TheOnlySuccDuplicates; |
| 300 | |
| 301 | assert(TheOnlySuccDuplicates > 0 && "Should be!"); |
| 302 | // If TheOnlySucc was BB's successor more than once, after transform it |
| 303 | // will be its successor only once. Remove redundant inputs from |
| 304 | // TheOnlySucc's Phis. |
| 305 | bool PreserveLCSSAPhi = !L.contains(TheOnlySucc); |
| 306 | for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup) |
| 307 | TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi); |
Max Kazantsev | 9cf417d | 2018-11-30 10:06:23 +0000 | [diff] [blame] | 308 | if (MSSAU && TheOnlySuccDuplicates > 1) |
| 309 | MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc); |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 310 | |
| 311 | IRBuilder<> Builder(BB->getContext()); |
| 312 | Instruction *Term = BB->getTerminator(); |
| 313 | Builder.SetInsertPoint(Term); |
| 314 | Builder.CreateBr(TheOnlySucc); |
| 315 | Term->eraseFromParent(); |
| 316 | |
| 317 | for (auto *DeadSucc : DeadSuccessors) |
| 318 | DTU.deleteEdge(BB, DeadSucc); |
| 319 | |
| 320 | ++NumTerminatorsFolded; |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | public: |
Max Kazantsev | 9cf417d | 2018-11-30 10:06:23 +0000 | [diff] [blame] | 325 | ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT, |
| 326 | MemorySSAUpdater *MSSAU) |
| 327 | : L(L), LI(LI), DT(DT), MSSAU(MSSAU) {} |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 328 | bool run() { |
| 329 | assert(L.getLoopLatch() && "Should be single latch!"); |
| 330 | |
| 331 | // Collect all available information about status of blocks after constant |
| 332 | // folding. |
| 333 | analyze(); |
| 334 | |
| 335 | LLVM_DEBUG(dbgs() << "In function " << L.getHeader()->getParent()->getName() |
| 336 | << ": "); |
| 337 | |
Max Kazantsev | a523a21 | 2018-12-07 05:44:45 +0000 | [diff] [blame] | 338 | if (HasIrreducibleCFG) { |
| 339 | LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n"); |
| 340 | return false; |
| 341 | } |
| 342 | |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 343 | // Nothing to constant-fold. |
| 344 | if (FoldCandidates.empty()) { |
| 345 | LLVM_DEBUG( |
| 346 | dbgs() << "No constant terminator folding candidates found in loop " |
| 347 | << L.getHeader()->getName() << "\n"); |
| 348 | return false; |
| 349 | } |
| 350 | |
| 351 | // TODO: Support deletion of the current loop. |
| 352 | if (DeleteCurrentLoop) { |
| 353 | LLVM_DEBUG( |
| 354 | dbgs() |
| 355 | << "Give up constant terminator folding in loop " |
| 356 | << L.getHeader()->getName() |
| 357 | << ": we don't currently support deletion of the current loop.\n"); |
| 358 | return false; |
| 359 | } |
| 360 | |
Ilya Biryukov | cb5331eb | 2018-12-06 13:21:01 +0000 | [diff] [blame] | 361 | // TODO: Support deletion of dead loop blocks. |
| 362 | if (!DeadLoopBlocks.empty()) { |
| 363 | LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop " |
| 364 | << L.getHeader()->getName() |
| 365 | << ": we don't currently" |
| 366 | " support deletion of dead in-loop blocks.\n"); |
| 367 | return false; |
| 368 | } |
| 369 | |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 370 | // TODO: Support dead loop exits. |
| 371 | if (!DeadExitBlocks.empty()) { |
| 372 | LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop " |
| 373 | << L.getHeader()->getName() |
| 374 | << ": we don't currently support dead loop exits.\n"); |
| 375 | return false; |
| 376 | } |
| 377 | |
| 378 | // TODO: Support blocks that are not dead, but also not in loop after the |
| 379 | // folding. |
Ilya Biryukov | cb5331eb | 2018-12-06 13:21:01 +0000 | [diff] [blame] | 380 | if (BlocksInLoopAfterFolding.size() != L.getNumBlocks()) { |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 381 | LLVM_DEBUG( |
| 382 | dbgs() << "Give up constant terminator folding in loop " |
| 383 | << L.getHeader()->getName() |
| 384 | << ": we don't currently" |
| 385 | " support blocks that are not dead, but will stop " |
| 386 | "being a part of the loop after constant-folding.\n"); |
| 387 | return false; |
| 388 | } |
| 389 | |
| 390 | // Dump analysis results. |
| 391 | LLVM_DEBUG(dump()); |
| 392 | |
| 393 | LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size() |
| 394 | << " terminators in loop " << L.getHeader()->getName() |
| 395 | << "\n"); |
| 396 | |
| 397 | // Make the actual transforms. |
| 398 | foldTerminators(); |
| 399 | |
| 400 | #ifndef NDEBUG |
| 401 | // Make sure that we have preserved all data structures after the transform. |
| 402 | DT.verify(); |
| 403 | assert(DT.isReachableFromEntry(L.getHeader())); |
| 404 | LI.verify(DT); |
| 405 | #endif |
| 406 | |
| 407 | return true; |
| 408 | } |
| 409 | }; |
| 410 | |
| 411 | /// Turn branches and switches with known constant conditions into unconditional |
| 412 | /// branches. |
Max Kazantsev | 9cf417d | 2018-11-30 10:06:23 +0000 | [diff] [blame] | 413 | static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI, |
| 414 | MemorySSAUpdater *MSSAU) { |
Max Kazantsev | e1c2dc2 | 2018-11-23 09:14:53 +0000 | [diff] [blame] | 415 | if (!EnableTermFolding) |
| 416 | return false; |
| 417 | |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 418 | // To keep things simple, only process loops with single latch. We |
| 419 | // canonicalize most loops to this form. We can support multi-latch if needed. |
| 420 | if (!L.getLoopLatch()) |
| 421 | return false; |
| 422 | |
Max Kazantsev | 9cf417d | 2018-11-30 10:06:23 +0000 | [diff] [blame] | 423 | ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, MSSAU); |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 424 | return BranchFolder.run(); |
| 425 | } |
| 426 | |
Max Kazantsev | 46955b5 | 2018-11-01 09:42:50 +0000 | [diff] [blame] | 427 | static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT, |
| 428 | LoopInfo &LI, MemorySSAUpdater *MSSAU) { |
Fiona Glaser | b417d46 | 2016-01-29 22:35:36 +0000 | [diff] [blame] | 429 | bool Changed = false; |
Chijun Sima | 21a8b60 | 2018-08-03 05:08:17 +0000 | [diff] [blame] | 430 | DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); |
Fiona Glaser | b417d46 | 2016-01-29 22:35:36 +0000 | [diff] [blame] | 431 | // Copy blocks into a temporary array to avoid iterator invalidation issues |
| 432 | // as we remove them. |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 433 | SmallVector<WeakTrackingVH, 16> Blocks(L.blocks()); |
Fiona Glaser | b417d46 | 2016-01-29 22:35:36 +0000 | [diff] [blame] | 434 | |
| 435 | for (auto &Block : Blocks) { |
| 436 | // Attempt to merge blocks in the trivial case. Don't modify blocks which |
| 437 | // belong to other loops. |
Fiona Glaser | 36e8230 | 2016-01-29 23:12:52 +0000 | [diff] [blame] | 438 | BasicBlock *Succ = cast_or_null<BasicBlock>(Block); |
Fiona Glaser | b417d46 | 2016-01-29 22:35:36 +0000 | [diff] [blame] | 439 | if (!Succ) |
| 440 | continue; |
| 441 | |
| 442 | BasicBlock *Pred = Succ->getSinglePredecessor(); |
Justin Bogner | ab6a513 | 2016-05-03 21:47:32 +0000 | [diff] [blame] | 443 | if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L) |
Fiona Glaser | b417d46 | 2016-01-29 22:35:36 +0000 | [diff] [blame] | 444 | continue; |
| 445 | |
Alina Sbirlea | dfd14ad | 2018-06-20 22:01:04 +0000 | [diff] [blame] | 446 | // Merge Succ into Pred and delete it. |
Alina Sbirlea | 8b83d68 | 2018-08-22 20:10:21 +0000 | [diff] [blame] | 447 | MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU); |
David Green | e6a9c24 | 2018-06-19 09:43:36 +0000 | [diff] [blame] | 448 | |
Fiona Glaser | b417d46 | 2016-01-29 22:35:36 +0000 | [diff] [blame] | 449 | Changed = true; |
| 450 | } |
| 451 | |
| 452 | return Changed; |
| 453 | } |
| 454 | |
Max Kazantsev | 46955b5 | 2018-11-01 09:42:50 +0000 | [diff] [blame] | 455 | static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI, |
| 456 | ScalarEvolution &SE, MemorySSAUpdater *MSSAU) { |
| 457 | bool Changed = false; |
| 458 | |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 459 | // Constant-fold terminators with known constant conditions. |
Max Kazantsev | 9cf417d | 2018-11-30 10:06:23 +0000 | [diff] [blame] | 460 | Changed |= constantFoldTerminators(L, DT, LI, MSSAU); |
Max Kazantsev | c04b530 | 2018-11-20 05:43:32 +0000 | [diff] [blame] | 461 | |
Max Kazantsev | 46955b5 | 2018-11-01 09:42:50 +0000 | [diff] [blame] | 462 | // Eliminate unconditional branches by merging blocks into their predecessors. |
| 463 | Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU); |
| 464 | |
| 465 | if (Changed) |
| 466 | SE.forgetTopmostLoop(&L); |
| 467 | |
| 468 | return Changed; |
| 469 | } |
| 470 | |
Chandler Carruth | 410eaeb | 2017-01-11 06:23:21 +0000 | [diff] [blame] | 471 | PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM, |
| 472 | LoopStandardAnalysisResults &AR, |
| 473 | LPMUpdater &) { |
Alina Sbirlea | 8b83d68 | 2018-08-22 20:10:21 +0000 | [diff] [blame] | 474 | Optional<MemorySSAUpdater> MSSAU; |
| 475 | if (EnableMSSALoopDependency && AR.MSSA) |
| 476 | MSSAU = MemorySSAUpdater(AR.MSSA); |
| 477 | if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE, |
| 478 | MSSAU.hasValue() ? MSSAU.getPointer() : nullptr)) |
Justin Bogner | ab6a513 | 2016-05-03 21:47:32 +0000 | [diff] [blame] | 479 | return PreservedAnalyses::all(); |
Chandler Carruth | ca68a3e | 2017-01-15 06:32:49 +0000 | [diff] [blame] | 480 | |
Justin Bogner | ab6a513 | 2016-05-03 21:47:32 +0000 | [diff] [blame] | 481 | return getLoopPassPreservedAnalyses(); |
| 482 | } |
| 483 | |
| 484 | namespace { |
| 485 | class LoopSimplifyCFGLegacyPass : public LoopPass { |
| 486 | public: |
| 487 | static char ID; // Pass ID, replacement for typeid |
| 488 | LoopSimplifyCFGLegacyPass() : LoopPass(ID) { |
| 489 | initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry()); |
| 490 | } |
| 491 | |
| 492 | bool runOnLoop(Loop *L, LPPassManager &) override { |
| 493 | if (skipLoop(L)) |
| 494 | return false; |
| 495 | |
| 496 | DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 497 | LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
David Green | e6a9c24 | 2018-06-19 09:43:36 +0000 | [diff] [blame] | 498 | ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); |
Alina Sbirlea | 8b83d68 | 2018-08-22 20:10:21 +0000 | [diff] [blame] | 499 | Optional<MemorySSAUpdater> MSSAU; |
| 500 | if (EnableMSSALoopDependency) { |
| 501 | MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA(); |
| 502 | MSSAU = MemorySSAUpdater(MSSA); |
| 503 | if (VerifyMemorySSA) |
| 504 | MSSA->verifyMemorySSA(); |
| 505 | } |
| 506 | return simplifyLoopCFG(*L, DT, LI, SE, |
| 507 | MSSAU.hasValue() ? MSSAU.getPointer() : nullptr); |
Justin Bogner | ab6a513 | 2016-05-03 21:47:32 +0000 | [diff] [blame] | 508 | } |
| 509 | |
| 510 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Alina Sbirlea | 8b83d68 | 2018-08-22 20:10:21 +0000 | [diff] [blame] | 511 | if (EnableMSSALoopDependency) { |
| 512 | AU.addRequired<MemorySSAWrapperPass>(); |
| 513 | AU.addPreserved<MemorySSAWrapperPass>(); |
| 514 | } |
Chandler Carruth | 49c2219 | 2016-05-12 22:19:39 +0000 | [diff] [blame] | 515 | AU.addPreserved<DependenceAnalysisWrapperPass>(); |
Justin Bogner | ab6a513 | 2016-05-03 21:47:32 +0000 | [diff] [blame] | 516 | getLoopAnalysisUsage(AU); |
| 517 | } |
| 518 | }; |
| 519 | } |
| 520 | |
| 521 | char LoopSimplifyCFGLegacyPass::ID = 0; |
| 522 | INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg", |
| 523 | "Simplify loop CFG", false, false) |
| 524 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
Alina Sbirlea | 8b83d68 | 2018-08-22 20:10:21 +0000 | [diff] [blame] | 525 | INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) |
Justin Bogner | ab6a513 | 2016-05-03 21:47:32 +0000 | [diff] [blame] | 526 | INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg", |
| 527 | "Simplify loop CFG", false, false) |
| 528 | |
| 529 | Pass *llvm::createLoopSimplifyCFGPass() { |
| 530 | return new LoopSimplifyCFGLegacyPass(); |
Fiona Glaser | b417d46 | 2016-01-29 22:35:36 +0000 | [diff] [blame] | 531 | } |