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