Chandler Carruth | d8b0c8c | 2018-07-07 01:12:56 +0000 | [diff] [blame] | 1 | ///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===// |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 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 |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 9 | #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" |
Eugene Zelenko | a369a45 | 2017-05-16 23:10:25 +0000 | [diff] [blame] | 10 | #include "llvm/ADT/DenseMap.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 11 | #include "llvm/ADT/STLExtras.h" |
Eugene Zelenko | a369a45 | 2017-05-16 23:10:25 +0000 | [diff] [blame] | 12 | #include "llvm/ADT/Sequence.h" |
| 13 | #include "llvm/ADT/SetVector.h" |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 14 | #include "llvm/ADT/SmallPtrSet.h" |
Eugene Zelenko | a369a45 | 2017-05-16 23:10:25 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/SmallVector.h" |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 16 | #include "llvm/ADT/Statistic.h" |
Eugene Zelenko | a369a45 | 2017-05-16 23:10:25 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/Twine.h" |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 18 | #include "llvm/Analysis/AssumptionCache.h" |
Chandler Carruth | 32e62f9 | 2018-04-19 18:44:25 +0000 | [diff] [blame] | 19 | #include "llvm/Analysis/CFG.h" |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/CodeMetrics.h" |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/GuardUtils.h" |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/InstructionSimplify.h" |
Eugene Zelenko | a369a45 | 2017-05-16 23:10:25 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/LoopAnalysisManager.h" |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/LoopInfo.h" |
Chandler Carruth | 32e62f9 | 2018-04-19 18:44:25 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/LoopIterator.h" |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/LoopPass.h" |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/MemorySSA.h" |
| 28 | #include "llvm/Analysis/MemorySSAUpdater.h" |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 29 | #include "llvm/Analysis/Utils/Local.h" |
Eugene Zelenko | a369a45 | 2017-05-16 23:10:25 +0000 | [diff] [blame] | 30 | #include "llvm/IR/BasicBlock.h" |
| 31 | #include "llvm/IR/Constant.h" |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 32 | #include "llvm/IR/Constants.h" |
| 33 | #include "llvm/IR/Dominators.h" |
| 34 | #include "llvm/IR/Function.h" |
Eugene Zelenko | a369a45 | 2017-05-16 23:10:25 +0000 | [diff] [blame] | 35 | #include "llvm/IR/InstrTypes.h" |
| 36 | #include "llvm/IR/Instruction.h" |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 37 | #include "llvm/IR/Instructions.h" |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 38 | #include "llvm/IR/IntrinsicInst.h" |
Eugene Zelenko | a369a45 | 2017-05-16 23:10:25 +0000 | [diff] [blame] | 39 | #include "llvm/IR/Use.h" |
| 40 | #include "llvm/IR/Value.h" |
| 41 | #include "llvm/Pass.h" |
| 42 | #include "llvm/Support/Casting.h" |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 43 | #include "llvm/Support/Debug.h" |
Eugene Zelenko | a369a45 | 2017-05-16 23:10:25 +0000 | [diff] [blame] | 44 | #include "llvm/Support/ErrorHandling.h" |
| 45 | #include "llvm/Support/GenericDomTree.h" |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 46 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 47 | #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 48 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 49 | #include "llvm/Transforms/Utils/Cloning.h" |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 50 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 51 | #include "llvm/Transforms/Utils/ValueMapper.h" |
Eugene Zelenko | a369a45 | 2017-05-16 23:10:25 +0000 | [diff] [blame] | 52 | #include <algorithm> |
| 53 | #include <cassert> |
| 54 | #include <iterator> |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 55 | #include <numeric> |
Eugene Zelenko | a369a45 | 2017-05-16 23:10:25 +0000 | [diff] [blame] | 56 | #include <utility> |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 57 | |
| 58 | #define DEBUG_TYPE "simple-loop-unswitch" |
| 59 | |
| 60 | using namespace llvm; |
| 61 | |
| 62 | STATISTIC(NumBranches, "Number of branches unswitched"); |
| 63 | STATISTIC(NumSwitches, "Number of switches unswitched"); |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 64 | STATISTIC(NumGuards, "Number of guards turned into branches for unswitching"); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 65 | STATISTIC(NumTrivial, "Number of unswitches that are trivial"); |
Fedor Sergeev | 2e3e224 | 2018-11-16 21:16:43 +0000 | [diff] [blame] | 66 | STATISTIC( |
| 67 | NumCostMultiplierSkipped, |
| 68 | "Number of unswitch candidates that had their cost multiplier skipped"); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 69 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 70 | static cl::opt<bool> EnableNonTrivialUnswitch( |
| 71 | "enable-nontrivial-unswitch", cl::init(false), cl::Hidden, |
| 72 | cl::desc("Forcibly enables non-trivial loop unswitching rather than " |
| 73 | "following the configuration passed into the pass.")); |
| 74 | |
| 75 | static cl::opt<int> |
| 76 | UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden, |
| 77 | cl::desc("The cost threshold for unswitching a loop.")); |
| 78 | |
Fedor Sergeev | 2e3e224 | 2018-11-16 21:16:43 +0000 | [diff] [blame] | 79 | static cl::opt<bool> EnableUnswitchCostMultiplier( |
| 80 | "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden, |
| 81 | cl::desc("Enable unswitch cost multiplier that prohibits exponential " |
| 82 | "explosion in nontrivial unswitch.")); |
| 83 | static cl::opt<int> UnswitchSiblingsToplevelDiv( |
| 84 | "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden, |
| 85 | cl::desc("Toplevel siblings divisor for cost multiplier.")); |
| 86 | static cl::opt<int> UnswitchNumInitialUnscaledCandidates( |
| 87 | "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden, |
| 88 | cl::desc("Number of unswitch candidates that are ignored when calculating " |
| 89 | "cost multiplier.")); |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 90 | static cl::opt<bool> UnswitchGuards( |
| 91 | "simple-loop-unswitch-guards", cl::init(true), cl::Hidden, |
| 92 | cl::desc("If enabled, simple loop unswitching will also consider " |
| 93 | "llvm.experimental.guard intrinsics as unswitch candidates.")); |
| 94 | |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 95 | /// Collect all of the loop invariant input values transitively used by the |
| 96 | /// homogeneous instruction graph from a given root. |
| 97 | /// |
| 98 | /// This essentially walks from a root recursively through loop variant operands |
| 99 | /// which have the exact same opcode and finds all inputs which are loop |
| 100 | /// invariant. For some operations these can be re-associated and unswitched out |
| 101 | /// of the loop entirely. |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 102 | static TinyPtrVector<Value *> |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 103 | collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root, |
| 104 | LoopInfo &LI) { |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 105 | assert(!L.isLoopInvariant(&Root) && |
| 106 | "Only need to walk the graph if root itself is not invariant."); |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 107 | TinyPtrVector<Value *> Invariants; |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 108 | |
| 109 | // Build a worklist and recurse through operators collecting invariants. |
| 110 | SmallVector<Instruction *, 4> Worklist; |
| 111 | SmallPtrSet<Instruction *, 8> Visited; |
| 112 | Worklist.push_back(&Root); |
| 113 | Visited.insert(&Root); |
| 114 | do { |
| 115 | Instruction &I = *Worklist.pop_back_val(); |
| 116 | for (Value *OpV : I.operand_values()) { |
| 117 | // Skip constants as unswitching isn't interesting for them. |
| 118 | if (isa<Constant>(OpV)) |
| 119 | continue; |
| 120 | |
| 121 | // Add it to our result if loop invariant. |
| 122 | if (L.isLoopInvariant(OpV)) { |
| 123 | Invariants.push_back(OpV); |
| 124 | continue; |
| 125 | } |
| 126 | |
| 127 | // If not an instruction with the same opcode, nothing we can do. |
| 128 | Instruction *OpI = dyn_cast<Instruction>(OpV); |
| 129 | if (!OpI || OpI->getOpcode() != Root.getOpcode()) |
| 130 | continue; |
| 131 | |
| 132 | // Visit this operand. |
| 133 | if (Visited.insert(OpI).second) |
| 134 | Worklist.push_back(OpI); |
| 135 | } |
| 136 | } while (!Worklist.empty()); |
| 137 | |
| 138 | return Invariants; |
| 139 | } |
| 140 | |
| 141 | static void replaceLoopInvariantUses(Loop &L, Value *Invariant, |
| 142 | Constant &Replacement) { |
| 143 | assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?"); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 144 | |
| 145 | // Replace uses of LIC in the loop with the given constant. |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 146 | for (auto UI = Invariant->use_begin(), UE = Invariant->use_end(); UI != UE;) { |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 147 | // Grab the use and walk past it so we can clobber it in the use list. |
| 148 | Use *U = &*UI++; |
| 149 | Instruction *UserI = dyn_cast<Instruction>(U->getUser()); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 150 | |
| 151 | // Replace this use within the loop body. |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 152 | if (UserI && L.contains(UserI)) |
| 153 | U->set(&Replacement); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 154 | } |
| 155 | } |
| 156 | |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 157 | /// Check that all the LCSSA PHI nodes in the loop exit block have trivial |
| 158 | /// incoming values along this edge. |
| 159 | static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB, |
| 160 | BasicBlock &ExitBB) { |
| 161 | for (Instruction &I : ExitBB) { |
| 162 | auto *PN = dyn_cast<PHINode>(&I); |
| 163 | if (!PN) |
| 164 | // No more PHIs to check. |
| 165 | return true; |
| 166 | |
| 167 | // If the incoming value for this edge isn't loop invariant the unswitch |
| 168 | // won't be trivial. |
| 169 | if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB))) |
| 170 | return false; |
| 171 | } |
| 172 | llvm_unreachable("Basic blocks should never be empty!"); |
| 173 | } |
| 174 | |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 175 | /// Insert code to test a set of loop invariant values, and conditionally branch |
| 176 | /// on them. |
| 177 | static void buildPartialUnswitchConditionalBranch(BasicBlock &BB, |
| 178 | ArrayRef<Value *> Invariants, |
| 179 | bool Direction, |
| 180 | BasicBlock &UnswitchedSucc, |
| 181 | BasicBlock &NormalSucc) { |
| 182 | IRBuilder<> IRB(&BB); |
| 183 | Value *Cond = Invariants.front(); |
| 184 | for (Value *Invariant : |
| 185 | make_range(std::next(Invariants.begin()), Invariants.end())) |
| 186 | if (Direction) |
| 187 | Cond = IRB.CreateOr(Cond, Invariant); |
| 188 | else |
| 189 | Cond = IRB.CreateAnd(Cond, Invariant); |
| 190 | |
| 191 | IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc, |
| 192 | Direction ? &NormalSucc : &UnswitchedSucc); |
| 193 | } |
| 194 | |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 195 | /// Rewrite the PHI nodes in an unswitched loop exit basic block. |
| 196 | /// |
| 197 | /// Requires that the loop exit and unswitched basic block are the same, and |
| 198 | /// that the exiting block was a unique predecessor of that block. Rewrites the |
| 199 | /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial |
| 200 | /// PHI nodes from the old preheader that now contains the unswitched |
| 201 | /// terminator. |
| 202 | static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB, |
| 203 | BasicBlock &OldExitingBB, |
| 204 | BasicBlock &OldPH) { |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 205 | for (PHINode &PN : UnswitchedBB.phis()) { |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 206 | // When the loop exit is directly unswitched we just need to update the |
| 207 | // incoming basic block. We loop to handle weird cases with repeated |
| 208 | // incoming blocks, but expect to typically only have one operand here. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 209 | for (auto i : seq<int>(0, PN.getNumOperands())) { |
| 210 | assert(PN.getIncomingBlock(i) == &OldExitingBB && |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 211 | "Found incoming block different from unique predecessor!"); |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 212 | PN.setIncomingBlock(i, &OldPH); |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 213 | } |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | /// Rewrite the PHI nodes in the loop exit basic block and the split off |
| 218 | /// unswitched block. |
| 219 | /// |
| 220 | /// Because the exit block remains an exit from the loop, this rewrites the |
| 221 | /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI |
| 222 | /// nodes into the unswitched basic block to select between the value in the |
| 223 | /// old preheader and the loop exit. |
| 224 | static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB, |
| 225 | BasicBlock &UnswitchedBB, |
| 226 | BasicBlock &OldExitingBB, |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 227 | BasicBlock &OldPH, |
| 228 | bool FullUnswitch) { |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 229 | assert(&ExitBB != &UnswitchedBB && |
| 230 | "Must have different loop exit and unswitched blocks!"); |
| 231 | Instruction *InsertPt = &*UnswitchedBB.begin(); |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 232 | for (PHINode &PN : ExitBB.phis()) { |
| 233 | auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2, |
| 234 | PN.getName() + ".split", InsertPt); |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 235 | |
| 236 | // Walk backwards over the old PHI node's inputs to minimize the cost of |
| 237 | // removing each one. We have to do this weird loop manually so that we |
| 238 | // create the same number of new incoming edges in the new PHI as we expect |
| 239 | // each case-based edge to be included in the unswitched switch in some |
| 240 | // cases. |
| 241 | // FIXME: This is really, really gross. It would be much cleaner if LLVM |
| 242 | // allowed us to create a single entry for a predecessor block without |
| 243 | // having separate entries for each "edge" even though these edges are |
| 244 | // required to produce identical results. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 245 | for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) { |
| 246 | if (PN.getIncomingBlock(i) != &OldExitingBB) |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 247 | continue; |
| 248 | |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 249 | Value *Incoming = PN.getIncomingValue(i); |
| 250 | if (FullUnswitch) |
| 251 | // No more edge from the old exiting block to the exit block. |
| 252 | PN.removeIncomingValue(i); |
| 253 | |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 254 | NewPN->addIncoming(Incoming, &OldPH); |
| 255 | } |
| 256 | |
| 257 | // Now replace the old PHI with the new one and wire the old one in as an |
| 258 | // input to the new one. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 259 | PN.replaceAllUsesWith(NewPN); |
| 260 | NewPN->addIncoming(&PN, &ExitBB); |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 261 | } |
| 262 | } |
| 263 | |
Chandler Carruth | d8b0c8c | 2018-07-07 01:12:56 +0000 | [diff] [blame] | 264 | /// Hoist the current loop up to the innermost loop containing a remaining exit. |
| 265 | /// |
| 266 | /// Because we've removed an exit from the loop, we may have changed the set of |
| 267 | /// loops reachable and need to move the current loop up the loop nest or even |
| 268 | /// to an entirely separate nest. |
| 269 | static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader, |
Alina Sbirlea | 97468e9 | 2019-02-21 21:13:34 +0000 | [diff] [blame] | 270 | DominatorTree &DT, LoopInfo &LI, |
| 271 | MemorySSAUpdater *MSSAU) { |
Chandler Carruth | d8b0c8c | 2018-07-07 01:12:56 +0000 | [diff] [blame] | 272 | // If the loop is already at the top level, we can't hoist it anywhere. |
| 273 | Loop *OldParentL = L.getParentLoop(); |
| 274 | if (!OldParentL) |
| 275 | return; |
| 276 | |
| 277 | SmallVector<BasicBlock *, 4> Exits; |
| 278 | L.getExitBlocks(Exits); |
| 279 | Loop *NewParentL = nullptr; |
| 280 | for (auto *ExitBB : Exits) |
| 281 | if (Loop *ExitL = LI.getLoopFor(ExitBB)) |
| 282 | if (!NewParentL || NewParentL->contains(ExitL)) |
| 283 | NewParentL = ExitL; |
| 284 | |
| 285 | if (NewParentL == OldParentL) |
| 286 | return; |
| 287 | |
| 288 | // The new parent loop (if different) should always contain the old one. |
| 289 | if (NewParentL) |
| 290 | assert(NewParentL->contains(OldParentL) && |
| 291 | "Can only hoist this loop up the nest!"); |
| 292 | |
| 293 | // The preheader will need to move with the body of this loop. However, |
| 294 | // because it isn't in this loop we also need to update the primary loop map. |
| 295 | assert(OldParentL == LI.getLoopFor(&Preheader) && |
| 296 | "Parent loop of this loop should contain this loop's preheader!"); |
| 297 | LI.changeLoopFor(&Preheader, NewParentL); |
| 298 | |
| 299 | // Remove this loop from its old parent. |
| 300 | OldParentL->removeChildLoop(&L); |
| 301 | |
| 302 | // Add the loop either to the new parent or as a top-level loop. |
| 303 | if (NewParentL) |
| 304 | NewParentL->addChildLoop(&L); |
| 305 | else |
| 306 | LI.addTopLevelLoop(&L); |
| 307 | |
| 308 | // Remove this loops blocks from the old parent and every other loop up the |
| 309 | // nest until reaching the new parent. Also update all of these |
| 310 | // no-longer-containing loops to reflect the nesting change. |
| 311 | for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL; |
| 312 | OldContainingL = OldContainingL->getParentLoop()) { |
| 313 | llvm::erase_if(OldContainingL->getBlocksVector(), |
| 314 | [&](const BasicBlock *BB) { |
| 315 | return BB == &Preheader || L.contains(BB); |
| 316 | }); |
| 317 | |
| 318 | OldContainingL->getBlocksSet().erase(&Preheader); |
| 319 | for (BasicBlock *BB : L.blocks()) |
| 320 | OldContainingL->getBlocksSet().erase(BB); |
| 321 | |
| 322 | // Because we just hoisted a loop out of this one, we have essentially |
| 323 | // created new exit paths from it. That means we need to form LCSSA PHI |
| 324 | // nodes for values used in the no-longer-nested loop. |
| 325 | formLCSSA(*OldContainingL, DT, &LI, nullptr); |
| 326 | |
| 327 | // We shouldn't need to form dedicated exits because the exit introduced |
Alina Sbirlea | 52e97a2 | 2018-08-28 20:41:05 +0000 | [diff] [blame] | 328 | // here is the (just split by unswitching) preheader. However, after trivial |
| 329 | // unswitching it is possible to get new non-dedicated exits out of parent |
| 330 | // loop so let's conservatively form dedicated exit blocks and figure out |
| 331 | // if we can optimize later. |
Alina Sbirlea | 97468e9 | 2019-02-21 21:13:34 +0000 | [diff] [blame] | 332 | formDedicatedExitBlocks(OldContainingL, &DT, &LI, MSSAU, |
| 333 | /*PreserveLCSSA*/ true); |
Chandler Carruth | d8b0c8c | 2018-07-07 01:12:56 +0000 | [diff] [blame] | 334 | } |
| 335 | } |
| 336 | |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 337 | /// Unswitch a trivial branch if the condition is loop invariant. |
| 338 | /// |
| 339 | /// This routine should only be called when loop code leading to the branch has |
| 340 | /// been validated as trivial (no side effects). This routine checks if the |
| 341 | /// condition is invariant and one of the successors is a loop exit. This |
| 342 | /// allows us to unswitch without duplicating the loop, making it trivial. |
| 343 | /// |
| 344 | /// If this routine fails to unswitch the branch it returns false. |
| 345 | /// |
| 346 | /// If the branch can be unswitched, this routine splits the preheader and |
| 347 | /// hoists the branch above that split. Preserves loop simplified form |
| 348 | /// (splitting the exit block as necessary). It simplifies the branch within |
| 349 | /// the loop to an unconditional branch but doesn't remove it entirely. Further |
| 350 | /// cleanup can be done with some simplify-cfg like pass. |
Chandler Carruth | 3897ded | 2018-07-03 09:13:27 +0000 | [diff] [blame] | 351 | /// |
| 352 | /// If `SE` is not null, it will be updated based on the potential loop SCEVs |
| 353 | /// invalidated by this. |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 354 | static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT, |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 355 | LoopInfo &LI, ScalarEvolution *SE, |
| 356 | MemorySSAUpdater *MSSAU) { |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 357 | assert(BI.isConditional() && "Can only unswitch a conditional branch!"); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 358 | LLVM_DEBUG(dbgs() << " Trying to unswitch branch: " << BI << "\n"); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 359 | |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 360 | // The loop invariant values that we want to unswitch. |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 361 | TinyPtrVector<Value *> Invariants; |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 362 | |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 363 | // When true, we're fully unswitching the branch rather than just unswitching |
| 364 | // some input conditions to the branch. |
| 365 | bool FullUnswitch = false; |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 366 | |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 367 | if (L.isLoopInvariant(BI.getCondition())) { |
| 368 | Invariants.push_back(BI.getCondition()); |
| 369 | FullUnswitch = true; |
| 370 | } else { |
| 371 | if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition())) |
| 372 | Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI); |
| 373 | if (Invariants.empty()) |
| 374 | // Couldn't find invariant inputs! |
| 375 | return false; |
| 376 | } |
| 377 | |
| 378 | // Check that one of the branch's successors exits, and which one. |
| 379 | bool ExitDirection = true; |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 380 | int LoopExitSuccIdx = 0; |
| 381 | auto *LoopExitBB = BI.getSuccessor(0); |
Chandler Carruth | baf045f | 2018-05-10 17:33:20 +0000 | [diff] [blame] | 382 | if (L.contains(LoopExitBB)) { |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 383 | ExitDirection = false; |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 384 | LoopExitSuccIdx = 1; |
| 385 | LoopExitBB = BI.getSuccessor(1); |
Chandler Carruth | baf045f | 2018-05-10 17:33:20 +0000 | [diff] [blame] | 386 | if (L.contains(LoopExitBB)) |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 387 | return false; |
| 388 | } |
| 389 | auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx); |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 390 | auto *ParentBB = BI.getParent(); |
| 391 | if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB)) |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 392 | return false; |
| 393 | |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 394 | // When unswitching only part of the branch's condition, we need the exit |
| 395 | // block to be reached directly from the partially unswitched input. This can |
| 396 | // be done when the exit block is along the true edge and the branch condition |
| 397 | // is a graph of `or` operations, or the exit block is along the false edge |
| 398 | // and the condition is a graph of `and` operations. |
| 399 | if (!FullUnswitch) { |
| 400 | if (ExitDirection) { |
| 401 | if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::Or) |
| 402 | return false; |
| 403 | } else { |
| 404 | if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::And) |
| 405 | return false; |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | LLVM_DEBUG({ |
| 410 | dbgs() << " unswitching trivial invariant conditions for: " << BI |
| 411 | << "\n"; |
| 412 | for (Value *Invariant : Invariants) { |
| 413 | dbgs() << " " << *Invariant << " == true"; |
| 414 | if (Invariant != Invariants.back()) |
| 415 | dbgs() << " ||"; |
| 416 | dbgs() << "\n"; |
| 417 | } |
| 418 | }); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 419 | |
Chandler Carruth | 3897ded | 2018-07-03 09:13:27 +0000 | [diff] [blame] | 420 | // If we have scalar evolutions, we need to invalidate them including this |
| 421 | // loop and the loop containing the exit block. |
| 422 | if (SE) { |
| 423 | if (Loop *ExitL = LI.getLoopFor(LoopExitBB)) |
| 424 | SE->forgetLoop(ExitL); |
| 425 | else |
| 426 | // Forget the entire nest as this exits the entire nest. |
| 427 | SE->forgetTopmostLoop(&L); |
| 428 | } |
| 429 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 430 | if (MSSAU && VerifyMemorySSA) |
| 431 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
| 432 | |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 433 | // Split the preheader, so that we know that there is a safe place to insert |
| 434 | // the conditional branch. We will change the preheader to have a conditional |
| 435 | // branch on LoopCond. |
| 436 | BasicBlock *OldPH = L.getLoopPreheader(); |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 437 | BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 438 | |
| 439 | // Now that we have a place to insert the conditional branch, create a place |
| 440 | // to branch to: this is the exit block out of the loop that we are |
| 441 | // unswitching. We need to split this if there are other loop predecessors. |
| 442 | // Because the loop is in simplified form, *any* other predecessor is enough. |
| 443 | BasicBlock *UnswitchedBB; |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 444 | if (FullUnswitch && LoopExitBB->getUniquePredecessor()) { |
| 445 | assert(LoopExitBB->getUniquePredecessor() == BI.getParent() && |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 446 | "A branch's parent isn't a predecessor!"); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 447 | UnswitchedBB = LoopExitBB; |
| 448 | } else { |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 449 | UnswitchedBB = |
| 450 | SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 451 | } |
| 452 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 453 | if (MSSAU && VerifyMemorySSA) |
| 454 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
| 455 | |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 456 | // Actually move the invariant uses into the unswitched position. If possible, |
| 457 | // we do this by moving the instructions, but when doing partial unswitching |
| 458 | // we do it by building a new merge of the values in the unswitched position. |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 459 | OldPH->getTerminator()->eraseFromParent(); |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 460 | if (FullUnswitch) { |
| 461 | // If fully unswitching, we can use the existing branch instruction. |
| 462 | // Splice it into the old PH to gate reaching the new preheader and re-point |
| 463 | // its successors. |
| 464 | OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(), |
| 465 | BI); |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 466 | if (MSSAU) { |
| 467 | // Temporarily clone the terminator, to make MSSA update cheaper by |
| 468 | // separating "insert edge" updates from "remove edge" ones. |
| 469 | ParentBB->getInstList().push_back(BI.clone()); |
| 470 | } else { |
| 471 | // Create a new unconditional branch that will continue the loop as a new |
| 472 | // terminator. |
| 473 | BranchInst::Create(ContinueBB, ParentBB); |
| 474 | } |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 475 | BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB); |
| 476 | BI.setSuccessor(1 - LoopExitSuccIdx, NewPH); |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 477 | } else { |
| 478 | // Only unswitching a subset of inputs to the condition, so we will need to |
| 479 | // build a new branch that merges the invariant inputs. |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 480 | if (ExitDirection) |
| 481 | assert(cast<Instruction>(BI.getCondition())->getOpcode() == |
| 482 | Instruction::Or && |
| 483 | "Must have an `or` of `i1`s for the condition!"); |
| 484 | else |
| 485 | assert(cast<Instruction>(BI.getCondition())->getOpcode() == |
| 486 | Instruction::And && |
| 487 | "Must have an `and` of `i1`s for the condition!"); |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 488 | buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection, |
| 489 | *UnswitchedBB, *NewPH); |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 490 | } |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 491 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 492 | // Update the dominator tree with the added edge. |
| 493 | DT.insertEdge(OldPH, UnswitchedBB); |
| 494 | |
| 495 | // After the dominator tree was updated with the added edge, update MemorySSA |
| 496 | // if available. |
| 497 | if (MSSAU) { |
| 498 | SmallVector<CFGUpdate, 1> Updates; |
| 499 | Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB}); |
| 500 | MSSAU->applyInsertUpdates(Updates, DT); |
| 501 | } |
| 502 | |
| 503 | // Finish updating dominator tree and memory ssa for full unswitch. |
| 504 | if (FullUnswitch) { |
| 505 | if (MSSAU) { |
| 506 | // Remove the cloned branch instruction. |
| 507 | ParentBB->getTerminator()->eraseFromParent(); |
| 508 | // Create unconditional branch now. |
| 509 | BranchInst::Create(ContinueBB, ParentBB); |
| 510 | MSSAU->removeEdge(ParentBB, LoopExitBB); |
| 511 | } |
| 512 | DT.deleteEdge(ParentBB, LoopExitBB); |
| 513 | } |
| 514 | |
| 515 | if (MSSAU && VerifyMemorySSA) |
| 516 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
| 517 | |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 518 | // Rewrite the relevant PHI nodes. |
| 519 | if (UnswitchedBB == LoopExitBB) |
| 520 | rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH); |
| 521 | else |
| 522 | rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB, |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 523 | *ParentBB, *OldPH, FullUnswitch); |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 524 | |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 525 | // The constant we can replace all of our invariants with inside the loop |
| 526 | // body. If any of the invariants have a value other than this the loop won't |
| 527 | // be entered. |
| 528 | ConstantInt *Replacement = ExitDirection |
| 529 | ? ConstantInt::getFalse(BI.getContext()) |
| 530 | : ConstantInt::getTrue(BI.getContext()); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 531 | |
| 532 | // Since this is an i1 condition we can also trivially replace uses of it |
| 533 | // within the loop with a constant. |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 534 | for (Value *Invariant : Invariants) |
| 535 | replaceLoopInvariantUses(L, Invariant, *Replacement); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 536 | |
Chandler Carruth | d8b0c8c | 2018-07-07 01:12:56 +0000 | [diff] [blame] | 537 | // If this was full unswitching, we may have changed the nesting relationship |
| 538 | // for this loop so hoist it to its correct parent if needed. |
| 539 | if (FullUnswitch) |
Alina Sbirlea | 97468e9 | 2019-02-21 21:13:34 +0000 | [diff] [blame] | 540 | hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU); |
| 541 | |
| 542 | if (MSSAU && VerifyMemorySSA) |
| 543 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
Chandler Carruth | d8b0c8c | 2018-07-07 01:12:56 +0000 | [diff] [blame] | 544 | |
Alina Sbirlea | 52e97a2 | 2018-08-28 20:41:05 +0000 | [diff] [blame] | 545 | LLVM_DEBUG(dbgs() << " done: unswitching trivial branch...\n"); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 546 | ++NumTrivial; |
| 547 | ++NumBranches; |
| 548 | return true; |
| 549 | } |
| 550 | |
| 551 | /// Unswitch a trivial switch if the condition is loop invariant. |
| 552 | /// |
| 553 | /// This routine should only be called when loop code leading to the switch has |
| 554 | /// been validated as trivial (no side effects). This routine checks if the |
| 555 | /// condition is invariant and that at least one of the successors is a loop |
| 556 | /// exit. This allows us to unswitch without duplicating the loop, making it |
| 557 | /// trivial. |
| 558 | /// |
| 559 | /// If this routine fails to unswitch the switch it returns false. |
| 560 | /// |
| 561 | /// If the switch can be unswitched, this routine splits the preheader and |
| 562 | /// copies the switch above that split. If the default case is one of the |
| 563 | /// exiting cases, it copies the non-exiting cases and points them at the new |
| 564 | /// preheader. If the default case is not exiting, it copies the exiting cases |
| 565 | /// and points the default at the preheader. It preserves loop simplified form |
| 566 | /// (splitting the exit blocks as necessary). It simplifies the switch within |
| 567 | /// the loop by removing now-dead cases. If the default case is one of those |
| 568 | /// unswitched, it replaces its destination with a new basic block containing |
| 569 | /// only unreachable. Such basic blocks, while technically loop exits, are not |
| 570 | /// considered for unswitching so this is a stable transform and the same |
| 571 | /// switch will not be revisited. If after unswitching there is only a single |
| 572 | /// in-loop successor, the switch is further simplified to an unconditional |
| 573 | /// branch. Still more cleanup can be done with some simplify-cfg like pass. |
Chandler Carruth | 3897ded | 2018-07-03 09:13:27 +0000 | [diff] [blame] | 574 | /// |
| 575 | /// If `SE` is not null, it will be updated based on the potential loop SCEVs |
| 576 | /// invalidated by this. |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 577 | static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT, |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 578 | LoopInfo &LI, ScalarEvolution *SE, |
| 579 | MemorySSAUpdater *MSSAU) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 580 | LLVM_DEBUG(dbgs() << " Trying to unswitch switch: " << SI << "\n"); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 581 | Value *LoopCond = SI.getCondition(); |
| 582 | |
| 583 | // If this isn't switching on an invariant condition, we can't unswitch it. |
| 584 | if (!L.isLoopInvariant(LoopCond)) |
| 585 | return false; |
| 586 | |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 587 | auto *ParentBB = SI.getParent(); |
| 588 | |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 589 | SmallVector<int, 4> ExitCaseIndices; |
| 590 | for (auto Case : SI.cases()) { |
| 591 | auto *SuccBB = Case.getCaseSuccessor(); |
Chandler Carruth | baf045f | 2018-05-10 17:33:20 +0000 | [diff] [blame] | 592 | if (!L.contains(SuccBB) && |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 593 | areLoopExitPHIsLoopInvariant(L, *ParentBB, *SuccBB)) |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 594 | ExitCaseIndices.push_back(Case.getCaseIndex()); |
| 595 | } |
| 596 | BasicBlock *DefaultExitBB = nullptr; |
Chandler Carruth | baf045f | 2018-05-10 17:33:20 +0000 | [diff] [blame] | 597 | if (!L.contains(SI.getDefaultDest()) && |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 598 | areLoopExitPHIsLoopInvariant(L, *ParentBB, *SI.getDefaultDest()) && |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 599 | !isa<UnreachableInst>(SI.getDefaultDest()->getTerminator())) |
| 600 | DefaultExitBB = SI.getDefaultDest(); |
| 601 | else if (ExitCaseIndices.empty()) |
| 602 | return false; |
| 603 | |
Alina Sbirlea | 52e97a2 | 2018-08-28 20:41:05 +0000 | [diff] [blame] | 604 | LLVM_DEBUG(dbgs() << " unswitching trivial switch...\n"); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 605 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 606 | if (MSSAU && VerifyMemorySSA) |
| 607 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
| 608 | |
Chandler Carruth | 3897ded | 2018-07-03 09:13:27 +0000 | [diff] [blame] | 609 | // We may need to invalidate SCEVs for the outermost loop reached by any of |
| 610 | // the exits. |
| 611 | Loop *OuterL = &L; |
| 612 | |
Chandler Carruth | 47dc3a3 | 2018-07-10 08:36:05 +0000 | [diff] [blame] | 613 | if (DefaultExitBB) { |
| 614 | // Clear out the default destination temporarily to allow accurate |
| 615 | // predecessor lists to be examined below. |
| 616 | SI.setDefaultDest(nullptr); |
| 617 | // Check the loop containing this exit. |
| 618 | Loop *ExitL = LI.getLoopFor(DefaultExitBB); |
| 619 | if (!ExitL || ExitL->contains(OuterL)) |
| 620 | OuterL = ExitL; |
| 621 | } |
| 622 | |
| 623 | // Store the exit cases into a separate data structure and remove them from |
| 624 | // the switch. |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 625 | SmallVector<std::pair<ConstantInt *, BasicBlock *>, 4> ExitCases; |
| 626 | ExitCases.reserve(ExitCaseIndices.size()); |
| 627 | // We walk the case indices backwards so that we remove the last case first |
| 628 | // and don't disrupt the earlier indices. |
| 629 | for (unsigned Index : reverse(ExitCaseIndices)) { |
| 630 | auto CaseI = SI.case_begin() + Index; |
Chandler Carruth | 3897ded | 2018-07-03 09:13:27 +0000 | [diff] [blame] | 631 | // Compute the outer loop from this exit. |
| 632 | Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor()); |
| 633 | if (!ExitL || ExitL->contains(OuterL)) |
| 634 | OuterL = ExitL; |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 635 | // Save the value of this case. |
| 636 | ExitCases.push_back({CaseI->getCaseValue(), CaseI->getCaseSuccessor()}); |
| 637 | // Delete the unswitched cases. |
| 638 | SI.removeCase(CaseI); |
| 639 | } |
| 640 | |
Chandler Carruth | 3897ded | 2018-07-03 09:13:27 +0000 | [diff] [blame] | 641 | if (SE) { |
| 642 | if (OuterL) |
| 643 | SE->forgetLoop(OuterL); |
| 644 | else |
| 645 | SE->forgetTopmostLoop(&L); |
| 646 | } |
| 647 | |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 648 | // Check if after this all of the remaining cases point at the same |
| 649 | // successor. |
| 650 | BasicBlock *CommonSuccBB = nullptr; |
| 651 | if (SI.getNumCases() > 0 && |
| 652 | std::all_of(std::next(SI.case_begin()), SI.case_end(), |
| 653 | [&SI](const SwitchInst::CaseHandle &Case) { |
| 654 | return Case.getCaseSuccessor() == |
| 655 | SI.case_begin()->getCaseSuccessor(); |
| 656 | })) |
| 657 | CommonSuccBB = SI.case_begin()->getCaseSuccessor(); |
Chandler Carruth | 47dc3a3 | 2018-07-10 08:36:05 +0000 | [diff] [blame] | 658 | if (!DefaultExitBB) { |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 659 | // If we're not unswitching the default, we need it to match any cases to |
| 660 | // have a common successor or if we have no cases it is the common |
| 661 | // successor. |
| 662 | if (SI.getNumCases() == 0) |
| 663 | CommonSuccBB = SI.getDefaultDest(); |
| 664 | else if (SI.getDefaultDest() != CommonSuccBB) |
| 665 | CommonSuccBB = nullptr; |
| 666 | } |
| 667 | |
| 668 | // Split the preheader, so that we know that there is a safe place to insert |
| 669 | // the switch. |
| 670 | BasicBlock *OldPH = L.getLoopPreheader(); |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 671 | BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 672 | OldPH->getTerminator()->eraseFromParent(); |
| 673 | |
| 674 | // Now add the unswitched switch. |
| 675 | auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH); |
| 676 | |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 677 | // Rewrite the IR for the unswitched basic blocks. This requires two steps. |
| 678 | // First, we split any exit blocks with remaining in-loop predecessors. Then |
| 679 | // we update the PHIs in one of two ways depending on if there was a split. |
| 680 | // We walk in reverse so that we split in the same order as the cases |
| 681 | // appeared. This is purely for convenience of reading the resulting IR, but |
| 682 | // it doesn't cost anything really. |
| 683 | SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs; |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 684 | SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap; |
| 685 | // Handle the default exit if necessary. |
| 686 | // FIXME: It'd be great if we could merge this with the loop below but LLVM's |
| 687 | // ranges aren't quite powerful enough yet. |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 688 | if (DefaultExitBB) { |
| 689 | if (pred_empty(DefaultExitBB)) { |
| 690 | UnswitchedExitBBs.insert(DefaultExitBB); |
| 691 | rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH); |
| 692 | } else { |
| 693 | auto *SplitBB = |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 694 | SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU); |
| 695 | rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB, |
| 696 | *ParentBB, *OldPH, |
| 697 | /*FullUnswitch*/ true); |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 698 | DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB; |
| 699 | } |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 700 | } |
| 701 | // Note that we must use a reference in the for loop so that we update the |
| 702 | // container. |
| 703 | for (auto &CasePair : reverse(ExitCases)) { |
| 704 | // Grab a reference to the exit block in the pair so that we can update it. |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 705 | BasicBlock *ExitBB = CasePair.second; |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 706 | |
| 707 | // If this case is the last edge into the exit block, we can simply reuse it |
| 708 | // as it will no longer be a loop exit. No mapping necessary. |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 709 | if (pred_empty(ExitBB)) { |
| 710 | // Only rewrite once. |
| 711 | if (UnswitchedExitBBs.insert(ExitBB).second) |
| 712 | rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 713 | continue; |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 714 | } |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 715 | |
| 716 | // Otherwise we need to split the exit block so that we retain an exit |
| 717 | // block from the loop and a target for the unswitched condition. |
| 718 | BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB]; |
| 719 | if (!SplitExitBB) { |
| 720 | // If this is the first time we see this, do the split and remember it. |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 721 | SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU); |
| 722 | rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB, |
| 723 | *ParentBB, *OldPH, |
| 724 | /*FullUnswitch*/ true); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 725 | } |
Chandler Carruth | d869b18 | 2017-05-12 02:19:59 +0000 | [diff] [blame] | 726 | // Update the case pair to point to the split block. |
| 727 | CasePair.second = SplitExitBB; |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 728 | } |
| 729 | |
| 730 | // Now add the unswitched cases. We do this in reverse order as we built them |
| 731 | // in reverse order. |
| 732 | for (auto CasePair : reverse(ExitCases)) { |
| 733 | ConstantInt *CaseVal = CasePair.first; |
| 734 | BasicBlock *UnswitchedBB = CasePair.second; |
| 735 | |
| 736 | NewSI->addCase(CaseVal, UnswitchedBB); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 737 | } |
| 738 | |
| 739 | // If the default was unswitched, re-point it and add explicit cases for |
| 740 | // entering the loop. |
| 741 | if (DefaultExitBB) { |
| 742 | NewSI->setDefaultDest(DefaultExitBB); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 743 | |
| 744 | // We removed all the exit cases, so we just copy the cases to the |
| 745 | // unswitched switch. |
| 746 | for (auto Case : SI.cases()) |
| 747 | NewSI->addCase(Case.getCaseValue(), NewPH); |
| 748 | } |
| 749 | |
| 750 | // If we ended up with a common successor for every path through the switch |
| 751 | // after unswitching, rewrite it to an unconditional branch to make it easy |
| 752 | // to recognize. Otherwise we potentially have to recognize the default case |
| 753 | // pointing at unreachable and other complexity. |
| 754 | if (CommonSuccBB) { |
| 755 | BasicBlock *BB = SI.getParent(); |
Chandler Carruth | 47dc3a3 | 2018-07-10 08:36:05 +0000 | [diff] [blame] | 756 | // We may have had multiple edges to this common successor block, so remove |
| 757 | // them as predecessors. We skip the first one, either the default or the |
| 758 | // actual first case. |
| 759 | bool SkippedFirst = DefaultExitBB == nullptr; |
| 760 | for (auto Case : SI.cases()) { |
| 761 | assert(Case.getCaseSuccessor() == CommonSuccBB && |
| 762 | "Non-common successor!"); |
Chandler Carruth | 148861f | 2018-07-10 08:57:04 +0000 | [diff] [blame] | 763 | (void)Case; |
Chandler Carruth | 47dc3a3 | 2018-07-10 08:36:05 +0000 | [diff] [blame] | 764 | if (!SkippedFirst) { |
| 765 | SkippedFirst = true; |
| 766 | continue; |
| 767 | } |
| 768 | CommonSuccBB->removePredecessor(BB, |
Max Kazantsev | 20b9189 | 2019-02-12 07:09:29 +0000 | [diff] [blame] | 769 | /*KeepOneInputPHIs*/ true); |
Chandler Carruth | 47dc3a3 | 2018-07-10 08:36:05 +0000 | [diff] [blame] | 770 | } |
| 771 | // Now nuke the switch and replace it with a direct branch. |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 772 | SI.eraseFromParent(); |
| 773 | BranchInst::Create(CommonSuccBB, BB); |
Chandler Carruth | 47dc3a3 | 2018-07-10 08:36:05 +0000 | [diff] [blame] | 774 | } else if (DefaultExitBB) { |
| 775 | assert(SI.getNumCases() > 0 && |
| 776 | "If we had no cases we'd have a common successor!"); |
| 777 | // Move the last case to the default successor. This is valid as if the |
| 778 | // default got unswitched it cannot be reached. This has the advantage of |
| 779 | // being simple and keeping the number of edges from this switch to |
| 780 | // successors the same, and avoiding any PHI update complexity. |
| 781 | auto LastCaseI = std::prev(SI.case_end()); |
| 782 | SI.setDefaultDest(LastCaseI->getCaseSuccessor()); |
| 783 | SI.removeCase(LastCaseI); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 784 | } |
| 785 | |
Chandler Carruth | 2c85a23 | 2018-05-01 09:54:39 +0000 | [diff] [blame] | 786 | // Walk the unswitched exit blocks and the unswitched split blocks and update |
| 787 | // the dominator tree based on the CFG edits. While we are walking unordered |
| 788 | // containers here, the API for applyUpdates takes an unordered list of |
| 789 | // updates and requires them to not contain duplicates. |
| 790 | SmallVector<DominatorTree::UpdateType, 4> DTUpdates; |
| 791 | for (auto *UnswitchedExitBB : UnswitchedExitBBs) { |
| 792 | DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB}); |
| 793 | DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB}); |
| 794 | } |
| 795 | for (auto SplitUnswitchedPair : SplitExitBBMap) { |
Alina Sbirlea | 90d2e3a | 2019-02-22 07:18:37 +0000 | [diff] [blame] | 796 | DTUpdates.push_back({DT.Delete, ParentBB, SplitUnswitchedPair.first}); |
| 797 | DTUpdates.push_back({DT.Insert, OldPH, SplitUnswitchedPair.second}); |
Chandler Carruth | 2c85a23 | 2018-05-01 09:54:39 +0000 | [diff] [blame] | 798 | } |
| 799 | DT.applyUpdates(DTUpdates); |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 800 | |
| 801 | if (MSSAU) { |
| 802 | MSSAU->applyUpdates(DTUpdates, DT); |
| 803 | if (VerifyMemorySSA) |
| 804 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
| 805 | } |
| 806 | |
David Green | 7c35de1 | 2018-02-28 11:00:08 +0000 | [diff] [blame] | 807 | assert(DT.verify(DominatorTree::VerificationLevel::Fast)); |
Chandler Carruth | d8b0c8c | 2018-07-07 01:12:56 +0000 | [diff] [blame] | 808 | |
| 809 | // We may have changed the nesting relationship for this loop so hoist it to |
| 810 | // its correct parent if needed. |
Alina Sbirlea | 97468e9 | 2019-02-21 21:13:34 +0000 | [diff] [blame] | 811 | hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU); |
| 812 | |
| 813 | if (MSSAU && VerifyMemorySSA) |
| 814 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
Chandler Carruth | d8b0c8c | 2018-07-07 01:12:56 +0000 | [diff] [blame] | 815 | |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 816 | ++NumTrivial; |
| 817 | ++NumSwitches; |
Alina Sbirlea | 52e97a2 | 2018-08-28 20:41:05 +0000 | [diff] [blame] | 818 | LLVM_DEBUG(dbgs() << " done: unswitching trivial switch...\n"); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 819 | return true; |
| 820 | } |
| 821 | |
| 822 | /// This routine scans the loop to find a branch or switch which occurs before |
| 823 | /// any side effects occur. These can potentially be unswitched without |
| 824 | /// duplicating the loop. If a branch or switch is successfully unswitched the |
| 825 | /// scanning continues to see if subsequent branches or switches have become |
| 826 | /// trivial. Once all trivial candidates have been unswitched, this routine |
| 827 | /// returns. |
| 828 | /// |
| 829 | /// The return value indicates whether anything was unswitched (and therefore |
| 830 | /// changed). |
Chandler Carruth | 3897ded | 2018-07-03 09:13:27 +0000 | [diff] [blame] | 831 | /// |
| 832 | /// If `SE` is not null, it will be updated based on the potential loop SCEVs |
| 833 | /// invalidated by this. |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 834 | static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT, |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 835 | LoopInfo &LI, ScalarEvolution *SE, |
| 836 | MemorySSAUpdater *MSSAU) { |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 837 | bool Changed = false; |
| 838 | |
| 839 | // If loop header has only one reachable successor we should keep looking for |
| 840 | // trivial condition candidates in the successor as well. An alternative is |
| 841 | // to constant fold conditions and merge successors into loop header (then we |
| 842 | // only need to check header's terminator). The reason for not doing this in |
| 843 | // LoopUnswitch pass is that it could potentially break LoopPassManager's |
| 844 | // invariants. Folding dead branches could either eliminate the current loop |
| 845 | // or make other loops unreachable. LCSSA form might also not be preserved |
| 846 | // after deleting branches. The following code keeps traversing loop header's |
| 847 | // successors until it finds the trivial condition candidate (condition that |
| 848 | // is not a constant). Since unswitching generates branches with constant |
| 849 | // conditions, this scenario could be very common in practice. |
| 850 | BasicBlock *CurrentBB = L.getHeader(); |
| 851 | SmallPtrSet<BasicBlock *, 8> Visited; |
| 852 | Visited.insert(CurrentBB); |
| 853 | do { |
| 854 | // Check if there are any side-effecting instructions (e.g. stores, calls, |
| 855 | // volatile loads) in the part of the loop that the code *would* execute |
| 856 | // without unswitching. |
Alina Sbirlea | 9321087 | 2019-01-28 17:48:45 +0000 | [diff] [blame] | 857 | if (MSSAU) // Possible early exit with MSSA |
| 858 | if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB)) |
| 859 | if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end())) |
| 860 | return Changed; |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 861 | if (llvm::any_of(*CurrentBB, |
| 862 | [](Instruction &I) { return I.mayHaveSideEffects(); })) |
| 863 | return Changed; |
| 864 | |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 865 | Instruction *CurrentTerm = CurrentBB->getTerminator(); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 866 | |
| 867 | if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) { |
| 868 | // Don't bother trying to unswitch past a switch with a constant |
| 869 | // condition. This should be removed prior to running this pass by |
| 870 | // simplify-cfg. |
| 871 | if (isa<Constant>(SI->getCondition())) |
| 872 | return Changed; |
| 873 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 874 | if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU)) |
Hiroshi Inoue | f209649 | 2018-06-14 05:41:49 +0000 | [diff] [blame] | 875 | // Couldn't unswitch this one so we're done. |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 876 | return Changed; |
| 877 | |
| 878 | // Mark that we managed to unswitch something. |
| 879 | Changed = true; |
| 880 | |
| 881 | // If unswitching turned the terminator into an unconditional branch then |
| 882 | // we can continue. The unswitching logic specifically works to fold any |
| 883 | // cases it can into an unconditional branch to make it easier to |
| 884 | // recognize here. |
| 885 | auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator()); |
| 886 | if (!BI || BI->isConditional()) |
| 887 | return Changed; |
| 888 | |
| 889 | CurrentBB = BI->getSuccessor(0); |
| 890 | continue; |
| 891 | } |
| 892 | |
| 893 | auto *BI = dyn_cast<BranchInst>(CurrentTerm); |
| 894 | if (!BI) |
| 895 | // We do not understand other terminator instructions. |
| 896 | return Changed; |
| 897 | |
| 898 | // Don't bother trying to unswitch past an unconditional branch or a branch |
| 899 | // with a constant value. These should be removed by simplify-cfg prior to |
| 900 | // running this pass. |
| 901 | if (!BI->isConditional() || isa<Constant>(BI->getCondition())) |
| 902 | return Changed; |
| 903 | |
| 904 | // Found a trivial condition candidate: non-foldable conditional branch. If |
| 905 | // we fail to unswitch this, we can't do anything else that is trivial. |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 906 | if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU)) |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 907 | return Changed; |
| 908 | |
| 909 | // Mark that we managed to unswitch something. |
| 910 | Changed = true; |
| 911 | |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 912 | // If we only unswitched some of the conditions feeding the branch, we won't |
| 913 | // have collapsed it to a single successor. |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 914 | BI = cast<BranchInst>(CurrentBB->getTerminator()); |
Chandler Carruth | 4da3331 | 2018-06-20 18:57:07 +0000 | [diff] [blame] | 915 | if (BI->isConditional()) |
| 916 | return Changed; |
| 917 | |
| 918 | // Follow the newly unconditional branch into its successor. |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 919 | CurrentBB = BI->getSuccessor(0); |
| 920 | |
| 921 | // When continuing, if we exit the loop or reach a previous visited block, |
| 922 | // then we can not reach any trivial condition candidates (unfoldable |
| 923 | // branch instructions or switch instructions) and no unswitch can happen. |
| 924 | } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second); |
| 925 | |
| 926 | return Changed; |
| 927 | } |
| 928 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 929 | /// Build the cloned blocks for an unswitched copy of the given loop. |
| 930 | /// |
| 931 | /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and |
| 932 | /// after the split block (`SplitBB`) that will be used to select between the |
| 933 | /// cloned and original loop. |
| 934 | /// |
| 935 | /// This routine handles cloning all of the necessary loop blocks and exit |
| 936 | /// blocks including rewriting their instructions and the relevant PHI nodes. |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 937 | /// Any loop blocks or exit blocks which are dominated by a different successor |
| 938 | /// than the one for this clone of the loop blocks can be trivially skipped. We |
| 939 | /// use the `DominatingSucc` map to determine whether a block satisfies that |
| 940 | /// property with a simple map lookup. |
| 941 | /// |
| 942 | /// It also correctly creates the unconditional branch in the cloned |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 943 | /// unswitched parent block to only point at the unswitched successor. |
| 944 | /// |
| 945 | /// This does not handle most of the necessary updates to `LoopInfo`. Only exit |
| 946 | /// block splitting is correctly reflected in `LoopInfo`, essentially all of |
| 947 | /// the cloned blocks (and their loops) are left without full `LoopInfo` |
| 948 | /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned |
| 949 | /// blocks to them but doesn't create the cloned `DominatorTree` structure and |
| 950 | /// instead the caller must recompute an accurate DT. It *does* correctly |
| 951 | /// update the `AssumptionCache` provided in `AC`. |
| 952 | static BasicBlock *buildClonedLoopBlocks( |
| 953 | Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB, |
| 954 | ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB, |
| 955 | BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB, |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 956 | const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc, |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 957 | ValueToValueMapTy &VMap, |
| 958 | SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC, |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 959 | DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) { |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 960 | SmallVector<BasicBlock *, 4> NewBlocks; |
| 961 | NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size()); |
| 962 | |
| 963 | // We will need to clone a bunch of blocks, wrap up the clone operation in |
| 964 | // a helper. |
| 965 | auto CloneBlock = [&](BasicBlock *OldBB) { |
| 966 | // Clone the basic block and insert it before the new preheader. |
| 967 | BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent()); |
| 968 | NewBB->moveBefore(LoopPH); |
| 969 | |
| 970 | // Record this block and the mapping. |
| 971 | NewBlocks.push_back(NewBB); |
| 972 | VMap[OldBB] = NewBB; |
| 973 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 974 | return NewBB; |
| 975 | }; |
| 976 | |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 977 | // We skip cloning blocks when they have a dominating succ that is not the |
| 978 | // succ we are cloning for. |
| 979 | auto SkipBlock = [&](BasicBlock *BB) { |
| 980 | auto It = DominatingSucc.find(BB); |
| 981 | return It != DominatingSucc.end() && It->second != UnswitchedSuccBB; |
| 982 | }; |
| 983 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 984 | // First, clone the preheader. |
| 985 | auto *ClonedPH = CloneBlock(LoopPH); |
| 986 | |
| 987 | // Then clone all the loop blocks, skipping the ones that aren't necessary. |
| 988 | for (auto *LoopBB : L.blocks()) |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 989 | if (!SkipBlock(LoopBB)) |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 990 | CloneBlock(LoopBB); |
| 991 | |
| 992 | // Split all the loop exit edges so that when we clone the exit blocks, if |
| 993 | // any of the exit blocks are *also* a preheader for some other loop, we |
| 994 | // don't create multiple predecessors entering the loop header. |
| 995 | for (auto *ExitBB : ExitBlocks) { |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 996 | if (SkipBlock(ExitBB)) |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 997 | continue; |
| 998 | |
| 999 | // When we are going to clone an exit, we don't need to clone all the |
| 1000 | // instructions in the exit block and we want to ensure we have an easy |
| 1001 | // place to merge the CFG, so split the exit first. This is always safe to |
| 1002 | // do because there cannot be any non-loop predecessors of a loop exit in |
| 1003 | // loop simplified form. |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 1004 | auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1005 | |
| 1006 | // Rearrange the names to make it easier to write test cases by having the |
| 1007 | // exit block carry the suffix rather than the merge block carrying the |
| 1008 | // suffix. |
| 1009 | MergeBB->takeName(ExitBB); |
| 1010 | ExitBB->setName(Twine(MergeBB->getName()) + ".split"); |
| 1011 | |
| 1012 | // Now clone the original exit block. |
| 1013 | auto *ClonedExitBB = CloneBlock(ExitBB); |
| 1014 | assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 && |
| 1015 | "Exit block should have been split to have one successor!"); |
| 1016 | assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB && |
| 1017 | "Cloned exit block has the wrong successor!"); |
| 1018 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1019 | // Remap any cloned instructions and create a merge phi node for them. |
| 1020 | for (auto ZippedInsts : llvm::zip_first( |
| 1021 | llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())), |
| 1022 | llvm::make_range(ClonedExitBB->begin(), |
| 1023 | std::prev(ClonedExitBB->end())))) { |
| 1024 | Instruction &I = std::get<0>(ZippedInsts); |
| 1025 | Instruction &ClonedI = std::get<1>(ZippedInsts); |
| 1026 | |
| 1027 | // The only instructions in the exit block should be PHI nodes and |
| 1028 | // potentially a landing pad. |
| 1029 | assert( |
| 1030 | (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) && |
| 1031 | "Bad instruction in exit block!"); |
| 1032 | // We should have a value map between the instruction and its clone. |
| 1033 | assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!"); |
| 1034 | |
| 1035 | auto *MergePN = |
| 1036 | PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi", |
| 1037 | &*MergeBB->getFirstInsertionPt()); |
| 1038 | I.replaceAllUsesWith(MergePN); |
| 1039 | MergePN->addIncoming(&I, ExitBB); |
| 1040 | MergePN->addIncoming(&ClonedI, ClonedExitBB); |
| 1041 | } |
| 1042 | } |
| 1043 | |
| 1044 | // Rewrite the instructions in the cloned blocks to refer to the instructions |
| 1045 | // in the cloned blocks. We have to do this as a second pass so that we have |
| 1046 | // everything available. Also, we have inserted new instructions which may |
| 1047 | // include assume intrinsics, so we update the assumption cache while |
| 1048 | // processing this. |
| 1049 | for (auto *ClonedBB : NewBlocks) |
| 1050 | for (Instruction &I : *ClonedBB) { |
| 1051 | RemapInstruction(&I, VMap, |
| 1052 | RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); |
| 1053 | if (auto *II = dyn_cast<IntrinsicInst>(&I)) |
| 1054 | if (II->getIntrinsicID() == Intrinsic::assume) |
| 1055 | AC.registerAssumption(II); |
| 1056 | } |
| 1057 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1058 | // Update any PHI nodes in the cloned successors of the skipped blocks to not |
| 1059 | // have spurious incoming values. |
| 1060 | for (auto *LoopBB : L.blocks()) |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 1061 | if (SkipBlock(LoopBB)) |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1062 | for (auto *SuccBB : successors(LoopBB)) |
| 1063 | if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB))) |
| 1064 | for (PHINode &PN : ClonedSuccBB->phis()) |
| 1065 | PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false); |
| 1066 | |
Chandler Carruth | ed29654 | 2018-07-09 10:30:48 +0000 | [diff] [blame] | 1067 | // Remove the cloned parent as a predecessor of any successor we ended up |
| 1068 | // cloning other than the unswitched one. |
| 1069 | auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB)); |
| 1070 | for (auto *SuccBB : successors(ParentBB)) { |
| 1071 | if (SuccBB == UnswitchedSuccBB) |
| 1072 | continue; |
| 1073 | |
| 1074 | auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)); |
| 1075 | if (!ClonedSuccBB) |
| 1076 | continue; |
| 1077 | |
| 1078 | ClonedSuccBB->removePredecessor(ClonedParentBB, |
Max Kazantsev | 20b9189 | 2019-02-12 07:09:29 +0000 | [diff] [blame] | 1079 | /*KeepOneInputPHIs*/ true); |
Chandler Carruth | ed29654 | 2018-07-09 10:30:48 +0000 | [diff] [blame] | 1080 | } |
| 1081 | |
| 1082 | // Replace the cloned branch with an unconditional branch to the cloned |
| 1083 | // unswitched successor. |
| 1084 | auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB)); |
| 1085 | ClonedParentBB->getTerminator()->eraseFromParent(); |
| 1086 | BranchInst::Create(ClonedSuccBB, ClonedParentBB); |
| 1087 | |
| 1088 | // If there are duplicate entries in the PHI nodes because of multiple edges |
| 1089 | // to the unswitched successor, we need to nuke all but one as we replaced it |
| 1090 | // with a direct branch. |
| 1091 | for (PHINode &PN : ClonedSuccBB->phis()) { |
| 1092 | bool Found = false; |
| 1093 | // Loop over the incoming operands backwards so we can easily delete as we |
| 1094 | // go without invalidating the index. |
| 1095 | for (int i = PN.getNumOperands() - 1; i >= 0; --i) { |
| 1096 | if (PN.getIncomingBlock(i) != ClonedParentBB) |
| 1097 | continue; |
| 1098 | if (!Found) { |
| 1099 | Found = true; |
| 1100 | continue; |
| 1101 | } |
| 1102 | PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false); |
| 1103 | } |
| 1104 | } |
| 1105 | |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 1106 | // Record the domtree updates for the new blocks. |
Chandler Carruth | 44aab92 | 2018-05-01 09:42:09 +0000 | [diff] [blame] | 1107 | SmallPtrSet<BasicBlock *, 4> SuccSet; |
| 1108 | for (auto *ClonedBB : NewBlocks) { |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 1109 | for (auto *SuccBB : successors(ClonedBB)) |
Chandler Carruth | 44aab92 | 2018-05-01 09:42:09 +0000 | [diff] [blame] | 1110 | if (SuccSet.insert(SuccBB).second) |
| 1111 | DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB}); |
| 1112 | SuccSet.clear(); |
| 1113 | } |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 1114 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1115 | return ClonedPH; |
| 1116 | } |
| 1117 | |
| 1118 | /// Recursively clone the specified loop and all of its children. |
| 1119 | /// |
| 1120 | /// The target parent loop for the clone should be provided, or can be null if |
| 1121 | /// the clone is a top-level loop. While cloning, all the blocks are mapped |
| 1122 | /// with the provided value map. The entire original loop must be present in |
| 1123 | /// the value map. The cloned loop is returned. |
| 1124 | static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL, |
| 1125 | const ValueToValueMapTy &VMap, LoopInfo &LI) { |
| 1126 | auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) { |
| 1127 | assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!"); |
| 1128 | ClonedL.reserveBlocks(OrigL.getNumBlocks()); |
| 1129 | for (auto *BB : OrigL.blocks()) { |
| 1130 | auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB)); |
| 1131 | ClonedL.addBlockEntry(ClonedBB); |
Chandler Carruth | 0ace148 | 2018-04-24 03:27:00 +0000 | [diff] [blame] | 1132 | if (LI.getLoopFor(BB) == &OrigL) |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1133 | LI.changeLoopFor(ClonedBB, &ClonedL); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1134 | } |
| 1135 | }; |
| 1136 | |
| 1137 | // We specially handle the first loop because it may get cloned into |
| 1138 | // a different parent and because we most commonly are cloning leaf loops. |
| 1139 | Loop *ClonedRootL = LI.AllocateLoop(); |
| 1140 | if (RootParentL) |
| 1141 | RootParentL->addChildLoop(ClonedRootL); |
| 1142 | else |
| 1143 | LI.addTopLevelLoop(ClonedRootL); |
| 1144 | AddClonedBlocksToLoop(OrigRootL, *ClonedRootL); |
| 1145 | |
| 1146 | if (OrigRootL.empty()) |
| 1147 | return ClonedRootL; |
| 1148 | |
| 1149 | // If we have a nest, we can quickly clone the entire loop nest using an |
| 1150 | // iterative approach because it is a tree. We keep the cloned parent in the |
| 1151 | // data structure to avoid repeatedly querying through a map to find it. |
| 1152 | SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone; |
| 1153 | // Build up the loops to clone in reverse order as we'll clone them from the |
| 1154 | // back. |
| 1155 | for (Loop *ChildL : llvm::reverse(OrigRootL)) |
| 1156 | LoopsToClone.push_back({ClonedRootL, ChildL}); |
| 1157 | do { |
| 1158 | Loop *ClonedParentL, *L; |
| 1159 | std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val(); |
| 1160 | Loop *ClonedL = LI.AllocateLoop(); |
| 1161 | ClonedParentL->addChildLoop(ClonedL); |
| 1162 | AddClonedBlocksToLoop(*L, *ClonedL); |
| 1163 | for (Loop *ChildL : llvm::reverse(*L)) |
| 1164 | LoopsToClone.push_back({ClonedL, ChildL}); |
| 1165 | } while (!LoopsToClone.empty()); |
| 1166 | |
| 1167 | return ClonedRootL; |
| 1168 | } |
| 1169 | |
| 1170 | /// Build the cloned loops of an original loop from unswitching. |
| 1171 | /// |
| 1172 | /// Because unswitching simplifies the CFG of the loop, this isn't a trivial |
| 1173 | /// operation. We need to re-verify that there even is a loop (as the backedge |
| 1174 | /// may not have been cloned), and even if there are remaining backedges the |
| 1175 | /// backedge set may be different. However, we know that each child loop is |
| 1176 | /// undisturbed, we only need to find where to place each child loop within |
| 1177 | /// either any parent loop or within a cloned version of the original loop. |
| 1178 | /// |
| 1179 | /// Because child loops may end up cloned outside of any cloned version of the |
| 1180 | /// original loop, multiple cloned sibling loops may be created. All of them |
| 1181 | /// are returned so that the newly introduced loop nest roots can be |
| 1182 | /// identified. |
Chandler Carruth | 9281503 | 2018-06-02 01:29:01 +0000 | [diff] [blame] | 1183 | static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks, |
| 1184 | const ValueToValueMapTy &VMap, LoopInfo &LI, |
| 1185 | SmallVectorImpl<Loop *> &NonChildClonedLoops) { |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1186 | Loop *ClonedL = nullptr; |
| 1187 | |
| 1188 | auto *OrigPH = OrigL.getLoopPreheader(); |
| 1189 | auto *OrigHeader = OrigL.getHeader(); |
| 1190 | |
| 1191 | auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH)); |
| 1192 | auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader)); |
| 1193 | |
| 1194 | // We need to know the loops of the cloned exit blocks to even compute the |
| 1195 | // accurate parent loop. If we only clone exits to some parent of the |
| 1196 | // original parent, we want to clone into that outer loop. We also keep track |
| 1197 | // of the loops that our cloned exit blocks participate in. |
| 1198 | Loop *ParentL = nullptr; |
| 1199 | SmallVector<BasicBlock *, 4> ClonedExitsInLoops; |
| 1200 | SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap; |
| 1201 | ClonedExitsInLoops.reserve(ExitBlocks.size()); |
| 1202 | for (auto *ExitBB : ExitBlocks) |
| 1203 | if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB))) |
| 1204 | if (Loop *ExitL = LI.getLoopFor(ExitBB)) { |
| 1205 | ExitLoopMap[ClonedExitBB] = ExitL; |
| 1206 | ClonedExitsInLoops.push_back(ClonedExitBB); |
| 1207 | if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL))) |
| 1208 | ParentL = ExitL; |
| 1209 | } |
| 1210 | assert((!ParentL || ParentL == OrigL.getParentLoop() || |
| 1211 | ParentL->contains(OrigL.getParentLoop())) && |
| 1212 | "The computed parent loop should always contain (or be) the parent of " |
| 1213 | "the original loop."); |
| 1214 | |
| 1215 | // We build the set of blocks dominated by the cloned header from the set of |
| 1216 | // cloned blocks out of the original loop. While not all of these will |
| 1217 | // necessarily be in the cloned loop, it is enough to establish that they |
| 1218 | // aren't in unreachable cycles, etc. |
| 1219 | SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks; |
| 1220 | for (auto *BB : OrigL.blocks()) |
| 1221 | if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB))) |
| 1222 | ClonedLoopBlocks.insert(ClonedBB); |
| 1223 | |
| 1224 | // Rebuild the set of blocks that will end up in the cloned loop. We may have |
| 1225 | // skipped cloning some region of this loop which can in turn skip some of |
| 1226 | // the backedges so we have to rebuild the blocks in the loop based on the |
| 1227 | // backedges that remain after cloning. |
| 1228 | SmallVector<BasicBlock *, 16> Worklist; |
| 1229 | SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop; |
| 1230 | for (auto *Pred : predecessors(ClonedHeader)) { |
| 1231 | // The only possible non-loop header predecessor is the preheader because |
| 1232 | // we know we cloned the loop in simplified form. |
| 1233 | if (Pred == ClonedPH) |
| 1234 | continue; |
| 1235 | |
| 1236 | // Because the loop was in simplified form, the only non-loop predecessor |
| 1237 | // should be the preheader. |
| 1238 | assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop " |
| 1239 | "header other than the preheader " |
| 1240 | "that is not part of the loop!"); |
| 1241 | |
| 1242 | // Insert this block into the loop set and on the first visit (and if it |
| 1243 | // isn't the header we're currently walking) put it into the worklist to |
| 1244 | // recurse through. |
| 1245 | if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader) |
| 1246 | Worklist.push_back(Pred); |
| 1247 | } |
| 1248 | |
| 1249 | // If we had any backedges then there *is* a cloned loop. Put the header into |
| 1250 | // the loop set and then walk the worklist backwards to find all the blocks |
| 1251 | // that remain within the loop after cloning. |
| 1252 | if (!BlocksInClonedLoop.empty()) { |
| 1253 | BlocksInClonedLoop.insert(ClonedHeader); |
| 1254 | |
| 1255 | while (!Worklist.empty()) { |
| 1256 | BasicBlock *BB = Worklist.pop_back_val(); |
| 1257 | assert(BlocksInClonedLoop.count(BB) && |
| 1258 | "Didn't put block into the loop set!"); |
| 1259 | |
| 1260 | // Insert any predecessors that are in the possible set into the cloned |
| 1261 | // set, and if the insert is successful, add them to the worklist. Note |
| 1262 | // that we filter on the blocks that are definitely reachable via the |
| 1263 | // backedge to the loop header so we may prune out dead code within the |
| 1264 | // cloned loop. |
| 1265 | for (auto *Pred : predecessors(BB)) |
| 1266 | if (ClonedLoopBlocks.count(Pred) && |
| 1267 | BlocksInClonedLoop.insert(Pred).second) |
| 1268 | Worklist.push_back(Pred); |
| 1269 | } |
| 1270 | |
| 1271 | ClonedL = LI.AllocateLoop(); |
| 1272 | if (ParentL) { |
| 1273 | ParentL->addBasicBlockToLoop(ClonedPH, LI); |
| 1274 | ParentL->addChildLoop(ClonedL); |
| 1275 | } else { |
| 1276 | LI.addTopLevelLoop(ClonedL); |
| 1277 | } |
Chandler Carruth | 9281503 | 2018-06-02 01:29:01 +0000 | [diff] [blame] | 1278 | NonChildClonedLoops.push_back(ClonedL); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1279 | |
| 1280 | ClonedL->reserveBlocks(BlocksInClonedLoop.size()); |
| 1281 | // We don't want to just add the cloned loop blocks based on how we |
| 1282 | // discovered them. The original order of blocks was carefully built in |
| 1283 | // a way that doesn't rely on predecessor ordering. Rather than re-invent |
| 1284 | // that logic, we just re-walk the original blocks (and those of the child |
| 1285 | // loops) and filter them as we add them into the cloned loop. |
| 1286 | for (auto *BB : OrigL.blocks()) { |
| 1287 | auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)); |
| 1288 | if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB)) |
| 1289 | continue; |
| 1290 | |
| 1291 | // Directly add the blocks that are only in this loop. |
| 1292 | if (LI.getLoopFor(BB) == &OrigL) { |
| 1293 | ClonedL->addBasicBlockToLoop(ClonedBB, LI); |
| 1294 | continue; |
| 1295 | } |
| 1296 | |
| 1297 | // We want to manually add it to this loop and parents. |
| 1298 | // Registering it with LoopInfo will happen when we clone the top |
| 1299 | // loop for this block. |
| 1300 | for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop()) |
| 1301 | PL->addBlockEntry(ClonedBB); |
| 1302 | } |
| 1303 | |
| 1304 | // Now add each child loop whose header remains within the cloned loop. All |
| 1305 | // of the blocks within the loop must satisfy the same constraints as the |
| 1306 | // header so once we pass the header checks we can just clone the entire |
| 1307 | // child loop nest. |
| 1308 | for (Loop *ChildL : OrigL) { |
| 1309 | auto *ClonedChildHeader = |
| 1310 | cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader())); |
| 1311 | if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader)) |
| 1312 | continue; |
| 1313 | |
| 1314 | #ifndef NDEBUG |
| 1315 | // We should never have a cloned child loop header but fail to have |
| 1316 | // all of the blocks for that child loop. |
| 1317 | for (auto *ChildLoopBB : ChildL->blocks()) |
| 1318 | assert(BlocksInClonedLoop.count( |
| 1319 | cast<BasicBlock>(VMap.lookup(ChildLoopBB))) && |
| 1320 | "Child cloned loop has a header within the cloned outer " |
| 1321 | "loop but not all of its blocks!"); |
| 1322 | #endif |
| 1323 | |
| 1324 | cloneLoopNest(*ChildL, ClonedL, VMap, LI); |
| 1325 | } |
| 1326 | } |
| 1327 | |
| 1328 | // Now that we've handled all the components of the original loop that were |
| 1329 | // cloned into a new loop, we still need to handle anything from the original |
| 1330 | // loop that wasn't in a cloned loop. |
| 1331 | |
| 1332 | // Figure out what blocks are left to place within any loop nest containing |
| 1333 | // the unswitched loop. If we never formed a loop, the cloned PH is one of |
| 1334 | // them. |
| 1335 | SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet; |
| 1336 | if (BlocksInClonedLoop.empty()) |
| 1337 | UnloopedBlockSet.insert(ClonedPH); |
| 1338 | for (auto *ClonedBB : ClonedLoopBlocks) |
| 1339 | if (!BlocksInClonedLoop.count(ClonedBB)) |
| 1340 | UnloopedBlockSet.insert(ClonedBB); |
| 1341 | |
| 1342 | // Copy the cloned exits and sort them in ascending loop depth, we'll work |
| 1343 | // backwards across these to process them inside out. The order shouldn't |
| 1344 | // matter as we're just trying to build up the map from inside-out; we use |
| 1345 | // the map in a more stably ordered way below. |
| 1346 | auto OrderedClonedExitsInLoops = ClonedExitsInLoops; |
Fangrui Song | 0cac726 | 2018-09-27 02:13:45 +0000 | [diff] [blame] | 1347 | llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) { |
| 1348 | return ExitLoopMap.lookup(LHS)->getLoopDepth() < |
| 1349 | ExitLoopMap.lookup(RHS)->getLoopDepth(); |
| 1350 | }); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1351 | |
| 1352 | // Populate the existing ExitLoopMap with everything reachable from each |
| 1353 | // exit, starting from the inner most exit. |
| 1354 | while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) { |
| 1355 | assert(Worklist.empty() && "Didn't clear worklist!"); |
| 1356 | |
| 1357 | BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val(); |
| 1358 | Loop *ExitL = ExitLoopMap.lookup(ExitBB); |
| 1359 | |
| 1360 | // Walk the CFG back until we hit the cloned PH adding everything reachable |
| 1361 | // and in the unlooped set to this exit block's loop. |
| 1362 | Worklist.push_back(ExitBB); |
| 1363 | do { |
| 1364 | BasicBlock *BB = Worklist.pop_back_val(); |
| 1365 | // We can stop recursing at the cloned preheader (if we get there). |
| 1366 | if (BB == ClonedPH) |
| 1367 | continue; |
| 1368 | |
| 1369 | for (BasicBlock *PredBB : predecessors(BB)) { |
| 1370 | // If this pred has already been moved to our set or is part of some |
| 1371 | // (inner) loop, no update needed. |
| 1372 | if (!UnloopedBlockSet.erase(PredBB)) { |
| 1373 | assert( |
| 1374 | (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) && |
| 1375 | "Predecessor not mapped to a loop!"); |
| 1376 | continue; |
| 1377 | } |
| 1378 | |
| 1379 | // We just insert into the loop set here. We'll add these blocks to the |
| 1380 | // exit loop after we build up the set in an order that doesn't rely on |
| 1381 | // predecessor order (which in turn relies on use list order). |
| 1382 | bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second; |
| 1383 | (void)Inserted; |
| 1384 | assert(Inserted && "Should only visit an unlooped block once!"); |
| 1385 | |
| 1386 | // And recurse through to its predecessors. |
| 1387 | Worklist.push_back(PredBB); |
| 1388 | } |
| 1389 | } while (!Worklist.empty()); |
| 1390 | } |
| 1391 | |
| 1392 | // Now that the ExitLoopMap gives as mapping for all the non-looping cloned |
| 1393 | // blocks to their outer loops, walk the cloned blocks and the cloned exits |
| 1394 | // in their original order adding them to the correct loop. |
| 1395 | |
| 1396 | // We need a stable insertion order. We use the order of the original loop |
| 1397 | // order and map into the correct parent loop. |
| 1398 | for (auto *BB : llvm::concat<BasicBlock *const>( |
| 1399 | makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops)) |
| 1400 | if (Loop *OuterL = ExitLoopMap.lookup(BB)) |
| 1401 | OuterL->addBasicBlockToLoop(BB, LI); |
| 1402 | |
| 1403 | #ifndef NDEBUG |
| 1404 | for (auto &BBAndL : ExitLoopMap) { |
| 1405 | auto *BB = BBAndL.first; |
| 1406 | auto *OuterL = BBAndL.second; |
| 1407 | assert(LI.getLoopFor(BB) == OuterL && |
| 1408 | "Failed to put all blocks into outer loops!"); |
| 1409 | } |
| 1410 | #endif |
| 1411 | |
| 1412 | // Now that all the blocks are placed into the correct containing loop in the |
| 1413 | // absence of child loops, find all the potentially cloned child loops and |
| 1414 | // clone them into whatever outer loop we placed their header into. |
| 1415 | for (Loop *ChildL : OrigL) { |
| 1416 | auto *ClonedChildHeader = |
| 1417 | cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader())); |
| 1418 | if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader)) |
| 1419 | continue; |
| 1420 | |
| 1421 | #ifndef NDEBUG |
| 1422 | for (auto *ChildLoopBB : ChildL->blocks()) |
| 1423 | assert(VMap.count(ChildLoopBB) && |
| 1424 | "Cloned a child loop header but not all of that loops blocks!"); |
| 1425 | #endif |
| 1426 | |
| 1427 | NonChildClonedLoops.push_back(cloneLoopNest( |
| 1428 | *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI)); |
| 1429 | } |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1430 | } |
| 1431 | |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 1432 | static void |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 1433 | deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks, |
| 1434 | ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps, |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 1435 | DominatorTree &DT, MemorySSAUpdater *MSSAU) { |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 1436 | // Find all the dead clones, and remove them from their successors. |
| 1437 | SmallVector<BasicBlock *, 16> DeadBlocks; |
| 1438 | for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks)) |
| 1439 | for (auto &VMap : VMaps) |
| 1440 | if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB))) |
| 1441 | if (!DT.isReachableFromEntry(ClonedBB)) { |
| 1442 | for (BasicBlock *SuccBB : successors(ClonedBB)) |
| 1443 | SuccBB->removePredecessor(ClonedBB); |
| 1444 | DeadBlocks.push_back(ClonedBB); |
| 1445 | } |
| 1446 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 1447 | // Remove all MemorySSA in the dead blocks |
| 1448 | if (MSSAU) { |
| 1449 | SmallPtrSet<BasicBlock *, 16> DeadBlockSet(DeadBlocks.begin(), |
| 1450 | DeadBlocks.end()); |
| 1451 | MSSAU->removeBlocks(DeadBlockSet); |
| 1452 | } |
| 1453 | |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 1454 | // Drop any remaining references to break cycles. |
| 1455 | for (BasicBlock *BB : DeadBlocks) |
| 1456 | BB->dropAllReferences(); |
| 1457 | // Erase them from the IR. |
| 1458 | for (BasicBlock *BB : DeadBlocks) |
| 1459 | BB->eraseFromParent(); |
| 1460 | } |
| 1461 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 1462 | static void deleteDeadBlocksFromLoop(Loop &L, |
| 1463 | SmallVectorImpl<BasicBlock *> &ExitBlocks, |
| 1464 | DominatorTree &DT, LoopInfo &LI, |
| 1465 | MemorySSAUpdater *MSSAU) { |
Fedor Sergeev | 8b6effd | 2018-09-04 20:19:41 +0000 | [diff] [blame] | 1466 | // Find all the dead blocks tied to this loop, and remove them from their |
| 1467 | // successors. |
| 1468 | SmallPtrSet<BasicBlock *, 16> DeadBlockSet; |
| 1469 | |
| 1470 | // Start with loop/exit blocks and get a transitive closure of reachable dead |
| 1471 | // blocks. |
| 1472 | SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(), |
| 1473 | ExitBlocks.end()); |
| 1474 | DeathCandidates.append(L.blocks().begin(), L.blocks().end()); |
| 1475 | while (!DeathCandidates.empty()) { |
| 1476 | auto *BB = DeathCandidates.pop_back_val(); |
| 1477 | if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) { |
| 1478 | for (BasicBlock *SuccBB : successors(BB)) { |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 1479 | SuccBB->removePredecessor(BB); |
Fedor Sergeev | 8b6effd | 2018-09-04 20:19:41 +0000 | [diff] [blame] | 1480 | DeathCandidates.push_back(SuccBB); |
Fedor Sergeev | 7b49aa0 | 2018-08-29 19:10:44 +0000 | [diff] [blame] | 1481 | } |
Fedor Sergeev | 8b6effd | 2018-09-04 20:19:41 +0000 | [diff] [blame] | 1482 | DeadBlockSet.insert(BB); |
| 1483 | } |
| 1484 | } |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1485 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 1486 | // Remove all MemorySSA in the dead blocks |
| 1487 | if (MSSAU) |
| 1488 | MSSAU->removeBlocks(DeadBlockSet); |
| 1489 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1490 | // Filter out the dead blocks from the exit blocks list so that it can be |
| 1491 | // used in the caller. |
| 1492 | llvm::erase_if(ExitBlocks, |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 1493 | [&](BasicBlock *BB) { return DeadBlockSet.count(BB); }); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1494 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1495 | // Walk from this loop up through its parents removing all of the dead blocks. |
| 1496 | for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) { |
Fedor Sergeev | 8b6effd | 2018-09-04 20:19:41 +0000 | [diff] [blame] | 1497 | for (auto *BB : DeadBlockSet) |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1498 | ParentL->getBlocksSet().erase(BB); |
| 1499 | llvm::erase_if(ParentL->getBlocksVector(), |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 1500 | [&](BasicBlock *BB) { return DeadBlockSet.count(BB); }); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1501 | } |
| 1502 | |
| 1503 | // Now delete the dead child loops. This raw delete will clear them |
| 1504 | // recursively. |
| 1505 | llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) { |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 1506 | if (!DeadBlockSet.count(ChildL->getHeader())) |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1507 | return false; |
| 1508 | |
| 1509 | assert(llvm::all_of(ChildL->blocks(), |
| 1510 | [&](BasicBlock *ChildBB) { |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 1511 | return DeadBlockSet.count(ChildBB); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1512 | }) && |
| 1513 | "If the child loop header is dead all blocks in the child loop must " |
| 1514 | "be dead as well!"); |
| 1515 | LI.destroy(ChildL); |
| 1516 | return true; |
| 1517 | }); |
| 1518 | |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 1519 | // Remove the loop mappings for the dead blocks and drop all the references |
| 1520 | // from these blocks to others to handle cyclic references as we start |
| 1521 | // deleting the blocks themselves. |
Fedor Sergeev | 8b6effd | 2018-09-04 20:19:41 +0000 | [diff] [blame] | 1522 | for (auto *BB : DeadBlockSet) { |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 1523 | // Check that the dominator tree has already been updated. |
| 1524 | assert(!DT.getNode(BB) && "Should already have cleared domtree!"); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1525 | LI.changeLoopFor(BB, nullptr); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1526 | BB->dropAllReferences(); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1527 | } |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 1528 | |
| 1529 | // Actually delete the blocks now that they've been fully unhooked from the |
| 1530 | // IR. |
Fedor Sergeev | 7b49aa0 | 2018-08-29 19:10:44 +0000 | [diff] [blame] | 1531 | for (auto *BB : DeadBlockSet) |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 1532 | BB->eraseFromParent(); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1533 | } |
| 1534 | |
| 1535 | /// Recompute the set of blocks in a loop after unswitching. |
| 1536 | /// |
| 1537 | /// This walks from the original headers predecessors to rebuild the loop. We |
| 1538 | /// take advantage of the fact that new blocks can't have been added, and so we |
| 1539 | /// filter by the original loop's blocks. This also handles potentially |
| 1540 | /// unreachable code that we don't want to explore but might be found examining |
| 1541 | /// the predecessors of the header. |
| 1542 | /// |
| 1543 | /// If the original loop is no longer a loop, this will return an empty set. If |
| 1544 | /// it remains a loop, all the blocks within it will be added to the set |
| 1545 | /// (including those blocks in inner loops). |
| 1546 | static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L, |
| 1547 | LoopInfo &LI) { |
| 1548 | SmallPtrSet<const BasicBlock *, 16> LoopBlockSet; |
| 1549 | |
| 1550 | auto *PH = L.getLoopPreheader(); |
| 1551 | auto *Header = L.getHeader(); |
| 1552 | |
| 1553 | // A worklist to use while walking backwards from the header. |
| 1554 | SmallVector<BasicBlock *, 16> Worklist; |
| 1555 | |
| 1556 | // First walk the predecessors of the header to find the backedges. This will |
| 1557 | // form the basis of our walk. |
| 1558 | for (auto *Pred : predecessors(Header)) { |
| 1559 | // Skip the preheader. |
| 1560 | if (Pred == PH) |
| 1561 | continue; |
| 1562 | |
| 1563 | // Because the loop was in simplified form, the only non-loop predecessor |
| 1564 | // is the preheader. |
| 1565 | assert(L.contains(Pred) && "Found a predecessor of the loop header other " |
| 1566 | "than the preheader that is not part of the " |
| 1567 | "loop!"); |
| 1568 | |
| 1569 | // Insert this block into the loop set and on the first visit and, if it |
| 1570 | // isn't the header we're currently walking, put it into the worklist to |
| 1571 | // recurse through. |
| 1572 | if (LoopBlockSet.insert(Pred).second && Pred != Header) |
| 1573 | Worklist.push_back(Pred); |
| 1574 | } |
| 1575 | |
| 1576 | // If no backedges were found, we're done. |
| 1577 | if (LoopBlockSet.empty()) |
| 1578 | return LoopBlockSet; |
| 1579 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1580 | // We found backedges, recurse through them to identify the loop blocks. |
| 1581 | while (!Worklist.empty()) { |
| 1582 | BasicBlock *BB = Worklist.pop_back_val(); |
| 1583 | assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!"); |
| 1584 | |
Chandler Carruth | 43acdb3 | 2018-04-24 10:33:08 +0000 | [diff] [blame] | 1585 | // No need to walk past the header. |
| 1586 | if (BB == Header) |
| 1587 | continue; |
| 1588 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1589 | // Because we know the inner loop structure remains valid we can use the |
| 1590 | // loop structure to jump immediately across the entire nested loop. |
| 1591 | // Further, because it is in loop simplified form, we can directly jump |
| 1592 | // to its preheader afterward. |
| 1593 | if (Loop *InnerL = LI.getLoopFor(BB)) |
| 1594 | if (InnerL != &L) { |
| 1595 | assert(L.contains(InnerL) && |
| 1596 | "Should not reach a loop *outside* this loop!"); |
| 1597 | // The preheader is the only possible predecessor of the loop so |
| 1598 | // insert it into the set and check whether it was already handled. |
| 1599 | auto *InnerPH = InnerL->getLoopPreheader(); |
| 1600 | assert(L.contains(InnerPH) && "Cannot contain an inner loop block " |
| 1601 | "but not contain the inner loop " |
| 1602 | "preheader!"); |
| 1603 | if (!LoopBlockSet.insert(InnerPH).second) |
| 1604 | // The only way to reach the preheader is through the loop body |
| 1605 | // itself so if it has been visited the loop is already handled. |
| 1606 | continue; |
| 1607 | |
| 1608 | // Insert all of the blocks (other than those already present) into |
Chandler Carruth | bf7190a | 2018-04-23 06:58:36 +0000 | [diff] [blame] | 1609 | // the loop set. We expect at least the block that led us to find the |
| 1610 | // inner loop to be in the block set, but we may also have other loop |
| 1611 | // blocks if they were already enqueued as predecessors of some other |
| 1612 | // outer loop block. |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1613 | for (auto *InnerBB : InnerL->blocks()) { |
| 1614 | if (InnerBB == BB) { |
| 1615 | assert(LoopBlockSet.count(InnerBB) && |
| 1616 | "Block should already be in the set!"); |
| 1617 | continue; |
| 1618 | } |
| 1619 | |
Chandler Carruth | bf7190a | 2018-04-23 06:58:36 +0000 | [diff] [blame] | 1620 | LoopBlockSet.insert(InnerBB); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1621 | } |
| 1622 | |
| 1623 | // Add the preheader to the worklist so we will continue past the |
| 1624 | // loop body. |
| 1625 | Worklist.push_back(InnerPH); |
| 1626 | continue; |
| 1627 | } |
| 1628 | |
| 1629 | // Insert any predecessors that were in the original loop into the new |
| 1630 | // set, and if the insert is successful, add them to the worklist. |
| 1631 | for (auto *Pred : predecessors(BB)) |
| 1632 | if (L.contains(Pred) && LoopBlockSet.insert(Pred).second) |
| 1633 | Worklist.push_back(Pred); |
| 1634 | } |
| 1635 | |
Chandler Carruth | 43acdb3 | 2018-04-24 10:33:08 +0000 | [diff] [blame] | 1636 | assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!"); |
| 1637 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1638 | // We've found all the blocks participating in the loop, return our completed |
| 1639 | // set. |
| 1640 | return LoopBlockSet; |
| 1641 | } |
| 1642 | |
| 1643 | /// Rebuild a loop after unswitching removes some subset of blocks and edges. |
| 1644 | /// |
| 1645 | /// The removal may have removed some child loops entirely but cannot have |
| 1646 | /// disturbed any remaining child loops. However, they may need to be hoisted |
| 1647 | /// to the parent loop (or to be top-level loops). The original loop may be |
| 1648 | /// completely removed. |
| 1649 | /// |
| 1650 | /// The sibling loops resulting from this update are returned. If the original |
| 1651 | /// loop remains a valid loop, it will be the first entry in this list with all |
| 1652 | /// of the newly sibling loops following it. |
| 1653 | /// |
| 1654 | /// Returns true if the loop remains a loop after unswitching, and false if it |
| 1655 | /// is no longer a loop after unswitching (and should not continue to be |
| 1656 | /// referenced). |
| 1657 | static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks, |
| 1658 | LoopInfo &LI, |
| 1659 | SmallVectorImpl<Loop *> &HoistedLoops) { |
| 1660 | auto *PH = L.getLoopPreheader(); |
| 1661 | |
| 1662 | // Compute the actual parent loop from the exit blocks. Because we may have |
| 1663 | // pruned some exits the loop may be different from the original parent. |
| 1664 | Loop *ParentL = nullptr; |
| 1665 | SmallVector<Loop *, 4> ExitLoops; |
| 1666 | SmallVector<BasicBlock *, 4> ExitsInLoops; |
| 1667 | ExitsInLoops.reserve(ExitBlocks.size()); |
| 1668 | for (auto *ExitBB : ExitBlocks) |
| 1669 | if (Loop *ExitL = LI.getLoopFor(ExitBB)) { |
| 1670 | ExitLoops.push_back(ExitL); |
| 1671 | ExitsInLoops.push_back(ExitBB); |
| 1672 | if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL))) |
| 1673 | ParentL = ExitL; |
| 1674 | } |
| 1675 | |
| 1676 | // Recompute the blocks participating in this loop. This may be empty if it |
| 1677 | // is no longer a loop. |
| 1678 | auto LoopBlockSet = recomputeLoopBlockSet(L, LI); |
| 1679 | |
| 1680 | // If we still have a loop, we need to re-set the loop's parent as the exit |
| 1681 | // block set changing may have moved it within the loop nest. Note that this |
| 1682 | // can only happen when this loop has a parent as it can only hoist the loop |
| 1683 | // *up* the nest. |
| 1684 | if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) { |
| 1685 | // Remove this loop's (original) blocks from all of the intervening loops. |
| 1686 | for (Loop *IL = L.getParentLoop(); IL != ParentL; |
| 1687 | IL = IL->getParentLoop()) { |
| 1688 | IL->getBlocksSet().erase(PH); |
| 1689 | for (auto *BB : L.blocks()) |
| 1690 | IL->getBlocksSet().erase(BB); |
| 1691 | llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) { |
| 1692 | return BB == PH || L.contains(BB); |
| 1693 | }); |
| 1694 | } |
| 1695 | |
| 1696 | LI.changeLoopFor(PH, ParentL); |
| 1697 | L.getParentLoop()->removeChildLoop(&L); |
| 1698 | if (ParentL) |
| 1699 | ParentL->addChildLoop(&L); |
| 1700 | else |
| 1701 | LI.addTopLevelLoop(&L); |
| 1702 | } |
| 1703 | |
| 1704 | // Now we update all the blocks which are no longer within the loop. |
| 1705 | auto &Blocks = L.getBlocksVector(); |
| 1706 | auto BlocksSplitI = |
| 1707 | LoopBlockSet.empty() |
| 1708 | ? Blocks.begin() |
| 1709 | : std::stable_partition( |
| 1710 | Blocks.begin(), Blocks.end(), |
| 1711 | [&](BasicBlock *BB) { return LoopBlockSet.count(BB); }); |
| 1712 | |
| 1713 | // Before we erase the list of unlooped blocks, build a set of them. |
| 1714 | SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end()); |
| 1715 | if (LoopBlockSet.empty()) |
| 1716 | UnloopedBlocks.insert(PH); |
| 1717 | |
| 1718 | // Now erase these blocks from the loop. |
| 1719 | for (auto *BB : make_range(BlocksSplitI, Blocks.end())) |
| 1720 | L.getBlocksSet().erase(BB); |
| 1721 | Blocks.erase(BlocksSplitI, Blocks.end()); |
| 1722 | |
| 1723 | // Sort the exits in ascending loop depth, we'll work backwards across these |
| 1724 | // to process them inside out. |
Fangrui Song | efd94c5 | 2019-04-23 14:51:27 +0000 | [diff] [blame] | 1725 | llvm::stable_sort(ExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) { |
| 1726 | return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS); |
| 1727 | }); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1728 | |
| 1729 | // We'll build up a set for each exit loop. |
| 1730 | SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks; |
| 1731 | Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop. |
| 1732 | |
| 1733 | auto RemoveUnloopedBlocksFromLoop = |
| 1734 | [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) { |
| 1735 | for (auto *BB : UnloopedBlocks) |
| 1736 | L.getBlocksSet().erase(BB); |
| 1737 | llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) { |
| 1738 | return UnloopedBlocks.count(BB); |
| 1739 | }); |
| 1740 | }; |
| 1741 | |
| 1742 | SmallVector<BasicBlock *, 16> Worklist; |
| 1743 | while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) { |
| 1744 | assert(Worklist.empty() && "Didn't clear worklist!"); |
| 1745 | assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!"); |
| 1746 | |
| 1747 | // Grab the next exit block, in decreasing loop depth order. |
| 1748 | BasicBlock *ExitBB = ExitsInLoops.pop_back_val(); |
| 1749 | Loop &ExitL = *LI.getLoopFor(ExitBB); |
| 1750 | assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!"); |
| 1751 | |
| 1752 | // Erase all of the unlooped blocks from the loops between the previous |
| 1753 | // exit loop and this exit loop. This works because the ExitInLoops list is |
| 1754 | // sorted in increasing order of loop depth and thus we visit loops in |
| 1755 | // decreasing order of loop depth. |
| 1756 | for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop()) |
| 1757 | RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks); |
| 1758 | |
| 1759 | // Walk the CFG back until we hit the cloned PH adding everything reachable |
| 1760 | // and in the unlooped set to this exit block's loop. |
| 1761 | Worklist.push_back(ExitBB); |
| 1762 | do { |
| 1763 | BasicBlock *BB = Worklist.pop_back_val(); |
| 1764 | // We can stop recursing at the cloned preheader (if we get there). |
| 1765 | if (BB == PH) |
| 1766 | continue; |
| 1767 | |
| 1768 | for (BasicBlock *PredBB : predecessors(BB)) { |
| 1769 | // If this pred has already been moved to our set or is part of some |
| 1770 | // (inner) loop, no update needed. |
| 1771 | if (!UnloopedBlocks.erase(PredBB)) { |
| 1772 | assert((NewExitLoopBlocks.count(PredBB) || |
| 1773 | ExitL.contains(LI.getLoopFor(PredBB))) && |
| 1774 | "Predecessor not in a nested loop (or already visited)!"); |
| 1775 | continue; |
| 1776 | } |
| 1777 | |
| 1778 | // We just insert into the loop set here. We'll add these blocks to the |
| 1779 | // exit loop after we build up the set in a deterministic order rather |
| 1780 | // than the predecessor-influenced visit order. |
| 1781 | bool Inserted = NewExitLoopBlocks.insert(PredBB).second; |
| 1782 | (void)Inserted; |
| 1783 | assert(Inserted && "Should only visit an unlooped block once!"); |
| 1784 | |
| 1785 | // And recurse through to its predecessors. |
| 1786 | Worklist.push_back(PredBB); |
| 1787 | } |
| 1788 | } while (!Worklist.empty()); |
| 1789 | |
| 1790 | // If blocks in this exit loop were directly part of the original loop (as |
| 1791 | // opposed to a child loop) update the map to point to this exit loop. This |
| 1792 | // just updates a map and so the fact that the order is unstable is fine. |
| 1793 | for (auto *BB : NewExitLoopBlocks) |
| 1794 | if (Loop *BBL = LI.getLoopFor(BB)) |
| 1795 | if (BBL == &L || !L.contains(BBL)) |
| 1796 | LI.changeLoopFor(BB, &ExitL); |
| 1797 | |
| 1798 | // We will remove the remaining unlooped blocks from this loop in the next |
| 1799 | // iteration or below. |
| 1800 | NewExitLoopBlocks.clear(); |
| 1801 | } |
| 1802 | |
| 1803 | // Any remaining unlooped blocks are no longer part of any loop unless they |
| 1804 | // are part of some child loop. |
| 1805 | for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop()) |
| 1806 | RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks); |
| 1807 | for (auto *BB : UnloopedBlocks) |
| 1808 | if (Loop *BBL = LI.getLoopFor(BB)) |
| 1809 | if (BBL == &L || !L.contains(BBL)) |
| 1810 | LI.changeLoopFor(BB, nullptr); |
| 1811 | |
| 1812 | // Sink all the child loops whose headers are no longer in the loop set to |
| 1813 | // the parent (or to be top level loops). We reach into the loop and directly |
| 1814 | // update its subloop vector to make this batch update efficient. |
| 1815 | auto &SubLoops = L.getSubLoopsVector(); |
| 1816 | auto SubLoopsSplitI = |
| 1817 | LoopBlockSet.empty() |
| 1818 | ? SubLoops.begin() |
| 1819 | : std::stable_partition( |
| 1820 | SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) { |
| 1821 | return LoopBlockSet.count(SubL->getHeader()); |
| 1822 | }); |
| 1823 | for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) { |
| 1824 | HoistedLoops.push_back(HoistedL); |
| 1825 | HoistedL->setParentLoop(nullptr); |
| 1826 | |
| 1827 | // To compute the new parent of this hoisted loop we look at where we |
| 1828 | // placed the preheader above. We can't lookup the header itself because we |
| 1829 | // retained the mapping from the header to the hoisted loop. But the |
| 1830 | // preheader and header should have the exact same new parent computed |
| 1831 | // based on the set of exit blocks from the original loop as the preheader |
| 1832 | // is a predecessor of the header and so reached in the reverse walk. And |
| 1833 | // because the loops were all in simplified form the preheader of the |
| 1834 | // hoisted loop can't be part of some *other* loop. |
| 1835 | if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader())) |
| 1836 | NewParentL->addChildLoop(HoistedL); |
| 1837 | else |
| 1838 | LI.addTopLevelLoop(HoistedL); |
| 1839 | } |
| 1840 | SubLoops.erase(SubLoopsSplitI, SubLoops.end()); |
| 1841 | |
| 1842 | // Actually delete the loop if nothing remained within it. |
| 1843 | if (Blocks.empty()) { |
| 1844 | assert(SubLoops.empty() && |
| 1845 | "Failed to remove all subloops from the original loop!"); |
| 1846 | if (Loop *ParentL = L.getParentLoop()) |
| 1847 | ParentL->removeChildLoop(llvm::find(*ParentL, &L)); |
| 1848 | else |
| 1849 | LI.removeLoop(llvm::find(LI, &L)); |
| 1850 | LI.destroy(&L); |
| 1851 | return false; |
| 1852 | } |
| 1853 | |
| 1854 | return true; |
| 1855 | } |
| 1856 | |
| 1857 | /// Helper to visit a dominator subtree, invoking a callable on each node. |
| 1858 | /// |
| 1859 | /// Returning false at any point will stop walking past that node of the tree. |
| 1860 | template <typename CallableT> |
| 1861 | void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) { |
| 1862 | SmallVector<DomTreeNode *, 4> DomWorklist; |
| 1863 | DomWorklist.push_back(DT[BB]); |
| 1864 | #ifndef NDEBUG |
| 1865 | SmallPtrSet<DomTreeNode *, 4> Visited; |
| 1866 | Visited.insert(DT[BB]); |
| 1867 | #endif |
| 1868 | do { |
| 1869 | DomTreeNode *N = DomWorklist.pop_back_val(); |
| 1870 | |
| 1871 | // Visit this node. |
| 1872 | if (!Callable(N->getBlock())) |
| 1873 | continue; |
| 1874 | |
| 1875 | // Accumulate the child nodes. |
| 1876 | for (DomTreeNode *ChildN : *N) { |
| 1877 | assert(Visited.insert(ChildN).second && |
| 1878 | "Cannot visit a node twice when walking a tree!"); |
| 1879 | DomWorklist.push_back(ChildN); |
| 1880 | } |
| 1881 | } while (!DomWorklist.empty()); |
| 1882 | } |
| 1883 | |
Max Kazantsev | bde3100 | 2018-10-26 09:52:58 +0000 | [diff] [blame] | 1884 | static void unswitchNontrivialInvariants( |
Chandler Carruth | 60b2e05 | 2018-10-18 00:40:26 +0000 | [diff] [blame] | 1885 | Loop &L, Instruction &TI, ArrayRef<Value *> Invariants, |
Max Kazantsev | bde3100 | 2018-10-26 09:52:58 +0000 | [diff] [blame] | 1886 | SmallVectorImpl<BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI, |
| 1887 | AssumptionCache &AC, function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB, |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 1888 | ScalarEvolution *SE, MemorySSAUpdater *MSSAU) { |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 1889 | auto *ParentBB = TI.getParent(); |
| 1890 | BranchInst *BI = dyn_cast<BranchInst>(&TI); |
| 1891 | SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI); |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 1892 | |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 1893 | // We can only unswitch switches, conditional branches with an invariant |
| 1894 | // condition, or combining invariant conditions with an instruction. |
| 1895 | assert((SI || BI->isConditional()) && |
| 1896 | "Can only unswitch switches and conditional branch!"); |
| 1897 | bool FullUnswitch = SI || BI->getCondition() == Invariants[0]; |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 1898 | if (FullUnswitch) |
| 1899 | assert(Invariants.size() == 1 && |
| 1900 | "Cannot have other invariants with full unswitching!"); |
| 1901 | else |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 1902 | assert(isa<Instruction>(BI->getCondition()) && |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 1903 | "Partial unswitching requires an instruction as the condition!"); |
| 1904 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 1905 | if (MSSAU && VerifyMemorySSA) |
| 1906 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
| 1907 | |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 1908 | // Constant and BBs tracking the cloned and continuing successor. When we are |
| 1909 | // unswitching the entire condition, this can just be trivially chosen to |
| 1910 | // unswitch towards `true`. However, when we are unswitching a set of |
| 1911 | // invariants combined with `and` or `or`, the combining operation determines |
| 1912 | // the best direction to unswitch: we want to unswitch the direction that will |
| 1913 | // collapse the branch. |
| 1914 | bool Direction = true; |
| 1915 | int ClonedSucc = 0; |
| 1916 | if (!FullUnswitch) { |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 1917 | if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) { |
| 1918 | assert(cast<Instruction>(BI->getCondition())->getOpcode() == |
| 1919 | Instruction::And && |
| 1920 | "Only `or` and `and` instructions can combine invariants being " |
| 1921 | "unswitched."); |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 1922 | Direction = false; |
| 1923 | ClonedSucc = 1; |
| 1924 | } |
| 1925 | } |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1926 | |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 1927 | BasicBlock *RetainedSuccBB = |
| 1928 | BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest(); |
| 1929 | SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs; |
| 1930 | if (BI) |
| 1931 | UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc)); |
| 1932 | else |
| 1933 | for (auto Case : SI->cases()) |
Chandler Carruth | ed29654 | 2018-07-09 10:30:48 +0000 | [diff] [blame] | 1934 | if (Case.getCaseSuccessor() != RetainedSuccBB) |
| 1935 | UnswitchedSuccBBs.insert(Case.getCaseSuccessor()); |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 1936 | |
| 1937 | assert(!UnswitchedSuccBBs.count(RetainedSuccBB) && |
| 1938 | "Should not unswitch the same successor we are retaining!"); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1939 | |
| 1940 | // The branch should be in this exact loop. Any inner loop's invariant branch |
| 1941 | // should be handled by unswitching that inner loop. The caller of this |
| 1942 | // routine should filter out any candidates that remain (but were skipped for |
| 1943 | // whatever reason). |
| 1944 | assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!"); |
| 1945 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1946 | // Compute the parent loop now before we start hacking on things. |
| 1947 | Loop *ParentL = L.getParentLoop(); |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 1948 | // Get blocks in RPO order for MSSA update, before changing the CFG. |
| 1949 | LoopBlocksRPO LBRPO(&L); |
| 1950 | if (MSSAU) |
| 1951 | LBRPO.perform(&LI); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1952 | |
| 1953 | // Compute the outer-most loop containing one of our exit blocks. This is the |
| 1954 | // furthest up our loopnest which can be mutated, which we will use below to |
| 1955 | // update things. |
| 1956 | Loop *OuterExitL = &L; |
| 1957 | for (auto *ExitBB : ExitBlocks) { |
| 1958 | Loop *NewOuterExitL = LI.getLoopFor(ExitBB); |
| 1959 | if (!NewOuterExitL) { |
| 1960 | // We exited the entire nest with this block, so we're done. |
| 1961 | OuterExitL = nullptr; |
| 1962 | break; |
| 1963 | } |
| 1964 | if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL)) |
| 1965 | OuterExitL = NewOuterExitL; |
| 1966 | } |
| 1967 | |
Chandler Carruth | 3897ded | 2018-07-03 09:13:27 +0000 | [diff] [blame] | 1968 | // At this point, we're definitely going to unswitch something so invalidate |
| 1969 | // any cached information in ScalarEvolution for the outer most loop |
| 1970 | // containing an exit block and all nested loops. |
| 1971 | if (SE) { |
| 1972 | if (OuterExitL) |
| 1973 | SE->forgetLoop(OuterExitL); |
| 1974 | else |
| 1975 | SE->forgetTopmostLoop(&L); |
| 1976 | } |
| 1977 | |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 1978 | // If the edge from this terminator to a successor dominates that successor, |
| 1979 | // store a map from each block in its dominator subtree to it. This lets us |
| 1980 | // tell when cloning for a particular successor if a block is dominated by |
| 1981 | // some *other* successor with a single data structure. We use this to |
| 1982 | // significantly reduce cloning. |
| 1983 | SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc; |
| 1984 | for (auto *SuccBB : llvm::concat<BasicBlock *const>( |
| 1985 | makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs)) |
| 1986 | if (SuccBB->getUniquePredecessor() || |
| 1987 | llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) { |
| 1988 | return PredBB == ParentBB || DT.dominates(SuccBB, PredBB); |
| 1989 | })) |
| 1990 | visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) { |
| 1991 | DominatingSucc[BB] = SuccBB; |
| 1992 | return true; |
| 1993 | }); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 1994 | |
| 1995 | // Split the preheader, so that we know that there is a safe place to insert |
| 1996 | // the conditional branch. We will change the preheader to have a conditional |
| 1997 | // branch on LoopCond. The original preheader will become the split point |
| 1998 | // between the unswitched versions, and we will have a new preheader for the |
| 1999 | // original loop. |
| 2000 | BasicBlock *SplitBB = L.getLoopPreheader(); |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2001 | BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2002 | |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 2003 | // Keep track of the dominator tree updates needed. |
| 2004 | SmallVector<DominatorTree::UpdateType, 4> DTUpdates; |
| 2005 | |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2006 | // Clone the loop for each unswitched successor. |
| 2007 | SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps; |
| 2008 | VMaps.reserve(UnswitchedSuccBBs.size()); |
| 2009 | SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs; |
| 2010 | for (auto *SuccBB : UnswitchedSuccBBs) { |
| 2011 | VMaps.emplace_back(new ValueToValueMapTy()); |
| 2012 | ClonedPHs[SuccBB] = buildClonedLoopBlocks( |
| 2013 | L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB, |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2014 | DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU); |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2015 | } |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2016 | |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2017 | // The stitching of the branched code back together depends on whether we're |
| 2018 | // doing full unswitching or not with the exception that we always want to |
| 2019 | // nuke the initial terminator placed in the split block. |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2020 | SplitBB->getTerminator()->eraseFromParent(); |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2021 | if (FullUnswitch) { |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2022 | // Splice the terminator from the original loop and rewrite its |
| 2023 | // successors. |
| 2024 | SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI); |
| 2025 | |
| 2026 | // Keep a clone of the terminator for MSSA updates. |
| 2027 | Instruction *NewTI = TI.clone(); |
| 2028 | ParentBB->getInstList().push_back(NewTI); |
| 2029 | |
| 2030 | // First wire up the moved terminator to the preheaders. |
| 2031 | if (BI) { |
| 2032 | BasicBlock *ClonedPH = ClonedPHs.begin()->second; |
| 2033 | BI->setSuccessor(ClonedSucc, ClonedPH); |
| 2034 | BI->setSuccessor(1 - ClonedSucc, LoopPH); |
| 2035 | DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH}); |
| 2036 | } else { |
| 2037 | assert(SI && "Must either be a branch or switch!"); |
| 2038 | |
| 2039 | // Walk the cases and directly update their successors. |
| 2040 | assert(SI->getDefaultDest() == RetainedSuccBB && |
| 2041 | "Not retaining default successor!"); |
| 2042 | SI->setDefaultDest(LoopPH); |
| 2043 | for (auto &Case : SI->cases()) |
| 2044 | if (Case.getCaseSuccessor() == RetainedSuccBB) |
| 2045 | Case.setSuccessor(LoopPH); |
| 2046 | else |
| 2047 | Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second); |
| 2048 | |
| 2049 | // We need to use the set to populate domtree updates as even when there |
| 2050 | // are multiple cases pointing at the same successor we only want to |
| 2051 | // remove and insert one edge in the domtree. |
| 2052 | for (BasicBlock *SuccBB : UnswitchedSuccBBs) |
| 2053 | DTUpdates.push_back( |
| 2054 | {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second}); |
| 2055 | } |
| 2056 | |
| 2057 | if (MSSAU) { |
| 2058 | DT.applyUpdates(DTUpdates); |
| 2059 | DTUpdates.clear(); |
| 2060 | |
| 2061 | // Remove all but one edge to the retained block and all unswitched |
| 2062 | // blocks. This is to avoid having duplicate entries in the cloned Phis, |
| 2063 | // when we know we only keep a single edge for each case. |
| 2064 | MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB); |
| 2065 | for (BasicBlock *SuccBB : UnswitchedSuccBBs) |
| 2066 | MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB); |
| 2067 | |
| 2068 | for (auto &VMap : VMaps) |
| 2069 | MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap, |
| 2070 | /*IgnoreIncomingWithNoClones=*/true); |
| 2071 | MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT); |
| 2072 | |
| 2073 | // Remove all edges to unswitched blocks. |
| 2074 | for (BasicBlock *SuccBB : UnswitchedSuccBBs) |
| 2075 | MSSAU->removeEdge(ParentBB, SuccBB); |
| 2076 | } |
| 2077 | |
| 2078 | // Now unhook the successor relationship as we'll be replacing |
Chandler Carruth | ed29654 | 2018-07-09 10:30:48 +0000 | [diff] [blame] | 2079 | // the terminator with a direct branch. This is much simpler for branches |
| 2080 | // than switches so we handle those first. |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2081 | if (BI) { |
Chandler Carruth | ed29654 | 2018-07-09 10:30:48 +0000 | [diff] [blame] | 2082 | // Remove the parent as a predecessor of the unswitched successor. |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2083 | assert(UnswitchedSuccBBs.size() == 1 && |
| 2084 | "Only one possible unswitched block for a branch!"); |
Chandler Carruth | ed29654 | 2018-07-09 10:30:48 +0000 | [diff] [blame] | 2085 | BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin(); |
| 2086 | UnswitchedSuccBB->removePredecessor(ParentBB, |
Max Kazantsev | 20b9189 | 2019-02-12 07:09:29 +0000 | [diff] [blame] | 2087 | /*KeepOneInputPHIs*/ true); |
Chandler Carruth | ed29654 | 2018-07-09 10:30:48 +0000 | [diff] [blame] | 2088 | DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB}); |
| 2089 | } else { |
| 2090 | // Note that we actually want to remove the parent block as a predecessor |
| 2091 | // of *every* case successor. The case successor is either unswitched, |
| 2092 | // completely eliminating an edge from the parent to that successor, or it |
| 2093 | // is a duplicate edge to the retained successor as the retained successor |
| 2094 | // is always the default successor and as we'll replace this with a direct |
| 2095 | // branch we no longer need the duplicate entries in the PHI nodes. |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2096 | SwitchInst *NewSI = cast<SwitchInst>(NewTI); |
| 2097 | assert(NewSI->getDefaultDest() == RetainedSuccBB && |
Chandler Carruth | ed29654 | 2018-07-09 10:30:48 +0000 | [diff] [blame] | 2098 | "Not retaining default successor!"); |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2099 | for (auto &Case : NewSI->cases()) |
Chandler Carruth | ed29654 | 2018-07-09 10:30:48 +0000 | [diff] [blame] | 2100 | Case.getCaseSuccessor()->removePredecessor( |
| 2101 | ParentBB, |
Max Kazantsev | 20b9189 | 2019-02-12 07:09:29 +0000 | [diff] [blame] | 2102 | /*KeepOneInputPHIs*/ true); |
Chandler Carruth | ed29654 | 2018-07-09 10:30:48 +0000 | [diff] [blame] | 2103 | |
| 2104 | // We need to use the set to populate domtree updates as even when there |
| 2105 | // are multiple cases pointing at the same successor we only want to |
| 2106 | // remove and insert one edge in the domtree. |
| 2107 | for (BasicBlock *SuccBB : UnswitchedSuccBBs) |
| 2108 | DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB}); |
| 2109 | } |
| 2110 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2111 | // After MSSAU update, remove the cloned terminator instruction NewTI. |
| 2112 | ParentBB->getTerminator()->eraseFromParent(); |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2113 | |
| 2114 | // Create a new unconditional branch to the continuing block (as opposed to |
| 2115 | // the one cloned). |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2116 | BranchInst::Create(RetainedSuccBB, ParentBB); |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2117 | } else { |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2118 | assert(BI && "Only branches have partial unswitching."); |
| 2119 | assert(UnswitchedSuccBBs.size() == 1 && |
| 2120 | "Only one possible unswitched block for a branch!"); |
| 2121 | BasicBlock *ClonedPH = ClonedPHs.begin()->second; |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2122 | // When doing a partial unswitch, we have to do a bit more work to build up |
| 2123 | // the branch in the split block. |
| 2124 | buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction, |
| 2125 | *ClonedPH, *LoopPH); |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2126 | DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH}); |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2127 | } |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2128 | |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2129 | // Apply the updates accumulated above to get an up-to-date dominator tree. |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 2130 | DT.applyUpdates(DTUpdates); |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2131 | if (!FullUnswitch && MSSAU) { |
| 2132 | // Update MSSA for partial unswitch, after DT update. |
| 2133 | SmallVector<CFGUpdate, 1> Updates; |
| 2134 | Updates.push_back( |
| 2135 | {cfg::UpdateKind::Insert, SplitBB, ClonedPHs.begin()->second}); |
| 2136 | MSSAU->applyInsertUpdates(Updates, DT); |
| 2137 | } |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 2138 | |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2139 | // Now that we have an accurate dominator tree, first delete the dead cloned |
| 2140 | // blocks so that we can accurately build any cloned loops. It is important to |
| 2141 | // not delete the blocks from the original loop yet because we still want to |
| 2142 | // reference the original loop to understand the cloned loop's structure. |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2143 | deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU); |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2144 | |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 2145 | // Build the cloned loop structure itself. This may be substantially |
| 2146 | // different from the original structure due to the simplified CFG. This also |
| 2147 | // handles inserting all the cloned blocks into the correct loops. |
| 2148 | SmallVector<Loop *, 4> NonChildClonedLoops; |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2149 | for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps) |
| 2150 | buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops); |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 2151 | |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2152 | // Now that our cloned loops have been built, we can update the original loop. |
| 2153 | // First we delete the dead blocks from it and then we rebuild the loop |
| 2154 | // structure taking these deletions into account. |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2155 | deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU); |
| 2156 | |
| 2157 | if (MSSAU && VerifyMemorySSA) |
| 2158 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
| 2159 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2160 | SmallVector<Loop *, 4> HoistedLoops; |
| 2161 | bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops); |
| 2162 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2163 | if (MSSAU && VerifyMemorySSA) |
| 2164 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
| 2165 | |
Chandler Carruth | 69e68f8 | 2018-04-25 00:18:07 +0000 | [diff] [blame] | 2166 | // This transformation has a high risk of corrupting the dominator tree, and |
| 2167 | // the below steps to rebuild loop structures will result in hard to debug |
| 2168 | // errors in that case so verify that the dominator tree is sane first. |
| 2169 | // FIXME: Remove this when the bugs stop showing up and rely on existing |
| 2170 | // verification steps. |
| 2171 | assert(DT.verify(DominatorTree::VerificationLevel::Fast)); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2172 | |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2173 | if (BI) { |
| 2174 | // If we unswitched a branch which collapses the condition to a known |
| 2175 | // constant we want to replace all the uses of the invariants within both |
| 2176 | // the original and cloned blocks. We do this here so that we can use the |
| 2177 | // now updated dominator tree to identify which side the users are on. |
| 2178 | assert(UnswitchedSuccBBs.size() == 1 && |
| 2179 | "Only one possible unswitched block for a branch!"); |
| 2180 | BasicBlock *ClonedPH = ClonedPHs.begin()->second; |
Fedor Sergeev | f9a02a7 | 2018-11-07 20:05:11 +0000 | [diff] [blame] | 2181 | |
| 2182 | // When considering multiple partially-unswitched invariants |
| 2183 | // we cant just go replace them with constants in both branches. |
| 2184 | // |
| 2185 | // For 'AND' we infer that true branch ("continue") means true |
| 2186 | // for each invariant operand. |
| 2187 | // For 'OR' we can infer that false branch ("continue") means false |
| 2188 | // for each invariant operand. |
| 2189 | // So it happens that for multiple-partial case we dont replace |
| 2190 | // in the unswitched branch. |
| 2191 | bool ReplaceUnswitched = FullUnswitch || (Invariants.size() == 1); |
| 2192 | |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2193 | ConstantInt *UnswitchedReplacement = |
| 2194 | Direction ? ConstantInt::getTrue(BI->getContext()) |
| 2195 | : ConstantInt::getFalse(BI->getContext()); |
| 2196 | ConstantInt *ContinueReplacement = |
| 2197 | Direction ? ConstantInt::getFalse(BI->getContext()) |
| 2198 | : ConstantInt::getTrue(BI->getContext()); |
| 2199 | for (Value *Invariant : Invariants) |
| 2200 | for (auto UI = Invariant->use_begin(), UE = Invariant->use_end(); |
| 2201 | UI != UE;) { |
| 2202 | // Grab the use and walk past it so we can clobber it in the use list. |
| 2203 | Use *U = &*UI++; |
| 2204 | Instruction *UserI = dyn_cast<Instruction>(U->getUser()); |
| 2205 | if (!UserI) |
| 2206 | continue; |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2207 | |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2208 | // Replace it with the 'continue' side if in the main loop body, and the |
| 2209 | // unswitched if in the cloned blocks. |
| 2210 | if (DT.dominates(LoopPH, UserI->getParent())) |
| 2211 | U->set(ContinueReplacement); |
Fedor Sergeev | f9a02a7 | 2018-11-07 20:05:11 +0000 | [diff] [blame] | 2212 | else if (ReplaceUnswitched && |
| 2213 | DT.dominates(ClonedPH, UserI->getParent())) |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2214 | U->set(UnswitchedReplacement); |
| 2215 | } |
| 2216 | } |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2217 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2218 | // We can change which blocks are exit blocks of all the cloned sibling |
| 2219 | // loops, the current loop, and any parent loops which shared exit blocks |
| 2220 | // with the current loop. As a consequence, we need to re-form LCSSA for |
| 2221 | // them. But we shouldn't need to re-form LCSSA for any child loops. |
| 2222 | // FIXME: This could be made more efficient by tracking which exit blocks are |
| 2223 | // new, and focusing on them, but that isn't likely to be necessary. |
| 2224 | // |
| 2225 | // In order to reasonably rebuild LCSSA we need to walk inside-out across the |
| 2226 | // loop nest and update every loop that could have had its exits changed. We |
| 2227 | // also need to cover any intervening loops. We add all of these loops to |
| 2228 | // a list and sort them by loop depth to achieve this without updating |
| 2229 | // unnecessary loops. |
Chandler Carruth | 9281503 | 2018-06-02 01:29:01 +0000 | [diff] [blame] | 2230 | auto UpdateLoop = [&](Loop &UpdateL) { |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2231 | #ifndef NDEBUG |
Chandler Carruth | 43acdb3 | 2018-04-24 10:33:08 +0000 | [diff] [blame] | 2232 | UpdateL.verifyLoop(); |
| 2233 | for (Loop *ChildL : UpdateL) { |
| 2234 | ChildL->verifyLoop(); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2235 | assert(ChildL->isRecursivelyLCSSAForm(DT, LI) && |
| 2236 | "Perturbed a child loop's LCSSA form!"); |
Chandler Carruth | 43acdb3 | 2018-04-24 10:33:08 +0000 | [diff] [blame] | 2237 | } |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2238 | #endif |
Chandler Carruth | 9281503 | 2018-06-02 01:29:01 +0000 | [diff] [blame] | 2239 | // First build LCSSA for this loop so that we can preserve it when |
| 2240 | // forming dedicated exits. We don't want to perturb some other loop's |
| 2241 | // LCSSA while doing that CFG edit. |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2242 | formLCSSA(UpdateL, DT, &LI, nullptr); |
Chandler Carruth | 9281503 | 2018-06-02 01:29:01 +0000 | [diff] [blame] | 2243 | |
| 2244 | // For loops reached by this loop's original exit blocks we may |
| 2245 | // introduced new, non-dedicated exits. At least try to re-form dedicated |
| 2246 | // exits for these loops. This may fail if they couldn't have dedicated |
| 2247 | // exits to start with. |
Alina Sbirlea | 97468e9 | 2019-02-21 21:13:34 +0000 | [diff] [blame] | 2248 | formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2249 | }; |
| 2250 | |
| 2251 | // For non-child cloned loops and hoisted loops, we just need to update LCSSA |
| 2252 | // and we can do it in any order as they don't nest relative to each other. |
Chandler Carruth | 9281503 | 2018-06-02 01:29:01 +0000 | [diff] [blame] | 2253 | // |
| 2254 | // Also check if any of the loops we have updated have become top-level loops |
| 2255 | // as that will necessitate widening the outer loop scope. |
| 2256 | for (Loop *UpdatedL : |
| 2257 | llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) { |
| 2258 | UpdateLoop(*UpdatedL); |
| 2259 | if (!UpdatedL->getParentLoop()) |
| 2260 | OuterExitL = nullptr; |
| 2261 | } |
| 2262 | if (IsStillLoop) { |
| 2263 | UpdateLoop(L); |
| 2264 | if (!L.getParentLoop()) |
| 2265 | OuterExitL = nullptr; |
| 2266 | } |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2267 | |
| 2268 | // If the original loop had exit blocks, walk up through the outer most loop |
| 2269 | // of those exit blocks to update LCSSA and form updated dedicated exits. |
Chandler Carruth | 9281503 | 2018-06-02 01:29:01 +0000 | [diff] [blame] | 2270 | if (OuterExitL != &L) |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2271 | for (Loop *OuterL = ParentL; OuterL != OuterExitL; |
| 2272 | OuterL = OuterL->getParentLoop()) |
Chandler Carruth | 9281503 | 2018-06-02 01:29:01 +0000 | [diff] [blame] | 2273 | UpdateLoop(*OuterL); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2274 | |
| 2275 | #ifndef NDEBUG |
| 2276 | // Verify the entire loop structure to catch any incorrect updates before we |
| 2277 | // progress in the pass pipeline. |
| 2278 | LI.verify(DT); |
| 2279 | #endif |
| 2280 | |
| 2281 | // Now that we've unswitched something, make callbacks to report the changes. |
| 2282 | // For that we need to merge together the updated loops and the cloned loops |
| 2283 | // and check whether the original loop survived. |
| 2284 | SmallVector<Loop *, 4> SibLoops; |
| 2285 | for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) |
| 2286 | if (UpdatedL->getParentLoop() == ParentL) |
| 2287 | SibLoops.push_back(UpdatedL); |
Chandler Carruth | 71fd270 | 2018-05-30 02:46:45 +0000 | [diff] [blame] | 2288 | UnswitchCB(IsStillLoop, SibLoops); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2289 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2290 | if (MSSAU && VerifyMemorySSA) |
| 2291 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
| 2292 | |
Zaara Syeda | b7dff9c | 2019-01-15 15:08:01 +0000 | [diff] [blame] | 2293 | if (BI) |
| 2294 | ++NumBranches; |
| 2295 | else |
| 2296 | ++NumSwitches; |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2297 | } |
| 2298 | |
| 2299 | /// Recursively compute the cost of a dominator subtree based on the per-block |
| 2300 | /// cost map provided. |
| 2301 | /// |
| 2302 | /// The recursive computation is memozied into the provided DT-indexed cost map |
| 2303 | /// to allow querying it for most nodes in the domtree without it becoming |
| 2304 | /// quadratic. |
| 2305 | static int |
| 2306 | computeDomSubtreeCost(DomTreeNode &N, |
| 2307 | const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap, |
| 2308 | SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) { |
| 2309 | // Don't accumulate cost (or recurse through) blocks not in our block cost |
| 2310 | // map and thus not part of the duplication cost being considered. |
| 2311 | auto BBCostIt = BBCostMap.find(N.getBlock()); |
| 2312 | if (BBCostIt == BBCostMap.end()) |
| 2313 | return 0; |
| 2314 | |
| 2315 | // Lookup this node to see if we already computed its cost. |
| 2316 | auto DTCostIt = DTCostMap.find(&N); |
| 2317 | if (DTCostIt != DTCostMap.end()) |
| 2318 | return DTCostIt->second; |
| 2319 | |
| 2320 | // If not, we have to compute it. We can't use insert above and update |
| 2321 | // because computing the cost may insert more things into the map. |
| 2322 | int Cost = std::accumulate( |
| 2323 | N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) { |
| 2324 | return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap); |
| 2325 | }); |
| 2326 | bool Inserted = DTCostMap.insert({&N, Cost}).second; |
| 2327 | (void)Inserted; |
| 2328 | assert(Inserted && "Should not insert a node while visiting children!"); |
| 2329 | return Cost; |
| 2330 | } |
| 2331 | |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2332 | /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch, |
| 2333 | /// making the following replacement: |
| 2334 | /// |
Simon Pilgrim | a132016 | 2018-10-27 15:14:42 +0000 | [diff] [blame] | 2335 | /// --code before guard-- |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2336 | /// call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ] |
Simon Pilgrim | a132016 | 2018-10-27 15:14:42 +0000 | [diff] [blame] | 2337 | /// --code after guard-- |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2338 | /// |
| 2339 | /// into |
| 2340 | /// |
Simon Pilgrim | a132016 | 2018-10-27 15:14:42 +0000 | [diff] [blame] | 2341 | /// --code before guard-- |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2342 | /// br i1 %cond, label %guarded, label %deopt |
| 2343 | /// |
| 2344 | /// guarded: |
Simon Pilgrim | a132016 | 2018-10-27 15:14:42 +0000 | [diff] [blame] | 2345 | /// --code after guard-- |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2346 | /// |
| 2347 | /// deopt: |
| 2348 | /// call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ] |
| 2349 | /// unreachable |
| 2350 | /// |
| 2351 | /// It also makes all relevant DT and LI updates, so that all structures are in |
| 2352 | /// valid state after this transform. |
| 2353 | static BranchInst * |
| 2354 | turnGuardIntoBranch(IntrinsicInst *GI, Loop &L, |
| 2355 | SmallVectorImpl<BasicBlock *> &ExitBlocks, |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2356 | DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) { |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2357 | SmallVector<DominatorTree::UpdateType, 4> DTUpdates; |
| 2358 | LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n"); |
| 2359 | BasicBlock *CheckBB = GI->getParent(); |
| 2360 | |
Alina Sbirlea | 797935f | 2018-12-04 14:43:24 +0000 | [diff] [blame] | 2361 | if (MSSAU && VerifyMemorySSA) |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2362 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2363 | |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2364 | // Remove all CheckBB's successors from DomTree. A block can be seen among |
| 2365 | // successors more than once, but for DomTree it should be added only once. |
| 2366 | SmallPtrSet<BasicBlock *, 4> Successors; |
| 2367 | for (auto *Succ : successors(CheckBB)) |
| 2368 | if (Successors.insert(Succ).second) |
| 2369 | DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ}); |
| 2370 | |
| 2371 | Instruction *DeoptBlockTerm = |
| 2372 | SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true); |
| 2373 | BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator()); |
| 2374 | // SplitBlockAndInsertIfThen inserts control flow that branches to |
| 2375 | // DeoptBlockTerm if the condition is true. We want the opposite. |
| 2376 | CheckBI->swapSuccessors(); |
| 2377 | |
| 2378 | BasicBlock *GuardedBlock = CheckBI->getSuccessor(0); |
| 2379 | GuardedBlock->setName("guarded"); |
| 2380 | CheckBI->getSuccessor(1)->setName("deopt"); |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2381 | BasicBlock *DeoptBlock = CheckBI->getSuccessor(1); |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2382 | |
| 2383 | // We now have a new exit block. |
| 2384 | ExitBlocks.push_back(CheckBI->getSuccessor(1)); |
| 2385 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2386 | if (MSSAU) |
| 2387 | MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI); |
| 2388 | |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2389 | GI->moveBefore(DeoptBlockTerm); |
| 2390 | GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext())); |
| 2391 | |
| 2392 | // Add new successors of CheckBB into DomTree. |
| 2393 | for (auto *Succ : successors(CheckBB)) |
| 2394 | DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ}); |
| 2395 | |
| 2396 | // Now the blocks that used to be CheckBB's successors are GuardedBlock's |
| 2397 | // successors. |
| 2398 | for (auto *Succ : Successors) |
| 2399 | DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ}); |
| 2400 | |
| 2401 | // Make proper changes to DT. |
| 2402 | DT.applyUpdates(DTUpdates); |
| 2403 | // Inform LI of a new loop block. |
| 2404 | L.addBasicBlockToLoop(GuardedBlock, LI); |
| 2405 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2406 | if (MSSAU) { |
| 2407 | MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI)); |
| 2408 | MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::End); |
| 2409 | if (VerifyMemorySSA) |
| 2410 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
| 2411 | } |
| 2412 | |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2413 | ++NumGuards; |
| 2414 | return CheckBI; |
| 2415 | } |
| 2416 | |
Fedor Sergeev | 2e3e224 | 2018-11-16 21:16:43 +0000 | [diff] [blame] | 2417 | /// Cost multiplier is a way to limit potentially exponential behavior |
| 2418 | /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch |
| 2419 | /// candidates available. Also accounting for the number of "sibling" loops with |
| 2420 | /// the idea to account for previous unswitches that already happened on this |
| 2421 | /// cluster of loops. There was an attempt to keep this formula simple, |
| 2422 | /// just enough to limit the worst case behavior. Even if it is not that simple |
| 2423 | /// now it is still not an attempt to provide a detailed heuristic size |
| 2424 | /// prediction. |
| 2425 | /// |
| 2426 | /// TODO: Make a proper accounting of "explosion" effect for all kinds of |
| 2427 | /// unswitch candidates, making adequate predictions instead of wild guesses. |
| 2428 | /// That requires knowing not just the number of "remaining" candidates but |
| 2429 | /// also costs of unswitching for each of these candidates. |
| 2430 | static int calculateUnswitchCostMultiplier( |
| 2431 | Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT, |
| 2432 | ArrayRef<std::pair<Instruction *, TinyPtrVector<Value *>>> |
| 2433 | UnswitchCandidates) { |
| 2434 | |
| 2435 | // Guards and other exiting conditions do not contribute to exponential |
| 2436 | // explosion as soon as they dominate the latch (otherwise there might be |
| 2437 | // another path to the latch remaining that does not allow to eliminate the |
| 2438 | // loop copy on unswitch). |
| 2439 | BasicBlock *Latch = L.getLoopLatch(); |
| 2440 | BasicBlock *CondBlock = TI.getParent(); |
| 2441 | if (DT.dominates(CondBlock, Latch) && |
| 2442 | (isGuard(&TI) || |
| 2443 | llvm::count_if(successors(&TI), [&L](BasicBlock *SuccBB) { |
| 2444 | return L.contains(SuccBB); |
| 2445 | }) <= 1)) { |
| 2446 | NumCostMultiplierSkipped++; |
| 2447 | return 1; |
| 2448 | } |
| 2449 | |
| 2450 | auto *ParentL = L.getParentLoop(); |
| 2451 | int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size() |
| 2452 | : std::distance(LI.begin(), LI.end())); |
| 2453 | // Count amount of clones that all the candidates might cause during |
| 2454 | // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases. |
| 2455 | int UnswitchedClones = 0; |
| 2456 | for (auto Candidate : UnswitchCandidates) { |
| 2457 | Instruction *CI = Candidate.first; |
| 2458 | BasicBlock *CondBlock = CI->getParent(); |
| 2459 | bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch); |
| 2460 | if (isGuard(CI)) { |
| 2461 | if (!SkipExitingSuccessors) |
| 2462 | UnswitchedClones++; |
| 2463 | continue; |
| 2464 | } |
| 2465 | int NonExitingSuccessors = llvm::count_if( |
| 2466 | successors(CondBlock), [SkipExitingSuccessors, &L](BasicBlock *SuccBB) { |
| 2467 | return !SkipExitingSuccessors || L.contains(SuccBB); |
| 2468 | }); |
| 2469 | UnswitchedClones += Log2_32(NonExitingSuccessors); |
| 2470 | } |
| 2471 | |
| 2472 | // Ignore up to the "unscaled candidates" number of unswitch candidates |
| 2473 | // when calculating the power-of-two scaling of the cost. The main idea |
| 2474 | // with this control is to allow a small number of unswitches to happen |
| 2475 | // and rely more on siblings multiplier (see below) when the number |
| 2476 | // of candidates is small. |
| 2477 | unsigned ClonesPower = |
| 2478 | std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0); |
| 2479 | |
| 2480 | // Allowing top-level loops to spread a bit more than nested ones. |
| 2481 | int SiblingsMultiplier = |
| 2482 | std::max((ParentL ? SiblingsCount |
| 2483 | : SiblingsCount / (int)UnswitchSiblingsToplevelDiv), |
| 2484 | 1); |
| 2485 | // Compute the cost multiplier in a way that won't overflow by saturating |
| 2486 | // at an upper bound. |
| 2487 | int CostMultiplier; |
| 2488 | if (ClonesPower > Log2_32(UnswitchThreshold) || |
| 2489 | SiblingsMultiplier > UnswitchThreshold) |
| 2490 | CostMultiplier = UnswitchThreshold; |
| 2491 | else |
| 2492 | CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower), |
| 2493 | (int)UnswitchThreshold); |
| 2494 | |
| 2495 | LLVM_DEBUG(dbgs() << " Computed multiplier " << CostMultiplier |
| 2496 | << " (siblings " << SiblingsMultiplier << " * clones " |
| 2497 | << (1 << ClonesPower) << ")" |
| 2498 | << " for unswitch candidate: " << TI << "\n"); |
| 2499 | return CostMultiplier; |
| 2500 | } |
| 2501 | |
Chandler Carruth | 3897ded | 2018-07-03 09:13:27 +0000 | [diff] [blame] | 2502 | static bool |
| 2503 | unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI, |
| 2504 | AssumptionCache &AC, TargetTransformInfo &TTI, |
| 2505 | function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB, |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2506 | ScalarEvolution *SE, MemorySSAUpdater *MSSAU) { |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2507 | // Collect all invariant conditions within this loop (as opposed to an inner |
| 2508 | // loop which would be handled when visiting that inner loop). |
Chandler Carruth | 60b2e05 | 2018-10-18 00:40:26 +0000 | [diff] [blame] | 2509 | SmallVector<std::pair<Instruction *, TinyPtrVector<Value *>>, 4> |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2510 | UnswitchCandidates; |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2511 | |
| 2512 | // Whether or not we should also collect guards in the loop. |
| 2513 | bool CollectGuards = false; |
| 2514 | if (UnswitchGuards) { |
| 2515 | auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction( |
| 2516 | Intrinsic::getName(Intrinsic::experimental_guard)); |
| 2517 | if (GuardDecl && !GuardDecl->use_empty()) |
| 2518 | CollectGuards = true; |
| 2519 | } |
| 2520 | |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2521 | for (auto *BB : L.blocks()) { |
| 2522 | if (LI.getLoopFor(BB) != &L) |
| 2523 | continue; |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2524 | |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2525 | if (CollectGuards) |
| 2526 | for (auto &I : *BB) |
| 2527 | if (isGuard(&I)) { |
| 2528 | auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0); |
| 2529 | // TODO: Support AND, OR conditions and partial unswitching. |
| 2530 | if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond)) |
| 2531 | UnswitchCandidates.push_back({&I, {Cond}}); |
| 2532 | } |
| 2533 | |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2534 | if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { |
| 2535 | // We can only consider fully loop-invariant switch conditions as we need |
| 2536 | // to completely eliminate the switch after unswitching. |
| 2537 | if (!isa<Constant>(SI->getCondition()) && |
| 2538 | L.isLoopInvariant(SI->getCondition())) |
| 2539 | UnswitchCandidates.push_back({SI, {SI->getCondition()}}); |
| 2540 | continue; |
| 2541 | } |
| 2542 | |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2543 | auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2544 | if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) || |
| 2545 | BI->getSuccessor(0) == BI->getSuccessor(1)) |
| 2546 | continue; |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2547 | |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2548 | if (L.isLoopInvariant(BI->getCondition())) { |
| 2549 | UnswitchCandidates.push_back({BI, {BI->getCondition()}}); |
| 2550 | continue; |
| 2551 | } |
| 2552 | |
| 2553 | Instruction &CondI = *cast<Instruction>(BI->getCondition()); |
| 2554 | if (CondI.getOpcode() != Instruction::And && |
| 2555 | CondI.getOpcode() != Instruction::Or) |
| 2556 | continue; |
| 2557 | |
| 2558 | TinyPtrVector<Value *> Invariants = |
| 2559 | collectHomogenousInstGraphLoopInvariants(L, CondI, LI); |
| 2560 | if (Invariants.empty()) |
| 2561 | continue; |
| 2562 | |
| 2563 | UnswitchCandidates.push_back({BI, std::move(Invariants)}); |
Chandler Carruth | 71fd270 | 2018-05-30 02:46:45 +0000 | [diff] [blame] | 2564 | } |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2565 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2566 | // If we didn't find any candidates, we're done. |
| 2567 | if (UnswitchCandidates.empty()) |
Chandler Carruth | 71fd270 | 2018-05-30 02:46:45 +0000 | [diff] [blame] | 2568 | return false; |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2569 | |
Chandler Carruth | 32e62f9 | 2018-04-19 18:44:25 +0000 | [diff] [blame] | 2570 | // Check if there are irreducible CFG cycles in this loop. If so, we cannot |
| 2571 | // easily unswitch non-trivial edges out of the loop. Doing so might turn the |
| 2572 | // irreducible control flow into reducible control flow and introduce new |
| 2573 | // loops "out of thin air". If we ever discover important use cases for doing |
| 2574 | // this, we can add support to loop unswitch, but it is a lot of complexity |
Hiroshi Inoue | f209649 | 2018-06-14 05:41:49 +0000 | [diff] [blame] | 2575 | // for what seems little or no real world benefit. |
Chandler Carruth | 32e62f9 | 2018-04-19 18:44:25 +0000 | [diff] [blame] | 2576 | LoopBlocksRPO RPOT(&L); |
| 2577 | RPOT.perform(&LI); |
| 2578 | if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI)) |
Chandler Carruth | 71fd270 | 2018-05-30 02:46:45 +0000 | [diff] [blame] | 2579 | return false; |
Chandler Carruth | 32e62f9 | 2018-04-19 18:44:25 +0000 | [diff] [blame] | 2580 | |
Max Kazantsev | bde3100 | 2018-10-26 09:52:58 +0000 | [diff] [blame] | 2581 | SmallVector<BasicBlock *, 4> ExitBlocks; |
| 2582 | L.getUniqueExitBlocks(ExitBlocks); |
| 2583 | |
| 2584 | // We cannot unswitch if exit blocks contain a cleanuppad instruction as we |
| 2585 | // don't know how to split those exit blocks. |
| 2586 | // FIXME: We should teach SplitBlock to handle this and remove this |
| 2587 | // restriction. |
| 2588 | for (auto *ExitBB : ExitBlocks) |
| 2589 | if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI())) { |
| 2590 | dbgs() << "Cannot unswitch because of cleanuppad in exit block\n"; |
| 2591 | return false; |
| 2592 | } |
| 2593 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2594 | LLVM_DEBUG( |
| 2595 | dbgs() << "Considering " << UnswitchCandidates.size() |
| 2596 | << " non-trivial loop invariant conditions for unswitching.\n"); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2597 | |
| 2598 | // Given that unswitching these terminators will require duplicating parts of |
| 2599 | // the loop, so we need to be able to model that cost. Compute the ephemeral |
| 2600 | // values and set up a data structure to hold per-BB costs. We cache each |
| 2601 | // block's cost so that we don't recompute this when considering different |
| 2602 | // subsets of the loop for duplication during unswitching. |
| 2603 | SmallPtrSet<const Value *, 4> EphValues; |
| 2604 | CodeMetrics::collectEphemeralValues(&L, &AC, EphValues); |
| 2605 | SmallDenseMap<BasicBlock *, int, 4> BBCostMap; |
| 2606 | |
| 2607 | // Compute the cost of each block, as well as the total loop cost. Also, bail |
| 2608 | // out if we see instructions which are incompatible with loop unswitching |
| 2609 | // (convergent, noduplicate, or cross-basic-block tokens). |
| 2610 | // FIXME: We might be able to safely handle some of these in non-duplicated |
| 2611 | // regions. |
| 2612 | int LoopCost = 0; |
| 2613 | for (auto *BB : L.blocks()) { |
| 2614 | int Cost = 0; |
| 2615 | for (auto &I : *BB) { |
| 2616 | if (EphValues.count(&I)) |
| 2617 | continue; |
| 2618 | |
| 2619 | if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB)) |
Chandler Carruth | 71fd270 | 2018-05-30 02:46:45 +0000 | [diff] [blame] | 2620 | return false; |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2621 | if (auto CS = CallSite(&I)) |
| 2622 | if (CS.isConvergent() || CS.cannotDuplicate()) |
Chandler Carruth | 71fd270 | 2018-05-30 02:46:45 +0000 | [diff] [blame] | 2623 | return false; |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2624 | |
| 2625 | Cost += TTI.getUserCost(&I); |
| 2626 | } |
| 2627 | assert(Cost >= 0 && "Must not have negative costs!"); |
| 2628 | LoopCost += Cost; |
| 2629 | assert(LoopCost >= 0 && "Must not have negative loop costs!"); |
| 2630 | BBCostMap[BB] = Cost; |
| 2631 | } |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2632 | LLVM_DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n"); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2633 | |
| 2634 | // Now we find the best candidate by searching for the one with the following |
| 2635 | // properties in order: |
| 2636 | // |
| 2637 | // 1) An unswitching cost below the threshold |
| 2638 | // 2) The smallest number of duplicated unswitch candidates (to avoid |
| 2639 | // creating redundant subsequent unswitching) |
| 2640 | // 3) The smallest cost after unswitching. |
| 2641 | // |
| 2642 | // We prioritize reducing fanout of unswitch candidates provided the cost |
| 2643 | // remains below the threshold because this has a multiplicative effect. |
| 2644 | // |
| 2645 | // This requires memoizing each dominator subtree to avoid redundant work. |
| 2646 | // |
| 2647 | // FIXME: Need to actually do the number of candidates part above. |
| 2648 | SmallDenseMap<DomTreeNode *, int, 4> DTCostMap; |
| 2649 | // Given a terminator which might be unswitched, computes the non-duplicated |
| 2650 | // cost for that terminator. |
Chandler Carruth | 60b2e05 | 2018-10-18 00:40:26 +0000 | [diff] [blame] | 2651 | auto ComputeUnswitchedCost = [&](Instruction &TI, bool FullUnswitch) { |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2652 | BasicBlock &BB = *TI.getParent(); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2653 | SmallPtrSet<BasicBlock *, 4> Visited; |
| 2654 | |
| 2655 | int Cost = LoopCost; |
| 2656 | for (BasicBlock *SuccBB : successors(&BB)) { |
| 2657 | // Don't count successors more than once. |
| 2658 | if (!Visited.insert(SuccBB).second) |
| 2659 | continue; |
| 2660 | |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2661 | // If this is a partial unswitch candidate, then it must be a conditional |
| 2662 | // branch with a condition of either `or` or `and`. In that case, one of |
| 2663 | // the successors is necessarily duplicated, so don't even try to remove |
| 2664 | // its cost. |
| 2665 | if (!FullUnswitch) { |
| 2666 | auto &BI = cast<BranchInst>(TI); |
| 2667 | if (cast<Instruction>(BI.getCondition())->getOpcode() == |
| 2668 | Instruction::And) { |
| 2669 | if (SuccBB == BI.getSuccessor(1)) |
| 2670 | continue; |
| 2671 | } else { |
| 2672 | assert(cast<Instruction>(BI.getCondition())->getOpcode() == |
| 2673 | Instruction::Or && |
| 2674 | "Only `and` and `or` conditions can result in a partial " |
| 2675 | "unswitch!"); |
| 2676 | if (SuccBB == BI.getSuccessor(0)) |
| 2677 | continue; |
| 2678 | } |
| 2679 | } |
| 2680 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2681 | // This successor's domtree will not need to be duplicated after |
| 2682 | // unswitching if the edge to the successor dominates it (and thus the |
| 2683 | // entire tree). This essentially means there is no other path into this |
| 2684 | // subtree and so it will end up live in only one clone of the loop. |
| 2685 | if (SuccBB->getUniquePredecessor() || |
| 2686 | llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) { |
| 2687 | return PredBB == &BB || DT.dominates(SuccBB, PredBB); |
| 2688 | })) { |
| 2689 | Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap); |
| 2690 | assert(Cost >= 0 && |
| 2691 | "Non-duplicated cost should never exceed total loop cost!"); |
| 2692 | } |
| 2693 | } |
| 2694 | |
| 2695 | // Now scale the cost by the number of unique successors minus one. We |
| 2696 | // subtract one because there is already at least one copy of the entire |
| 2697 | // loop. This is computing the new cost of unswitching a condition. |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2698 | // Note that guards always have 2 unique successors that are implicit and |
| 2699 | // will be materialized if we decide to unswitch it. |
| 2700 | int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size(); |
| 2701 | assert(SuccessorsCount > 1 && |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2702 | "Cannot unswitch a condition without multiple distinct successors!"); |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2703 | return Cost * (SuccessorsCount - 1); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2704 | }; |
Chandler Carruth | 60b2e05 | 2018-10-18 00:40:26 +0000 | [diff] [blame] | 2705 | Instruction *BestUnswitchTI = nullptr; |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2706 | int BestUnswitchCost; |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2707 | ArrayRef<Value *> BestUnswitchInvariants; |
| 2708 | for (auto &TerminatorAndInvariants : UnswitchCandidates) { |
Chandler Carruth | 60b2e05 | 2018-10-18 00:40:26 +0000 | [diff] [blame] | 2709 | Instruction &TI = *TerminatorAndInvariants.first; |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2710 | ArrayRef<Value *> Invariants = TerminatorAndInvariants.second; |
| 2711 | BranchInst *BI = dyn_cast<BranchInst>(&TI); |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2712 | int CandidateCost = ComputeUnswitchedCost( |
| 2713 | TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 && |
| 2714 | Invariants[0] == BI->getCondition())); |
Fedor Sergeev | 2e3e224 | 2018-11-16 21:16:43 +0000 | [diff] [blame] | 2715 | // Calculate cost multiplier which is a tool to limit potentially |
| 2716 | // exponential behavior of loop-unswitch. |
| 2717 | if (EnableUnswitchCostMultiplier) { |
| 2718 | int CostMultiplier = |
| 2719 | calculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates); |
| 2720 | assert( |
| 2721 | (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) && |
| 2722 | "cost multiplier needs to be in the range of 1..UnswitchThreshold"); |
| 2723 | CandidateCost *= CostMultiplier; |
| 2724 | LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost |
| 2725 | << " (multiplier: " << CostMultiplier << ")" |
| 2726 | << " for unswitch candidate: " << TI << "\n"); |
| 2727 | } else { |
| 2728 | LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost |
| 2729 | << " for unswitch candidate: " << TI << "\n"); |
| 2730 | } |
| 2731 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2732 | if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) { |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2733 | BestUnswitchTI = &TI; |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2734 | BestUnswitchCost = CandidateCost; |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2735 | BestUnswitchInvariants = Invariants; |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2736 | } |
| 2737 | } |
| 2738 | |
Chandler Carruth | 71fd270 | 2018-05-30 02:46:45 +0000 | [diff] [blame] | 2739 | if (BestUnswitchCost >= UnswitchThreshold) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2740 | LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: " |
| 2741 | << BestUnswitchCost << "\n"); |
Chandler Carruth | 71fd270 | 2018-05-30 02:46:45 +0000 | [diff] [blame] | 2742 | return false; |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2743 | } |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2744 | |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2745 | // If the best candidate is a guard, turn it into a branch. |
| 2746 | if (isGuard(BestUnswitchTI)) |
| 2747 | BestUnswitchTI = turnGuardIntoBranch(cast<IntrinsicInst>(BestUnswitchTI), L, |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2748 | ExitBlocks, DT, LI, MSSAU); |
Max Kazantsev | 619a834 | 2018-10-26 14:20:11 +0000 | [diff] [blame] | 2749 | |
Max Kazantsev | bde3100 | 2018-10-26 09:52:58 +0000 | [diff] [blame] | 2750 | LLVM_DEBUG(dbgs() << " Unswitching non-trivial (cost = " |
Chandler Carruth | 1652996 | 2018-06-25 23:32:54 +0000 | [diff] [blame] | 2751 | << BestUnswitchCost << ") terminator: " << *BestUnswitchTI |
| 2752 | << "\n"); |
Max Kazantsev | bde3100 | 2018-10-26 09:52:58 +0000 | [diff] [blame] | 2753 | unswitchNontrivialInvariants(L, *BestUnswitchTI, BestUnswitchInvariants, |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2754 | ExitBlocks, DT, LI, AC, UnswitchCB, SE, MSSAU); |
Max Kazantsev | bde3100 | 2018-10-26 09:52:58 +0000 | [diff] [blame] | 2755 | return true; |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2756 | } |
| 2757 | |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2758 | /// Unswitch control flow predicated on loop invariant conditions. |
| 2759 | /// |
| 2760 | /// This first hoists all branches or switches which are trivial (IE, do not |
| 2761 | /// require duplicating any part of the loop) out of the loop body. It then |
| 2762 | /// looks at other loop invariant control flows and tries to unswitch those as |
| 2763 | /// well by cloning the loop if the result is small enough. |
Chandler Carruth | 3897ded | 2018-07-03 09:13:27 +0000 | [diff] [blame] | 2764 | /// |
| 2765 | /// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also |
| 2766 | /// updated based on the unswitch. |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2767 | /// The `MSSA` analysis is also updated if valid (i.e. its use is enabled). |
Chandler Carruth | 3897ded | 2018-07-03 09:13:27 +0000 | [diff] [blame] | 2768 | /// |
| 2769 | /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is |
| 2770 | /// true, we will attempt to do non-trivial unswitching as well as trivial |
| 2771 | /// unswitching. |
| 2772 | /// |
| 2773 | /// The `UnswitchCB` callback provided will be run after unswitching is |
| 2774 | /// complete, with the first parameter set to `true` if the provided loop |
| 2775 | /// remains a loop, and a list of new sibling loops created. |
| 2776 | /// |
| 2777 | /// If `SE` is non-null, we will update that analysis based on the unswitching |
| 2778 | /// done. |
| 2779 | static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, |
| 2780 | AssumptionCache &AC, TargetTransformInfo &TTI, |
| 2781 | bool NonTrivial, |
| 2782 | function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB, |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2783 | ScalarEvolution *SE, MemorySSAUpdater *MSSAU) { |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2784 | assert(L.isRecursivelyLCSSAForm(DT, LI) && |
| 2785 | "Loops must be in LCSSA form before unswitching."); |
| 2786 | bool Changed = false; |
| 2787 | |
| 2788 | // Must be in loop simplified form: we need a preheader and dedicated exits. |
| 2789 | if (!L.isLoopSimplifyForm()) |
| 2790 | return false; |
| 2791 | |
| 2792 | // Try trivial unswitch first before loop over other basic blocks in the loop. |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2793 | if (unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) { |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2794 | // If we unswitched successfully we will want to clean up the loop before |
| 2795 | // processing it further so just mark it as unswitched and return. |
| 2796 | UnswitchCB(/*CurrentLoopValid*/ true, {}); |
| 2797 | return true; |
| 2798 | } |
| 2799 | |
| 2800 | // If we're not doing non-trivial unswitching, we're done. We both accept |
| 2801 | // a parameter but also check a local flag that can be used for testing |
| 2802 | // a debugging. |
| 2803 | if (!NonTrivial && !EnableNonTrivialUnswitch) |
| 2804 | return false; |
| 2805 | |
| 2806 | // For non-trivial unswitching, because it often creates new loops, we rely on |
| 2807 | // the pass manager to iterate on the loops rather than trying to immediately |
| 2808 | // reach a fixed point. There is no substantial advantage to iterating |
| 2809 | // internally, and if any of the new loops are simplified enough to contain |
| 2810 | // trivial unswitching we want to prefer those. |
| 2811 | |
| 2812 | // Try to unswitch the best invariant condition. We prefer this full unswitch to |
| 2813 | // a partial unswitch when possible below the threshold. |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2814 | if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE, MSSAU)) |
Chandler Carruth | d1dab0c | 2018-06-21 06:14:03 +0000 | [diff] [blame] | 2815 | return true; |
| 2816 | |
| 2817 | // No other opportunities to unswitch. |
| 2818 | return Changed; |
| 2819 | } |
| 2820 | |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2821 | PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM, |
| 2822 | LoopStandardAnalysisResults &AR, |
| 2823 | LPMUpdater &U) { |
| 2824 | Function &F = *L.getHeader()->getParent(); |
| 2825 | (void)F; |
| 2826 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2827 | LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L |
| 2828 | << "\n"); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2829 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2830 | // Save the current loop name in a variable so that we can report it even |
| 2831 | // after it has been deleted. |
| 2832 | std::string LoopName = L.getName(); |
| 2833 | |
Chandler Carruth | 71fd270 | 2018-05-30 02:46:45 +0000 | [diff] [blame] | 2834 | auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid, |
| 2835 | ArrayRef<Loop *> NewLoops) { |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2836 | // If we did a non-trivial unswitch, we have added new (cloned) loops. |
Chandler Carruth | 71fd270 | 2018-05-30 02:46:45 +0000 | [diff] [blame] | 2837 | if (!NewLoops.empty()) |
| 2838 | U.addSiblingLoops(NewLoops); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2839 | |
| 2840 | // If the current loop remains valid, we should revisit it to catch any |
| 2841 | // other unswitch opportunities. Otherwise, we need to mark it as deleted. |
| 2842 | if (CurrentLoopValid) |
| 2843 | U.revisitCurrentLoop(); |
| 2844 | else |
| 2845 | U.markLoopAsDeleted(L, LoopName); |
| 2846 | }; |
| 2847 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2848 | Optional<MemorySSAUpdater> MSSAU; |
| 2849 | if (AR.MSSA) { |
| 2850 | MSSAU = MemorySSAUpdater(AR.MSSA); |
| 2851 | if (VerifyMemorySSA) |
| 2852 | AR.MSSA->verifyMemorySSA(); |
| 2853 | } |
Chandler Carruth | 3897ded | 2018-07-03 09:13:27 +0000 | [diff] [blame] | 2854 | if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB, |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2855 | &AR.SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr)) |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2856 | return PreservedAnalyses::all(); |
| 2857 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2858 | if (AR.MSSA && VerifyMemorySSA) |
| 2859 | AR.MSSA->verifyMemorySSA(); |
| 2860 | |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2861 | // Historically this pass has had issues with the dominator tree so verify it |
| 2862 | // in asserts builds. |
David Green | 7c35de1 | 2018-02-28 11:00:08 +0000 | [diff] [blame] | 2863 | assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast)); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2864 | return getLoopPassPreservedAnalyses(); |
| 2865 | } |
| 2866 | |
| 2867 | namespace { |
Eugene Zelenko | a369a45 | 2017-05-16 23:10:25 +0000 | [diff] [blame] | 2868 | |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2869 | class SimpleLoopUnswitchLegacyPass : public LoopPass { |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2870 | bool NonTrivial; |
| 2871 | |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2872 | public: |
| 2873 | static char ID; // Pass ID, replacement for typeid |
Eugene Zelenko | a369a45 | 2017-05-16 23:10:25 +0000 | [diff] [blame] | 2874 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2875 | explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false) |
| 2876 | : LoopPass(ID), NonTrivial(NonTrivial) { |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2877 | initializeSimpleLoopUnswitchLegacyPassPass( |
| 2878 | *PassRegistry::getPassRegistry()); |
| 2879 | } |
| 2880 | |
| 2881 | bool runOnLoop(Loop *L, LPPassManager &LPM) override; |
| 2882 | |
| 2883 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 2884 | AU.addRequired<AssumptionCacheTracker>(); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2885 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2886 | if (EnableMSSALoopDependency) { |
| 2887 | AU.addRequired<MemorySSAWrapperPass>(); |
| 2888 | AU.addPreserved<MemorySSAWrapperPass>(); |
| 2889 | } |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2890 | getLoopAnalysisUsage(AU); |
| 2891 | } |
| 2892 | }; |
Eugene Zelenko | a369a45 | 2017-05-16 23:10:25 +0000 | [diff] [blame] | 2893 | |
| 2894 | } // end anonymous namespace |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2895 | |
| 2896 | bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) { |
| 2897 | if (skipLoop(L)) |
| 2898 | return false; |
| 2899 | |
| 2900 | Function &F = *L->getHeader()->getParent(); |
| 2901 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2902 | LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L |
| 2903 | << "\n"); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2904 | |
| 2905 | auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 2906 | auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
| 2907 | auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2908 | auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2909 | MemorySSA *MSSA = nullptr; |
| 2910 | Optional<MemorySSAUpdater> MSSAU; |
| 2911 | if (EnableMSSALoopDependency) { |
| 2912 | MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA(); |
| 2913 | MSSAU = MemorySSAUpdater(MSSA); |
| 2914 | } |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2915 | |
Chandler Carruth | 3897ded | 2018-07-03 09:13:27 +0000 | [diff] [blame] | 2916 | auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); |
| 2917 | auto *SE = SEWP ? &SEWP->getSE() : nullptr; |
| 2918 | |
Chandler Carruth | 71fd270 | 2018-05-30 02:46:45 +0000 | [diff] [blame] | 2919 | auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid, |
| 2920 | ArrayRef<Loop *> NewLoops) { |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2921 | // If we did a non-trivial unswitch, we have added new (cloned) loops. |
| 2922 | for (auto *NewL : NewLoops) |
| 2923 | LPM.addLoop(*NewL); |
| 2924 | |
| 2925 | // If the current loop remains valid, re-add it to the queue. This is |
| 2926 | // a little wasteful as we'll finish processing the current loop as well, |
| 2927 | // but it is the best we can do in the old PM. |
| 2928 | if (CurrentLoopValid) |
| 2929 | LPM.addLoop(*L); |
| 2930 | else |
| 2931 | LPM.markLoopAsDeleted(*L); |
| 2932 | }; |
| 2933 | |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2934 | if (MSSA && VerifyMemorySSA) |
| 2935 | MSSA->verifyMemorySSA(); |
| 2936 | |
| 2937 | bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE, |
| 2938 | MSSAU.hasValue() ? MSSAU.getPointer() : nullptr); |
| 2939 | |
| 2940 | if (MSSA && VerifyMemorySSA) |
| 2941 | MSSA->verifyMemorySSA(); |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2942 | |
| 2943 | // If anything was unswitched, also clear any cached information about this |
| 2944 | // loop. |
| 2945 | LPM.deleteSimpleAnalysisLoop(L); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2946 | |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2947 | // Historically this pass has had issues with the dominator tree so verify it |
| 2948 | // in asserts builds. |
David Green | 7c35de1 | 2018-02-28 11:00:08 +0000 | [diff] [blame] | 2949 | assert(DT.verify(DominatorTree::VerificationLevel::Fast)); |
| 2950 | |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2951 | return Changed; |
| 2952 | } |
| 2953 | |
| 2954 | char SimpleLoopUnswitchLegacyPass::ID = 0; |
| 2955 | INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch", |
| 2956 | "Simple unswitch loops", false, false) |
| 2957 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2958 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 2959 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2960 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
Alina Sbirlea | a2eebb8 | 2018-12-04 14:23:37 +0000 | [diff] [blame] | 2961 | INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2962 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) |
| 2963 | INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch", |
| 2964 | "Simple unswitch loops", false, false) |
| 2965 | |
Chandler Carruth | 693eedb | 2017-11-17 19:58:36 +0000 | [diff] [blame] | 2966 | Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) { |
| 2967 | return new SimpleLoopUnswitchLegacyPass(NonTrivial); |
Chandler Carruth | 1353f9a | 2017-04-27 18:45:20 +0000 | [diff] [blame] | 2968 | } |