blob: 06d65b55890ad2ccf7cf2fd621db4601aa5fb172 [file] [log] [blame]
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +00001///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===//
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chandler Carruth1353f9a2017-04-27 18:45:20 +00006//
7//===----------------------------------------------------------------------===//
8
Chandler Carruth6bda14b2017-06-06 11:49:48 +00009#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000010#include "llvm/ADT/DenseMap.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000011#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000012#include "llvm/ADT/Sequence.h"
13#include "llvm/ADT/SetVector.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000014#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000015#include "llvm/ADT/SmallVector.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000016#include "llvm/ADT/Statistic.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000017#include "llvm/ADT/Twine.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000018#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth32e62f92018-04-19 18:44:25 +000019#include "llvm/Analysis/CFG.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000020#include "llvm/Analysis/CodeMetrics.h"
Max Kazantsev619a8342018-10-26 14:20:11 +000021#include "llvm/Analysis/GuardUtils.h"
Chandler Carruth4da33312018-06-20 18:57:07 +000022#include "llvm/Analysis/InstructionSimplify.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000023#include "llvm/Analysis/LoopAnalysisManager.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000024#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth32e62f92018-04-19 18:44:25 +000025#include "llvm/Analysis/LoopIterator.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000026#include "llvm/Analysis/LoopPass.h"
Alina Sbirleaa2eebb82018-12-04 14:23:37 +000027#include "llvm/Analysis/MemorySSA.h"
28#include "llvm/Analysis/MemorySSAUpdater.h"
Chandler Carruth4da33312018-06-20 18:57:07 +000029#include "llvm/Analysis/Utils/Local.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000030#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/Constant.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/Dominators.h"
34#include "llvm/IR/Function.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000035#include "llvm/IR/InstrTypes.h"
36#include "llvm/IR/Instruction.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000037#include "llvm/IR/Instructions.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000038#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000039#include "llvm/IR/Use.h"
40#include "llvm/IR/Value.h"
41#include "llvm/Pass.h"
42#include "llvm/Support/Casting.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000043#include "llvm/Support/Debug.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000044#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/GenericDomTree.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000046#include "llvm/Support/raw_ostream.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000047#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000048#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000049#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000050#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000051#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000052#include <algorithm>
53#include <cassert>
54#include <iterator>
Chandler Carruth693eedb2017-11-17 19:58:36 +000055#include <numeric>
Eugene Zelenkoa369a452017-05-16 23:10:25 +000056#include <utility>
Chandler Carruth1353f9a2017-04-27 18:45:20 +000057
58#define DEBUG_TYPE "simple-loop-unswitch"
59
60using namespace llvm;
61
62STATISTIC(NumBranches, "Number of branches unswitched");
63STATISTIC(NumSwitches, "Number of switches unswitched");
Max Kazantsev619a8342018-10-26 14:20:11 +000064STATISTIC(NumGuards, "Number of guards turned into branches for unswitching");
Chandler Carruth1353f9a2017-04-27 18:45:20 +000065STATISTIC(NumTrivial, "Number of unswitches that are trivial");
Fedor Sergeev2e3e2242018-11-16 21:16:43 +000066STATISTIC(
67 NumCostMultiplierSkipped,
68 "Number of unswitch candidates that had their cost multiplier skipped");
Chandler Carruth1353f9a2017-04-27 18:45:20 +000069
Chandler Carruth693eedb2017-11-17 19:58:36 +000070static 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
75static cl::opt<int>
76 UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
77 cl::desc("The cost threshold for unswitching a loop."));
78
Fedor Sergeev2e3e2242018-11-16 21:16:43 +000079static 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."));
83static cl::opt<int> UnswitchSiblingsToplevelDiv(
84 "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden,
85 cl::desc("Toplevel siblings divisor for cost multiplier."));
86static cl::opt<int> UnswitchNumInitialUnscaledCandidates(
87 "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden,
88 cl::desc("Number of unswitch candidates that are ignored when calculating "
89 "cost multiplier."));
Max Kazantsev619a8342018-10-26 14:20:11 +000090static cl::opt<bool> UnswitchGuards(
91 "simple-loop-unswitch-guards", cl::init(true), cl::Hidden,
92 cl::desc("If enabled, simple loop unswitching will also consider "
93 "llvm.experimental.guard intrinsics as unswitch candidates."));
94
Chandler Carruth4da33312018-06-20 18:57:07 +000095/// Collect all of the loop invariant input values transitively used by the
96/// homogeneous instruction graph from a given root.
97///
98/// This essentially walks from a root recursively through loop variant operands
99/// which have the exact same opcode and finds all inputs which are loop
100/// invariant. For some operations these can be re-associated and unswitched out
101/// of the loop entirely.
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000102static TinyPtrVector<Value *>
Chandler Carruth4da33312018-06-20 18:57:07 +0000103collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root,
104 LoopInfo &LI) {
Chandler Carruth4da33312018-06-20 18:57:07 +0000105 assert(!L.isLoopInvariant(&Root) &&
106 "Only need to walk the graph if root itself is not invariant.");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000107 TinyPtrVector<Value *> Invariants;
Chandler Carruth4da33312018-06-20 18:57:07 +0000108
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
141static void replaceLoopInvariantUses(Loop &L, Value *Invariant,
142 Constant &Replacement) {
143 assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000144
145 // Replace uses of LIC in the loop with the given constant.
Chandler Carruth4da33312018-06-20 18:57:07 +0000146 for (auto UI = Invariant->use_begin(), UE = Invariant->use_end(); UI != UE;) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000147 // Grab the use and walk past it so we can clobber it in the use list.
148 Use *U = &*UI++;
149 Instruction *UserI = dyn_cast<Instruction>(U->getUser());
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000150
151 // Replace this use within the loop body.
Chandler Carruth4da33312018-06-20 18:57:07 +0000152 if (UserI && L.contains(UserI))
153 U->set(&Replacement);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000154 }
155}
156
Chandler Carruthd869b182017-05-12 02:19:59 +0000157/// Check that all the LCSSA PHI nodes in the loop exit block have trivial
158/// incoming values along this edge.
159static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB,
160 BasicBlock &ExitBB) {
161 for (Instruction &I : ExitBB) {
162 auto *PN = dyn_cast<PHINode>(&I);
163 if (!PN)
164 // No more PHIs to check.
165 return true;
166
167 // If the incoming value for this edge isn't loop invariant the unswitch
168 // won't be trivial.
169 if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
170 return false;
171 }
172 llvm_unreachable("Basic blocks should never be empty!");
173}
174
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000175/// Insert code to test a set of loop invariant values, and conditionally branch
176/// on them.
177static void buildPartialUnswitchConditionalBranch(BasicBlock &BB,
178 ArrayRef<Value *> Invariants,
179 bool Direction,
180 BasicBlock &UnswitchedSucc,
181 BasicBlock &NormalSucc) {
182 IRBuilder<> IRB(&BB);
183 Value *Cond = Invariants.front();
184 for (Value *Invariant :
185 make_range(std::next(Invariants.begin()), Invariants.end()))
186 if (Direction)
187 Cond = IRB.CreateOr(Cond, Invariant);
188 else
189 Cond = IRB.CreateAnd(Cond, Invariant);
190
191 IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
192 Direction ? &NormalSucc : &UnswitchedSucc);
193}
194
Chandler Carruthd869b182017-05-12 02:19:59 +0000195/// Rewrite the PHI nodes in an unswitched loop exit basic block.
196///
197/// Requires that the loop exit and unswitched basic block are the same, and
198/// that the exiting block was a unique predecessor of that block. Rewrites the
199/// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
200/// PHI nodes from the old preheader that now contains the unswitched
201/// terminator.
202static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
203 BasicBlock &OldExitingBB,
204 BasicBlock &OldPH) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000205 for (PHINode &PN : UnswitchedBB.phis()) {
Chandler Carruthd869b182017-05-12 02:19:59 +0000206 // When the loop exit is directly unswitched we just need to update the
207 // incoming basic block. We loop to handle weird cases with repeated
208 // incoming blocks, but expect to typically only have one operand here.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000209 for (auto i : seq<int>(0, PN.getNumOperands())) {
210 assert(PN.getIncomingBlock(i) == &OldExitingBB &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000211 "Found incoming block different from unique predecessor!");
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000212 PN.setIncomingBlock(i, &OldPH);
Chandler Carruthd869b182017-05-12 02:19:59 +0000213 }
214 }
215}
216
217/// Rewrite the PHI nodes in the loop exit basic block and the split off
218/// unswitched block.
219///
220/// Because the exit block remains an exit from the loop, this rewrites the
221/// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
222/// nodes into the unswitched basic block to select between the value in the
223/// old preheader and the loop exit.
224static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
225 BasicBlock &UnswitchedBB,
226 BasicBlock &OldExitingBB,
Chandler Carruth4da33312018-06-20 18:57:07 +0000227 BasicBlock &OldPH,
228 bool FullUnswitch) {
Chandler Carruthd869b182017-05-12 02:19:59 +0000229 assert(&ExitBB != &UnswitchedBB &&
230 "Must have different loop exit and unswitched blocks!");
231 Instruction *InsertPt = &*UnswitchedBB.begin();
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000232 for (PHINode &PN : ExitBB.phis()) {
233 auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
234 PN.getName() + ".split", InsertPt);
Chandler Carruthd869b182017-05-12 02:19:59 +0000235
236 // Walk backwards over the old PHI node's inputs to minimize the cost of
237 // removing each one. We have to do this weird loop manually so that we
238 // create the same number of new incoming edges in the new PHI as we expect
239 // each case-based edge to be included in the unswitched switch in some
240 // cases.
241 // FIXME: This is really, really gross. It would be much cleaner if LLVM
242 // allowed us to create a single entry for a predecessor block without
243 // having separate entries for each "edge" even though these edges are
244 // required to produce identical results.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000245 for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
246 if (PN.getIncomingBlock(i) != &OldExitingBB)
Chandler Carruthd869b182017-05-12 02:19:59 +0000247 continue;
248
Chandler Carruth4da33312018-06-20 18:57:07 +0000249 Value *Incoming = PN.getIncomingValue(i);
250 if (FullUnswitch)
251 // No more edge from the old exiting block to the exit block.
252 PN.removeIncomingValue(i);
253
Chandler Carruthd869b182017-05-12 02:19:59 +0000254 NewPN->addIncoming(Incoming, &OldPH);
255 }
256
257 // Now replace the old PHI with the new one and wire the old one in as an
258 // input to the new one.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000259 PN.replaceAllUsesWith(NewPN);
260 NewPN->addIncoming(&PN, &ExitBB);
Chandler Carruthd869b182017-05-12 02:19:59 +0000261 }
262}
263
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000264/// Hoist the current loop up to the innermost loop containing a remaining exit.
265///
266/// Because we've removed an exit from the loop, we may have changed the set of
267/// loops reachable and need to move the current loop up the loop nest or even
268/// to an entirely separate nest.
269static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
Alina Sbirlea97468e92019-02-21 21:13:34 +0000270 DominatorTree &DT, LoopInfo &LI,
271 MemorySSAUpdater *MSSAU) {
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000272 // If the loop is already at the top level, we can't hoist it anywhere.
273 Loop *OldParentL = L.getParentLoop();
274 if (!OldParentL)
275 return;
276
277 SmallVector<BasicBlock *, 4> Exits;
278 L.getExitBlocks(Exits);
279 Loop *NewParentL = nullptr;
280 for (auto *ExitBB : Exits)
281 if (Loop *ExitL = LI.getLoopFor(ExitBB))
282 if (!NewParentL || NewParentL->contains(ExitL))
283 NewParentL = ExitL;
284
285 if (NewParentL == OldParentL)
286 return;
287
288 // The new parent loop (if different) should always contain the old one.
289 if (NewParentL)
290 assert(NewParentL->contains(OldParentL) &&
291 "Can only hoist this loop up the nest!");
292
293 // The preheader will need to move with the body of this loop. However,
294 // because it isn't in this loop we also need to update the primary loop map.
295 assert(OldParentL == LI.getLoopFor(&Preheader) &&
296 "Parent loop of this loop should contain this loop's preheader!");
297 LI.changeLoopFor(&Preheader, NewParentL);
298
299 // Remove this loop from its old parent.
300 OldParentL->removeChildLoop(&L);
301
302 // Add the loop either to the new parent or as a top-level loop.
303 if (NewParentL)
304 NewParentL->addChildLoop(&L);
305 else
306 LI.addTopLevelLoop(&L);
307
308 // Remove this loops blocks from the old parent and every other loop up the
309 // nest until reaching the new parent. Also update all of these
310 // no-longer-containing loops to reflect the nesting change.
311 for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
312 OldContainingL = OldContainingL->getParentLoop()) {
313 llvm::erase_if(OldContainingL->getBlocksVector(),
314 [&](const BasicBlock *BB) {
315 return BB == &Preheader || L.contains(BB);
316 });
317
318 OldContainingL->getBlocksSet().erase(&Preheader);
319 for (BasicBlock *BB : L.blocks())
320 OldContainingL->getBlocksSet().erase(BB);
321
322 // Because we just hoisted a loop out of this one, we have essentially
323 // created new exit paths from it. That means we need to form LCSSA PHI
324 // nodes for values used in the no-longer-nested loop.
325 formLCSSA(*OldContainingL, DT, &LI, nullptr);
326
327 // We shouldn't need to form dedicated exits because the exit introduced
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000328 // here is the (just split by unswitching) preheader. However, after trivial
329 // unswitching it is possible to get new non-dedicated exits out of parent
330 // loop so let's conservatively form dedicated exit blocks and figure out
331 // if we can optimize later.
Alina Sbirlea97468e92019-02-21 21:13:34 +0000332 formDedicatedExitBlocks(OldContainingL, &DT, &LI, MSSAU,
333 /*PreserveLCSSA*/ true);
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000334 }
335}
336
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000337/// Unswitch a trivial branch if the condition is loop invariant.
338///
339/// This routine should only be called when loop code leading to the branch has
340/// been validated as trivial (no side effects). This routine checks if the
341/// condition is invariant and one of the successors is a loop exit. This
342/// allows us to unswitch without duplicating the loop, making it trivial.
343///
344/// If this routine fails to unswitch the branch it returns false.
345///
346/// If the branch can be unswitched, this routine splits the preheader and
347/// hoists the branch above that split. Preserves loop simplified form
348/// (splitting the exit block as necessary). It simplifies the branch within
349/// the loop to an unconditional branch but doesn't remove it entirely. Further
350/// cleanup can be done with some simplify-cfg like pass.
Chandler Carruth3897ded2018-07-03 09:13:27 +0000351///
352/// If `SE` is not null, it will be updated based on the potential loop SCEVs
353/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000354static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000355 LoopInfo &LI, ScalarEvolution *SE,
356 MemorySSAUpdater *MSSAU) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000357 assert(BI.isConditional() && "Can only unswitch a conditional branch!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000358 LLVM_DEBUG(dbgs() << " Trying to unswitch branch: " << BI << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000359
Chandler Carruth4da33312018-06-20 18:57:07 +0000360 // The loop invariant values that we want to unswitch.
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000361 TinyPtrVector<Value *> Invariants;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000362
Chandler Carruth4da33312018-06-20 18:57:07 +0000363 // When true, we're fully unswitching the branch rather than just unswitching
364 // some input conditions to the branch.
365 bool FullUnswitch = false;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000366
Chandler Carruth4da33312018-06-20 18:57:07 +0000367 if (L.isLoopInvariant(BI.getCondition())) {
368 Invariants.push_back(BI.getCondition());
369 FullUnswitch = true;
370 } else {
371 if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition()))
372 Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
373 if (Invariants.empty())
374 // Couldn't find invariant inputs!
375 return false;
376 }
377
378 // Check that one of the branch's successors exits, and which one.
379 bool ExitDirection = true;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000380 int LoopExitSuccIdx = 0;
381 auto *LoopExitBB = BI.getSuccessor(0);
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000382 if (L.contains(LoopExitBB)) {
Chandler Carruth4da33312018-06-20 18:57:07 +0000383 ExitDirection = false;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000384 LoopExitSuccIdx = 1;
385 LoopExitBB = BI.getSuccessor(1);
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000386 if (L.contains(LoopExitBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000387 return false;
388 }
389 auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
Chandler Carruthd869b182017-05-12 02:19:59 +0000390 auto *ParentBB = BI.getParent();
391 if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000392 return false;
393
Chandler Carruth4da33312018-06-20 18:57:07 +0000394 // When unswitching only part of the branch's condition, we need the exit
395 // block to be reached directly from the partially unswitched input. This can
396 // be done when the exit block is along the true edge and the branch condition
397 // is a graph of `or` operations, or the exit block is along the false edge
398 // and the condition is a graph of `and` operations.
399 if (!FullUnswitch) {
400 if (ExitDirection) {
401 if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::Or)
402 return false;
403 } else {
404 if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::And)
405 return false;
406 }
407 }
408
409 LLVM_DEBUG({
410 dbgs() << " unswitching trivial invariant conditions for: " << BI
411 << "\n";
412 for (Value *Invariant : Invariants) {
413 dbgs() << " " << *Invariant << " == true";
414 if (Invariant != Invariants.back())
415 dbgs() << " ||";
416 dbgs() << "\n";
417 }
418 });
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000419
Chandler Carruth3897ded2018-07-03 09:13:27 +0000420 // If we have scalar evolutions, we need to invalidate them including this
421 // loop and the loop containing the exit block.
422 if (SE) {
423 if (Loop *ExitL = LI.getLoopFor(LoopExitBB))
424 SE->forgetLoop(ExitL);
425 else
426 // Forget the entire nest as this exits the entire nest.
427 SE->forgetTopmostLoop(&L);
428 }
429
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000430 if (MSSAU && VerifyMemorySSA)
431 MSSAU->getMemorySSA()->verifyMemorySSA();
432
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000433 // Split the preheader, so that we know that there is a safe place to insert
434 // the conditional branch. We will change the preheader to have a conditional
435 // branch on LoopCond.
436 BasicBlock *OldPH = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000437 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000438
439 // Now that we have a place to insert the conditional branch, create a place
440 // to branch to: this is the exit block out of the loop that we are
441 // unswitching. We need to split this if there are other loop predecessors.
442 // Because the loop is in simplified form, *any* other predecessor is enough.
443 BasicBlock *UnswitchedBB;
Chandler Carruth4da33312018-06-20 18:57:07 +0000444 if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
445 assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000446 "A branch's parent isn't a predecessor!");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000447 UnswitchedBB = LoopExitBB;
448 } else {
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000449 UnswitchedBB =
450 SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000451 }
452
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000453 if (MSSAU && VerifyMemorySSA)
454 MSSAU->getMemorySSA()->verifyMemorySSA();
455
Chandler Carruth4da33312018-06-20 18:57:07 +0000456 // Actually move the invariant uses into the unswitched position. If possible,
457 // we do this by moving the instructions, but when doing partial unswitching
458 // we do it by building a new merge of the values in the unswitched position.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000459 OldPH->getTerminator()->eraseFromParent();
Chandler Carruth4da33312018-06-20 18:57:07 +0000460 if (FullUnswitch) {
461 // If fully unswitching, we can use the existing branch instruction.
462 // Splice it into the old PH to gate reaching the new preheader and re-point
463 // its successors.
464 OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
465 BI);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000466 if (MSSAU) {
467 // Temporarily clone the terminator, to make MSSA update cheaper by
468 // separating "insert edge" updates from "remove edge" ones.
469 ParentBB->getInstList().push_back(BI.clone());
470 } else {
471 // Create a new unconditional branch that will continue the loop as a new
472 // terminator.
473 BranchInst::Create(ContinueBB, ParentBB);
474 }
Chandler Carruth4da33312018-06-20 18:57:07 +0000475 BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
476 BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
Chandler Carruth4da33312018-06-20 18:57:07 +0000477 } else {
478 // Only unswitching a subset of inputs to the condition, so we will need to
479 // build a new branch that merges the invariant inputs.
Chandler Carruth4da33312018-06-20 18:57:07 +0000480 if (ExitDirection)
481 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
482 Instruction::Or &&
483 "Must have an `or` of `i1`s for the condition!");
484 else
485 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
486 Instruction::And &&
487 "Must have an `and` of `i1`s for the condition!");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000488 buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection,
489 *UnswitchedBB, *NewPH);
Chandler Carruth4da33312018-06-20 18:57:07 +0000490 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000491
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000492 // Update the dominator tree with the added edge.
493 DT.insertEdge(OldPH, UnswitchedBB);
494
495 // After the dominator tree was updated with the added edge, update MemorySSA
496 // if available.
497 if (MSSAU) {
498 SmallVector<CFGUpdate, 1> Updates;
499 Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
500 MSSAU->applyInsertUpdates(Updates, DT);
501 }
502
503 // Finish updating dominator tree and memory ssa for full unswitch.
504 if (FullUnswitch) {
505 if (MSSAU) {
506 // Remove the cloned branch instruction.
507 ParentBB->getTerminator()->eraseFromParent();
508 // Create unconditional branch now.
509 BranchInst::Create(ContinueBB, ParentBB);
510 MSSAU->removeEdge(ParentBB, LoopExitBB);
511 }
512 DT.deleteEdge(ParentBB, LoopExitBB);
513 }
514
515 if (MSSAU && VerifyMemorySSA)
516 MSSAU->getMemorySSA()->verifyMemorySSA();
517
Chandler Carruthd869b182017-05-12 02:19:59 +0000518 // Rewrite the relevant PHI nodes.
519 if (UnswitchedBB == LoopExitBB)
520 rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
521 else
522 rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
Chandler Carruth4da33312018-06-20 18:57:07 +0000523 *ParentBB, *OldPH, FullUnswitch);
Chandler Carruthd869b182017-05-12 02:19:59 +0000524
Chandler Carruth4da33312018-06-20 18:57:07 +0000525 // The constant we can replace all of our invariants with inside the loop
526 // body. If any of the invariants have a value other than this the loop won't
527 // be entered.
528 ConstantInt *Replacement = ExitDirection
529 ? ConstantInt::getFalse(BI.getContext())
530 : ConstantInt::getTrue(BI.getContext());
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000531
532 // Since this is an i1 condition we can also trivially replace uses of it
533 // within the loop with a constant.
Chandler Carruth4da33312018-06-20 18:57:07 +0000534 for (Value *Invariant : Invariants)
535 replaceLoopInvariantUses(L, Invariant, *Replacement);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000536
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000537 // If this was full unswitching, we may have changed the nesting relationship
538 // for this loop so hoist it to its correct parent if needed.
539 if (FullUnswitch)
Alina Sbirlea97468e92019-02-21 21:13:34 +0000540 hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU);
541
542 if (MSSAU && VerifyMemorySSA)
543 MSSAU->getMemorySSA()->verifyMemorySSA();
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000544
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000545 LLVM_DEBUG(dbgs() << " done: unswitching trivial branch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000546 ++NumTrivial;
547 ++NumBranches;
548 return true;
549}
550
551/// Unswitch a trivial switch if the condition is loop invariant.
552///
553/// This routine should only be called when loop code leading to the switch has
554/// been validated as trivial (no side effects). This routine checks if the
555/// condition is invariant and that at least one of the successors is a loop
556/// exit. This allows us to unswitch without duplicating the loop, making it
557/// trivial.
558///
559/// If this routine fails to unswitch the switch it returns false.
560///
561/// If the switch can be unswitched, this routine splits the preheader and
562/// copies the switch above that split. If the default case is one of the
563/// exiting cases, it copies the non-exiting cases and points them at the new
564/// preheader. If the default case is not exiting, it copies the exiting cases
565/// and points the default at the preheader. It preserves loop simplified form
566/// (splitting the exit blocks as necessary). It simplifies the switch within
567/// the loop by removing now-dead cases. If the default case is one of those
568/// unswitched, it replaces its destination with a new basic block containing
569/// only unreachable. Such basic blocks, while technically loop exits, are not
570/// considered for unswitching so this is a stable transform and the same
571/// switch will not be revisited. If after unswitching there is only a single
572/// in-loop successor, the switch is further simplified to an unconditional
573/// branch. Still more cleanup can be done with some simplify-cfg like pass.
Chandler Carruth3897ded2018-07-03 09:13:27 +0000574///
575/// If `SE` is not null, it will be updated based on the potential loop SCEVs
576/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000577static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000578 LoopInfo &LI, ScalarEvolution *SE,
579 MemorySSAUpdater *MSSAU) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000580 LLVM_DEBUG(dbgs() << " Trying to unswitch switch: " << SI << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000581 Value *LoopCond = SI.getCondition();
582
583 // If this isn't switching on an invariant condition, we can't unswitch it.
584 if (!L.isLoopInvariant(LoopCond))
585 return false;
586
Chandler Carruthd869b182017-05-12 02:19:59 +0000587 auto *ParentBB = SI.getParent();
588
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000589 SmallVector<int, 4> ExitCaseIndices;
590 for (auto Case : SI.cases()) {
591 auto *SuccBB = Case.getCaseSuccessor();
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000592 if (!L.contains(SuccBB) &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000593 areLoopExitPHIsLoopInvariant(L, *ParentBB, *SuccBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000594 ExitCaseIndices.push_back(Case.getCaseIndex());
595 }
596 BasicBlock *DefaultExitBB = nullptr;
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000597 if (!L.contains(SI.getDefaultDest()) &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000598 areLoopExitPHIsLoopInvariant(L, *ParentBB, *SI.getDefaultDest()) &&
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000599 !isa<UnreachableInst>(SI.getDefaultDest()->getTerminator()))
600 DefaultExitBB = SI.getDefaultDest();
601 else if (ExitCaseIndices.empty())
602 return false;
603
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000604 LLVM_DEBUG(dbgs() << " unswitching trivial switch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000605
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000606 if (MSSAU && VerifyMemorySSA)
607 MSSAU->getMemorySSA()->verifyMemorySSA();
608
Chandler Carruth3897ded2018-07-03 09:13:27 +0000609 // We may need to invalidate SCEVs for the outermost loop reached by any of
610 // the exits.
611 Loop *OuterL = &L;
612
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000613 if (DefaultExitBB) {
614 // Clear out the default destination temporarily to allow accurate
615 // predecessor lists to be examined below.
616 SI.setDefaultDest(nullptr);
617 // Check the loop containing this exit.
618 Loop *ExitL = LI.getLoopFor(DefaultExitBB);
619 if (!ExitL || ExitL->contains(OuterL))
620 OuterL = ExitL;
621 }
622
623 // Store the exit cases into a separate data structure and remove them from
624 // the switch.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000625 SmallVector<std::pair<ConstantInt *, BasicBlock *>, 4> ExitCases;
626 ExitCases.reserve(ExitCaseIndices.size());
627 // We walk the case indices backwards so that we remove the last case first
628 // and don't disrupt the earlier indices.
629 for (unsigned Index : reverse(ExitCaseIndices)) {
630 auto CaseI = SI.case_begin() + Index;
Chandler Carruth3897ded2018-07-03 09:13:27 +0000631 // Compute the outer loop from this exit.
632 Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor());
633 if (!ExitL || ExitL->contains(OuterL))
634 OuterL = ExitL;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000635 // Save the value of this case.
636 ExitCases.push_back({CaseI->getCaseValue(), CaseI->getCaseSuccessor()});
637 // Delete the unswitched cases.
638 SI.removeCase(CaseI);
639 }
640
Chandler Carruth3897ded2018-07-03 09:13:27 +0000641 if (SE) {
642 if (OuterL)
643 SE->forgetLoop(OuterL);
644 else
645 SE->forgetTopmostLoop(&L);
646 }
647
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000648 // Check if after this all of the remaining cases point at the same
649 // successor.
650 BasicBlock *CommonSuccBB = nullptr;
651 if (SI.getNumCases() > 0 &&
652 std::all_of(std::next(SI.case_begin()), SI.case_end(),
653 [&SI](const SwitchInst::CaseHandle &Case) {
654 return Case.getCaseSuccessor() ==
655 SI.case_begin()->getCaseSuccessor();
656 }))
657 CommonSuccBB = SI.case_begin()->getCaseSuccessor();
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000658 if (!DefaultExitBB) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000659 // If we're not unswitching the default, we need it to match any cases to
660 // have a common successor or if we have no cases it is the common
661 // successor.
662 if (SI.getNumCases() == 0)
663 CommonSuccBB = SI.getDefaultDest();
664 else if (SI.getDefaultDest() != CommonSuccBB)
665 CommonSuccBB = nullptr;
666 }
667
668 // Split the preheader, so that we know that there is a safe place to insert
669 // the switch.
670 BasicBlock *OldPH = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000671 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000672 OldPH->getTerminator()->eraseFromParent();
673
674 // Now add the unswitched switch.
675 auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
676
Chandler Carruthd869b182017-05-12 02:19:59 +0000677 // Rewrite the IR for the unswitched basic blocks. This requires two steps.
678 // First, we split any exit blocks with remaining in-loop predecessors. Then
679 // we update the PHIs in one of two ways depending on if there was a split.
680 // We walk in reverse so that we split in the same order as the cases
681 // appeared. This is purely for convenience of reading the resulting IR, but
682 // it doesn't cost anything really.
683 SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000684 SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
685 // Handle the default exit if necessary.
686 // FIXME: It'd be great if we could merge this with the loop below but LLVM's
687 // ranges aren't quite powerful enough yet.
Chandler Carruthd869b182017-05-12 02:19:59 +0000688 if (DefaultExitBB) {
689 if (pred_empty(DefaultExitBB)) {
690 UnswitchedExitBBs.insert(DefaultExitBB);
691 rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
692 } else {
693 auto *SplitBB =
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000694 SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU);
695 rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
696 *ParentBB, *OldPH,
697 /*FullUnswitch*/ true);
Chandler Carruthd869b182017-05-12 02:19:59 +0000698 DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
699 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000700 }
701 // Note that we must use a reference in the for loop so that we update the
702 // container.
703 for (auto &CasePair : reverse(ExitCases)) {
704 // Grab a reference to the exit block in the pair so that we can update it.
Chandler Carruthd869b182017-05-12 02:19:59 +0000705 BasicBlock *ExitBB = CasePair.second;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000706
707 // If this case is the last edge into the exit block, we can simply reuse it
708 // as it will no longer be a loop exit. No mapping necessary.
Chandler Carruthd869b182017-05-12 02:19:59 +0000709 if (pred_empty(ExitBB)) {
710 // Only rewrite once.
711 if (UnswitchedExitBBs.insert(ExitBB).second)
712 rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000713 continue;
Chandler Carruthd869b182017-05-12 02:19:59 +0000714 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000715
716 // Otherwise we need to split the exit block so that we retain an exit
717 // block from the loop and a target for the unswitched condition.
718 BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
719 if (!SplitExitBB) {
720 // If this is the first time we see this, do the split and remember it.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000721 SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
722 rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
723 *ParentBB, *OldPH,
724 /*FullUnswitch*/ true);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000725 }
Chandler Carruthd869b182017-05-12 02:19:59 +0000726 // Update the case pair to point to the split block.
727 CasePair.second = SplitExitBB;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000728 }
729
730 // Now add the unswitched cases. We do this in reverse order as we built them
731 // in reverse order.
732 for (auto CasePair : reverse(ExitCases)) {
733 ConstantInt *CaseVal = CasePair.first;
734 BasicBlock *UnswitchedBB = CasePair.second;
735
736 NewSI->addCase(CaseVal, UnswitchedBB);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000737 }
738
739 // If the default was unswitched, re-point it and add explicit cases for
740 // entering the loop.
741 if (DefaultExitBB) {
742 NewSI->setDefaultDest(DefaultExitBB);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000743
744 // We removed all the exit cases, so we just copy the cases to the
745 // unswitched switch.
746 for (auto Case : SI.cases())
747 NewSI->addCase(Case.getCaseValue(), NewPH);
748 }
749
750 // If we ended up with a common successor for every path through the switch
751 // after unswitching, rewrite it to an unconditional branch to make it easy
752 // to recognize. Otherwise we potentially have to recognize the default case
753 // pointing at unreachable and other complexity.
754 if (CommonSuccBB) {
755 BasicBlock *BB = SI.getParent();
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000756 // We may have had multiple edges to this common successor block, so remove
757 // them as predecessors. We skip the first one, either the default or the
758 // actual first case.
759 bool SkippedFirst = DefaultExitBB == nullptr;
760 for (auto Case : SI.cases()) {
761 assert(Case.getCaseSuccessor() == CommonSuccBB &&
762 "Non-common successor!");
Chandler Carruth148861f2018-07-10 08:57:04 +0000763 (void)Case;
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000764 if (!SkippedFirst) {
765 SkippedFirst = true;
766 continue;
767 }
768 CommonSuccBB->removePredecessor(BB,
Max Kazantsev20b91892019-02-12 07:09:29 +0000769 /*KeepOneInputPHIs*/ true);
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000770 }
771 // Now nuke the switch and replace it with a direct branch.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000772 SI.eraseFromParent();
773 BranchInst::Create(CommonSuccBB, BB);
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000774 } else if (DefaultExitBB) {
775 assert(SI.getNumCases() > 0 &&
776 "If we had no cases we'd have a common successor!");
777 // Move the last case to the default successor. This is valid as if the
778 // default got unswitched it cannot be reached. This has the advantage of
779 // being simple and keeping the number of edges from this switch to
780 // successors the same, and avoiding any PHI update complexity.
781 auto LastCaseI = std::prev(SI.case_end());
782 SI.setDefaultDest(LastCaseI->getCaseSuccessor());
783 SI.removeCase(LastCaseI);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000784 }
785
Chandler Carruth2c85a232018-05-01 09:54:39 +0000786 // Walk the unswitched exit blocks and the unswitched split blocks and update
787 // the dominator tree based on the CFG edits. While we are walking unordered
788 // containers here, the API for applyUpdates takes an unordered list of
789 // updates and requires them to not contain duplicates.
790 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
791 for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
792 DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
793 DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
794 }
795 for (auto SplitUnswitchedPair : SplitExitBBMap) {
Alina Sbirlea90d2e3a2019-02-22 07:18:37 +0000796 DTUpdates.push_back({DT.Delete, ParentBB, SplitUnswitchedPair.first});
797 DTUpdates.push_back({DT.Insert, OldPH, SplitUnswitchedPair.second});
Chandler Carruth2c85a232018-05-01 09:54:39 +0000798 }
799 DT.applyUpdates(DTUpdates);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000800
801 if (MSSAU) {
802 MSSAU->applyUpdates(DTUpdates, DT);
803 if (VerifyMemorySSA)
804 MSSAU->getMemorySSA()->verifyMemorySSA();
805 }
806
David Green7c35de12018-02-28 11:00:08 +0000807 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000808
809 // We may have changed the nesting relationship for this loop so hoist it to
810 // its correct parent if needed.
Alina Sbirlea97468e92019-02-21 21:13:34 +0000811 hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU);
812
813 if (MSSAU && VerifyMemorySSA)
814 MSSAU->getMemorySSA()->verifyMemorySSA();
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000815
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000816 ++NumTrivial;
817 ++NumSwitches;
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000818 LLVM_DEBUG(dbgs() << " done: unswitching trivial switch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000819 return true;
820}
821
822/// This routine scans the loop to find a branch or switch which occurs before
823/// any side effects occur. These can potentially be unswitched without
824/// duplicating the loop. If a branch or switch is successfully unswitched the
825/// scanning continues to see if subsequent branches or switches have become
826/// trivial. Once all trivial candidates have been unswitched, this routine
827/// returns.
828///
829/// The return value indicates whether anything was unswitched (and therefore
830/// changed).
Chandler Carruth3897ded2018-07-03 09:13:27 +0000831///
832/// If `SE` is not null, it will be updated based on the potential loop SCEVs
833/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000834static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000835 LoopInfo &LI, ScalarEvolution *SE,
836 MemorySSAUpdater *MSSAU) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000837 bool Changed = false;
838
839 // If loop header has only one reachable successor we should keep looking for
840 // trivial condition candidates in the successor as well. An alternative is
841 // to constant fold conditions and merge successors into loop header (then we
842 // only need to check header's terminator). The reason for not doing this in
843 // LoopUnswitch pass is that it could potentially break LoopPassManager's
844 // invariants. Folding dead branches could either eliminate the current loop
845 // or make other loops unreachable. LCSSA form might also not be preserved
846 // after deleting branches. The following code keeps traversing loop header's
847 // successors until it finds the trivial condition candidate (condition that
848 // is not a constant). Since unswitching generates branches with constant
849 // conditions, this scenario could be very common in practice.
850 BasicBlock *CurrentBB = L.getHeader();
851 SmallPtrSet<BasicBlock *, 8> Visited;
852 Visited.insert(CurrentBB);
853 do {
854 // Check if there are any side-effecting instructions (e.g. stores, calls,
855 // volatile loads) in the part of the loop that the code *would* execute
856 // without unswitching.
Alina Sbirlea93210872019-01-28 17:48:45 +0000857 if (MSSAU) // Possible early exit with MSSA
858 if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB))
859 if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
860 return Changed;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000861 if (llvm::any_of(*CurrentBB,
862 [](Instruction &I) { return I.mayHaveSideEffects(); }))
863 return Changed;
864
Chandler Carruthedb12a82018-10-15 10:04:59 +0000865 Instruction *CurrentTerm = CurrentBB->getTerminator();
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000866
867 if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
868 // Don't bother trying to unswitch past a switch with a constant
869 // condition. This should be removed prior to running this pass by
870 // simplify-cfg.
871 if (isa<Constant>(SI->getCondition()))
872 return Changed;
873
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000874 if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
Hiroshi Inouef2096492018-06-14 05:41:49 +0000875 // Couldn't unswitch this one so we're done.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000876 return Changed;
877
878 // Mark that we managed to unswitch something.
879 Changed = true;
880
881 // If unswitching turned the terminator into an unconditional branch then
882 // we can continue. The unswitching logic specifically works to fold any
883 // cases it can into an unconditional branch to make it easier to
884 // recognize here.
885 auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
886 if (!BI || BI->isConditional())
887 return Changed;
888
889 CurrentBB = BI->getSuccessor(0);
890 continue;
891 }
892
893 auto *BI = dyn_cast<BranchInst>(CurrentTerm);
894 if (!BI)
895 // We do not understand other terminator instructions.
896 return Changed;
897
898 // Don't bother trying to unswitch past an unconditional branch or a branch
899 // with a constant value. These should be removed by simplify-cfg prior to
900 // running this pass.
901 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
902 return Changed;
903
904 // Found a trivial condition candidate: non-foldable conditional branch. If
905 // we fail to unswitch this, we can't do anything else that is trivial.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000906 if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000907 return Changed;
908
909 // Mark that we managed to unswitch something.
910 Changed = true;
911
Chandler Carruth4da33312018-06-20 18:57:07 +0000912 // If we only unswitched some of the conditions feeding the branch, we won't
913 // have collapsed it to a single successor.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000914 BI = cast<BranchInst>(CurrentBB->getTerminator());
Chandler Carruth4da33312018-06-20 18:57:07 +0000915 if (BI->isConditional())
916 return Changed;
917
918 // Follow the newly unconditional branch into its successor.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000919 CurrentBB = BI->getSuccessor(0);
920
921 // When continuing, if we exit the loop or reach a previous visited block,
922 // then we can not reach any trivial condition candidates (unfoldable
923 // branch instructions or switch instructions) and no unswitch can happen.
924 } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
925
926 return Changed;
927}
928
Chandler Carruth693eedb2017-11-17 19:58:36 +0000929/// Build the cloned blocks for an unswitched copy of the given loop.
930///
931/// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
932/// after the split block (`SplitBB`) that will be used to select between the
933/// cloned and original loop.
934///
935/// This routine handles cloning all of the necessary loop blocks and exit
936/// blocks including rewriting their instructions and the relevant PHI nodes.
Chandler Carruth16529962018-06-25 23:32:54 +0000937/// Any loop blocks or exit blocks which are dominated by a different successor
938/// than the one for this clone of the loop blocks can be trivially skipped. We
939/// use the `DominatingSucc` map to determine whether a block satisfies that
940/// property with a simple map lookup.
941///
942/// It also correctly creates the unconditional branch in the cloned
Chandler Carruth693eedb2017-11-17 19:58:36 +0000943/// unswitched parent block to only point at the unswitched successor.
944///
945/// This does not handle most of the necessary updates to `LoopInfo`. Only exit
946/// block splitting is correctly reflected in `LoopInfo`, essentially all of
947/// the cloned blocks (and their loops) are left without full `LoopInfo`
948/// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
949/// blocks to them but doesn't create the cloned `DominatorTree` structure and
950/// instead the caller must recompute an accurate DT. It *does* correctly
951/// update the `AssumptionCache` provided in `AC`.
952static BasicBlock *buildClonedLoopBlocks(
953 Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
954 ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
955 BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
Chandler Carruth16529962018-06-25 23:32:54 +0000956 const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
Chandler Carruth69e68f82018-04-25 00:18:07 +0000957 ValueToValueMapTy &VMap,
958 SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000959 DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Chandler Carruth693eedb2017-11-17 19:58:36 +0000960 SmallVector<BasicBlock *, 4> NewBlocks;
961 NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
962
963 // We will need to clone a bunch of blocks, wrap up the clone operation in
964 // a helper.
965 auto CloneBlock = [&](BasicBlock *OldBB) {
966 // Clone the basic block and insert it before the new preheader.
967 BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
968 NewBB->moveBefore(LoopPH);
969
970 // Record this block and the mapping.
971 NewBlocks.push_back(NewBB);
972 VMap[OldBB] = NewBB;
973
Chandler Carruth693eedb2017-11-17 19:58:36 +0000974 return NewBB;
975 };
976
Chandler Carruth16529962018-06-25 23:32:54 +0000977 // We skip cloning blocks when they have a dominating succ that is not the
978 // succ we are cloning for.
979 auto SkipBlock = [&](BasicBlock *BB) {
980 auto It = DominatingSucc.find(BB);
981 return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
982 };
983
Chandler Carruth693eedb2017-11-17 19:58:36 +0000984 // First, clone the preheader.
985 auto *ClonedPH = CloneBlock(LoopPH);
986
987 // Then clone all the loop blocks, skipping the ones that aren't necessary.
988 for (auto *LoopBB : L.blocks())
Chandler Carruth16529962018-06-25 23:32:54 +0000989 if (!SkipBlock(LoopBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +0000990 CloneBlock(LoopBB);
991
992 // Split all the loop exit edges so that when we clone the exit blocks, if
993 // any of the exit blocks are *also* a preheader for some other loop, we
994 // don't create multiple predecessors entering the loop header.
995 for (auto *ExitBB : ExitBlocks) {
Chandler Carruth16529962018-06-25 23:32:54 +0000996 if (SkipBlock(ExitBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +0000997 continue;
998
999 // When we are going to clone an exit, we don't need to clone all the
1000 // instructions in the exit block and we want to ensure we have an easy
1001 // place to merge the CFG, so split the exit first. This is always safe to
1002 // do because there cannot be any non-loop predecessors of a loop exit in
1003 // loop simplified form.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001004 auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001005
1006 // Rearrange the names to make it easier to write test cases by having the
1007 // exit block carry the suffix rather than the merge block carrying the
1008 // suffix.
1009 MergeBB->takeName(ExitBB);
1010 ExitBB->setName(Twine(MergeBB->getName()) + ".split");
1011
1012 // Now clone the original exit block.
1013 auto *ClonedExitBB = CloneBlock(ExitBB);
1014 assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
1015 "Exit block should have been split to have one successor!");
1016 assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
1017 "Cloned exit block has the wrong successor!");
1018
Chandler Carruth693eedb2017-11-17 19:58:36 +00001019 // Remap any cloned instructions and create a merge phi node for them.
1020 for (auto ZippedInsts : llvm::zip_first(
1021 llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
1022 llvm::make_range(ClonedExitBB->begin(),
1023 std::prev(ClonedExitBB->end())))) {
1024 Instruction &I = std::get<0>(ZippedInsts);
1025 Instruction &ClonedI = std::get<1>(ZippedInsts);
1026
1027 // The only instructions in the exit block should be PHI nodes and
1028 // potentially a landing pad.
1029 assert(
1030 (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
1031 "Bad instruction in exit block!");
1032 // We should have a value map between the instruction and its clone.
1033 assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
1034
1035 auto *MergePN =
1036 PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
1037 &*MergeBB->getFirstInsertionPt());
1038 I.replaceAllUsesWith(MergePN);
1039 MergePN->addIncoming(&I, ExitBB);
1040 MergePN->addIncoming(&ClonedI, ClonedExitBB);
1041 }
1042 }
1043
1044 // Rewrite the instructions in the cloned blocks to refer to the instructions
1045 // in the cloned blocks. We have to do this as a second pass so that we have
1046 // everything available. Also, we have inserted new instructions which may
1047 // include assume intrinsics, so we update the assumption cache while
1048 // processing this.
1049 for (auto *ClonedBB : NewBlocks)
1050 for (Instruction &I : *ClonedBB) {
1051 RemapInstruction(&I, VMap,
1052 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1053 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1054 if (II->getIntrinsicID() == Intrinsic::assume)
1055 AC.registerAssumption(II);
1056 }
1057
Chandler Carruth693eedb2017-11-17 19:58:36 +00001058 // Update any PHI nodes in the cloned successors of the skipped blocks to not
1059 // have spurious incoming values.
1060 for (auto *LoopBB : L.blocks())
Chandler Carruth16529962018-06-25 23:32:54 +00001061 if (SkipBlock(LoopBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001062 for (auto *SuccBB : successors(LoopBB))
1063 if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
1064 for (PHINode &PN : ClonedSuccBB->phis())
1065 PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
1066
Chandler Carruthed296542018-07-09 10:30:48 +00001067 // Remove the cloned parent as a predecessor of any successor we ended up
1068 // cloning other than the unswitched one.
1069 auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
1070 for (auto *SuccBB : successors(ParentBB)) {
1071 if (SuccBB == UnswitchedSuccBB)
1072 continue;
1073
1074 auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
1075 if (!ClonedSuccBB)
1076 continue;
1077
1078 ClonedSuccBB->removePredecessor(ClonedParentBB,
Max Kazantsev20b91892019-02-12 07:09:29 +00001079 /*KeepOneInputPHIs*/ true);
Chandler Carruthed296542018-07-09 10:30:48 +00001080 }
1081
1082 // Replace the cloned branch with an unconditional branch to the cloned
1083 // unswitched successor.
1084 auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
1085 ClonedParentBB->getTerminator()->eraseFromParent();
1086 BranchInst::Create(ClonedSuccBB, ClonedParentBB);
1087
1088 // If there are duplicate entries in the PHI nodes because of multiple edges
1089 // to the unswitched successor, we need to nuke all but one as we replaced it
1090 // with a direct branch.
1091 for (PHINode &PN : ClonedSuccBB->phis()) {
1092 bool Found = false;
1093 // Loop over the incoming operands backwards so we can easily delete as we
1094 // go without invalidating the index.
1095 for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
1096 if (PN.getIncomingBlock(i) != ClonedParentBB)
1097 continue;
1098 if (!Found) {
1099 Found = true;
1100 continue;
1101 }
1102 PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
1103 }
1104 }
1105
Chandler Carruth69e68f82018-04-25 00:18:07 +00001106 // Record the domtree updates for the new blocks.
Chandler Carruth44aab922018-05-01 09:42:09 +00001107 SmallPtrSet<BasicBlock *, 4> SuccSet;
1108 for (auto *ClonedBB : NewBlocks) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001109 for (auto *SuccBB : successors(ClonedBB))
Chandler Carruth44aab922018-05-01 09:42:09 +00001110 if (SuccSet.insert(SuccBB).second)
1111 DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
1112 SuccSet.clear();
1113 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00001114
Chandler Carruth693eedb2017-11-17 19:58:36 +00001115 return ClonedPH;
1116}
1117
1118/// Recursively clone the specified loop and all of its children.
1119///
1120/// The target parent loop for the clone should be provided, or can be null if
1121/// the clone is a top-level loop. While cloning, all the blocks are mapped
1122/// with the provided value map. The entire original loop must be present in
1123/// the value map. The cloned loop is returned.
1124static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
1125 const ValueToValueMapTy &VMap, LoopInfo &LI) {
1126 auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
1127 assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
1128 ClonedL.reserveBlocks(OrigL.getNumBlocks());
1129 for (auto *BB : OrigL.blocks()) {
1130 auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
1131 ClonedL.addBlockEntry(ClonedBB);
Chandler Carruth0ace1482018-04-24 03:27:00 +00001132 if (LI.getLoopFor(BB) == &OrigL)
Chandler Carruth693eedb2017-11-17 19:58:36 +00001133 LI.changeLoopFor(ClonedBB, &ClonedL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001134 }
1135 };
1136
1137 // We specially handle the first loop because it may get cloned into
1138 // a different parent and because we most commonly are cloning leaf loops.
1139 Loop *ClonedRootL = LI.AllocateLoop();
1140 if (RootParentL)
1141 RootParentL->addChildLoop(ClonedRootL);
1142 else
1143 LI.addTopLevelLoop(ClonedRootL);
1144 AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1145
1146 if (OrigRootL.empty())
1147 return ClonedRootL;
1148
1149 // If we have a nest, we can quickly clone the entire loop nest using an
1150 // iterative approach because it is a tree. We keep the cloned parent in the
1151 // data structure to avoid repeatedly querying through a map to find it.
1152 SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1153 // Build up the loops to clone in reverse order as we'll clone them from the
1154 // back.
1155 for (Loop *ChildL : llvm::reverse(OrigRootL))
1156 LoopsToClone.push_back({ClonedRootL, ChildL});
1157 do {
1158 Loop *ClonedParentL, *L;
1159 std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1160 Loop *ClonedL = LI.AllocateLoop();
1161 ClonedParentL->addChildLoop(ClonedL);
1162 AddClonedBlocksToLoop(*L, *ClonedL);
1163 for (Loop *ChildL : llvm::reverse(*L))
1164 LoopsToClone.push_back({ClonedL, ChildL});
1165 } while (!LoopsToClone.empty());
1166
1167 return ClonedRootL;
1168}
1169
1170/// Build the cloned loops of an original loop from unswitching.
1171///
1172/// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1173/// operation. We need to re-verify that there even is a loop (as the backedge
1174/// may not have been cloned), and even if there are remaining backedges the
1175/// backedge set may be different. However, we know that each child loop is
1176/// undisturbed, we only need to find where to place each child loop within
1177/// either any parent loop or within a cloned version of the original loop.
1178///
1179/// Because child loops may end up cloned outside of any cloned version of the
1180/// original loop, multiple cloned sibling loops may be created. All of them
1181/// are returned so that the newly introduced loop nest roots can be
1182/// identified.
Chandler Carruth92815032018-06-02 01:29:01 +00001183static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1184 const ValueToValueMapTy &VMap, LoopInfo &LI,
1185 SmallVectorImpl<Loop *> &NonChildClonedLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00001186 Loop *ClonedL = nullptr;
1187
1188 auto *OrigPH = OrigL.getLoopPreheader();
1189 auto *OrigHeader = OrigL.getHeader();
1190
1191 auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1192 auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1193
1194 // We need to know the loops of the cloned exit blocks to even compute the
1195 // accurate parent loop. If we only clone exits to some parent of the
1196 // original parent, we want to clone into that outer loop. We also keep track
1197 // of the loops that our cloned exit blocks participate in.
1198 Loop *ParentL = nullptr;
1199 SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1200 SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1201 ClonedExitsInLoops.reserve(ExitBlocks.size());
1202 for (auto *ExitBB : ExitBlocks)
1203 if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1204 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1205 ExitLoopMap[ClonedExitBB] = ExitL;
1206 ClonedExitsInLoops.push_back(ClonedExitBB);
1207 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1208 ParentL = ExitL;
1209 }
1210 assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1211 ParentL->contains(OrigL.getParentLoop())) &&
1212 "The computed parent loop should always contain (or be) the parent of "
1213 "the original loop.");
1214
1215 // We build the set of blocks dominated by the cloned header from the set of
1216 // cloned blocks out of the original loop. While not all of these will
1217 // necessarily be in the cloned loop, it is enough to establish that they
1218 // aren't in unreachable cycles, etc.
1219 SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1220 for (auto *BB : OrigL.blocks())
1221 if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1222 ClonedLoopBlocks.insert(ClonedBB);
1223
1224 // Rebuild the set of blocks that will end up in the cloned loop. We may have
1225 // skipped cloning some region of this loop which can in turn skip some of
1226 // the backedges so we have to rebuild the blocks in the loop based on the
1227 // backedges that remain after cloning.
1228 SmallVector<BasicBlock *, 16> Worklist;
1229 SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1230 for (auto *Pred : predecessors(ClonedHeader)) {
1231 // The only possible non-loop header predecessor is the preheader because
1232 // we know we cloned the loop in simplified form.
1233 if (Pred == ClonedPH)
1234 continue;
1235
1236 // Because the loop was in simplified form, the only non-loop predecessor
1237 // should be the preheader.
1238 assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1239 "header other than the preheader "
1240 "that is not part of the loop!");
1241
1242 // Insert this block into the loop set and on the first visit (and if it
1243 // isn't the header we're currently walking) put it into the worklist to
1244 // recurse through.
1245 if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1246 Worklist.push_back(Pred);
1247 }
1248
1249 // If we had any backedges then there *is* a cloned loop. Put the header into
1250 // the loop set and then walk the worklist backwards to find all the blocks
1251 // that remain within the loop after cloning.
1252 if (!BlocksInClonedLoop.empty()) {
1253 BlocksInClonedLoop.insert(ClonedHeader);
1254
1255 while (!Worklist.empty()) {
1256 BasicBlock *BB = Worklist.pop_back_val();
1257 assert(BlocksInClonedLoop.count(BB) &&
1258 "Didn't put block into the loop set!");
1259
1260 // Insert any predecessors that are in the possible set into the cloned
1261 // set, and if the insert is successful, add them to the worklist. Note
1262 // that we filter on the blocks that are definitely reachable via the
1263 // backedge to the loop header so we may prune out dead code within the
1264 // cloned loop.
1265 for (auto *Pred : predecessors(BB))
1266 if (ClonedLoopBlocks.count(Pred) &&
1267 BlocksInClonedLoop.insert(Pred).second)
1268 Worklist.push_back(Pred);
1269 }
1270
1271 ClonedL = LI.AllocateLoop();
1272 if (ParentL) {
1273 ParentL->addBasicBlockToLoop(ClonedPH, LI);
1274 ParentL->addChildLoop(ClonedL);
1275 } else {
1276 LI.addTopLevelLoop(ClonedL);
1277 }
Chandler Carruth92815032018-06-02 01:29:01 +00001278 NonChildClonedLoops.push_back(ClonedL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001279
1280 ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1281 // We don't want to just add the cloned loop blocks based on how we
1282 // discovered them. The original order of blocks was carefully built in
1283 // a way that doesn't rely on predecessor ordering. Rather than re-invent
1284 // that logic, we just re-walk the original blocks (and those of the child
1285 // loops) and filter them as we add them into the cloned loop.
1286 for (auto *BB : OrigL.blocks()) {
1287 auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1288 if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1289 continue;
1290
1291 // Directly add the blocks that are only in this loop.
1292 if (LI.getLoopFor(BB) == &OrigL) {
1293 ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1294 continue;
1295 }
1296
1297 // We want to manually add it to this loop and parents.
1298 // Registering it with LoopInfo will happen when we clone the top
1299 // loop for this block.
1300 for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1301 PL->addBlockEntry(ClonedBB);
1302 }
1303
1304 // Now add each child loop whose header remains within the cloned loop. All
1305 // of the blocks within the loop must satisfy the same constraints as the
1306 // header so once we pass the header checks we can just clone the entire
1307 // child loop nest.
1308 for (Loop *ChildL : OrigL) {
1309 auto *ClonedChildHeader =
1310 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1311 if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1312 continue;
1313
1314#ifndef NDEBUG
1315 // We should never have a cloned child loop header but fail to have
1316 // all of the blocks for that child loop.
1317 for (auto *ChildLoopBB : ChildL->blocks())
1318 assert(BlocksInClonedLoop.count(
1319 cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1320 "Child cloned loop has a header within the cloned outer "
1321 "loop but not all of its blocks!");
1322#endif
1323
1324 cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1325 }
1326 }
1327
1328 // Now that we've handled all the components of the original loop that were
1329 // cloned into a new loop, we still need to handle anything from the original
1330 // loop that wasn't in a cloned loop.
1331
1332 // Figure out what blocks are left to place within any loop nest containing
1333 // the unswitched loop. If we never formed a loop, the cloned PH is one of
1334 // them.
1335 SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1336 if (BlocksInClonedLoop.empty())
1337 UnloopedBlockSet.insert(ClonedPH);
1338 for (auto *ClonedBB : ClonedLoopBlocks)
1339 if (!BlocksInClonedLoop.count(ClonedBB))
1340 UnloopedBlockSet.insert(ClonedBB);
1341
1342 // Copy the cloned exits and sort them in ascending loop depth, we'll work
1343 // backwards across these to process them inside out. The order shouldn't
1344 // matter as we're just trying to build up the map from inside-out; we use
1345 // the map in a more stably ordered way below.
1346 auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
Fangrui Song0cac7262018-09-27 02:13:45 +00001347 llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1348 return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1349 ExitLoopMap.lookup(RHS)->getLoopDepth();
1350 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001351
1352 // Populate the existing ExitLoopMap with everything reachable from each
1353 // exit, starting from the inner most exit.
1354 while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1355 assert(Worklist.empty() && "Didn't clear worklist!");
1356
1357 BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1358 Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1359
1360 // Walk the CFG back until we hit the cloned PH adding everything reachable
1361 // and in the unlooped set to this exit block's loop.
1362 Worklist.push_back(ExitBB);
1363 do {
1364 BasicBlock *BB = Worklist.pop_back_val();
1365 // We can stop recursing at the cloned preheader (if we get there).
1366 if (BB == ClonedPH)
1367 continue;
1368
1369 for (BasicBlock *PredBB : predecessors(BB)) {
1370 // If this pred has already been moved to our set or is part of some
1371 // (inner) loop, no update needed.
1372 if (!UnloopedBlockSet.erase(PredBB)) {
1373 assert(
1374 (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1375 "Predecessor not mapped to a loop!");
1376 continue;
1377 }
1378
1379 // We just insert into the loop set here. We'll add these blocks to the
1380 // exit loop after we build up the set in an order that doesn't rely on
1381 // predecessor order (which in turn relies on use list order).
1382 bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1383 (void)Inserted;
1384 assert(Inserted && "Should only visit an unlooped block once!");
1385
1386 // And recurse through to its predecessors.
1387 Worklist.push_back(PredBB);
1388 }
1389 } while (!Worklist.empty());
1390 }
1391
1392 // Now that the ExitLoopMap gives as mapping for all the non-looping cloned
1393 // blocks to their outer loops, walk the cloned blocks and the cloned exits
1394 // in their original order adding them to the correct loop.
1395
1396 // We need a stable insertion order. We use the order of the original loop
1397 // order and map into the correct parent loop.
1398 for (auto *BB : llvm::concat<BasicBlock *const>(
1399 makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1400 if (Loop *OuterL = ExitLoopMap.lookup(BB))
1401 OuterL->addBasicBlockToLoop(BB, LI);
1402
1403#ifndef NDEBUG
1404 for (auto &BBAndL : ExitLoopMap) {
1405 auto *BB = BBAndL.first;
1406 auto *OuterL = BBAndL.second;
1407 assert(LI.getLoopFor(BB) == OuterL &&
1408 "Failed to put all blocks into outer loops!");
1409 }
1410#endif
1411
1412 // Now that all the blocks are placed into the correct containing loop in the
1413 // absence of child loops, find all the potentially cloned child loops and
1414 // clone them into whatever outer loop we placed their header into.
1415 for (Loop *ChildL : OrigL) {
1416 auto *ClonedChildHeader =
1417 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1418 if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1419 continue;
1420
1421#ifndef NDEBUG
1422 for (auto *ChildLoopBB : ChildL->blocks())
1423 assert(VMap.count(ChildLoopBB) &&
1424 "Cloned a child loop header but not all of that loops blocks!");
1425#endif
1426
1427 NonChildClonedLoops.push_back(cloneLoopNest(
1428 *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1429 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001430}
1431
Chandler Carruth69e68f82018-04-25 00:18:07 +00001432static void
Chandler Carruth16529962018-06-25 23:32:54 +00001433deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1434 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001435 DominatorTree &DT, MemorySSAUpdater *MSSAU) {
Chandler Carruth16529962018-06-25 23:32:54 +00001436 // Find all the dead clones, and remove them from their successors.
1437 SmallVector<BasicBlock *, 16> DeadBlocks;
1438 for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1439 for (auto &VMap : VMaps)
1440 if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
1441 if (!DT.isReachableFromEntry(ClonedBB)) {
1442 for (BasicBlock *SuccBB : successors(ClonedBB))
1443 SuccBB->removePredecessor(ClonedBB);
1444 DeadBlocks.push_back(ClonedBB);
1445 }
1446
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001447 // Remove all MemorySSA in the dead blocks
1448 if (MSSAU) {
1449 SmallPtrSet<BasicBlock *, 16> DeadBlockSet(DeadBlocks.begin(),
1450 DeadBlocks.end());
1451 MSSAU->removeBlocks(DeadBlockSet);
1452 }
1453
Chandler Carruth16529962018-06-25 23:32:54 +00001454 // Drop any remaining references to break cycles.
1455 for (BasicBlock *BB : DeadBlocks)
1456 BB->dropAllReferences();
1457 // Erase them from the IR.
1458 for (BasicBlock *BB : DeadBlocks)
1459 BB->eraseFromParent();
1460}
1461
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001462static void deleteDeadBlocksFromLoop(Loop &L,
1463 SmallVectorImpl<BasicBlock *> &ExitBlocks,
1464 DominatorTree &DT, LoopInfo &LI,
1465 MemorySSAUpdater *MSSAU) {
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001466 // Find all the dead blocks tied to this loop, and remove them from their
1467 // successors.
1468 SmallPtrSet<BasicBlock *, 16> DeadBlockSet;
1469
1470 // Start with loop/exit blocks and get a transitive closure of reachable dead
1471 // blocks.
1472 SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(),
1473 ExitBlocks.end());
1474 DeathCandidates.append(L.blocks().begin(), L.blocks().end());
1475 while (!DeathCandidates.empty()) {
1476 auto *BB = DeathCandidates.pop_back_val();
1477 if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) {
1478 for (BasicBlock *SuccBB : successors(BB)) {
Chandler Carruth16529962018-06-25 23:32:54 +00001479 SuccBB->removePredecessor(BB);
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001480 DeathCandidates.push_back(SuccBB);
Fedor Sergeev7b49aa02018-08-29 19:10:44 +00001481 }
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001482 DeadBlockSet.insert(BB);
1483 }
1484 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001485
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001486 // Remove all MemorySSA in the dead blocks
1487 if (MSSAU)
1488 MSSAU->removeBlocks(DeadBlockSet);
1489
Chandler Carruth693eedb2017-11-17 19:58:36 +00001490 // Filter out the dead blocks from the exit blocks list so that it can be
1491 // used in the caller.
1492 llvm::erase_if(ExitBlocks,
Chandler Carruth69e68f82018-04-25 00:18:07 +00001493 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001494
Chandler Carruth693eedb2017-11-17 19:58:36 +00001495 // Walk from this loop up through its parents removing all of the dead blocks.
1496 for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001497 for (auto *BB : DeadBlockSet)
Chandler Carruth693eedb2017-11-17 19:58:36 +00001498 ParentL->getBlocksSet().erase(BB);
1499 llvm::erase_if(ParentL->getBlocksVector(),
Chandler Carruth69e68f82018-04-25 00:18:07 +00001500 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001501 }
1502
1503 // Now delete the dead child loops. This raw delete will clear them
1504 // recursively.
1505 llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001506 if (!DeadBlockSet.count(ChildL->getHeader()))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001507 return false;
1508
1509 assert(llvm::all_of(ChildL->blocks(),
1510 [&](BasicBlock *ChildBB) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001511 return DeadBlockSet.count(ChildBB);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001512 }) &&
1513 "If the child loop header is dead all blocks in the child loop must "
1514 "be dead as well!");
1515 LI.destroy(ChildL);
1516 return true;
1517 });
1518
Chandler Carruth69e68f82018-04-25 00:18:07 +00001519 // Remove the loop mappings for the dead blocks and drop all the references
1520 // from these blocks to others to handle cyclic references as we start
1521 // deleting the blocks themselves.
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001522 for (auto *BB : DeadBlockSet) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001523 // Check that the dominator tree has already been updated.
1524 assert(!DT.getNode(BB) && "Should already have cleared domtree!");
Chandler Carruth693eedb2017-11-17 19:58:36 +00001525 LI.changeLoopFor(BB, nullptr);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001526 BB->dropAllReferences();
Chandler Carruth693eedb2017-11-17 19:58:36 +00001527 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00001528
1529 // Actually delete the blocks now that they've been fully unhooked from the
1530 // IR.
Fedor Sergeev7b49aa02018-08-29 19:10:44 +00001531 for (auto *BB : DeadBlockSet)
Chandler Carruth69e68f82018-04-25 00:18:07 +00001532 BB->eraseFromParent();
Chandler Carruth693eedb2017-11-17 19:58:36 +00001533}
1534
1535/// Recompute the set of blocks in a loop after unswitching.
1536///
1537/// This walks from the original headers predecessors to rebuild the loop. We
1538/// take advantage of the fact that new blocks can't have been added, and so we
1539/// filter by the original loop's blocks. This also handles potentially
1540/// unreachable code that we don't want to explore but might be found examining
1541/// the predecessors of the header.
1542///
1543/// If the original loop is no longer a loop, this will return an empty set. If
1544/// it remains a loop, all the blocks within it will be added to the set
1545/// (including those blocks in inner loops).
1546static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1547 LoopInfo &LI) {
1548 SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1549
1550 auto *PH = L.getLoopPreheader();
1551 auto *Header = L.getHeader();
1552
1553 // A worklist to use while walking backwards from the header.
1554 SmallVector<BasicBlock *, 16> Worklist;
1555
1556 // First walk the predecessors of the header to find the backedges. This will
1557 // form the basis of our walk.
1558 for (auto *Pred : predecessors(Header)) {
1559 // Skip the preheader.
1560 if (Pred == PH)
1561 continue;
1562
1563 // Because the loop was in simplified form, the only non-loop predecessor
1564 // is the preheader.
1565 assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1566 "than the preheader that is not part of the "
1567 "loop!");
1568
1569 // Insert this block into the loop set and on the first visit and, if it
1570 // isn't the header we're currently walking, put it into the worklist to
1571 // recurse through.
1572 if (LoopBlockSet.insert(Pred).second && Pred != Header)
1573 Worklist.push_back(Pred);
1574 }
1575
1576 // If no backedges were found, we're done.
1577 if (LoopBlockSet.empty())
1578 return LoopBlockSet;
1579
Chandler Carruth693eedb2017-11-17 19:58:36 +00001580 // We found backedges, recurse through them to identify the loop blocks.
1581 while (!Worklist.empty()) {
1582 BasicBlock *BB = Worklist.pop_back_val();
1583 assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1584
Chandler Carruth43acdb32018-04-24 10:33:08 +00001585 // No need to walk past the header.
1586 if (BB == Header)
1587 continue;
1588
Chandler Carruth693eedb2017-11-17 19:58:36 +00001589 // Because we know the inner loop structure remains valid we can use the
1590 // loop structure to jump immediately across the entire nested loop.
1591 // Further, because it is in loop simplified form, we can directly jump
1592 // to its preheader afterward.
1593 if (Loop *InnerL = LI.getLoopFor(BB))
1594 if (InnerL != &L) {
1595 assert(L.contains(InnerL) &&
1596 "Should not reach a loop *outside* this loop!");
1597 // The preheader is the only possible predecessor of the loop so
1598 // insert it into the set and check whether it was already handled.
1599 auto *InnerPH = InnerL->getLoopPreheader();
1600 assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1601 "but not contain the inner loop "
1602 "preheader!");
1603 if (!LoopBlockSet.insert(InnerPH).second)
1604 // The only way to reach the preheader is through the loop body
1605 // itself so if it has been visited the loop is already handled.
1606 continue;
1607
1608 // Insert all of the blocks (other than those already present) into
Chandler Carruthbf7190a2018-04-23 06:58:36 +00001609 // the loop set. We expect at least the block that led us to find the
1610 // inner loop to be in the block set, but we may also have other loop
1611 // blocks if they were already enqueued as predecessors of some other
1612 // outer loop block.
Chandler Carruth693eedb2017-11-17 19:58:36 +00001613 for (auto *InnerBB : InnerL->blocks()) {
1614 if (InnerBB == BB) {
1615 assert(LoopBlockSet.count(InnerBB) &&
1616 "Block should already be in the set!");
1617 continue;
1618 }
1619
Chandler Carruthbf7190a2018-04-23 06:58:36 +00001620 LoopBlockSet.insert(InnerBB);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001621 }
1622
1623 // Add the preheader to the worklist so we will continue past the
1624 // loop body.
1625 Worklist.push_back(InnerPH);
1626 continue;
1627 }
1628
1629 // Insert any predecessors that were in the original loop into the new
1630 // set, and if the insert is successful, add them to the worklist.
1631 for (auto *Pred : predecessors(BB))
1632 if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1633 Worklist.push_back(Pred);
1634 }
1635
Chandler Carruth43acdb32018-04-24 10:33:08 +00001636 assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
1637
Chandler Carruth693eedb2017-11-17 19:58:36 +00001638 // We've found all the blocks participating in the loop, return our completed
1639 // set.
1640 return LoopBlockSet;
1641}
1642
1643/// Rebuild a loop after unswitching removes some subset of blocks and edges.
1644///
1645/// The removal may have removed some child loops entirely but cannot have
1646/// disturbed any remaining child loops. However, they may need to be hoisted
1647/// to the parent loop (or to be top-level loops). The original loop may be
1648/// completely removed.
1649///
1650/// The sibling loops resulting from this update are returned. If the original
1651/// loop remains a valid loop, it will be the first entry in this list with all
1652/// of the newly sibling loops following it.
1653///
1654/// Returns true if the loop remains a loop after unswitching, and false if it
1655/// is no longer a loop after unswitching (and should not continue to be
1656/// referenced).
1657static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1658 LoopInfo &LI,
1659 SmallVectorImpl<Loop *> &HoistedLoops) {
1660 auto *PH = L.getLoopPreheader();
1661
1662 // Compute the actual parent loop from the exit blocks. Because we may have
1663 // pruned some exits the loop may be different from the original parent.
1664 Loop *ParentL = nullptr;
1665 SmallVector<Loop *, 4> ExitLoops;
1666 SmallVector<BasicBlock *, 4> ExitsInLoops;
1667 ExitsInLoops.reserve(ExitBlocks.size());
1668 for (auto *ExitBB : ExitBlocks)
1669 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1670 ExitLoops.push_back(ExitL);
1671 ExitsInLoops.push_back(ExitBB);
1672 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1673 ParentL = ExitL;
1674 }
1675
1676 // Recompute the blocks participating in this loop. This may be empty if it
1677 // is no longer a loop.
1678 auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1679
1680 // If we still have a loop, we need to re-set the loop's parent as the exit
1681 // block set changing may have moved it within the loop nest. Note that this
1682 // can only happen when this loop has a parent as it can only hoist the loop
1683 // *up* the nest.
1684 if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1685 // Remove this loop's (original) blocks from all of the intervening loops.
1686 for (Loop *IL = L.getParentLoop(); IL != ParentL;
1687 IL = IL->getParentLoop()) {
1688 IL->getBlocksSet().erase(PH);
1689 for (auto *BB : L.blocks())
1690 IL->getBlocksSet().erase(BB);
1691 llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1692 return BB == PH || L.contains(BB);
1693 });
1694 }
1695
1696 LI.changeLoopFor(PH, ParentL);
1697 L.getParentLoop()->removeChildLoop(&L);
1698 if (ParentL)
1699 ParentL->addChildLoop(&L);
1700 else
1701 LI.addTopLevelLoop(&L);
1702 }
1703
1704 // Now we update all the blocks which are no longer within the loop.
1705 auto &Blocks = L.getBlocksVector();
1706 auto BlocksSplitI =
1707 LoopBlockSet.empty()
1708 ? Blocks.begin()
1709 : std::stable_partition(
1710 Blocks.begin(), Blocks.end(),
1711 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1712
1713 // Before we erase the list of unlooped blocks, build a set of them.
1714 SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1715 if (LoopBlockSet.empty())
1716 UnloopedBlocks.insert(PH);
1717
1718 // Now erase these blocks from the loop.
1719 for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1720 L.getBlocksSet().erase(BB);
1721 Blocks.erase(BlocksSplitI, Blocks.end());
1722
1723 // Sort the exits in ascending loop depth, we'll work backwards across these
1724 // to process them inside out.
Fangrui Songefd94c52019-04-23 14:51:27 +00001725 llvm::stable_sort(ExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1726 return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1727 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001728
1729 // We'll build up a set for each exit loop.
1730 SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1731 Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1732
1733 auto RemoveUnloopedBlocksFromLoop =
1734 [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1735 for (auto *BB : UnloopedBlocks)
1736 L.getBlocksSet().erase(BB);
1737 llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1738 return UnloopedBlocks.count(BB);
1739 });
1740 };
1741
1742 SmallVector<BasicBlock *, 16> Worklist;
1743 while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1744 assert(Worklist.empty() && "Didn't clear worklist!");
1745 assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1746
1747 // Grab the next exit block, in decreasing loop depth order.
1748 BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1749 Loop &ExitL = *LI.getLoopFor(ExitBB);
1750 assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1751
1752 // Erase all of the unlooped blocks from the loops between the previous
1753 // exit loop and this exit loop. This works because the ExitInLoops list is
1754 // sorted in increasing order of loop depth and thus we visit loops in
1755 // decreasing order of loop depth.
1756 for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1757 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1758
1759 // Walk the CFG back until we hit the cloned PH adding everything reachable
1760 // and in the unlooped set to this exit block's loop.
1761 Worklist.push_back(ExitBB);
1762 do {
1763 BasicBlock *BB = Worklist.pop_back_val();
1764 // We can stop recursing at the cloned preheader (if we get there).
1765 if (BB == PH)
1766 continue;
1767
1768 for (BasicBlock *PredBB : predecessors(BB)) {
1769 // If this pred has already been moved to our set or is part of some
1770 // (inner) loop, no update needed.
1771 if (!UnloopedBlocks.erase(PredBB)) {
1772 assert((NewExitLoopBlocks.count(PredBB) ||
1773 ExitL.contains(LI.getLoopFor(PredBB))) &&
1774 "Predecessor not in a nested loop (or already visited)!");
1775 continue;
1776 }
1777
1778 // We just insert into the loop set here. We'll add these blocks to the
1779 // exit loop after we build up the set in a deterministic order rather
1780 // than the predecessor-influenced visit order.
1781 bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1782 (void)Inserted;
1783 assert(Inserted && "Should only visit an unlooped block once!");
1784
1785 // And recurse through to its predecessors.
1786 Worklist.push_back(PredBB);
1787 }
1788 } while (!Worklist.empty());
1789
1790 // If blocks in this exit loop were directly part of the original loop (as
1791 // opposed to a child loop) update the map to point to this exit loop. This
1792 // just updates a map and so the fact that the order is unstable is fine.
1793 for (auto *BB : NewExitLoopBlocks)
1794 if (Loop *BBL = LI.getLoopFor(BB))
1795 if (BBL == &L || !L.contains(BBL))
1796 LI.changeLoopFor(BB, &ExitL);
1797
1798 // We will remove the remaining unlooped blocks from this loop in the next
1799 // iteration or below.
1800 NewExitLoopBlocks.clear();
1801 }
1802
1803 // Any remaining unlooped blocks are no longer part of any loop unless they
1804 // are part of some child loop.
1805 for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1806 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1807 for (auto *BB : UnloopedBlocks)
1808 if (Loop *BBL = LI.getLoopFor(BB))
1809 if (BBL == &L || !L.contains(BBL))
1810 LI.changeLoopFor(BB, nullptr);
1811
1812 // Sink all the child loops whose headers are no longer in the loop set to
1813 // the parent (or to be top level loops). We reach into the loop and directly
1814 // update its subloop vector to make this batch update efficient.
1815 auto &SubLoops = L.getSubLoopsVector();
1816 auto SubLoopsSplitI =
1817 LoopBlockSet.empty()
1818 ? SubLoops.begin()
1819 : std::stable_partition(
1820 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1821 return LoopBlockSet.count(SubL->getHeader());
1822 });
1823 for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1824 HoistedLoops.push_back(HoistedL);
1825 HoistedL->setParentLoop(nullptr);
1826
1827 // To compute the new parent of this hoisted loop we look at where we
1828 // placed the preheader above. We can't lookup the header itself because we
1829 // retained the mapping from the header to the hoisted loop. But the
1830 // preheader and header should have the exact same new parent computed
1831 // based on the set of exit blocks from the original loop as the preheader
1832 // is a predecessor of the header and so reached in the reverse walk. And
1833 // because the loops were all in simplified form the preheader of the
1834 // hoisted loop can't be part of some *other* loop.
1835 if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1836 NewParentL->addChildLoop(HoistedL);
1837 else
1838 LI.addTopLevelLoop(HoistedL);
1839 }
1840 SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1841
1842 // Actually delete the loop if nothing remained within it.
1843 if (Blocks.empty()) {
1844 assert(SubLoops.empty() &&
1845 "Failed to remove all subloops from the original loop!");
1846 if (Loop *ParentL = L.getParentLoop())
1847 ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1848 else
1849 LI.removeLoop(llvm::find(LI, &L));
1850 LI.destroy(&L);
1851 return false;
1852 }
1853
1854 return true;
1855}
1856
1857/// Helper to visit a dominator subtree, invoking a callable on each node.
1858///
1859/// Returning false at any point will stop walking past that node of the tree.
1860template <typename CallableT>
1861void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1862 SmallVector<DomTreeNode *, 4> DomWorklist;
1863 DomWorklist.push_back(DT[BB]);
1864#ifndef NDEBUG
1865 SmallPtrSet<DomTreeNode *, 4> Visited;
1866 Visited.insert(DT[BB]);
1867#endif
1868 do {
1869 DomTreeNode *N = DomWorklist.pop_back_val();
1870
1871 // Visit this node.
1872 if (!Callable(N->getBlock()))
1873 continue;
1874
1875 // Accumulate the child nodes.
1876 for (DomTreeNode *ChildN : *N) {
1877 assert(Visited.insert(ChildN).second &&
1878 "Cannot visit a node twice when walking a tree!");
1879 DomWorklist.push_back(ChildN);
1880 }
1881 } while (!DomWorklist.empty());
1882}
1883
Max Kazantsevbde31002018-10-26 09:52:58 +00001884static void unswitchNontrivialInvariants(
Chandler Carruth60b2e052018-10-18 00:40:26 +00001885 Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
Max Kazantsevbde31002018-10-26 09:52:58 +00001886 SmallVectorImpl<BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI,
1887 AssumptionCache &AC, function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001888 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruth16529962018-06-25 23:32:54 +00001889 auto *ParentBB = TI.getParent();
1890 BranchInst *BI = dyn_cast<BranchInst>(&TI);
1891 SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001892
Chandler Carruth16529962018-06-25 23:32:54 +00001893 // We can only unswitch switches, conditional branches with an invariant
1894 // condition, or combining invariant conditions with an instruction.
1895 assert((SI || BI->isConditional()) &&
1896 "Can only unswitch switches and conditional branch!");
1897 bool FullUnswitch = SI || BI->getCondition() == Invariants[0];
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001898 if (FullUnswitch)
1899 assert(Invariants.size() == 1 &&
1900 "Cannot have other invariants with full unswitching!");
1901 else
Chandler Carruth16529962018-06-25 23:32:54 +00001902 assert(isa<Instruction>(BI->getCondition()) &&
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001903 "Partial unswitching requires an instruction as the condition!");
1904
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001905 if (MSSAU && VerifyMemorySSA)
1906 MSSAU->getMemorySSA()->verifyMemorySSA();
1907
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001908 // Constant and BBs tracking the cloned and continuing successor. When we are
1909 // unswitching the entire condition, this can just be trivially chosen to
1910 // unswitch towards `true`. However, when we are unswitching a set of
1911 // invariants combined with `and` or `or`, the combining operation determines
1912 // the best direction to unswitch: we want to unswitch the direction that will
1913 // collapse the branch.
1914 bool Direction = true;
1915 int ClonedSucc = 0;
1916 if (!FullUnswitch) {
Chandler Carruth16529962018-06-25 23:32:54 +00001917 if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) {
1918 assert(cast<Instruction>(BI->getCondition())->getOpcode() ==
1919 Instruction::And &&
1920 "Only `or` and `and` instructions can combine invariants being "
1921 "unswitched.");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001922 Direction = false;
1923 ClonedSucc = 1;
1924 }
1925 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001926
Chandler Carruth16529962018-06-25 23:32:54 +00001927 BasicBlock *RetainedSuccBB =
1928 BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
1929 SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
1930 if (BI)
1931 UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
1932 else
1933 for (auto Case : SI->cases())
Chandler Carruthed296542018-07-09 10:30:48 +00001934 if (Case.getCaseSuccessor() != RetainedSuccBB)
1935 UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
Chandler Carruth16529962018-06-25 23:32:54 +00001936
1937 assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
1938 "Should not unswitch the same successor we are retaining!");
Chandler Carruth693eedb2017-11-17 19:58:36 +00001939
1940 // The branch should be in this exact loop. Any inner loop's invariant branch
1941 // should be handled by unswitching that inner loop. The caller of this
1942 // routine should filter out any candidates that remain (but were skipped for
1943 // whatever reason).
1944 assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
1945
Chandler Carruth693eedb2017-11-17 19:58:36 +00001946 // Compute the parent loop now before we start hacking on things.
1947 Loop *ParentL = L.getParentLoop();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001948 // Get blocks in RPO order for MSSA update, before changing the CFG.
1949 LoopBlocksRPO LBRPO(&L);
1950 if (MSSAU)
1951 LBRPO.perform(&LI);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001952
1953 // Compute the outer-most loop containing one of our exit blocks. This is the
1954 // furthest up our loopnest which can be mutated, which we will use below to
1955 // update things.
1956 Loop *OuterExitL = &L;
1957 for (auto *ExitBB : ExitBlocks) {
1958 Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
1959 if (!NewOuterExitL) {
1960 // We exited the entire nest with this block, so we're done.
1961 OuterExitL = nullptr;
1962 break;
1963 }
1964 if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
1965 OuterExitL = NewOuterExitL;
1966 }
1967
Chandler Carruth3897ded2018-07-03 09:13:27 +00001968 // At this point, we're definitely going to unswitch something so invalidate
1969 // any cached information in ScalarEvolution for the outer most loop
1970 // containing an exit block and all nested loops.
1971 if (SE) {
1972 if (OuterExitL)
1973 SE->forgetLoop(OuterExitL);
1974 else
1975 SE->forgetTopmostLoop(&L);
1976 }
1977
Chandler Carruth16529962018-06-25 23:32:54 +00001978 // If the edge from this terminator to a successor dominates that successor,
1979 // store a map from each block in its dominator subtree to it. This lets us
1980 // tell when cloning for a particular successor if a block is dominated by
1981 // some *other* successor with a single data structure. We use this to
1982 // significantly reduce cloning.
1983 SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
1984 for (auto *SuccBB : llvm::concat<BasicBlock *const>(
1985 makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
1986 if (SuccBB->getUniquePredecessor() ||
1987 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
1988 return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
1989 }))
1990 visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
1991 DominatingSucc[BB] = SuccBB;
1992 return true;
1993 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001994
1995 // Split the preheader, so that we know that there is a safe place to insert
1996 // the conditional branch. We will change the preheader to have a conditional
1997 // branch on LoopCond. The original preheader will become the split point
1998 // between the unswitched versions, and we will have a new preheader for the
1999 // original loop.
2000 BasicBlock *SplitBB = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002001 BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002002
Chandler Carruth69e68f82018-04-25 00:18:07 +00002003 // Keep track of the dominator tree updates needed.
2004 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2005
Chandler Carruth16529962018-06-25 23:32:54 +00002006 // Clone the loop for each unswitched successor.
2007 SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
2008 VMaps.reserve(UnswitchedSuccBBs.size());
2009 SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
2010 for (auto *SuccBB : UnswitchedSuccBBs) {
2011 VMaps.emplace_back(new ValueToValueMapTy());
2012 ClonedPHs[SuccBB] = buildClonedLoopBlocks(
2013 L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002014 DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU);
Chandler Carruth16529962018-06-25 23:32:54 +00002015 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002016
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002017 // The stitching of the branched code back together depends on whether we're
2018 // doing full unswitching or not with the exception that we always want to
2019 // nuke the initial terminator placed in the split block.
Chandler Carruth693eedb2017-11-17 19:58:36 +00002020 SplitBB->getTerminator()->eraseFromParent();
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002021 if (FullUnswitch) {
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002022 // Splice the terminator from the original loop and rewrite its
2023 // successors.
2024 SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
2025
2026 // Keep a clone of the terminator for MSSA updates.
2027 Instruction *NewTI = TI.clone();
2028 ParentBB->getInstList().push_back(NewTI);
2029
2030 // First wire up the moved terminator to the preheaders.
2031 if (BI) {
2032 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2033 BI->setSuccessor(ClonedSucc, ClonedPH);
2034 BI->setSuccessor(1 - ClonedSucc, LoopPH);
2035 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2036 } else {
2037 assert(SI && "Must either be a branch or switch!");
2038
2039 // Walk the cases and directly update their successors.
2040 assert(SI->getDefaultDest() == RetainedSuccBB &&
2041 "Not retaining default successor!");
2042 SI->setDefaultDest(LoopPH);
2043 for (auto &Case : SI->cases())
2044 if (Case.getCaseSuccessor() == RetainedSuccBB)
2045 Case.setSuccessor(LoopPH);
2046 else
2047 Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
2048
2049 // We need to use the set to populate domtree updates as even when there
2050 // are multiple cases pointing at the same successor we only want to
2051 // remove and insert one edge in the domtree.
2052 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2053 DTUpdates.push_back(
2054 {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
2055 }
2056
2057 if (MSSAU) {
2058 DT.applyUpdates(DTUpdates);
2059 DTUpdates.clear();
2060
2061 // Remove all but one edge to the retained block and all unswitched
2062 // blocks. This is to avoid having duplicate entries in the cloned Phis,
2063 // when we know we only keep a single edge for each case.
2064 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
2065 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2066 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
2067
2068 for (auto &VMap : VMaps)
2069 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2070 /*IgnoreIncomingWithNoClones=*/true);
2071 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2072
2073 // Remove all edges to unswitched blocks.
2074 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2075 MSSAU->removeEdge(ParentBB, SuccBB);
2076 }
2077
2078 // Now unhook the successor relationship as we'll be replacing
Chandler Carruthed296542018-07-09 10:30:48 +00002079 // the terminator with a direct branch. This is much simpler for branches
2080 // than switches so we handle those first.
Chandler Carruth16529962018-06-25 23:32:54 +00002081 if (BI) {
Chandler Carruthed296542018-07-09 10:30:48 +00002082 // Remove the parent as a predecessor of the unswitched successor.
Chandler Carruth16529962018-06-25 23:32:54 +00002083 assert(UnswitchedSuccBBs.size() == 1 &&
2084 "Only one possible unswitched block for a branch!");
Chandler Carruthed296542018-07-09 10:30:48 +00002085 BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
2086 UnswitchedSuccBB->removePredecessor(ParentBB,
Max Kazantsev20b91892019-02-12 07:09:29 +00002087 /*KeepOneInputPHIs*/ true);
Chandler Carruthed296542018-07-09 10:30:48 +00002088 DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
2089 } else {
2090 // Note that we actually want to remove the parent block as a predecessor
2091 // of *every* case successor. The case successor is either unswitched,
2092 // completely eliminating an edge from the parent to that successor, or it
2093 // is a duplicate edge to the retained successor as the retained successor
2094 // is always the default successor and as we'll replace this with a direct
2095 // branch we no longer need the duplicate entries in the PHI nodes.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002096 SwitchInst *NewSI = cast<SwitchInst>(NewTI);
2097 assert(NewSI->getDefaultDest() == RetainedSuccBB &&
Chandler Carruthed296542018-07-09 10:30:48 +00002098 "Not retaining default successor!");
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002099 for (auto &Case : NewSI->cases())
Chandler Carruthed296542018-07-09 10:30:48 +00002100 Case.getCaseSuccessor()->removePredecessor(
2101 ParentBB,
Max Kazantsev20b91892019-02-12 07:09:29 +00002102 /*KeepOneInputPHIs*/ true);
Chandler Carruthed296542018-07-09 10:30:48 +00002103
2104 // We need to use the set to populate domtree updates as even when there
2105 // are multiple cases pointing at the same successor we only want to
2106 // remove and insert one edge in the domtree.
2107 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2108 DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
2109 }
2110
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002111 // After MSSAU update, remove the cloned terminator instruction NewTI.
2112 ParentBB->getTerminator()->eraseFromParent();
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002113
2114 // Create a new unconditional branch to the continuing block (as opposed to
2115 // the one cloned).
Chandler Carruth16529962018-06-25 23:32:54 +00002116 BranchInst::Create(RetainedSuccBB, ParentBB);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002117 } else {
Chandler Carruth16529962018-06-25 23:32:54 +00002118 assert(BI && "Only branches have partial unswitching.");
2119 assert(UnswitchedSuccBBs.size() == 1 &&
2120 "Only one possible unswitched block for a branch!");
2121 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002122 // When doing a partial unswitch, we have to do a bit more work to build up
2123 // the branch in the split block.
2124 buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
2125 *ClonedPH, *LoopPH);
Chandler Carruth16529962018-06-25 23:32:54 +00002126 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002127 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002128
Chandler Carruth16529962018-06-25 23:32:54 +00002129 // Apply the updates accumulated above to get an up-to-date dominator tree.
Chandler Carruth69e68f82018-04-25 00:18:07 +00002130 DT.applyUpdates(DTUpdates);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002131 if (!FullUnswitch && MSSAU) {
2132 // Update MSSA for partial unswitch, after DT update.
2133 SmallVector<CFGUpdate, 1> Updates;
2134 Updates.push_back(
2135 {cfg::UpdateKind::Insert, SplitBB, ClonedPHs.begin()->second});
2136 MSSAU->applyInsertUpdates(Updates, DT);
2137 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00002138
Chandler Carruth16529962018-06-25 23:32:54 +00002139 // Now that we have an accurate dominator tree, first delete the dead cloned
2140 // blocks so that we can accurately build any cloned loops. It is important to
2141 // not delete the blocks from the original loop yet because we still want to
2142 // reference the original loop to understand the cloned loop's structure.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002143 deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
Chandler Carruth16529962018-06-25 23:32:54 +00002144
Chandler Carruth69e68f82018-04-25 00:18:07 +00002145 // Build the cloned loop structure itself. This may be substantially
2146 // different from the original structure due to the simplified CFG. This also
2147 // handles inserting all the cloned blocks into the correct loops.
2148 SmallVector<Loop *, 4> NonChildClonedLoops;
Chandler Carruth16529962018-06-25 23:32:54 +00002149 for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2150 buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
Chandler Carruth69e68f82018-04-25 00:18:07 +00002151
Chandler Carruth16529962018-06-25 23:32:54 +00002152 // Now that our cloned loops have been built, we can update the original loop.
2153 // First we delete the dead blocks from it and then we rebuild the loop
2154 // structure taking these deletions into account.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002155 deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU);
2156
2157 if (MSSAU && VerifyMemorySSA)
2158 MSSAU->getMemorySSA()->verifyMemorySSA();
2159
Chandler Carruth693eedb2017-11-17 19:58:36 +00002160 SmallVector<Loop *, 4> HoistedLoops;
2161 bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
2162
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002163 if (MSSAU && VerifyMemorySSA)
2164 MSSAU->getMemorySSA()->verifyMemorySSA();
2165
Chandler Carruth69e68f82018-04-25 00:18:07 +00002166 // This transformation has a high risk of corrupting the dominator tree, and
2167 // the below steps to rebuild loop structures will result in hard to debug
2168 // errors in that case so verify that the dominator tree is sane first.
2169 // FIXME: Remove this when the bugs stop showing up and rely on existing
2170 // verification steps.
2171 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruth693eedb2017-11-17 19:58:36 +00002172
Chandler Carruth16529962018-06-25 23:32:54 +00002173 if (BI) {
2174 // If we unswitched a branch which collapses the condition to a known
2175 // constant we want to replace all the uses of the invariants within both
2176 // the original and cloned blocks. We do this here so that we can use the
2177 // now updated dominator tree to identify which side the users are on.
2178 assert(UnswitchedSuccBBs.size() == 1 &&
2179 "Only one possible unswitched block for a branch!");
2180 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
Fedor Sergeevf9a02a72018-11-07 20:05:11 +00002181
2182 // When considering multiple partially-unswitched invariants
2183 // we cant just go replace them with constants in both branches.
2184 //
2185 // For 'AND' we infer that true branch ("continue") means true
2186 // for each invariant operand.
2187 // For 'OR' we can infer that false branch ("continue") means false
2188 // for each invariant operand.
2189 // So it happens that for multiple-partial case we dont replace
2190 // in the unswitched branch.
2191 bool ReplaceUnswitched = FullUnswitch || (Invariants.size() == 1);
2192
Chandler Carruth16529962018-06-25 23:32:54 +00002193 ConstantInt *UnswitchedReplacement =
2194 Direction ? ConstantInt::getTrue(BI->getContext())
2195 : ConstantInt::getFalse(BI->getContext());
2196 ConstantInt *ContinueReplacement =
2197 Direction ? ConstantInt::getFalse(BI->getContext())
2198 : ConstantInt::getTrue(BI->getContext());
2199 for (Value *Invariant : Invariants)
2200 for (auto UI = Invariant->use_begin(), UE = Invariant->use_end();
2201 UI != UE;) {
2202 // Grab the use and walk past it so we can clobber it in the use list.
2203 Use *U = &*UI++;
2204 Instruction *UserI = dyn_cast<Instruction>(U->getUser());
2205 if (!UserI)
2206 continue;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002207
Chandler Carruth16529962018-06-25 23:32:54 +00002208 // Replace it with the 'continue' side if in the main loop body, and the
2209 // unswitched if in the cloned blocks.
2210 if (DT.dominates(LoopPH, UserI->getParent()))
2211 U->set(ContinueReplacement);
Fedor Sergeevf9a02a72018-11-07 20:05:11 +00002212 else if (ReplaceUnswitched &&
2213 DT.dominates(ClonedPH, UserI->getParent()))
Chandler Carruth16529962018-06-25 23:32:54 +00002214 U->set(UnswitchedReplacement);
2215 }
2216 }
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002217
Chandler Carruth693eedb2017-11-17 19:58:36 +00002218 // We can change which blocks are exit blocks of all the cloned sibling
2219 // loops, the current loop, and any parent loops which shared exit blocks
2220 // with the current loop. As a consequence, we need to re-form LCSSA for
2221 // them. But we shouldn't need to re-form LCSSA for any child loops.
2222 // FIXME: This could be made more efficient by tracking which exit blocks are
2223 // new, and focusing on them, but that isn't likely to be necessary.
2224 //
2225 // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2226 // loop nest and update every loop that could have had its exits changed. We
2227 // also need to cover any intervening loops. We add all of these loops to
2228 // a list and sort them by loop depth to achieve this without updating
2229 // unnecessary loops.
Chandler Carruth92815032018-06-02 01:29:01 +00002230 auto UpdateLoop = [&](Loop &UpdateL) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002231#ifndef NDEBUG
Chandler Carruth43acdb32018-04-24 10:33:08 +00002232 UpdateL.verifyLoop();
2233 for (Loop *ChildL : UpdateL) {
2234 ChildL->verifyLoop();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002235 assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2236 "Perturbed a child loop's LCSSA form!");
Chandler Carruth43acdb32018-04-24 10:33:08 +00002237 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002238#endif
Chandler Carruth92815032018-06-02 01:29:01 +00002239 // First build LCSSA for this loop so that we can preserve it when
2240 // forming dedicated exits. We don't want to perturb some other loop's
2241 // LCSSA while doing that CFG edit.
Chandler Carruth693eedb2017-11-17 19:58:36 +00002242 formLCSSA(UpdateL, DT, &LI, nullptr);
Chandler Carruth92815032018-06-02 01:29:01 +00002243
2244 // For loops reached by this loop's original exit blocks we may
2245 // introduced new, non-dedicated exits. At least try to re-form dedicated
2246 // exits for these loops. This may fail if they couldn't have dedicated
2247 // exits to start with.
Alina Sbirlea97468e92019-02-21 21:13:34 +00002248 formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002249 };
2250
2251 // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2252 // and we can do it in any order as they don't nest relative to each other.
Chandler Carruth92815032018-06-02 01:29:01 +00002253 //
2254 // Also check if any of the loops we have updated have become top-level loops
2255 // as that will necessitate widening the outer loop scope.
2256 for (Loop *UpdatedL :
2257 llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2258 UpdateLoop(*UpdatedL);
2259 if (!UpdatedL->getParentLoop())
2260 OuterExitL = nullptr;
2261 }
2262 if (IsStillLoop) {
2263 UpdateLoop(L);
2264 if (!L.getParentLoop())
2265 OuterExitL = nullptr;
2266 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002267
2268 // If the original loop had exit blocks, walk up through the outer most loop
2269 // of those exit blocks to update LCSSA and form updated dedicated exits.
Chandler Carruth92815032018-06-02 01:29:01 +00002270 if (OuterExitL != &L)
Chandler Carruth693eedb2017-11-17 19:58:36 +00002271 for (Loop *OuterL = ParentL; OuterL != OuterExitL;
2272 OuterL = OuterL->getParentLoop())
Chandler Carruth92815032018-06-02 01:29:01 +00002273 UpdateLoop(*OuterL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002274
2275#ifndef NDEBUG
2276 // Verify the entire loop structure to catch any incorrect updates before we
2277 // progress in the pass pipeline.
2278 LI.verify(DT);
2279#endif
2280
2281 // Now that we've unswitched something, make callbacks to report the changes.
2282 // For that we need to merge together the updated loops and the cloned loops
2283 // and check whether the original loop survived.
2284 SmallVector<Loop *, 4> SibLoops;
2285 for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2286 if (UpdatedL->getParentLoop() == ParentL)
2287 SibLoops.push_back(UpdatedL);
Chandler Carruth71fd2702018-05-30 02:46:45 +00002288 UnswitchCB(IsStillLoop, SibLoops);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002289
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002290 if (MSSAU && VerifyMemorySSA)
2291 MSSAU->getMemorySSA()->verifyMemorySSA();
2292
Zaara Syedab7dff9c2019-01-15 15:08:01 +00002293 if (BI)
2294 ++NumBranches;
2295 else
2296 ++NumSwitches;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002297}
2298
2299/// Recursively compute the cost of a dominator subtree based on the per-block
2300/// cost map provided.
2301///
2302/// The recursive computation is memozied into the provided DT-indexed cost map
2303/// to allow querying it for most nodes in the domtree without it becoming
2304/// quadratic.
2305static int
2306computeDomSubtreeCost(DomTreeNode &N,
2307 const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
2308 SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
2309 // Don't accumulate cost (or recurse through) blocks not in our block cost
2310 // map and thus not part of the duplication cost being considered.
2311 auto BBCostIt = BBCostMap.find(N.getBlock());
2312 if (BBCostIt == BBCostMap.end())
2313 return 0;
2314
2315 // Lookup this node to see if we already computed its cost.
2316 auto DTCostIt = DTCostMap.find(&N);
2317 if (DTCostIt != DTCostMap.end())
2318 return DTCostIt->second;
2319
2320 // If not, we have to compute it. We can't use insert above and update
2321 // because computing the cost may insert more things into the map.
2322 int Cost = std::accumulate(
2323 N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
2324 return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2325 });
2326 bool Inserted = DTCostMap.insert({&N, Cost}).second;
2327 (void)Inserted;
2328 assert(Inserted && "Should not insert a node while visiting children!");
2329 return Cost;
2330}
2331
Max Kazantsev619a8342018-10-26 14:20:11 +00002332/// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2333/// making the following replacement:
2334///
Simon Pilgrima1320162018-10-27 15:14:42 +00002335/// --code before guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002336/// call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
Simon Pilgrima1320162018-10-27 15:14:42 +00002337/// --code after guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002338///
2339/// into
2340///
Simon Pilgrima1320162018-10-27 15:14:42 +00002341/// --code before guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002342/// br i1 %cond, label %guarded, label %deopt
2343///
2344/// guarded:
Simon Pilgrima1320162018-10-27 15:14:42 +00002345/// --code after guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002346///
2347/// deopt:
2348/// call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2349/// unreachable
2350///
2351/// It also makes all relevant DT and LI updates, so that all structures are in
2352/// valid state after this transform.
2353static BranchInst *
2354turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2355 SmallVectorImpl<BasicBlock *> &ExitBlocks,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002356 DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Max Kazantsev619a8342018-10-26 14:20:11 +00002357 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2358 LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
2359 BasicBlock *CheckBB = GI->getParent();
2360
Alina Sbirlea797935f2018-12-04 14:43:24 +00002361 if (MSSAU && VerifyMemorySSA)
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002362 MSSAU->getMemorySSA()->verifyMemorySSA();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002363
Max Kazantsev619a8342018-10-26 14:20:11 +00002364 // Remove all CheckBB's successors from DomTree. A block can be seen among
2365 // successors more than once, but for DomTree it should be added only once.
2366 SmallPtrSet<BasicBlock *, 4> Successors;
2367 for (auto *Succ : successors(CheckBB))
2368 if (Successors.insert(Succ).second)
2369 DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
2370
2371 Instruction *DeoptBlockTerm =
2372 SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
2373 BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
2374 // SplitBlockAndInsertIfThen inserts control flow that branches to
2375 // DeoptBlockTerm if the condition is true. We want the opposite.
2376 CheckBI->swapSuccessors();
2377
2378 BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2379 GuardedBlock->setName("guarded");
2380 CheckBI->getSuccessor(1)->setName("deopt");
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002381 BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
Max Kazantsev619a8342018-10-26 14:20:11 +00002382
2383 // We now have a new exit block.
2384 ExitBlocks.push_back(CheckBI->getSuccessor(1));
2385
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002386 if (MSSAU)
2387 MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
2388
Max Kazantsev619a8342018-10-26 14:20:11 +00002389 GI->moveBefore(DeoptBlockTerm);
2390 GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
2391
2392 // Add new successors of CheckBB into DomTree.
2393 for (auto *Succ : successors(CheckBB))
2394 DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
2395
2396 // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2397 // successors.
2398 for (auto *Succ : Successors)
2399 DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
2400
2401 // Make proper changes to DT.
2402 DT.applyUpdates(DTUpdates);
2403 // Inform LI of a new loop block.
2404 L.addBasicBlockToLoop(GuardedBlock, LI);
2405
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002406 if (MSSAU) {
2407 MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
2408 MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::End);
2409 if (VerifyMemorySSA)
2410 MSSAU->getMemorySSA()->verifyMemorySSA();
2411 }
2412
Max Kazantsev619a8342018-10-26 14:20:11 +00002413 ++NumGuards;
2414 return CheckBI;
2415}
2416
Fedor Sergeev2e3e2242018-11-16 21:16:43 +00002417/// Cost multiplier is a way to limit potentially exponential behavior
2418/// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
2419/// candidates available. Also accounting for the number of "sibling" loops with
2420/// the idea to account for previous unswitches that already happened on this
2421/// cluster of loops. There was an attempt to keep this formula simple,
2422/// just enough to limit the worst case behavior. Even if it is not that simple
2423/// now it is still not an attempt to provide a detailed heuristic size
2424/// prediction.
2425///
2426/// TODO: Make a proper accounting of "explosion" effect for all kinds of
2427/// unswitch candidates, making adequate predictions instead of wild guesses.
2428/// That requires knowing not just the number of "remaining" candidates but
2429/// also costs of unswitching for each of these candidates.
2430static int calculateUnswitchCostMultiplier(
2431 Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT,
2432 ArrayRef<std::pair<Instruction *, TinyPtrVector<Value *>>>
2433 UnswitchCandidates) {
2434
2435 // Guards and other exiting conditions do not contribute to exponential
2436 // explosion as soon as they dominate the latch (otherwise there might be
2437 // another path to the latch remaining that does not allow to eliminate the
2438 // loop copy on unswitch).
2439 BasicBlock *Latch = L.getLoopLatch();
2440 BasicBlock *CondBlock = TI.getParent();
2441 if (DT.dominates(CondBlock, Latch) &&
2442 (isGuard(&TI) ||
2443 llvm::count_if(successors(&TI), [&L](BasicBlock *SuccBB) {
2444 return L.contains(SuccBB);
2445 }) <= 1)) {
2446 NumCostMultiplierSkipped++;
2447 return 1;
2448 }
2449
2450 auto *ParentL = L.getParentLoop();
2451 int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
2452 : std::distance(LI.begin(), LI.end()));
2453 // Count amount of clones that all the candidates might cause during
2454 // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
2455 int UnswitchedClones = 0;
2456 for (auto Candidate : UnswitchCandidates) {
2457 Instruction *CI = Candidate.first;
2458 BasicBlock *CondBlock = CI->getParent();
2459 bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
2460 if (isGuard(CI)) {
2461 if (!SkipExitingSuccessors)
2462 UnswitchedClones++;
2463 continue;
2464 }
2465 int NonExitingSuccessors = llvm::count_if(
2466 successors(CondBlock), [SkipExitingSuccessors, &L](BasicBlock *SuccBB) {
2467 return !SkipExitingSuccessors || L.contains(SuccBB);
2468 });
2469 UnswitchedClones += Log2_32(NonExitingSuccessors);
2470 }
2471
2472 // Ignore up to the "unscaled candidates" number of unswitch candidates
2473 // when calculating the power-of-two scaling of the cost. The main idea
2474 // with this control is to allow a small number of unswitches to happen
2475 // and rely more on siblings multiplier (see below) when the number
2476 // of candidates is small.
2477 unsigned ClonesPower =
2478 std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
2479
2480 // Allowing top-level loops to spread a bit more than nested ones.
2481 int SiblingsMultiplier =
2482 std::max((ParentL ? SiblingsCount
2483 : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
2484 1);
2485 // Compute the cost multiplier in a way that won't overflow by saturating
2486 // at an upper bound.
2487 int CostMultiplier;
2488 if (ClonesPower > Log2_32(UnswitchThreshold) ||
2489 SiblingsMultiplier > UnswitchThreshold)
2490 CostMultiplier = UnswitchThreshold;
2491 else
2492 CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
2493 (int)UnswitchThreshold);
2494
2495 LLVM_DEBUG(dbgs() << " Computed multiplier " << CostMultiplier
2496 << " (siblings " << SiblingsMultiplier << " * clones "
2497 << (1 << ClonesPower) << ")"
2498 << " for unswitch candidate: " << TI << "\n");
2499 return CostMultiplier;
2500}
2501
Chandler Carruth3897ded2018-07-03 09:13:27 +00002502static bool
2503unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
2504 AssumptionCache &AC, TargetTransformInfo &TTI,
2505 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002506 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002507 // Collect all invariant conditions within this loop (as opposed to an inner
2508 // loop which would be handled when visiting that inner loop).
Chandler Carruth60b2e052018-10-18 00:40:26 +00002509 SmallVector<std::pair<Instruction *, TinyPtrVector<Value *>>, 4>
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002510 UnswitchCandidates;
Max Kazantsev619a8342018-10-26 14:20:11 +00002511
2512 // Whether or not we should also collect guards in the loop.
2513 bool CollectGuards = false;
2514 if (UnswitchGuards) {
2515 auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
2516 Intrinsic::getName(Intrinsic::experimental_guard));
2517 if (GuardDecl && !GuardDecl->use_empty())
2518 CollectGuards = true;
2519 }
2520
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002521 for (auto *BB : L.blocks()) {
2522 if (LI.getLoopFor(BB) != &L)
2523 continue;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002524
Max Kazantsev619a8342018-10-26 14:20:11 +00002525 if (CollectGuards)
2526 for (auto &I : *BB)
2527 if (isGuard(&I)) {
2528 auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0);
2529 // TODO: Support AND, OR conditions and partial unswitching.
2530 if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
2531 UnswitchCandidates.push_back({&I, {Cond}});
2532 }
2533
Chandler Carruth16529962018-06-25 23:32:54 +00002534 if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2535 // We can only consider fully loop-invariant switch conditions as we need
2536 // to completely eliminate the switch after unswitching.
2537 if (!isa<Constant>(SI->getCondition()) &&
2538 L.isLoopInvariant(SI->getCondition()))
2539 UnswitchCandidates.push_back({SI, {SI->getCondition()}});
2540 continue;
2541 }
2542
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002543 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002544 if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2545 BI->getSuccessor(0) == BI->getSuccessor(1))
2546 continue;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002547
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002548 if (L.isLoopInvariant(BI->getCondition())) {
2549 UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2550 continue;
2551 }
2552
2553 Instruction &CondI = *cast<Instruction>(BI->getCondition());
2554 if (CondI.getOpcode() != Instruction::And &&
2555 CondI.getOpcode() != Instruction::Or)
2556 continue;
2557
2558 TinyPtrVector<Value *> Invariants =
2559 collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2560 if (Invariants.empty())
2561 continue;
2562
2563 UnswitchCandidates.push_back({BI, std::move(Invariants)});
Chandler Carruth71fd2702018-05-30 02:46:45 +00002564 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002565
Chandler Carruth693eedb2017-11-17 19:58:36 +00002566 // If we didn't find any candidates, we're done.
2567 if (UnswitchCandidates.empty())
Chandler Carruth71fd2702018-05-30 02:46:45 +00002568 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002569
Chandler Carruth32e62f92018-04-19 18:44:25 +00002570 // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2571 // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2572 // irreducible control flow into reducible control flow and introduce new
2573 // loops "out of thin air". If we ever discover important use cases for doing
2574 // this, we can add support to loop unswitch, but it is a lot of complexity
Hiroshi Inouef2096492018-06-14 05:41:49 +00002575 // for what seems little or no real world benefit.
Chandler Carruth32e62f92018-04-19 18:44:25 +00002576 LoopBlocksRPO RPOT(&L);
2577 RPOT.perform(&LI);
2578 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
Chandler Carruth71fd2702018-05-30 02:46:45 +00002579 return false;
Chandler Carruth32e62f92018-04-19 18:44:25 +00002580
Max Kazantsevbde31002018-10-26 09:52:58 +00002581 SmallVector<BasicBlock *, 4> ExitBlocks;
2582 L.getUniqueExitBlocks(ExitBlocks);
2583
2584 // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
2585 // don't know how to split those exit blocks.
2586 // FIXME: We should teach SplitBlock to handle this and remove this
2587 // restriction.
2588 for (auto *ExitBB : ExitBlocks)
2589 if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI())) {
2590 dbgs() << "Cannot unswitch because of cleanuppad in exit block\n";
2591 return false;
2592 }
2593
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002594 LLVM_DEBUG(
2595 dbgs() << "Considering " << UnswitchCandidates.size()
2596 << " non-trivial loop invariant conditions for unswitching.\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002597
2598 // Given that unswitching these terminators will require duplicating parts of
2599 // the loop, so we need to be able to model that cost. Compute the ephemeral
2600 // values and set up a data structure to hold per-BB costs. We cache each
2601 // block's cost so that we don't recompute this when considering different
2602 // subsets of the loop for duplication during unswitching.
2603 SmallPtrSet<const Value *, 4> EphValues;
2604 CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2605 SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
2606
2607 // Compute the cost of each block, as well as the total loop cost. Also, bail
2608 // out if we see instructions which are incompatible with loop unswitching
2609 // (convergent, noduplicate, or cross-basic-block tokens).
2610 // FIXME: We might be able to safely handle some of these in non-duplicated
2611 // regions.
2612 int LoopCost = 0;
2613 for (auto *BB : L.blocks()) {
2614 int Cost = 0;
2615 for (auto &I : *BB) {
2616 if (EphValues.count(&I))
2617 continue;
2618
2619 if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
Chandler Carruth71fd2702018-05-30 02:46:45 +00002620 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002621 if (auto CS = CallSite(&I))
2622 if (CS.isConvergent() || CS.cannotDuplicate())
Chandler Carruth71fd2702018-05-30 02:46:45 +00002623 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002624
2625 Cost += TTI.getUserCost(&I);
2626 }
2627 assert(Cost >= 0 && "Must not have negative costs!");
2628 LoopCost += Cost;
2629 assert(LoopCost >= 0 && "Must not have negative loop costs!");
2630 BBCostMap[BB] = Cost;
2631 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002632 LLVM_DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002633
2634 // Now we find the best candidate by searching for the one with the following
2635 // properties in order:
2636 //
2637 // 1) An unswitching cost below the threshold
2638 // 2) The smallest number of duplicated unswitch candidates (to avoid
2639 // creating redundant subsequent unswitching)
2640 // 3) The smallest cost after unswitching.
2641 //
2642 // We prioritize reducing fanout of unswitch candidates provided the cost
2643 // remains below the threshold because this has a multiplicative effect.
2644 //
2645 // This requires memoizing each dominator subtree to avoid redundant work.
2646 //
2647 // FIXME: Need to actually do the number of candidates part above.
2648 SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
2649 // Given a terminator which might be unswitched, computes the non-duplicated
2650 // cost for that terminator.
Chandler Carruth60b2e052018-10-18 00:40:26 +00002651 auto ComputeUnswitchedCost = [&](Instruction &TI, bool FullUnswitch) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002652 BasicBlock &BB = *TI.getParent();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002653 SmallPtrSet<BasicBlock *, 4> Visited;
2654
2655 int Cost = LoopCost;
2656 for (BasicBlock *SuccBB : successors(&BB)) {
2657 // Don't count successors more than once.
2658 if (!Visited.insert(SuccBB).second)
2659 continue;
2660
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002661 // If this is a partial unswitch candidate, then it must be a conditional
2662 // branch with a condition of either `or` or `and`. In that case, one of
2663 // the successors is necessarily duplicated, so don't even try to remove
2664 // its cost.
2665 if (!FullUnswitch) {
2666 auto &BI = cast<BranchInst>(TI);
2667 if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2668 Instruction::And) {
2669 if (SuccBB == BI.getSuccessor(1))
2670 continue;
2671 } else {
2672 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2673 Instruction::Or &&
2674 "Only `and` and `or` conditions can result in a partial "
2675 "unswitch!");
2676 if (SuccBB == BI.getSuccessor(0))
2677 continue;
2678 }
2679 }
2680
Chandler Carruth693eedb2017-11-17 19:58:36 +00002681 // This successor's domtree will not need to be duplicated after
2682 // unswitching if the edge to the successor dominates it (and thus the
2683 // entire tree). This essentially means there is no other path into this
2684 // subtree and so it will end up live in only one clone of the loop.
2685 if (SuccBB->getUniquePredecessor() ||
2686 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2687 return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2688 })) {
2689 Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2690 assert(Cost >= 0 &&
2691 "Non-duplicated cost should never exceed total loop cost!");
2692 }
2693 }
2694
2695 // Now scale the cost by the number of unique successors minus one. We
2696 // subtract one because there is already at least one copy of the entire
2697 // loop. This is computing the new cost of unswitching a condition.
Max Kazantsev619a8342018-10-26 14:20:11 +00002698 // Note that guards always have 2 unique successors that are implicit and
2699 // will be materialized if we decide to unswitch it.
2700 int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
2701 assert(SuccessorsCount > 1 &&
Chandler Carruth693eedb2017-11-17 19:58:36 +00002702 "Cannot unswitch a condition without multiple distinct successors!");
Max Kazantsev619a8342018-10-26 14:20:11 +00002703 return Cost * (SuccessorsCount - 1);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002704 };
Chandler Carruth60b2e052018-10-18 00:40:26 +00002705 Instruction *BestUnswitchTI = nullptr;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002706 int BestUnswitchCost;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002707 ArrayRef<Value *> BestUnswitchInvariants;
2708 for (auto &TerminatorAndInvariants : UnswitchCandidates) {
Chandler Carruth60b2e052018-10-18 00:40:26 +00002709 Instruction &TI = *TerminatorAndInvariants.first;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002710 ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2711 BranchInst *BI = dyn_cast<BranchInst>(&TI);
Chandler Carruth16529962018-06-25 23:32:54 +00002712 int CandidateCost = ComputeUnswitchedCost(
2713 TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
2714 Invariants[0] == BI->getCondition()));
Fedor Sergeev2e3e2242018-11-16 21:16:43 +00002715 // Calculate cost multiplier which is a tool to limit potentially
2716 // exponential behavior of loop-unswitch.
2717 if (EnableUnswitchCostMultiplier) {
2718 int CostMultiplier =
2719 calculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
2720 assert(
2721 (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
2722 "cost multiplier needs to be in the range of 1..UnswitchThreshold");
2723 CandidateCost *= CostMultiplier;
2724 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2725 << " (multiplier: " << CostMultiplier << ")"
2726 << " for unswitch candidate: " << TI << "\n");
2727 } else {
2728 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2729 << " for unswitch candidate: " << TI << "\n");
2730 }
2731
Chandler Carruth693eedb2017-11-17 19:58:36 +00002732 if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002733 BestUnswitchTI = &TI;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002734 BestUnswitchCost = CandidateCost;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002735 BestUnswitchInvariants = Invariants;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002736 }
2737 }
2738
Chandler Carruth71fd2702018-05-30 02:46:45 +00002739 if (BestUnswitchCost >= UnswitchThreshold) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002740 LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
2741 << BestUnswitchCost << "\n");
Chandler Carruth71fd2702018-05-30 02:46:45 +00002742 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002743 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002744
Max Kazantsev619a8342018-10-26 14:20:11 +00002745 // If the best candidate is a guard, turn it into a branch.
2746 if (isGuard(BestUnswitchTI))
2747 BestUnswitchTI = turnGuardIntoBranch(cast<IntrinsicInst>(BestUnswitchTI), L,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002748 ExitBlocks, DT, LI, MSSAU);
Max Kazantsev619a8342018-10-26 14:20:11 +00002749
Max Kazantsevbde31002018-10-26 09:52:58 +00002750 LLVM_DEBUG(dbgs() << " Unswitching non-trivial (cost = "
Chandler Carruth16529962018-06-25 23:32:54 +00002751 << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
2752 << "\n");
Max Kazantsevbde31002018-10-26 09:52:58 +00002753 unswitchNontrivialInvariants(L, *BestUnswitchTI, BestUnswitchInvariants,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002754 ExitBlocks, DT, LI, AC, UnswitchCB, SE, MSSAU);
Max Kazantsevbde31002018-10-26 09:52:58 +00002755 return true;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002756}
2757
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002758/// Unswitch control flow predicated on loop invariant conditions.
2759///
2760/// This first hoists all branches or switches which are trivial (IE, do not
2761/// require duplicating any part of the loop) out of the loop body. It then
2762/// looks at other loop invariant control flows and tries to unswitch those as
2763/// well by cloning the loop if the result is small enough.
Chandler Carruth3897ded2018-07-03 09:13:27 +00002764///
2765/// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
2766/// updated based on the unswitch.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002767/// The `MSSA` analysis is also updated if valid (i.e. its use is enabled).
Chandler Carruth3897ded2018-07-03 09:13:27 +00002768///
2769/// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
2770/// true, we will attempt to do non-trivial unswitching as well as trivial
2771/// unswitching.
2772///
2773/// The `UnswitchCB` callback provided will be run after unswitching is
2774/// complete, with the first parameter set to `true` if the provided loop
2775/// remains a loop, and a list of new sibling loops created.
2776///
2777/// If `SE` is non-null, we will update that analysis based on the unswitching
2778/// done.
2779static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
2780 AssumptionCache &AC, TargetTransformInfo &TTI,
2781 bool NonTrivial,
2782 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002783 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002784 assert(L.isRecursivelyLCSSAForm(DT, LI) &&
2785 "Loops must be in LCSSA form before unswitching.");
2786 bool Changed = false;
2787
2788 // Must be in loop simplified form: we need a preheader and dedicated exits.
2789 if (!L.isLoopSimplifyForm())
2790 return false;
2791
2792 // Try trivial unswitch first before loop over other basic blocks in the loop.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002793 if (unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002794 // If we unswitched successfully we will want to clean up the loop before
2795 // processing it further so just mark it as unswitched and return.
2796 UnswitchCB(/*CurrentLoopValid*/ true, {});
2797 return true;
2798 }
2799
2800 // If we're not doing non-trivial unswitching, we're done. We both accept
2801 // a parameter but also check a local flag that can be used for testing
2802 // a debugging.
2803 if (!NonTrivial && !EnableNonTrivialUnswitch)
2804 return false;
2805
2806 // For non-trivial unswitching, because it often creates new loops, we rely on
2807 // the pass manager to iterate on the loops rather than trying to immediately
2808 // reach a fixed point. There is no substantial advantage to iterating
2809 // internally, and if any of the new loops are simplified enough to contain
2810 // trivial unswitching we want to prefer those.
2811
2812 // Try to unswitch the best invariant condition. We prefer this full unswitch to
2813 // a partial unswitch when possible below the threshold.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002814 if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE, MSSAU))
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002815 return true;
2816
2817 // No other opportunities to unswitch.
2818 return Changed;
2819}
2820
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002821PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
2822 LoopStandardAnalysisResults &AR,
2823 LPMUpdater &U) {
2824 Function &F = *L.getHeader()->getParent();
2825 (void)F;
2826
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002827 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
2828 << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002829
Chandler Carruth693eedb2017-11-17 19:58:36 +00002830 // Save the current loop name in a variable so that we can report it even
2831 // after it has been deleted.
2832 std::string LoopName = L.getName();
2833
Chandler Carruth71fd2702018-05-30 02:46:45 +00002834 auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2835 ArrayRef<Loop *> NewLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002836 // If we did a non-trivial unswitch, we have added new (cloned) loops.
Chandler Carruth71fd2702018-05-30 02:46:45 +00002837 if (!NewLoops.empty())
2838 U.addSiblingLoops(NewLoops);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002839
2840 // If the current loop remains valid, we should revisit it to catch any
2841 // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2842 if (CurrentLoopValid)
2843 U.revisitCurrentLoop();
2844 else
2845 U.markLoopAsDeleted(L, LoopName);
2846 };
2847
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002848 Optional<MemorySSAUpdater> MSSAU;
2849 if (AR.MSSA) {
2850 MSSAU = MemorySSAUpdater(AR.MSSA);
2851 if (VerifyMemorySSA)
2852 AR.MSSA->verifyMemorySSA();
2853 }
Chandler Carruth3897ded2018-07-03 09:13:27 +00002854 if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002855 &AR.SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002856 return PreservedAnalyses::all();
2857
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002858 if (AR.MSSA && VerifyMemorySSA)
2859 AR.MSSA->verifyMemorySSA();
2860
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002861 // Historically this pass has had issues with the dominator tree so verify it
2862 // in asserts builds.
David Green7c35de12018-02-28 11:00:08 +00002863 assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002864 return getLoopPassPreservedAnalyses();
2865}
2866
2867namespace {
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002868
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002869class SimpleLoopUnswitchLegacyPass : public LoopPass {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002870 bool NonTrivial;
2871
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002872public:
2873 static char ID; // Pass ID, replacement for typeid
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002874
Chandler Carruth693eedb2017-11-17 19:58:36 +00002875 explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2876 : LoopPass(ID), NonTrivial(NonTrivial) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002877 initializeSimpleLoopUnswitchLegacyPassPass(
2878 *PassRegistry::getPassRegistry());
2879 }
2880
2881 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
2882
2883 void getAnalysisUsage(AnalysisUsage &AU) const override {
2884 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002885 AU.addRequired<TargetTransformInfoWrapperPass>();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002886 if (EnableMSSALoopDependency) {
2887 AU.addRequired<MemorySSAWrapperPass>();
2888 AU.addPreserved<MemorySSAWrapperPass>();
2889 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002890 getLoopAnalysisUsage(AU);
2891 }
2892};
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002893
2894} // end anonymous namespace
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002895
2896bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
2897 if (skipLoop(L))
2898 return false;
2899
2900 Function &F = *L->getHeader()->getParent();
2901
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002902 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
2903 << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002904
2905 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2906 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2907 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002908 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002909 MemorySSA *MSSA = nullptr;
2910 Optional<MemorySSAUpdater> MSSAU;
2911 if (EnableMSSALoopDependency) {
2912 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
2913 MSSAU = MemorySSAUpdater(MSSA);
2914 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002915
Chandler Carruth3897ded2018-07-03 09:13:27 +00002916 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
2917 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
2918
Chandler Carruth71fd2702018-05-30 02:46:45 +00002919 auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2920 ArrayRef<Loop *> NewLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002921 // If we did a non-trivial unswitch, we have added new (cloned) loops.
2922 for (auto *NewL : NewLoops)
2923 LPM.addLoop(*NewL);
2924
2925 // If the current loop remains valid, re-add it to the queue. This is
2926 // a little wasteful as we'll finish processing the current loop as well,
2927 // but it is the best we can do in the old PM.
2928 if (CurrentLoopValid)
2929 LPM.addLoop(*L);
2930 else
2931 LPM.markLoopAsDeleted(*L);
2932 };
2933
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002934 if (MSSA && VerifyMemorySSA)
2935 MSSA->verifyMemorySSA();
2936
2937 bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE,
2938 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
2939
2940 if (MSSA && VerifyMemorySSA)
2941 MSSA->verifyMemorySSA();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002942
2943 // If anything was unswitched, also clear any cached information about this
2944 // loop.
2945 LPM.deleteSimpleAnalysisLoop(L);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002946
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002947 // Historically this pass has had issues with the dominator tree so verify it
2948 // in asserts builds.
David Green7c35de12018-02-28 11:00:08 +00002949 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2950
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002951 return Changed;
2952}
2953
2954char SimpleLoopUnswitchLegacyPass::ID = 0;
2955INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2956 "Simple unswitch loops", false, false)
2957INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth693eedb2017-11-17 19:58:36 +00002958INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2959INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002960INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002961INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002962INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2963INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2964 "Simple unswitch loops", false, false)
2965
Chandler Carruth693eedb2017-11-17 19:58:36 +00002966Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
2967 return new SimpleLoopUnswitchLegacyPass(NonTrivial);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002968}