blob: ac832b9b456711cd8f2dfe4d52910670aa5fcbf7 [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);
Philip Reames9e62c862019-07-06 03:46:18 +0000183
184 Value *Cond = Direction ? IRB.CreateOr(Invariants) :
185 IRB.CreateAnd(Invariants);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000186 IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
187 Direction ? &NormalSucc : &UnswitchedSucc);
188}
189
Chandler Carruthd869b182017-05-12 02:19:59 +0000190/// Rewrite the PHI nodes in an unswitched loop exit basic block.
191///
192/// Requires that the loop exit and unswitched basic block are the same, and
193/// that the exiting block was a unique predecessor of that block. Rewrites the
194/// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
195/// PHI nodes from the old preheader that now contains the unswitched
196/// terminator.
197static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
198 BasicBlock &OldExitingBB,
199 BasicBlock &OldPH) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000200 for (PHINode &PN : UnswitchedBB.phis()) {
Chandler Carruthd869b182017-05-12 02:19:59 +0000201 // When the loop exit is directly unswitched we just need to update the
202 // incoming basic block. We loop to handle weird cases with repeated
203 // incoming blocks, but expect to typically only have one operand here.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000204 for (auto i : seq<int>(0, PN.getNumOperands())) {
205 assert(PN.getIncomingBlock(i) == &OldExitingBB &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000206 "Found incoming block different from unique predecessor!");
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000207 PN.setIncomingBlock(i, &OldPH);
Chandler Carruthd869b182017-05-12 02:19:59 +0000208 }
209 }
210}
211
212/// Rewrite the PHI nodes in the loop exit basic block and the split off
213/// unswitched block.
214///
215/// Because the exit block remains an exit from the loop, this rewrites the
216/// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
217/// nodes into the unswitched basic block to select between the value in the
218/// old preheader and the loop exit.
219static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
220 BasicBlock &UnswitchedBB,
221 BasicBlock &OldExitingBB,
Chandler Carruth4da33312018-06-20 18:57:07 +0000222 BasicBlock &OldPH,
223 bool FullUnswitch) {
Chandler Carruthd869b182017-05-12 02:19:59 +0000224 assert(&ExitBB != &UnswitchedBB &&
225 "Must have different loop exit and unswitched blocks!");
226 Instruction *InsertPt = &*UnswitchedBB.begin();
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000227 for (PHINode &PN : ExitBB.phis()) {
228 auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
229 PN.getName() + ".split", InsertPt);
Chandler Carruthd869b182017-05-12 02:19:59 +0000230
231 // Walk backwards over the old PHI node's inputs to minimize the cost of
232 // removing each one. We have to do this weird loop manually so that we
233 // create the same number of new incoming edges in the new PHI as we expect
234 // each case-based edge to be included in the unswitched switch in some
235 // cases.
236 // FIXME: This is really, really gross. It would be much cleaner if LLVM
237 // allowed us to create a single entry for a predecessor block without
238 // having separate entries for each "edge" even though these edges are
239 // required to produce identical results.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000240 for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
241 if (PN.getIncomingBlock(i) != &OldExitingBB)
Chandler Carruthd869b182017-05-12 02:19:59 +0000242 continue;
243
Chandler Carruth4da33312018-06-20 18:57:07 +0000244 Value *Incoming = PN.getIncomingValue(i);
245 if (FullUnswitch)
246 // No more edge from the old exiting block to the exit block.
247 PN.removeIncomingValue(i);
248
Chandler Carruthd869b182017-05-12 02:19:59 +0000249 NewPN->addIncoming(Incoming, &OldPH);
250 }
251
252 // Now replace the old PHI with the new one and wire the old one in as an
253 // input to the new one.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000254 PN.replaceAllUsesWith(NewPN);
255 NewPN->addIncoming(&PN, &ExitBB);
Chandler Carruthd869b182017-05-12 02:19:59 +0000256 }
257}
258
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000259/// Hoist the current loop up to the innermost loop containing a remaining exit.
260///
261/// Because we've removed an exit from the loop, we may have changed the set of
262/// loops reachable and need to move the current loop up the loop nest or even
263/// to an entirely separate nest.
264static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
Alina Sbirlea97468e92019-02-21 21:13:34 +0000265 DominatorTree &DT, LoopInfo &LI,
266 MemorySSAUpdater *MSSAU) {
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000267 // If the loop is already at the top level, we can't hoist it anywhere.
268 Loop *OldParentL = L.getParentLoop();
269 if (!OldParentL)
270 return;
271
272 SmallVector<BasicBlock *, 4> Exits;
273 L.getExitBlocks(Exits);
274 Loop *NewParentL = nullptr;
275 for (auto *ExitBB : Exits)
276 if (Loop *ExitL = LI.getLoopFor(ExitBB))
277 if (!NewParentL || NewParentL->contains(ExitL))
278 NewParentL = ExitL;
279
280 if (NewParentL == OldParentL)
281 return;
282
283 // The new parent loop (if different) should always contain the old one.
284 if (NewParentL)
285 assert(NewParentL->contains(OldParentL) &&
286 "Can only hoist this loop up the nest!");
287
288 // The preheader will need to move with the body of this loop. However,
289 // because it isn't in this loop we also need to update the primary loop map.
290 assert(OldParentL == LI.getLoopFor(&Preheader) &&
291 "Parent loop of this loop should contain this loop's preheader!");
292 LI.changeLoopFor(&Preheader, NewParentL);
293
294 // Remove this loop from its old parent.
295 OldParentL->removeChildLoop(&L);
296
297 // Add the loop either to the new parent or as a top-level loop.
298 if (NewParentL)
299 NewParentL->addChildLoop(&L);
300 else
301 LI.addTopLevelLoop(&L);
302
303 // Remove this loops blocks from the old parent and every other loop up the
304 // nest until reaching the new parent. Also update all of these
305 // no-longer-containing loops to reflect the nesting change.
306 for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
307 OldContainingL = OldContainingL->getParentLoop()) {
308 llvm::erase_if(OldContainingL->getBlocksVector(),
309 [&](const BasicBlock *BB) {
310 return BB == &Preheader || L.contains(BB);
311 });
312
313 OldContainingL->getBlocksSet().erase(&Preheader);
314 for (BasicBlock *BB : L.blocks())
315 OldContainingL->getBlocksSet().erase(BB);
316
317 // Because we just hoisted a loop out of this one, we have essentially
318 // created new exit paths from it. That means we need to form LCSSA PHI
319 // nodes for values used in the no-longer-nested loop.
320 formLCSSA(*OldContainingL, DT, &LI, nullptr);
321
322 // We shouldn't need to form dedicated exits because the exit introduced
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000323 // here is the (just split by unswitching) preheader. However, after trivial
324 // unswitching it is possible to get new non-dedicated exits out of parent
325 // loop so let's conservatively form dedicated exit blocks and figure out
326 // if we can optimize later.
Alina Sbirlea97468e92019-02-21 21:13:34 +0000327 formDedicatedExitBlocks(OldContainingL, &DT, &LI, MSSAU,
328 /*PreserveLCSSA*/ true);
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000329 }
330}
331
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000332/// Unswitch a trivial branch if the condition is loop invariant.
333///
334/// This routine should only be called when loop code leading to the branch has
335/// been validated as trivial (no side effects). This routine checks if the
336/// condition is invariant and one of the successors is a loop exit. This
337/// allows us to unswitch without duplicating the loop, making it trivial.
338///
339/// If this routine fails to unswitch the branch it returns false.
340///
341/// If the branch can be unswitched, this routine splits the preheader and
342/// hoists the branch above that split. Preserves loop simplified form
343/// (splitting the exit block as necessary). It simplifies the branch within
344/// the loop to an unconditional branch but doesn't remove it entirely. Further
345/// cleanup can be done with some simplify-cfg like pass.
Chandler Carruth3897ded2018-07-03 09:13:27 +0000346///
347/// If `SE` is not null, it will be updated based on the potential loop SCEVs
348/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000349static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000350 LoopInfo &LI, ScalarEvolution *SE,
351 MemorySSAUpdater *MSSAU) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000352 assert(BI.isConditional() && "Can only unswitch a conditional branch!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000353 LLVM_DEBUG(dbgs() << " Trying to unswitch branch: " << BI << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000354
Chandler Carruth4da33312018-06-20 18:57:07 +0000355 // The loop invariant values that we want to unswitch.
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000356 TinyPtrVector<Value *> Invariants;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000357
Chandler Carruth4da33312018-06-20 18:57:07 +0000358 // When true, we're fully unswitching the branch rather than just unswitching
359 // some input conditions to the branch.
360 bool FullUnswitch = false;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000361
Chandler Carruth4da33312018-06-20 18:57:07 +0000362 if (L.isLoopInvariant(BI.getCondition())) {
363 Invariants.push_back(BI.getCondition());
364 FullUnswitch = true;
365 } else {
366 if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition()))
367 Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
368 if (Invariants.empty())
369 // Couldn't find invariant inputs!
370 return false;
371 }
372
373 // Check that one of the branch's successors exits, and which one.
374 bool ExitDirection = true;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000375 int LoopExitSuccIdx = 0;
376 auto *LoopExitBB = BI.getSuccessor(0);
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000377 if (L.contains(LoopExitBB)) {
Chandler Carruth4da33312018-06-20 18:57:07 +0000378 ExitDirection = false;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000379 LoopExitSuccIdx = 1;
380 LoopExitBB = BI.getSuccessor(1);
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000381 if (L.contains(LoopExitBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000382 return false;
383 }
384 auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
Chandler Carruthd869b182017-05-12 02:19:59 +0000385 auto *ParentBB = BI.getParent();
386 if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000387 return false;
388
Chandler Carruth4da33312018-06-20 18:57:07 +0000389 // When unswitching only part of the branch's condition, we need the exit
390 // block to be reached directly from the partially unswitched input. This can
391 // be done when the exit block is along the true edge and the branch condition
392 // is a graph of `or` operations, or the exit block is along the false edge
393 // and the condition is a graph of `and` operations.
394 if (!FullUnswitch) {
395 if (ExitDirection) {
396 if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::Or)
397 return false;
398 } else {
399 if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::And)
400 return false;
401 }
402 }
403
404 LLVM_DEBUG({
405 dbgs() << " unswitching trivial invariant conditions for: " << BI
406 << "\n";
407 for (Value *Invariant : Invariants) {
408 dbgs() << " " << *Invariant << " == true";
409 if (Invariant != Invariants.back())
410 dbgs() << " ||";
411 dbgs() << "\n";
412 }
413 });
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000414
Chandler Carruth3897ded2018-07-03 09:13:27 +0000415 // If we have scalar evolutions, we need to invalidate them including this
416 // loop and the loop containing the exit block.
417 if (SE) {
418 if (Loop *ExitL = LI.getLoopFor(LoopExitBB))
419 SE->forgetLoop(ExitL);
420 else
421 // Forget the entire nest as this exits the entire nest.
422 SE->forgetTopmostLoop(&L);
423 }
424
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000425 if (MSSAU && VerifyMemorySSA)
426 MSSAU->getMemorySSA()->verifyMemorySSA();
427
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000428 // Split the preheader, so that we know that there is a safe place to insert
429 // the conditional branch. We will change the preheader to have a conditional
430 // branch on LoopCond.
431 BasicBlock *OldPH = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000432 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000433
434 // Now that we have a place to insert the conditional branch, create a place
435 // to branch to: this is the exit block out of the loop that we are
436 // unswitching. We need to split this if there are other loop predecessors.
437 // Because the loop is in simplified form, *any* other predecessor is enough.
438 BasicBlock *UnswitchedBB;
Chandler Carruth4da33312018-06-20 18:57:07 +0000439 if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
440 assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000441 "A branch's parent isn't a predecessor!");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000442 UnswitchedBB = LoopExitBB;
443 } else {
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000444 UnswitchedBB =
445 SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000446 }
447
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000448 if (MSSAU && VerifyMemorySSA)
449 MSSAU->getMemorySSA()->verifyMemorySSA();
450
Chandler Carruth4da33312018-06-20 18:57:07 +0000451 // Actually move the invariant uses into the unswitched position. If possible,
452 // we do this by moving the instructions, but when doing partial unswitching
453 // we do it by building a new merge of the values in the unswitched position.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000454 OldPH->getTerminator()->eraseFromParent();
Chandler Carruth4da33312018-06-20 18:57:07 +0000455 if (FullUnswitch) {
456 // If fully unswitching, we can use the existing branch instruction.
457 // Splice it into the old PH to gate reaching the new preheader and re-point
458 // its successors.
459 OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
460 BI);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000461 if (MSSAU) {
462 // Temporarily clone the terminator, to make MSSA update cheaper by
463 // separating "insert edge" updates from "remove edge" ones.
464 ParentBB->getInstList().push_back(BI.clone());
465 } else {
466 // Create a new unconditional branch that will continue the loop as a new
467 // terminator.
468 BranchInst::Create(ContinueBB, ParentBB);
469 }
Chandler Carruth4da33312018-06-20 18:57:07 +0000470 BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
471 BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
Chandler Carruth4da33312018-06-20 18:57:07 +0000472 } else {
473 // Only unswitching a subset of inputs to the condition, so we will need to
474 // build a new branch that merges the invariant inputs.
Chandler Carruth4da33312018-06-20 18:57:07 +0000475 if (ExitDirection)
476 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
477 Instruction::Or &&
478 "Must have an `or` of `i1`s for the condition!");
479 else
480 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
481 Instruction::And &&
482 "Must have an `and` of `i1`s for the condition!");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000483 buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection,
484 *UnswitchedBB, *NewPH);
Chandler Carruth4da33312018-06-20 18:57:07 +0000485 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000486
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000487 // Update the dominator tree with the added edge.
488 DT.insertEdge(OldPH, UnswitchedBB);
489
490 // After the dominator tree was updated with the added edge, update MemorySSA
491 // if available.
492 if (MSSAU) {
493 SmallVector<CFGUpdate, 1> Updates;
494 Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
495 MSSAU->applyInsertUpdates(Updates, DT);
496 }
497
498 // Finish updating dominator tree and memory ssa for full unswitch.
499 if (FullUnswitch) {
500 if (MSSAU) {
501 // Remove the cloned branch instruction.
502 ParentBB->getTerminator()->eraseFromParent();
503 // Create unconditional branch now.
504 BranchInst::Create(ContinueBB, ParentBB);
505 MSSAU->removeEdge(ParentBB, LoopExitBB);
506 }
507 DT.deleteEdge(ParentBB, LoopExitBB);
508 }
509
510 if (MSSAU && VerifyMemorySSA)
511 MSSAU->getMemorySSA()->verifyMemorySSA();
512
Chandler Carruthd869b182017-05-12 02:19:59 +0000513 // Rewrite the relevant PHI nodes.
514 if (UnswitchedBB == LoopExitBB)
515 rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
516 else
517 rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
Chandler Carruth4da33312018-06-20 18:57:07 +0000518 *ParentBB, *OldPH, FullUnswitch);
Chandler Carruthd869b182017-05-12 02:19:59 +0000519
Chandler Carruth4da33312018-06-20 18:57:07 +0000520 // The constant we can replace all of our invariants with inside the loop
521 // body. If any of the invariants have a value other than this the loop won't
522 // be entered.
523 ConstantInt *Replacement = ExitDirection
524 ? ConstantInt::getFalse(BI.getContext())
525 : ConstantInt::getTrue(BI.getContext());
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000526
527 // Since this is an i1 condition we can also trivially replace uses of it
528 // within the loop with a constant.
Chandler Carruth4da33312018-06-20 18:57:07 +0000529 for (Value *Invariant : Invariants)
530 replaceLoopInvariantUses(L, Invariant, *Replacement);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000531
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000532 // If this was full unswitching, we may have changed the nesting relationship
533 // for this loop so hoist it to its correct parent if needed.
534 if (FullUnswitch)
Alina Sbirlea97468e92019-02-21 21:13:34 +0000535 hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU);
536
537 if (MSSAU && VerifyMemorySSA)
538 MSSAU->getMemorySSA()->verifyMemorySSA();
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000539
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000540 LLVM_DEBUG(dbgs() << " done: unswitching trivial branch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000541 ++NumTrivial;
542 ++NumBranches;
543 return true;
544}
545
546/// Unswitch a trivial switch if the condition is loop invariant.
547///
548/// This routine should only be called when loop code leading to the switch has
549/// been validated as trivial (no side effects). This routine checks if the
550/// condition is invariant and that at least one of the successors is a loop
551/// exit. This allows us to unswitch without duplicating the loop, making it
552/// trivial.
553///
554/// If this routine fails to unswitch the switch it returns false.
555///
556/// If the switch can be unswitched, this routine splits the preheader and
557/// copies the switch above that split. If the default case is one of the
558/// exiting cases, it copies the non-exiting cases and points them at the new
559/// preheader. If the default case is not exiting, it copies the exiting cases
560/// and points the default at the preheader. It preserves loop simplified form
561/// (splitting the exit blocks as necessary). It simplifies the switch within
562/// the loop by removing now-dead cases. If the default case is one of those
563/// unswitched, it replaces its destination with a new basic block containing
564/// only unreachable. Such basic blocks, while technically loop exits, are not
565/// considered for unswitching so this is a stable transform and the same
566/// switch will not be revisited. If after unswitching there is only a single
567/// in-loop successor, the switch is further simplified to an unconditional
568/// branch. Still more cleanup can be done with some simplify-cfg like pass.
Chandler Carruth3897ded2018-07-03 09:13:27 +0000569///
570/// If `SE` is not null, it will be updated based on the potential loop SCEVs
571/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000572static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000573 LoopInfo &LI, ScalarEvolution *SE,
574 MemorySSAUpdater *MSSAU) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000575 LLVM_DEBUG(dbgs() << " Trying to unswitch switch: " << SI << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000576 Value *LoopCond = SI.getCondition();
577
578 // If this isn't switching on an invariant condition, we can't unswitch it.
579 if (!L.isLoopInvariant(LoopCond))
580 return false;
581
Chandler Carruthd869b182017-05-12 02:19:59 +0000582 auto *ParentBB = SI.getParent();
583
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000584 SmallVector<int, 4> ExitCaseIndices;
585 for (auto Case : SI.cases()) {
586 auto *SuccBB = Case.getCaseSuccessor();
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000587 if (!L.contains(SuccBB) &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000588 areLoopExitPHIsLoopInvariant(L, *ParentBB, *SuccBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000589 ExitCaseIndices.push_back(Case.getCaseIndex());
590 }
591 BasicBlock *DefaultExitBB = nullptr;
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000592 SwitchInstProfUpdateWrapper::CaseWeightOpt DefaultCaseWeight =
593 SwitchInstProfUpdateWrapper::getSuccessorWeight(SI, 0);
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000594 if (!L.contains(SI.getDefaultDest()) &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000595 areLoopExitPHIsLoopInvariant(L, *ParentBB, *SI.getDefaultDest()) &&
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000596 !isa<UnreachableInst>(SI.getDefaultDest()->getTerminator())) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000597 DefaultExitBB = SI.getDefaultDest();
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000598 } else if (ExitCaseIndices.empty())
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000599 return false;
600
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000601 LLVM_DEBUG(dbgs() << " unswitching trivial switch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000602
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000603 if (MSSAU && VerifyMemorySSA)
604 MSSAU->getMemorySSA()->verifyMemorySSA();
605
Chandler Carruth3897ded2018-07-03 09:13:27 +0000606 // We may need to invalidate SCEVs for the outermost loop reached by any of
607 // the exits.
608 Loop *OuterL = &L;
609
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000610 if (DefaultExitBB) {
611 // Clear out the default destination temporarily to allow accurate
612 // predecessor lists to be examined below.
613 SI.setDefaultDest(nullptr);
614 // Check the loop containing this exit.
615 Loop *ExitL = LI.getLoopFor(DefaultExitBB);
616 if (!ExitL || ExitL->contains(OuterL))
617 OuterL = ExitL;
618 }
619
620 // Store the exit cases into a separate data structure and remove them from
621 // the switch.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000622 SmallVector<std::tuple<ConstantInt *, BasicBlock *,
623 SwitchInstProfUpdateWrapper::CaseWeightOpt>,
624 4> ExitCases;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000625 ExitCases.reserve(ExitCaseIndices.size());
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000626 SwitchInstProfUpdateWrapper SIW(SI);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000627 // 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.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000636 auto W = SIW.getSuccessorWeight(CaseI->getSuccessorIndex());
637 ExitCases.emplace_back(CaseI->getCaseValue(), CaseI->getCaseSuccessor(), W);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000638 // Delete the unswitched cases.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000639 SIW.removeCase(CaseI);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000640 }
641
Chandler Carruth3897ded2018-07-03 09:13:27 +0000642 if (SE) {
643 if (OuterL)
644 SE->forgetLoop(OuterL);
645 else
646 SE->forgetTopmostLoop(&L);
647 }
648
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000649 // Check if after this all of the remaining cases point at the same
650 // successor.
651 BasicBlock *CommonSuccBB = nullptr;
652 if (SI.getNumCases() > 0 &&
653 std::all_of(std::next(SI.case_begin()), SI.case_end(),
654 [&SI](const SwitchInst::CaseHandle &Case) {
655 return Case.getCaseSuccessor() ==
656 SI.case_begin()->getCaseSuccessor();
657 }))
658 CommonSuccBB = SI.case_begin()->getCaseSuccessor();
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000659 if (!DefaultExitBB) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000660 // If we're not unswitching the default, we need it to match any cases to
661 // have a common successor or if we have no cases it is the common
662 // successor.
663 if (SI.getNumCases() == 0)
664 CommonSuccBB = SI.getDefaultDest();
665 else if (SI.getDefaultDest() != CommonSuccBB)
666 CommonSuccBB = nullptr;
667 }
668
669 // Split the preheader, so that we know that there is a safe place to insert
670 // the switch.
671 BasicBlock *OldPH = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000672 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000673 OldPH->getTerminator()->eraseFromParent();
674
675 // Now add the unswitched switch.
676 auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000677 SwitchInstProfUpdateWrapper NewSIW(*NewSI);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000678
Chandler Carruthd869b182017-05-12 02:19:59 +0000679 // Rewrite the IR for the unswitched basic blocks. This requires two steps.
680 // First, we split any exit blocks with remaining in-loop predecessors. Then
681 // we update the PHIs in one of two ways depending on if there was a split.
682 // We walk in reverse so that we split in the same order as the cases
683 // appeared. This is purely for convenience of reading the resulting IR, but
684 // it doesn't cost anything really.
685 SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000686 SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
687 // Handle the default exit if necessary.
688 // FIXME: It'd be great if we could merge this with the loop below but LLVM's
689 // ranges aren't quite powerful enough yet.
Chandler Carruthd869b182017-05-12 02:19:59 +0000690 if (DefaultExitBB) {
691 if (pred_empty(DefaultExitBB)) {
692 UnswitchedExitBBs.insert(DefaultExitBB);
693 rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
694 } else {
695 auto *SplitBB =
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000696 SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU);
697 rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
698 *ParentBB, *OldPH,
699 /*FullUnswitch*/ true);
Chandler Carruthd869b182017-05-12 02:19:59 +0000700 DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
701 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000702 }
703 // Note that we must use a reference in the for loop so that we update the
704 // container.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000705 for (auto &ExitCase : reverse(ExitCases)) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000706 // Grab a reference to the exit block in the pair so that we can update it.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000707 BasicBlock *ExitBB = std::get<1>(ExitCase);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000708
709 // If this case is the last edge into the exit block, we can simply reuse it
710 // as it will no longer be a loop exit. No mapping necessary.
Chandler Carruthd869b182017-05-12 02:19:59 +0000711 if (pred_empty(ExitBB)) {
712 // Only rewrite once.
713 if (UnswitchedExitBBs.insert(ExitBB).second)
714 rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000715 continue;
Chandler Carruthd869b182017-05-12 02:19:59 +0000716 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000717
718 // Otherwise we need to split the exit block so that we retain an exit
719 // block from the loop and a target for the unswitched condition.
720 BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
721 if (!SplitExitBB) {
722 // If this is the first time we see this, do the split and remember it.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000723 SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
724 rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
725 *ParentBB, *OldPH,
726 /*FullUnswitch*/ true);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000727 }
Chandler Carruthd869b182017-05-12 02:19:59 +0000728 // Update the case pair to point to the split block.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000729 std::get<1>(ExitCase) = SplitExitBB;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000730 }
731
732 // Now add the unswitched cases. We do this in reverse order as we built them
733 // in reverse order.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000734 for (auto &ExitCase : reverse(ExitCases)) {
735 ConstantInt *CaseVal = std::get<0>(ExitCase);
736 BasicBlock *UnswitchedBB = std::get<1>(ExitCase);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000737
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000738 NewSIW.addCase(CaseVal, UnswitchedBB, std::get<2>(ExitCase));
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000739 }
740
741 // If the default was unswitched, re-point it and add explicit cases for
742 // entering the loop.
743 if (DefaultExitBB) {
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000744 NewSIW->setDefaultDest(DefaultExitBB);
745 NewSIW.setSuccessorWeight(0, DefaultCaseWeight);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000746
747 // We removed all the exit cases, so we just copy the cases to the
748 // unswitched switch.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000749 for (const auto &Case : SI.cases())
750 NewSIW.addCase(Case.getCaseValue(), NewPH,
751 SIW.getSuccessorWeight(Case.getSuccessorIndex()));
752 } else if (DefaultCaseWeight) {
753 // We have to set branch weight of the default case.
754 uint64_t SW = *DefaultCaseWeight;
755 for (const auto &Case : SI.cases()) {
756 auto W = SIW.getSuccessorWeight(Case.getSuccessorIndex());
757 assert(W &&
758 "case weight must be defined as default case weight is defined");
759 SW += *W;
760 }
761 NewSIW.setSuccessorWeight(0, SW);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000762 }
763
764 // If we ended up with a common successor for every path through the switch
765 // after unswitching, rewrite it to an unconditional branch to make it easy
766 // to recognize. Otherwise we potentially have to recognize the default case
767 // pointing at unreachable and other complexity.
768 if (CommonSuccBB) {
769 BasicBlock *BB = SI.getParent();
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000770 // We may have had multiple edges to this common successor block, so remove
771 // them as predecessors. We skip the first one, either the default or the
772 // actual first case.
773 bool SkippedFirst = DefaultExitBB == nullptr;
774 for (auto Case : SI.cases()) {
775 assert(Case.getCaseSuccessor() == CommonSuccBB &&
776 "Non-common successor!");
Chandler Carruth148861f2018-07-10 08:57:04 +0000777 (void)Case;
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000778 if (!SkippedFirst) {
779 SkippedFirst = true;
780 continue;
781 }
782 CommonSuccBB->removePredecessor(BB,
Max Kazantsev20b91892019-02-12 07:09:29 +0000783 /*KeepOneInputPHIs*/ true);
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000784 }
785 // Now nuke the switch and replace it with a direct branch.
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000786 SIW.eraseFromParent();
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000787 BranchInst::Create(CommonSuccBB, BB);
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000788 } else if (DefaultExitBB) {
789 assert(SI.getNumCases() > 0 &&
790 "If we had no cases we'd have a common successor!");
791 // Move the last case to the default successor. This is valid as if the
792 // default got unswitched it cannot be reached. This has the advantage of
793 // being simple and keeping the number of edges from this switch to
794 // successors the same, and avoiding any PHI update complexity.
795 auto LastCaseI = std::prev(SI.case_end());
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000796
Chandler Carruth47dc3a32018-07-10 08:36:05 +0000797 SI.setDefaultDest(LastCaseI->getCaseSuccessor());
Yevgeny Rouband4097b42019-07-01 08:43:53 +0000798 SIW.setSuccessorWeight(
799 0, SIW.getSuccessorWeight(LastCaseI->getSuccessorIndex()));
800 SIW.removeCase(LastCaseI);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000801 }
802
Chandler Carruth2c85a232018-05-01 09:54:39 +0000803 // Walk the unswitched exit blocks and the unswitched split blocks and update
804 // the dominator tree based on the CFG edits. While we are walking unordered
805 // containers here, the API for applyUpdates takes an unordered list of
806 // updates and requires them to not contain duplicates.
807 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
808 for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
809 DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
810 DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
811 }
812 for (auto SplitUnswitchedPair : SplitExitBBMap) {
Alina Sbirlea90d2e3a2019-02-22 07:18:37 +0000813 DTUpdates.push_back({DT.Delete, ParentBB, SplitUnswitchedPair.first});
814 DTUpdates.push_back({DT.Insert, OldPH, SplitUnswitchedPair.second});
Chandler Carruth2c85a232018-05-01 09:54:39 +0000815 }
816 DT.applyUpdates(DTUpdates);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000817
818 if (MSSAU) {
819 MSSAU->applyUpdates(DTUpdates, DT);
820 if (VerifyMemorySSA)
821 MSSAU->getMemorySSA()->verifyMemorySSA();
822 }
823
David Green7c35de12018-02-28 11:00:08 +0000824 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000825
826 // We may have changed the nesting relationship for this loop so hoist it to
827 // its correct parent if needed.
Alina Sbirlea97468e92019-02-21 21:13:34 +0000828 hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU);
829
830 if (MSSAU && VerifyMemorySSA)
831 MSSAU->getMemorySSA()->verifyMemorySSA();
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000832
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000833 ++NumTrivial;
834 ++NumSwitches;
Alina Sbirlea52e97a22018-08-28 20:41:05 +0000835 LLVM_DEBUG(dbgs() << " done: unswitching trivial switch...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000836 return true;
837}
838
839/// This routine scans the loop to find a branch or switch which occurs before
840/// any side effects occur. These can potentially be unswitched without
841/// duplicating the loop. If a branch or switch is successfully unswitched the
842/// scanning continues to see if subsequent branches or switches have become
843/// trivial. Once all trivial candidates have been unswitched, this routine
844/// returns.
845///
846/// The return value indicates whether anything was unswitched (and therefore
847/// changed).
Chandler Carruth3897ded2018-07-03 09:13:27 +0000848///
849/// If `SE` is not null, it will be updated based on the potential loop SCEVs
850/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000851static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000852 LoopInfo &LI, ScalarEvolution *SE,
853 MemorySSAUpdater *MSSAU) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000854 bool Changed = false;
855
856 // If loop header has only one reachable successor we should keep looking for
857 // trivial condition candidates in the successor as well. An alternative is
858 // to constant fold conditions and merge successors into loop header (then we
859 // only need to check header's terminator). The reason for not doing this in
860 // LoopUnswitch pass is that it could potentially break LoopPassManager's
861 // invariants. Folding dead branches could either eliminate the current loop
862 // or make other loops unreachable. LCSSA form might also not be preserved
863 // after deleting branches. The following code keeps traversing loop header's
864 // successors until it finds the trivial condition candidate (condition that
865 // is not a constant). Since unswitching generates branches with constant
866 // conditions, this scenario could be very common in practice.
867 BasicBlock *CurrentBB = L.getHeader();
868 SmallPtrSet<BasicBlock *, 8> Visited;
869 Visited.insert(CurrentBB);
870 do {
871 // Check if there are any side-effecting instructions (e.g. stores, calls,
872 // volatile loads) in the part of the loop that the code *would* execute
873 // without unswitching.
Alina Sbirlea93210872019-01-28 17:48:45 +0000874 if (MSSAU) // Possible early exit with MSSA
875 if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB))
876 if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
877 return Changed;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000878 if (llvm::any_of(*CurrentBB,
879 [](Instruction &I) { return I.mayHaveSideEffects(); }))
880 return Changed;
881
Chandler Carruthedb12a82018-10-15 10:04:59 +0000882 Instruction *CurrentTerm = CurrentBB->getTerminator();
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000883
884 if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
885 // Don't bother trying to unswitch past a switch with a constant
886 // condition. This should be removed prior to running this pass by
887 // simplify-cfg.
888 if (isa<Constant>(SI->getCondition()))
889 return Changed;
890
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000891 if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
Hiroshi Inouef2096492018-06-14 05:41:49 +0000892 // Couldn't unswitch this one so we're done.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000893 return Changed;
894
895 // Mark that we managed to unswitch something.
896 Changed = true;
897
898 // If unswitching turned the terminator into an unconditional branch then
899 // we can continue. The unswitching logic specifically works to fold any
900 // cases it can into an unconditional branch to make it easier to
901 // recognize here.
902 auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
903 if (!BI || BI->isConditional())
904 return Changed;
905
906 CurrentBB = BI->getSuccessor(0);
907 continue;
908 }
909
910 auto *BI = dyn_cast<BranchInst>(CurrentTerm);
911 if (!BI)
912 // We do not understand other terminator instructions.
913 return Changed;
914
915 // Don't bother trying to unswitch past an unconditional branch or a branch
916 // with a constant value. These should be removed by simplify-cfg prior to
917 // running this pass.
918 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
919 return Changed;
920
921 // Found a trivial condition candidate: non-foldable conditional branch. If
922 // we fail to unswitch this, we can't do anything else that is trivial.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000923 if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000924 return Changed;
925
926 // Mark that we managed to unswitch something.
927 Changed = true;
928
Chandler Carruth4da33312018-06-20 18:57:07 +0000929 // If we only unswitched some of the conditions feeding the branch, we won't
930 // have collapsed it to a single successor.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000931 BI = cast<BranchInst>(CurrentBB->getTerminator());
Chandler Carruth4da33312018-06-20 18:57:07 +0000932 if (BI->isConditional())
933 return Changed;
934
935 // Follow the newly unconditional branch into its successor.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000936 CurrentBB = BI->getSuccessor(0);
937
938 // When continuing, if we exit the loop or reach a previous visited block,
939 // then we can not reach any trivial condition candidates (unfoldable
940 // branch instructions or switch instructions) and no unswitch can happen.
941 } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
942
943 return Changed;
944}
945
Chandler Carruth693eedb2017-11-17 19:58:36 +0000946/// Build the cloned blocks for an unswitched copy of the given loop.
947///
948/// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
949/// after the split block (`SplitBB`) that will be used to select between the
950/// cloned and original loop.
951///
952/// This routine handles cloning all of the necessary loop blocks and exit
953/// blocks including rewriting their instructions and the relevant PHI nodes.
Chandler Carruth16529962018-06-25 23:32:54 +0000954/// Any loop blocks or exit blocks which are dominated by a different successor
955/// than the one for this clone of the loop blocks can be trivially skipped. We
956/// use the `DominatingSucc` map to determine whether a block satisfies that
957/// property with a simple map lookup.
958///
959/// It also correctly creates the unconditional branch in the cloned
Chandler Carruth693eedb2017-11-17 19:58:36 +0000960/// unswitched parent block to only point at the unswitched successor.
961///
962/// This does not handle most of the necessary updates to `LoopInfo`. Only exit
963/// block splitting is correctly reflected in `LoopInfo`, essentially all of
964/// the cloned blocks (and their loops) are left without full `LoopInfo`
965/// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
966/// blocks to them but doesn't create the cloned `DominatorTree` structure and
967/// instead the caller must recompute an accurate DT. It *does* correctly
968/// update the `AssumptionCache` provided in `AC`.
969static BasicBlock *buildClonedLoopBlocks(
970 Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
971 ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
972 BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
Chandler Carruth16529962018-06-25 23:32:54 +0000973 const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
Chandler Carruth69e68f82018-04-25 00:18:07 +0000974 ValueToValueMapTy &VMap,
975 SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +0000976 DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Chandler Carruth693eedb2017-11-17 19:58:36 +0000977 SmallVector<BasicBlock *, 4> NewBlocks;
978 NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
979
980 // We will need to clone a bunch of blocks, wrap up the clone operation in
981 // a helper.
982 auto CloneBlock = [&](BasicBlock *OldBB) {
983 // Clone the basic block and insert it before the new preheader.
984 BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
985 NewBB->moveBefore(LoopPH);
986
987 // Record this block and the mapping.
988 NewBlocks.push_back(NewBB);
989 VMap[OldBB] = NewBB;
990
Chandler Carruth693eedb2017-11-17 19:58:36 +0000991 return NewBB;
992 };
993
Chandler Carruth16529962018-06-25 23:32:54 +0000994 // We skip cloning blocks when they have a dominating succ that is not the
995 // succ we are cloning for.
996 auto SkipBlock = [&](BasicBlock *BB) {
997 auto It = DominatingSucc.find(BB);
998 return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
999 };
1000
Chandler Carruth693eedb2017-11-17 19:58:36 +00001001 // First, clone the preheader.
1002 auto *ClonedPH = CloneBlock(LoopPH);
1003
1004 // Then clone all the loop blocks, skipping the ones that aren't necessary.
1005 for (auto *LoopBB : L.blocks())
Chandler Carruth16529962018-06-25 23:32:54 +00001006 if (!SkipBlock(LoopBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001007 CloneBlock(LoopBB);
1008
1009 // Split all the loop exit edges so that when we clone the exit blocks, if
1010 // any of the exit blocks are *also* a preheader for some other loop, we
1011 // don't create multiple predecessors entering the loop header.
1012 for (auto *ExitBB : ExitBlocks) {
Chandler Carruth16529962018-06-25 23:32:54 +00001013 if (SkipBlock(ExitBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001014 continue;
1015
1016 // When we are going to clone an exit, we don't need to clone all the
1017 // instructions in the exit block and we want to ensure we have an easy
1018 // place to merge the CFG, so split the exit first. This is always safe to
1019 // do because there cannot be any non-loop predecessors of a loop exit in
1020 // loop simplified form.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001021 auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001022
1023 // Rearrange the names to make it easier to write test cases by having the
1024 // exit block carry the suffix rather than the merge block carrying the
1025 // suffix.
1026 MergeBB->takeName(ExitBB);
1027 ExitBB->setName(Twine(MergeBB->getName()) + ".split");
1028
1029 // Now clone the original exit block.
1030 auto *ClonedExitBB = CloneBlock(ExitBB);
1031 assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
1032 "Exit block should have been split to have one successor!");
1033 assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
1034 "Cloned exit block has the wrong successor!");
1035
Chandler Carruth693eedb2017-11-17 19:58:36 +00001036 // Remap any cloned instructions and create a merge phi node for them.
1037 for (auto ZippedInsts : llvm::zip_first(
1038 llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
1039 llvm::make_range(ClonedExitBB->begin(),
1040 std::prev(ClonedExitBB->end())))) {
1041 Instruction &I = std::get<0>(ZippedInsts);
1042 Instruction &ClonedI = std::get<1>(ZippedInsts);
1043
1044 // The only instructions in the exit block should be PHI nodes and
1045 // potentially a landing pad.
1046 assert(
1047 (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
1048 "Bad instruction in exit block!");
1049 // We should have a value map between the instruction and its clone.
1050 assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
1051
1052 auto *MergePN =
1053 PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
1054 &*MergeBB->getFirstInsertionPt());
1055 I.replaceAllUsesWith(MergePN);
1056 MergePN->addIncoming(&I, ExitBB);
1057 MergePN->addIncoming(&ClonedI, ClonedExitBB);
1058 }
1059 }
1060
1061 // Rewrite the instructions in the cloned blocks to refer to the instructions
1062 // in the cloned blocks. We have to do this as a second pass so that we have
1063 // everything available. Also, we have inserted new instructions which may
1064 // include assume intrinsics, so we update the assumption cache while
1065 // processing this.
1066 for (auto *ClonedBB : NewBlocks)
1067 for (Instruction &I : *ClonedBB) {
1068 RemapInstruction(&I, VMap,
1069 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1070 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1071 if (II->getIntrinsicID() == Intrinsic::assume)
1072 AC.registerAssumption(II);
1073 }
1074
Chandler Carruth693eedb2017-11-17 19:58:36 +00001075 // Update any PHI nodes in the cloned successors of the skipped blocks to not
1076 // have spurious incoming values.
1077 for (auto *LoopBB : L.blocks())
Chandler Carruth16529962018-06-25 23:32:54 +00001078 if (SkipBlock(LoopBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001079 for (auto *SuccBB : successors(LoopBB))
1080 if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
1081 for (PHINode &PN : ClonedSuccBB->phis())
1082 PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
1083
Chandler Carruthed296542018-07-09 10:30:48 +00001084 // Remove the cloned parent as a predecessor of any successor we ended up
1085 // cloning other than the unswitched one.
1086 auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
1087 for (auto *SuccBB : successors(ParentBB)) {
1088 if (SuccBB == UnswitchedSuccBB)
1089 continue;
1090
1091 auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
1092 if (!ClonedSuccBB)
1093 continue;
1094
1095 ClonedSuccBB->removePredecessor(ClonedParentBB,
Max Kazantsev20b91892019-02-12 07:09:29 +00001096 /*KeepOneInputPHIs*/ true);
Chandler Carruthed296542018-07-09 10:30:48 +00001097 }
1098
1099 // Replace the cloned branch with an unconditional branch to the cloned
1100 // unswitched successor.
1101 auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
1102 ClonedParentBB->getTerminator()->eraseFromParent();
1103 BranchInst::Create(ClonedSuccBB, ClonedParentBB);
1104
1105 // If there are duplicate entries in the PHI nodes because of multiple edges
1106 // to the unswitched successor, we need to nuke all but one as we replaced it
1107 // with a direct branch.
1108 for (PHINode &PN : ClonedSuccBB->phis()) {
1109 bool Found = false;
1110 // Loop over the incoming operands backwards so we can easily delete as we
1111 // go without invalidating the index.
1112 for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
1113 if (PN.getIncomingBlock(i) != ClonedParentBB)
1114 continue;
1115 if (!Found) {
1116 Found = true;
1117 continue;
1118 }
1119 PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
1120 }
1121 }
1122
Chandler Carruth69e68f82018-04-25 00:18:07 +00001123 // Record the domtree updates for the new blocks.
Chandler Carruth44aab922018-05-01 09:42:09 +00001124 SmallPtrSet<BasicBlock *, 4> SuccSet;
1125 for (auto *ClonedBB : NewBlocks) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001126 for (auto *SuccBB : successors(ClonedBB))
Chandler Carruth44aab922018-05-01 09:42:09 +00001127 if (SuccSet.insert(SuccBB).second)
1128 DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
1129 SuccSet.clear();
1130 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00001131
Chandler Carruth693eedb2017-11-17 19:58:36 +00001132 return ClonedPH;
1133}
1134
1135/// Recursively clone the specified loop and all of its children.
1136///
1137/// The target parent loop for the clone should be provided, or can be null if
1138/// the clone is a top-level loop. While cloning, all the blocks are mapped
1139/// with the provided value map. The entire original loop must be present in
1140/// the value map. The cloned loop is returned.
1141static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
1142 const ValueToValueMapTy &VMap, LoopInfo &LI) {
1143 auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
1144 assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
1145 ClonedL.reserveBlocks(OrigL.getNumBlocks());
1146 for (auto *BB : OrigL.blocks()) {
1147 auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
1148 ClonedL.addBlockEntry(ClonedBB);
Chandler Carruth0ace1482018-04-24 03:27:00 +00001149 if (LI.getLoopFor(BB) == &OrigL)
Chandler Carruth693eedb2017-11-17 19:58:36 +00001150 LI.changeLoopFor(ClonedBB, &ClonedL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001151 }
1152 };
1153
1154 // We specially handle the first loop because it may get cloned into
1155 // a different parent and because we most commonly are cloning leaf loops.
1156 Loop *ClonedRootL = LI.AllocateLoop();
1157 if (RootParentL)
1158 RootParentL->addChildLoop(ClonedRootL);
1159 else
1160 LI.addTopLevelLoop(ClonedRootL);
1161 AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1162
1163 if (OrigRootL.empty())
1164 return ClonedRootL;
1165
1166 // If we have a nest, we can quickly clone the entire loop nest using an
1167 // iterative approach because it is a tree. We keep the cloned parent in the
1168 // data structure to avoid repeatedly querying through a map to find it.
1169 SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1170 // Build up the loops to clone in reverse order as we'll clone them from the
1171 // back.
1172 for (Loop *ChildL : llvm::reverse(OrigRootL))
1173 LoopsToClone.push_back({ClonedRootL, ChildL});
1174 do {
1175 Loop *ClonedParentL, *L;
1176 std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1177 Loop *ClonedL = LI.AllocateLoop();
1178 ClonedParentL->addChildLoop(ClonedL);
1179 AddClonedBlocksToLoop(*L, *ClonedL);
1180 for (Loop *ChildL : llvm::reverse(*L))
1181 LoopsToClone.push_back({ClonedL, ChildL});
1182 } while (!LoopsToClone.empty());
1183
1184 return ClonedRootL;
1185}
1186
1187/// Build the cloned loops of an original loop from unswitching.
1188///
1189/// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1190/// operation. We need to re-verify that there even is a loop (as the backedge
1191/// may not have been cloned), and even if there are remaining backedges the
1192/// backedge set may be different. However, we know that each child loop is
1193/// undisturbed, we only need to find where to place each child loop within
1194/// either any parent loop or within a cloned version of the original loop.
1195///
1196/// Because child loops may end up cloned outside of any cloned version of the
1197/// original loop, multiple cloned sibling loops may be created. All of them
1198/// are returned so that the newly introduced loop nest roots can be
1199/// identified.
Chandler Carruth92815032018-06-02 01:29:01 +00001200static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1201 const ValueToValueMapTy &VMap, LoopInfo &LI,
1202 SmallVectorImpl<Loop *> &NonChildClonedLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00001203 Loop *ClonedL = nullptr;
1204
1205 auto *OrigPH = OrigL.getLoopPreheader();
1206 auto *OrigHeader = OrigL.getHeader();
1207
1208 auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1209 auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1210
1211 // We need to know the loops of the cloned exit blocks to even compute the
1212 // accurate parent loop. If we only clone exits to some parent of the
1213 // original parent, we want to clone into that outer loop. We also keep track
1214 // of the loops that our cloned exit blocks participate in.
1215 Loop *ParentL = nullptr;
1216 SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1217 SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1218 ClonedExitsInLoops.reserve(ExitBlocks.size());
1219 for (auto *ExitBB : ExitBlocks)
1220 if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1221 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1222 ExitLoopMap[ClonedExitBB] = ExitL;
1223 ClonedExitsInLoops.push_back(ClonedExitBB);
1224 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1225 ParentL = ExitL;
1226 }
1227 assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1228 ParentL->contains(OrigL.getParentLoop())) &&
1229 "The computed parent loop should always contain (or be) the parent of "
1230 "the original loop.");
1231
1232 // We build the set of blocks dominated by the cloned header from the set of
1233 // cloned blocks out of the original loop. While not all of these will
1234 // necessarily be in the cloned loop, it is enough to establish that they
1235 // aren't in unreachable cycles, etc.
1236 SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1237 for (auto *BB : OrigL.blocks())
1238 if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1239 ClonedLoopBlocks.insert(ClonedBB);
1240
1241 // Rebuild the set of blocks that will end up in the cloned loop. We may have
1242 // skipped cloning some region of this loop which can in turn skip some of
1243 // the backedges so we have to rebuild the blocks in the loop based on the
1244 // backedges that remain after cloning.
1245 SmallVector<BasicBlock *, 16> Worklist;
1246 SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1247 for (auto *Pred : predecessors(ClonedHeader)) {
1248 // The only possible non-loop header predecessor is the preheader because
1249 // we know we cloned the loop in simplified form.
1250 if (Pred == ClonedPH)
1251 continue;
1252
1253 // Because the loop was in simplified form, the only non-loop predecessor
1254 // should be the preheader.
1255 assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1256 "header other than the preheader "
1257 "that is not part of the loop!");
1258
1259 // Insert this block into the loop set and on the first visit (and if it
1260 // isn't the header we're currently walking) put it into the worklist to
1261 // recurse through.
1262 if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1263 Worklist.push_back(Pred);
1264 }
1265
1266 // If we had any backedges then there *is* a cloned loop. Put the header into
1267 // the loop set and then walk the worklist backwards to find all the blocks
1268 // that remain within the loop after cloning.
1269 if (!BlocksInClonedLoop.empty()) {
1270 BlocksInClonedLoop.insert(ClonedHeader);
1271
1272 while (!Worklist.empty()) {
1273 BasicBlock *BB = Worklist.pop_back_val();
1274 assert(BlocksInClonedLoop.count(BB) &&
1275 "Didn't put block into the loop set!");
1276
1277 // Insert any predecessors that are in the possible set into the cloned
1278 // set, and if the insert is successful, add them to the worklist. Note
1279 // that we filter on the blocks that are definitely reachable via the
1280 // backedge to the loop header so we may prune out dead code within the
1281 // cloned loop.
1282 for (auto *Pred : predecessors(BB))
1283 if (ClonedLoopBlocks.count(Pred) &&
1284 BlocksInClonedLoop.insert(Pred).second)
1285 Worklist.push_back(Pred);
1286 }
1287
1288 ClonedL = LI.AllocateLoop();
1289 if (ParentL) {
1290 ParentL->addBasicBlockToLoop(ClonedPH, LI);
1291 ParentL->addChildLoop(ClonedL);
1292 } else {
1293 LI.addTopLevelLoop(ClonedL);
1294 }
Chandler Carruth92815032018-06-02 01:29:01 +00001295 NonChildClonedLoops.push_back(ClonedL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001296
1297 ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1298 // We don't want to just add the cloned loop blocks based on how we
1299 // discovered them. The original order of blocks was carefully built in
1300 // a way that doesn't rely on predecessor ordering. Rather than re-invent
1301 // that logic, we just re-walk the original blocks (and those of the child
1302 // loops) and filter them as we add them into the cloned loop.
1303 for (auto *BB : OrigL.blocks()) {
1304 auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1305 if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1306 continue;
1307
1308 // Directly add the blocks that are only in this loop.
1309 if (LI.getLoopFor(BB) == &OrigL) {
1310 ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1311 continue;
1312 }
1313
1314 // We want to manually add it to this loop and parents.
1315 // Registering it with LoopInfo will happen when we clone the top
1316 // loop for this block.
1317 for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1318 PL->addBlockEntry(ClonedBB);
1319 }
1320
1321 // Now add each child loop whose header remains within the cloned loop. All
1322 // of the blocks within the loop must satisfy the same constraints as the
1323 // header so once we pass the header checks we can just clone the entire
1324 // child loop nest.
1325 for (Loop *ChildL : OrigL) {
1326 auto *ClonedChildHeader =
1327 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1328 if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1329 continue;
1330
1331#ifndef NDEBUG
1332 // We should never have a cloned child loop header but fail to have
1333 // all of the blocks for that child loop.
1334 for (auto *ChildLoopBB : ChildL->blocks())
1335 assert(BlocksInClonedLoop.count(
1336 cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1337 "Child cloned loop has a header within the cloned outer "
1338 "loop but not all of its blocks!");
1339#endif
1340
1341 cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1342 }
1343 }
1344
1345 // Now that we've handled all the components of the original loop that were
1346 // cloned into a new loop, we still need to handle anything from the original
1347 // loop that wasn't in a cloned loop.
1348
1349 // Figure out what blocks are left to place within any loop nest containing
1350 // the unswitched loop. If we never formed a loop, the cloned PH is one of
1351 // them.
1352 SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1353 if (BlocksInClonedLoop.empty())
1354 UnloopedBlockSet.insert(ClonedPH);
1355 for (auto *ClonedBB : ClonedLoopBlocks)
1356 if (!BlocksInClonedLoop.count(ClonedBB))
1357 UnloopedBlockSet.insert(ClonedBB);
1358
1359 // Copy the cloned exits and sort them in ascending loop depth, we'll work
1360 // backwards across these to process them inside out. The order shouldn't
1361 // matter as we're just trying to build up the map from inside-out; we use
1362 // the map in a more stably ordered way below.
1363 auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
Fangrui Song0cac7262018-09-27 02:13:45 +00001364 llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1365 return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1366 ExitLoopMap.lookup(RHS)->getLoopDepth();
1367 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001368
1369 // Populate the existing ExitLoopMap with everything reachable from each
1370 // exit, starting from the inner most exit.
1371 while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1372 assert(Worklist.empty() && "Didn't clear worklist!");
1373
1374 BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1375 Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1376
1377 // Walk the CFG back until we hit the cloned PH adding everything reachable
1378 // and in the unlooped set to this exit block's loop.
1379 Worklist.push_back(ExitBB);
1380 do {
1381 BasicBlock *BB = Worklist.pop_back_val();
1382 // We can stop recursing at the cloned preheader (if we get there).
1383 if (BB == ClonedPH)
1384 continue;
1385
1386 for (BasicBlock *PredBB : predecessors(BB)) {
1387 // If this pred has already been moved to our set or is part of some
1388 // (inner) loop, no update needed.
1389 if (!UnloopedBlockSet.erase(PredBB)) {
1390 assert(
1391 (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1392 "Predecessor not mapped to a loop!");
1393 continue;
1394 }
1395
1396 // We just insert into the loop set here. We'll add these blocks to the
1397 // exit loop after we build up the set in an order that doesn't rely on
1398 // predecessor order (which in turn relies on use list order).
1399 bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1400 (void)Inserted;
1401 assert(Inserted && "Should only visit an unlooped block once!");
1402
1403 // And recurse through to its predecessors.
1404 Worklist.push_back(PredBB);
1405 }
1406 } while (!Worklist.empty());
1407 }
1408
1409 // Now that the ExitLoopMap gives as mapping for all the non-looping cloned
1410 // blocks to their outer loops, walk the cloned blocks and the cloned exits
1411 // in their original order adding them to the correct loop.
1412
1413 // We need a stable insertion order. We use the order of the original loop
1414 // order and map into the correct parent loop.
1415 for (auto *BB : llvm::concat<BasicBlock *const>(
1416 makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1417 if (Loop *OuterL = ExitLoopMap.lookup(BB))
1418 OuterL->addBasicBlockToLoop(BB, LI);
1419
1420#ifndef NDEBUG
1421 for (auto &BBAndL : ExitLoopMap) {
1422 auto *BB = BBAndL.first;
1423 auto *OuterL = BBAndL.second;
1424 assert(LI.getLoopFor(BB) == OuterL &&
1425 "Failed to put all blocks into outer loops!");
1426 }
1427#endif
1428
1429 // Now that all the blocks are placed into the correct containing loop in the
1430 // absence of child loops, find all the potentially cloned child loops and
1431 // clone them into whatever outer loop we placed their header into.
1432 for (Loop *ChildL : OrigL) {
1433 auto *ClonedChildHeader =
1434 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1435 if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1436 continue;
1437
1438#ifndef NDEBUG
1439 for (auto *ChildLoopBB : ChildL->blocks())
1440 assert(VMap.count(ChildLoopBB) &&
1441 "Cloned a child loop header but not all of that loops blocks!");
1442#endif
1443
1444 NonChildClonedLoops.push_back(cloneLoopNest(
1445 *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1446 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001447}
1448
Chandler Carruth69e68f82018-04-25 00:18:07 +00001449static void
Chandler Carruth16529962018-06-25 23:32:54 +00001450deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1451 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001452 DominatorTree &DT, MemorySSAUpdater *MSSAU) {
Chandler Carruth16529962018-06-25 23:32:54 +00001453 // Find all the dead clones, and remove them from their successors.
1454 SmallVector<BasicBlock *, 16> DeadBlocks;
1455 for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1456 for (auto &VMap : VMaps)
1457 if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
1458 if (!DT.isReachableFromEntry(ClonedBB)) {
1459 for (BasicBlock *SuccBB : successors(ClonedBB))
1460 SuccBB->removePredecessor(ClonedBB);
1461 DeadBlocks.push_back(ClonedBB);
1462 }
1463
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001464 // Remove all MemorySSA in the dead blocks
1465 if (MSSAU) {
Alina Sbirleadb101862019-07-12 22:30:30 +00001466 SmallSetVector<BasicBlock *, 8> DeadBlockSet(DeadBlocks.begin(),
1467 DeadBlocks.end());
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001468 MSSAU->removeBlocks(DeadBlockSet);
1469 }
1470
Chandler Carruth16529962018-06-25 23:32:54 +00001471 // Drop any remaining references to break cycles.
1472 for (BasicBlock *BB : DeadBlocks)
1473 BB->dropAllReferences();
1474 // Erase them from the IR.
1475 for (BasicBlock *BB : DeadBlocks)
1476 BB->eraseFromParent();
1477}
1478
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001479static void deleteDeadBlocksFromLoop(Loop &L,
1480 SmallVectorImpl<BasicBlock *> &ExitBlocks,
1481 DominatorTree &DT, LoopInfo &LI,
1482 MemorySSAUpdater *MSSAU) {
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001483 // Find all the dead blocks tied to this loop, and remove them from their
1484 // successors.
Alina Sbirleadb101862019-07-12 22:30:30 +00001485 SmallSetVector<BasicBlock *, 8> DeadBlockSet;
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001486
1487 // Start with loop/exit blocks and get a transitive closure of reachable dead
1488 // blocks.
1489 SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(),
1490 ExitBlocks.end());
1491 DeathCandidates.append(L.blocks().begin(), L.blocks().end());
1492 while (!DeathCandidates.empty()) {
1493 auto *BB = DeathCandidates.pop_back_val();
1494 if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) {
1495 for (BasicBlock *SuccBB : successors(BB)) {
Chandler Carruth16529962018-06-25 23:32:54 +00001496 SuccBB->removePredecessor(BB);
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001497 DeathCandidates.push_back(SuccBB);
Fedor Sergeev7b49aa02018-08-29 19:10:44 +00001498 }
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001499 DeadBlockSet.insert(BB);
1500 }
1501 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001502
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001503 // Remove all MemorySSA in the dead blocks
1504 if (MSSAU)
1505 MSSAU->removeBlocks(DeadBlockSet);
1506
Chandler Carruth693eedb2017-11-17 19:58:36 +00001507 // Filter out the dead blocks from the exit blocks list so that it can be
1508 // used in the caller.
1509 llvm::erase_if(ExitBlocks,
Chandler Carruth69e68f82018-04-25 00:18:07 +00001510 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001511
Chandler Carruth693eedb2017-11-17 19:58:36 +00001512 // Walk from this loop up through its parents removing all of the dead blocks.
1513 for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001514 for (auto *BB : DeadBlockSet)
Chandler Carruth693eedb2017-11-17 19:58:36 +00001515 ParentL->getBlocksSet().erase(BB);
1516 llvm::erase_if(ParentL->getBlocksVector(),
Chandler Carruth69e68f82018-04-25 00:18:07 +00001517 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001518 }
1519
1520 // Now delete the dead child loops. This raw delete will clear them
1521 // recursively.
1522 llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001523 if (!DeadBlockSet.count(ChildL->getHeader()))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001524 return false;
1525
1526 assert(llvm::all_of(ChildL->blocks(),
1527 [&](BasicBlock *ChildBB) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001528 return DeadBlockSet.count(ChildBB);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001529 }) &&
1530 "If the child loop header is dead all blocks in the child loop must "
1531 "be dead as well!");
1532 LI.destroy(ChildL);
1533 return true;
1534 });
1535
Chandler Carruth69e68f82018-04-25 00:18:07 +00001536 // Remove the loop mappings for the dead blocks and drop all the references
1537 // from these blocks to others to handle cyclic references as we start
1538 // deleting the blocks themselves.
Fedor Sergeev8b6effd2018-09-04 20:19:41 +00001539 for (auto *BB : DeadBlockSet) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001540 // Check that the dominator tree has already been updated.
1541 assert(!DT.getNode(BB) && "Should already have cleared domtree!");
Chandler Carruth693eedb2017-11-17 19:58:36 +00001542 LI.changeLoopFor(BB, nullptr);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001543 BB->dropAllReferences();
Chandler Carruth693eedb2017-11-17 19:58:36 +00001544 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00001545
1546 // Actually delete the blocks now that they've been fully unhooked from the
1547 // IR.
Fedor Sergeev7b49aa02018-08-29 19:10:44 +00001548 for (auto *BB : DeadBlockSet)
Chandler Carruth69e68f82018-04-25 00:18:07 +00001549 BB->eraseFromParent();
Chandler Carruth693eedb2017-11-17 19:58:36 +00001550}
1551
1552/// Recompute the set of blocks in a loop after unswitching.
1553///
1554/// This walks from the original headers predecessors to rebuild the loop. We
1555/// take advantage of the fact that new blocks can't have been added, and so we
1556/// filter by the original loop's blocks. This also handles potentially
1557/// unreachable code that we don't want to explore but might be found examining
1558/// the predecessors of the header.
1559///
1560/// If the original loop is no longer a loop, this will return an empty set. If
1561/// it remains a loop, all the blocks within it will be added to the set
1562/// (including those blocks in inner loops).
1563static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1564 LoopInfo &LI) {
1565 SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1566
1567 auto *PH = L.getLoopPreheader();
1568 auto *Header = L.getHeader();
1569
1570 // A worklist to use while walking backwards from the header.
1571 SmallVector<BasicBlock *, 16> Worklist;
1572
1573 // First walk the predecessors of the header to find the backedges. This will
1574 // form the basis of our walk.
1575 for (auto *Pred : predecessors(Header)) {
1576 // Skip the preheader.
1577 if (Pred == PH)
1578 continue;
1579
1580 // Because the loop was in simplified form, the only non-loop predecessor
1581 // is the preheader.
1582 assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1583 "than the preheader that is not part of the "
1584 "loop!");
1585
1586 // Insert this block into the loop set and on the first visit and, if it
1587 // isn't the header we're currently walking, put it into the worklist to
1588 // recurse through.
1589 if (LoopBlockSet.insert(Pred).second && Pred != Header)
1590 Worklist.push_back(Pred);
1591 }
1592
1593 // If no backedges were found, we're done.
1594 if (LoopBlockSet.empty())
1595 return LoopBlockSet;
1596
Chandler Carruth693eedb2017-11-17 19:58:36 +00001597 // We found backedges, recurse through them to identify the loop blocks.
1598 while (!Worklist.empty()) {
1599 BasicBlock *BB = Worklist.pop_back_val();
1600 assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1601
Chandler Carruth43acdb32018-04-24 10:33:08 +00001602 // No need to walk past the header.
1603 if (BB == Header)
1604 continue;
1605
Chandler Carruth693eedb2017-11-17 19:58:36 +00001606 // Because we know the inner loop structure remains valid we can use the
1607 // loop structure to jump immediately across the entire nested loop.
1608 // Further, because it is in loop simplified form, we can directly jump
1609 // to its preheader afterward.
1610 if (Loop *InnerL = LI.getLoopFor(BB))
1611 if (InnerL != &L) {
1612 assert(L.contains(InnerL) &&
1613 "Should not reach a loop *outside* this loop!");
1614 // The preheader is the only possible predecessor of the loop so
1615 // insert it into the set and check whether it was already handled.
1616 auto *InnerPH = InnerL->getLoopPreheader();
1617 assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1618 "but not contain the inner loop "
1619 "preheader!");
1620 if (!LoopBlockSet.insert(InnerPH).second)
1621 // The only way to reach the preheader is through the loop body
1622 // itself so if it has been visited the loop is already handled.
1623 continue;
1624
1625 // Insert all of the blocks (other than those already present) into
Chandler Carruthbf7190a2018-04-23 06:58:36 +00001626 // the loop set. We expect at least the block that led us to find the
1627 // inner loop to be in the block set, but we may also have other loop
1628 // blocks if they were already enqueued as predecessors of some other
1629 // outer loop block.
Chandler Carruth693eedb2017-11-17 19:58:36 +00001630 for (auto *InnerBB : InnerL->blocks()) {
1631 if (InnerBB == BB) {
1632 assert(LoopBlockSet.count(InnerBB) &&
1633 "Block should already be in the set!");
1634 continue;
1635 }
1636
Chandler Carruthbf7190a2018-04-23 06:58:36 +00001637 LoopBlockSet.insert(InnerBB);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001638 }
1639
1640 // Add the preheader to the worklist so we will continue past the
1641 // loop body.
1642 Worklist.push_back(InnerPH);
1643 continue;
1644 }
1645
1646 // Insert any predecessors that were in the original loop into the new
1647 // set, and if the insert is successful, add them to the worklist.
1648 for (auto *Pred : predecessors(BB))
1649 if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1650 Worklist.push_back(Pred);
1651 }
1652
Chandler Carruth43acdb32018-04-24 10:33:08 +00001653 assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
1654
Chandler Carruth693eedb2017-11-17 19:58:36 +00001655 // We've found all the blocks participating in the loop, return our completed
1656 // set.
1657 return LoopBlockSet;
1658}
1659
1660/// Rebuild a loop after unswitching removes some subset of blocks and edges.
1661///
1662/// The removal may have removed some child loops entirely but cannot have
1663/// disturbed any remaining child loops. However, they may need to be hoisted
1664/// to the parent loop (or to be top-level loops). The original loop may be
1665/// completely removed.
1666///
1667/// The sibling loops resulting from this update are returned. If the original
1668/// loop remains a valid loop, it will be the first entry in this list with all
1669/// of the newly sibling loops following it.
1670///
1671/// Returns true if the loop remains a loop after unswitching, and false if it
1672/// is no longer a loop after unswitching (and should not continue to be
1673/// referenced).
1674static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1675 LoopInfo &LI,
1676 SmallVectorImpl<Loop *> &HoistedLoops) {
1677 auto *PH = L.getLoopPreheader();
1678
1679 // Compute the actual parent loop from the exit blocks. Because we may have
1680 // pruned some exits the loop may be different from the original parent.
1681 Loop *ParentL = nullptr;
1682 SmallVector<Loop *, 4> ExitLoops;
1683 SmallVector<BasicBlock *, 4> ExitsInLoops;
1684 ExitsInLoops.reserve(ExitBlocks.size());
1685 for (auto *ExitBB : ExitBlocks)
1686 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1687 ExitLoops.push_back(ExitL);
1688 ExitsInLoops.push_back(ExitBB);
1689 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1690 ParentL = ExitL;
1691 }
1692
1693 // Recompute the blocks participating in this loop. This may be empty if it
1694 // is no longer a loop.
1695 auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1696
1697 // If we still have a loop, we need to re-set the loop's parent as the exit
1698 // block set changing may have moved it within the loop nest. Note that this
1699 // can only happen when this loop has a parent as it can only hoist the loop
1700 // *up* the nest.
1701 if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1702 // Remove this loop's (original) blocks from all of the intervening loops.
1703 for (Loop *IL = L.getParentLoop(); IL != ParentL;
1704 IL = IL->getParentLoop()) {
1705 IL->getBlocksSet().erase(PH);
1706 for (auto *BB : L.blocks())
1707 IL->getBlocksSet().erase(BB);
1708 llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1709 return BB == PH || L.contains(BB);
1710 });
1711 }
1712
1713 LI.changeLoopFor(PH, ParentL);
1714 L.getParentLoop()->removeChildLoop(&L);
1715 if (ParentL)
1716 ParentL->addChildLoop(&L);
1717 else
1718 LI.addTopLevelLoop(&L);
1719 }
1720
1721 // Now we update all the blocks which are no longer within the loop.
1722 auto &Blocks = L.getBlocksVector();
1723 auto BlocksSplitI =
1724 LoopBlockSet.empty()
1725 ? Blocks.begin()
1726 : std::stable_partition(
1727 Blocks.begin(), Blocks.end(),
1728 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1729
1730 // Before we erase the list of unlooped blocks, build a set of them.
1731 SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1732 if (LoopBlockSet.empty())
1733 UnloopedBlocks.insert(PH);
1734
1735 // Now erase these blocks from the loop.
1736 for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1737 L.getBlocksSet().erase(BB);
1738 Blocks.erase(BlocksSplitI, Blocks.end());
1739
1740 // Sort the exits in ascending loop depth, we'll work backwards across these
1741 // to process them inside out.
Fangrui Songefd94c52019-04-23 14:51:27 +00001742 llvm::stable_sort(ExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1743 return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1744 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001745
1746 // We'll build up a set for each exit loop.
1747 SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1748 Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1749
1750 auto RemoveUnloopedBlocksFromLoop =
1751 [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1752 for (auto *BB : UnloopedBlocks)
1753 L.getBlocksSet().erase(BB);
1754 llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1755 return UnloopedBlocks.count(BB);
1756 });
1757 };
1758
1759 SmallVector<BasicBlock *, 16> Worklist;
1760 while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1761 assert(Worklist.empty() && "Didn't clear worklist!");
1762 assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1763
1764 // Grab the next exit block, in decreasing loop depth order.
1765 BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1766 Loop &ExitL = *LI.getLoopFor(ExitBB);
1767 assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1768
1769 // Erase all of the unlooped blocks from the loops between the previous
1770 // exit loop and this exit loop. This works because the ExitInLoops list is
1771 // sorted in increasing order of loop depth and thus we visit loops in
1772 // decreasing order of loop depth.
1773 for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1774 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1775
1776 // Walk the CFG back until we hit the cloned PH adding everything reachable
1777 // and in the unlooped set to this exit block's loop.
1778 Worklist.push_back(ExitBB);
1779 do {
1780 BasicBlock *BB = Worklist.pop_back_val();
1781 // We can stop recursing at the cloned preheader (if we get there).
1782 if (BB == PH)
1783 continue;
1784
1785 for (BasicBlock *PredBB : predecessors(BB)) {
1786 // If this pred has already been moved to our set or is part of some
1787 // (inner) loop, no update needed.
1788 if (!UnloopedBlocks.erase(PredBB)) {
1789 assert((NewExitLoopBlocks.count(PredBB) ||
1790 ExitL.contains(LI.getLoopFor(PredBB))) &&
1791 "Predecessor not in a nested loop (or already visited)!");
1792 continue;
1793 }
1794
1795 // We just insert into the loop set here. We'll add these blocks to the
1796 // exit loop after we build up the set in a deterministic order rather
1797 // than the predecessor-influenced visit order.
1798 bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1799 (void)Inserted;
1800 assert(Inserted && "Should only visit an unlooped block once!");
1801
1802 // And recurse through to its predecessors.
1803 Worklist.push_back(PredBB);
1804 }
1805 } while (!Worklist.empty());
1806
1807 // If blocks in this exit loop were directly part of the original loop (as
1808 // opposed to a child loop) update the map to point to this exit loop. This
1809 // just updates a map and so the fact that the order is unstable is fine.
1810 for (auto *BB : NewExitLoopBlocks)
1811 if (Loop *BBL = LI.getLoopFor(BB))
1812 if (BBL == &L || !L.contains(BBL))
1813 LI.changeLoopFor(BB, &ExitL);
1814
1815 // We will remove the remaining unlooped blocks from this loop in the next
1816 // iteration or below.
1817 NewExitLoopBlocks.clear();
1818 }
1819
1820 // Any remaining unlooped blocks are no longer part of any loop unless they
1821 // are part of some child loop.
1822 for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1823 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1824 for (auto *BB : UnloopedBlocks)
1825 if (Loop *BBL = LI.getLoopFor(BB))
1826 if (BBL == &L || !L.contains(BBL))
1827 LI.changeLoopFor(BB, nullptr);
1828
1829 // Sink all the child loops whose headers are no longer in the loop set to
1830 // the parent (or to be top level loops). We reach into the loop and directly
1831 // update its subloop vector to make this batch update efficient.
1832 auto &SubLoops = L.getSubLoopsVector();
1833 auto SubLoopsSplitI =
1834 LoopBlockSet.empty()
1835 ? SubLoops.begin()
1836 : std::stable_partition(
1837 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1838 return LoopBlockSet.count(SubL->getHeader());
1839 });
1840 for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1841 HoistedLoops.push_back(HoistedL);
1842 HoistedL->setParentLoop(nullptr);
1843
1844 // To compute the new parent of this hoisted loop we look at where we
1845 // placed the preheader above. We can't lookup the header itself because we
1846 // retained the mapping from the header to the hoisted loop. But the
1847 // preheader and header should have the exact same new parent computed
1848 // based on the set of exit blocks from the original loop as the preheader
1849 // is a predecessor of the header and so reached in the reverse walk. And
1850 // because the loops were all in simplified form the preheader of the
1851 // hoisted loop can't be part of some *other* loop.
1852 if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1853 NewParentL->addChildLoop(HoistedL);
1854 else
1855 LI.addTopLevelLoop(HoistedL);
1856 }
1857 SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1858
1859 // Actually delete the loop if nothing remained within it.
1860 if (Blocks.empty()) {
1861 assert(SubLoops.empty() &&
1862 "Failed to remove all subloops from the original loop!");
1863 if (Loop *ParentL = L.getParentLoop())
1864 ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1865 else
1866 LI.removeLoop(llvm::find(LI, &L));
1867 LI.destroy(&L);
1868 return false;
1869 }
1870
1871 return true;
1872}
1873
1874/// Helper to visit a dominator subtree, invoking a callable on each node.
1875///
1876/// Returning false at any point will stop walking past that node of the tree.
1877template <typename CallableT>
1878void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1879 SmallVector<DomTreeNode *, 4> DomWorklist;
1880 DomWorklist.push_back(DT[BB]);
1881#ifndef NDEBUG
1882 SmallPtrSet<DomTreeNode *, 4> Visited;
1883 Visited.insert(DT[BB]);
1884#endif
1885 do {
1886 DomTreeNode *N = DomWorklist.pop_back_val();
1887
1888 // Visit this node.
1889 if (!Callable(N->getBlock()))
1890 continue;
1891
1892 // Accumulate the child nodes.
1893 for (DomTreeNode *ChildN : *N) {
1894 assert(Visited.insert(ChildN).second &&
1895 "Cannot visit a node twice when walking a tree!");
1896 DomWorklist.push_back(ChildN);
1897 }
1898 } while (!DomWorklist.empty());
1899}
1900
Max Kazantsevbde31002018-10-26 09:52:58 +00001901static void unswitchNontrivialInvariants(
Chandler Carruth60b2e052018-10-18 00:40:26 +00001902 Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
Max Kazantsevbde31002018-10-26 09:52:58 +00001903 SmallVectorImpl<BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI,
1904 AssumptionCache &AC, function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001905 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruth16529962018-06-25 23:32:54 +00001906 auto *ParentBB = TI.getParent();
1907 BranchInst *BI = dyn_cast<BranchInst>(&TI);
1908 SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001909
Chandler Carruth16529962018-06-25 23:32:54 +00001910 // We can only unswitch switches, conditional branches with an invariant
1911 // condition, or combining invariant conditions with an instruction.
Simon Pilgrimc598ef72019-10-16 10:38:18 +00001912 assert((SI || (BI && BI->isConditional())) &&
Chandler Carruth16529962018-06-25 23:32:54 +00001913 "Can only unswitch switches and conditional branch!");
1914 bool FullUnswitch = SI || BI->getCondition() == Invariants[0];
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001915 if (FullUnswitch)
1916 assert(Invariants.size() == 1 &&
1917 "Cannot have other invariants with full unswitching!");
1918 else
Chandler Carruth16529962018-06-25 23:32:54 +00001919 assert(isa<Instruction>(BI->getCondition()) &&
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001920 "Partial unswitching requires an instruction as the condition!");
1921
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001922 if (MSSAU && VerifyMemorySSA)
1923 MSSAU->getMemorySSA()->verifyMemorySSA();
1924
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001925 // Constant and BBs tracking the cloned and continuing successor. When we are
1926 // unswitching the entire condition, this can just be trivially chosen to
1927 // unswitch towards `true`. However, when we are unswitching a set of
1928 // invariants combined with `and` or `or`, the combining operation determines
1929 // the best direction to unswitch: we want to unswitch the direction that will
1930 // collapse the branch.
1931 bool Direction = true;
1932 int ClonedSucc = 0;
1933 if (!FullUnswitch) {
Chandler Carruth16529962018-06-25 23:32:54 +00001934 if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) {
1935 assert(cast<Instruction>(BI->getCondition())->getOpcode() ==
1936 Instruction::And &&
1937 "Only `or` and `and` instructions can combine invariants being "
1938 "unswitched.");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001939 Direction = false;
1940 ClonedSucc = 1;
1941 }
1942 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001943
Chandler Carruth16529962018-06-25 23:32:54 +00001944 BasicBlock *RetainedSuccBB =
1945 BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
1946 SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
1947 if (BI)
1948 UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
1949 else
1950 for (auto Case : SI->cases())
Chandler Carruthed296542018-07-09 10:30:48 +00001951 if (Case.getCaseSuccessor() != RetainedSuccBB)
1952 UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
Chandler Carruth16529962018-06-25 23:32:54 +00001953
1954 assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
1955 "Should not unswitch the same successor we are retaining!");
Chandler Carruth693eedb2017-11-17 19:58:36 +00001956
1957 // The branch should be in this exact loop. Any inner loop's invariant branch
1958 // should be handled by unswitching that inner loop. The caller of this
1959 // routine should filter out any candidates that remain (but were skipped for
1960 // whatever reason).
1961 assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
1962
Chandler Carruth693eedb2017-11-17 19:58:36 +00001963 // Compute the parent loop now before we start hacking on things.
1964 Loop *ParentL = L.getParentLoop();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00001965 // Get blocks in RPO order for MSSA update, before changing the CFG.
1966 LoopBlocksRPO LBRPO(&L);
1967 if (MSSAU)
1968 LBRPO.perform(&LI);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001969
1970 // Compute the outer-most loop containing one of our exit blocks. This is the
1971 // furthest up our loopnest which can be mutated, which we will use below to
1972 // update things.
1973 Loop *OuterExitL = &L;
1974 for (auto *ExitBB : ExitBlocks) {
1975 Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
1976 if (!NewOuterExitL) {
1977 // We exited the entire nest with this block, so we're done.
1978 OuterExitL = nullptr;
1979 break;
1980 }
1981 if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
1982 OuterExitL = NewOuterExitL;
1983 }
1984
Chandler Carruth3897ded2018-07-03 09:13:27 +00001985 // At this point, we're definitely going to unswitch something so invalidate
1986 // any cached information in ScalarEvolution for the outer most loop
1987 // containing an exit block and all nested loops.
1988 if (SE) {
1989 if (OuterExitL)
1990 SE->forgetLoop(OuterExitL);
1991 else
1992 SE->forgetTopmostLoop(&L);
1993 }
1994
Chandler Carruth16529962018-06-25 23:32:54 +00001995 // If the edge from this terminator to a successor dominates that successor,
1996 // store a map from each block in its dominator subtree to it. This lets us
1997 // tell when cloning for a particular successor if a block is dominated by
1998 // some *other* successor with a single data structure. We use this to
1999 // significantly reduce cloning.
2000 SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
2001 for (auto *SuccBB : llvm::concat<BasicBlock *const>(
2002 makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
2003 if (SuccBB->getUniquePredecessor() ||
2004 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2005 return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
2006 }))
2007 visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
2008 DominatingSucc[BB] = SuccBB;
2009 return true;
2010 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00002011
2012 // Split the preheader, so that we know that there is a safe place to insert
2013 // the conditional branch. We will change the preheader to have a conditional
2014 // branch on LoopCond. The original preheader will become the split point
2015 // between the unswitched versions, and we will have a new preheader for the
2016 // original loop.
2017 BasicBlock *SplitBB = L.getLoopPreheader();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002018 BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002019
Chandler Carruth69e68f82018-04-25 00:18:07 +00002020 // Keep track of the dominator tree updates needed.
2021 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2022
Chandler Carruth16529962018-06-25 23:32:54 +00002023 // Clone the loop for each unswitched successor.
2024 SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
2025 VMaps.reserve(UnswitchedSuccBBs.size());
2026 SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
2027 for (auto *SuccBB : UnswitchedSuccBBs) {
2028 VMaps.emplace_back(new ValueToValueMapTy());
2029 ClonedPHs[SuccBB] = buildClonedLoopBlocks(
2030 L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002031 DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU);
Chandler Carruth16529962018-06-25 23:32:54 +00002032 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002033
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002034 // The stitching of the branched code back together depends on whether we're
2035 // doing full unswitching or not with the exception that we always want to
2036 // nuke the initial terminator placed in the split block.
Chandler Carruth693eedb2017-11-17 19:58:36 +00002037 SplitBB->getTerminator()->eraseFromParent();
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002038 if (FullUnswitch) {
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002039 // Splice the terminator from the original loop and rewrite its
2040 // successors.
2041 SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
2042
2043 // Keep a clone of the terminator for MSSA updates.
2044 Instruction *NewTI = TI.clone();
2045 ParentBB->getInstList().push_back(NewTI);
2046
2047 // First wire up the moved terminator to the preheaders.
2048 if (BI) {
2049 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2050 BI->setSuccessor(ClonedSucc, ClonedPH);
2051 BI->setSuccessor(1 - ClonedSucc, LoopPH);
2052 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2053 } else {
2054 assert(SI && "Must either be a branch or switch!");
2055
2056 // Walk the cases and directly update their successors.
2057 assert(SI->getDefaultDest() == RetainedSuccBB &&
2058 "Not retaining default successor!");
2059 SI->setDefaultDest(LoopPH);
2060 for (auto &Case : SI->cases())
2061 if (Case.getCaseSuccessor() == RetainedSuccBB)
2062 Case.setSuccessor(LoopPH);
2063 else
2064 Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
2065
2066 // We need to use the set to populate domtree updates as even when there
2067 // are multiple cases pointing at the same successor we only want to
2068 // remove and insert one edge in the domtree.
2069 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2070 DTUpdates.push_back(
2071 {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
2072 }
2073
2074 if (MSSAU) {
2075 DT.applyUpdates(DTUpdates);
2076 DTUpdates.clear();
2077
2078 // Remove all but one edge to the retained block and all unswitched
2079 // blocks. This is to avoid having duplicate entries in the cloned Phis,
2080 // when we know we only keep a single edge for each case.
2081 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
2082 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2083 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
2084
2085 for (auto &VMap : VMaps)
2086 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2087 /*IgnoreIncomingWithNoClones=*/true);
2088 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2089
2090 // Remove all edges to unswitched blocks.
2091 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2092 MSSAU->removeEdge(ParentBB, SuccBB);
2093 }
2094
2095 // Now unhook the successor relationship as we'll be replacing
Chandler Carruthed296542018-07-09 10:30:48 +00002096 // the terminator with a direct branch. This is much simpler for branches
2097 // than switches so we handle those first.
Chandler Carruth16529962018-06-25 23:32:54 +00002098 if (BI) {
Chandler Carruthed296542018-07-09 10:30:48 +00002099 // Remove the parent as a predecessor of the unswitched successor.
Chandler Carruth16529962018-06-25 23:32:54 +00002100 assert(UnswitchedSuccBBs.size() == 1 &&
2101 "Only one possible unswitched block for a branch!");
Chandler Carruthed296542018-07-09 10:30:48 +00002102 BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
2103 UnswitchedSuccBB->removePredecessor(ParentBB,
Max Kazantsev20b91892019-02-12 07:09:29 +00002104 /*KeepOneInputPHIs*/ true);
Chandler Carruthed296542018-07-09 10:30:48 +00002105 DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
2106 } else {
2107 // Note that we actually want to remove the parent block as a predecessor
2108 // of *every* case successor. The case successor is either unswitched,
2109 // completely eliminating an edge from the parent to that successor, or it
2110 // is a duplicate edge to the retained successor as the retained successor
2111 // is always the default successor and as we'll replace this with a direct
2112 // branch we no longer need the duplicate entries in the PHI nodes.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002113 SwitchInst *NewSI = cast<SwitchInst>(NewTI);
2114 assert(NewSI->getDefaultDest() == RetainedSuccBB &&
Chandler Carruthed296542018-07-09 10:30:48 +00002115 "Not retaining default successor!");
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002116 for (auto &Case : NewSI->cases())
Chandler Carruthed296542018-07-09 10:30:48 +00002117 Case.getCaseSuccessor()->removePredecessor(
2118 ParentBB,
Max Kazantsev20b91892019-02-12 07:09:29 +00002119 /*KeepOneInputPHIs*/ true);
Chandler Carruthed296542018-07-09 10:30:48 +00002120
2121 // We need to use the set to populate domtree updates as even when there
2122 // are multiple cases pointing at the same successor we only want to
2123 // remove and insert one edge in the domtree.
2124 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2125 DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
2126 }
2127
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002128 // After MSSAU update, remove the cloned terminator instruction NewTI.
2129 ParentBB->getTerminator()->eraseFromParent();
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002130
2131 // Create a new unconditional branch to the continuing block (as opposed to
2132 // the one cloned).
Chandler Carruth16529962018-06-25 23:32:54 +00002133 BranchInst::Create(RetainedSuccBB, ParentBB);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002134 } else {
Chandler Carruth16529962018-06-25 23:32:54 +00002135 assert(BI && "Only branches have partial unswitching.");
2136 assert(UnswitchedSuccBBs.size() == 1 &&
2137 "Only one possible unswitched block for a branch!");
2138 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002139 // When doing a partial unswitch, we have to do a bit more work to build up
2140 // the branch in the split block.
2141 buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
2142 *ClonedPH, *LoopPH);
Alina Sbirlea35c8af12019-10-15 17:15:19 +00002143 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2144
Alina Sbirleab7a33532019-10-14 23:52:39 +00002145 if (MSSAU) {
Alina Sbirlea35c8af12019-10-15 17:15:19 +00002146 DT.applyUpdates(DTUpdates);
2147 DTUpdates.clear();
2148
Alina Sbirleab7a33532019-10-14 23:52:39 +00002149 // Perform MSSA cloning updates.
2150 for (auto &VMap : VMaps)
2151 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2152 /*IgnoreIncomingWithNoClones=*/true);
2153 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2154 }
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002155 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002156
Chandler Carruth16529962018-06-25 23:32:54 +00002157 // Apply the updates accumulated above to get an up-to-date dominator tree.
Chandler Carruth69e68f82018-04-25 00:18:07 +00002158 DT.applyUpdates(DTUpdates);
2159
Chandler Carruth16529962018-06-25 23:32:54 +00002160 // Now that we have an accurate dominator tree, first delete the dead cloned
2161 // blocks so that we can accurately build any cloned loops. It is important to
2162 // not delete the blocks from the original loop yet because we still want to
2163 // reference the original loop to understand the cloned loop's structure.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002164 deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
Chandler Carruth16529962018-06-25 23:32:54 +00002165
Chandler Carruth69e68f82018-04-25 00:18:07 +00002166 // Build the cloned loop structure itself. This may be substantially
2167 // different from the original structure due to the simplified CFG. This also
2168 // handles inserting all the cloned blocks into the correct loops.
2169 SmallVector<Loop *, 4> NonChildClonedLoops;
Chandler Carruth16529962018-06-25 23:32:54 +00002170 for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2171 buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
Chandler Carruth69e68f82018-04-25 00:18:07 +00002172
Chandler Carruth16529962018-06-25 23:32:54 +00002173 // Now that our cloned loops have been built, we can update the original loop.
2174 // First we delete the dead blocks from it and then we rebuild the loop
2175 // structure taking these deletions into account.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002176 deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU);
2177
2178 if (MSSAU && VerifyMemorySSA)
2179 MSSAU->getMemorySSA()->verifyMemorySSA();
2180
Chandler Carruth693eedb2017-11-17 19:58:36 +00002181 SmallVector<Loop *, 4> HoistedLoops;
2182 bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
2183
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002184 if (MSSAU && VerifyMemorySSA)
2185 MSSAU->getMemorySSA()->verifyMemorySSA();
2186
Chandler Carruth69e68f82018-04-25 00:18:07 +00002187 // This transformation has a high risk of corrupting the dominator tree, and
2188 // the below steps to rebuild loop structures will result in hard to debug
2189 // errors in that case so verify that the dominator tree is sane first.
2190 // FIXME: Remove this when the bugs stop showing up and rely on existing
2191 // verification steps.
2192 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruth693eedb2017-11-17 19:58:36 +00002193
Chandler Carruth16529962018-06-25 23:32:54 +00002194 if (BI) {
2195 // If we unswitched a branch which collapses the condition to a known
2196 // constant we want to replace all the uses of the invariants within both
2197 // the original and cloned blocks. We do this here so that we can use the
2198 // now updated dominator tree to identify which side the users are on.
2199 assert(UnswitchedSuccBBs.size() == 1 &&
2200 "Only one possible unswitched block for a branch!");
2201 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
Fedor Sergeevf9a02a72018-11-07 20:05:11 +00002202
2203 // When considering multiple partially-unswitched invariants
2204 // we cant just go replace them with constants in both branches.
2205 //
2206 // For 'AND' we infer that true branch ("continue") means true
2207 // for each invariant operand.
2208 // For 'OR' we can infer that false branch ("continue") means false
2209 // for each invariant operand.
2210 // So it happens that for multiple-partial case we dont replace
2211 // in the unswitched branch.
2212 bool ReplaceUnswitched = FullUnswitch || (Invariants.size() == 1);
2213
Chandler Carruth16529962018-06-25 23:32:54 +00002214 ConstantInt *UnswitchedReplacement =
2215 Direction ? ConstantInt::getTrue(BI->getContext())
2216 : ConstantInt::getFalse(BI->getContext());
2217 ConstantInt *ContinueReplacement =
2218 Direction ? ConstantInt::getFalse(BI->getContext())
2219 : ConstantInt::getTrue(BI->getContext());
2220 for (Value *Invariant : Invariants)
2221 for (auto UI = Invariant->use_begin(), UE = Invariant->use_end();
2222 UI != UE;) {
2223 // Grab the use and walk past it so we can clobber it in the use list.
2224 Use *U = &*UI++;
2225 Instruction *UserI = dyn_cast<Instruction>(U->getUser());
2226 if (!UserI)
2227 continue;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002228
Chandler Carruth16529962018-06-25 23:32:54 +00002229 // Replace it with the 'continue' side if in the main loop body, and the
2230 // unswitched if in the cloned blocks.
2231 if (DT.dominates(LoopPH, UserI->getParent()))
2232 U->set(ContinueReplacement);
Fedor Sergeevf9a02a72018-11-07 20:05:11 +00002233 else if (ReplaceUnswitched &&
2234 DT.dominates(ClonedPH, UserI->getParent()))
Chandler Carruth16529962018-06-25 23:32:54 +00002235 U->set(UnswitchedReplacement);
2236 }
2237 }
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002238
Chandler Carruth693eedb2017-11-17 19:58:36 +00002239 // We can change which blocks are exit blocks of all the cloned sibling
2240 // loops, the current loop, and any parent loops which shared exit blocks
2241 // with the current loop. As a consequence, we need to re-form LCSSA for
2242 // them. But we shouldn't need to re-form LCSSA for any child loops.
2243 // FIXME: This could be made more efficient by tracking which exit blocks are
2244 // new, and focusing on them, but that isn't likely to be necessary.
2245 //
2246 // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2247 // loop nest and update every loop that could have had its exits changed. We
2248 // also need to cover any intervening loops. We add all of these loops to
2249 // a list and sort them by loop depth to achieve this without updating
2250 // unnecessary loops.
Chandler Carruth92815032018-06-02 01:29:01 +00002251 auto UpdateLoop = [&](Loop &UpdateL) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002252#ifndef NDEBUG
Chandler Carruth43acdb32018-04-24 10:33:08 +00002253 UpdateL.verifyLoop();
2254 for (Loop *ChildL : UpdateL) {
2255 ChildL->verifyLoop();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002256 assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2257 "Perturbed a child loop's LCSSA form!");
Chandler Carruth43acdb32018-04-24 10:33:08 +00002258 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002259#endif
Chandler Carruth92815032018-06-02 01:29:01 +00002260 // First build LCSSA for this loop so that we can preserve it when
2261 // forming dedicated exits. We don't want to perturb some other loop's
2262 // LCSSA while doing that CFG edit.
Chandler Carruth693eedb2017-11-17 19:58:36 +00002263 formLCSSA(UpdateL, DT, &LI, nullptr);
Chandler Carruth92815032018-06-02 01:29:01 +00002264
2265 // For loops reached by this loop's original exit blocks we may
2266 // introduced new, non-dedicated exits. At least try to re-form dedicated
2267 // exits for these loops. This may fail if they couldn't have dedicated
2268 // exits to start with.
Alina Sbirlea97468e92019-02-21 21:13:34 +00002269 formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002270 };
2271
2272 // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2273 // and we can do it in any order as they don't nest relative to each other.
Chandler Carruth92815032018-06-02 01:29:01 +00002274 //
2275 // Also check if any of the loops we have updated have become top-level loops
2276 // as that will necessitate widening the outer loop scope.
2277 for (Loop *UpdatedL :
2278 llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2279 UpdateLoop(*UpdatedL);
2280 if (!UpdatedL->getParentLoop())
2281 OuterExitL = nullptr;
2282 }
2283 if (IsStillLoop) {
2284 UpdateLoop(L);
2285 if (!L.getParentLoop())
2286 OuterExitL = nullptr;
2287 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002288
2289 // If the original loop had exit blocks, walk up through the outer most loop
2290 // of those exit blocks to update LCSSA and form updated dedicated exits.
Chandler Carruth92815032018-06-02 01:29:01 +00002291 if (OuterExitL != &L)
Chandler Carruth693eedb2017-11-17 19:58:36 +00002292 for (Loop *OuterL = ParentL; OuterL != OuterExitL;
2293 OuterL = OuterL->getParentLoop())
Chandler Carruth92815032018-06-02 01:29:01 +00002294 UpdateLoop(*OuterL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002295
2296#ifndef NDEBUG
2297 // Verify the entire loop structure to catch any incorrect updates before we
2298 // progress in the pass pipeline.
2299 LI.verify(DT);
2300#endif
2301
2302 // Now that we've unswitched something, make callbacks to report the changes.
2303 // For that we need to merge together the updated loops and the cloned loops
2304 // and check whether the original loop survived.
2305 SmallVector<Loop *, 4> SibLoops;
2306 for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2307 if (UpdatedL->getParentLoop() == ParentL)
2308 SibLoops.push_back(UpdatedL);
Chandler Carruth71fd2702018-05-30 02:46:45 +00002309 UnswitchCB(IsStillLoop, SibLoops);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002310
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002311 if (MSSAU && VerifyMemorySSA)
2312 MSSAU->getMemorySSA()->verifyMemorySSA();
2313
Zaara Syedab7dff9c2019-01-15 15:08:01 +00002314 if (BI)
2315 ++NumBranches;
2316 else
2317 ++NumSwitches;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002318}
2319
2320/// Recursively compute the cost of a dominator subtree based on the per-block
2321/// cost map provided.
2322///
2323/// The recursive computation is memozied into the provided DT-indexed cost map
2324/// to allow querying it for most nodes in the domtree without it becoming
2325/// quadratic.
2326static int
2327computeDomSubtreeCost(DomTreeNode &N,
2328 const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
2329 SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
2330 // Don't accumulate cost (or recurse through) blocks not in our block cost
2331 // map and thus not part of the duplication cost being considered.
2332 auto BBCostIt = BBCostMap.find(N.getBlock());
2333 if (BBCostIt == BBCostMap.end())
2334 return 0;
2335
2336 // Lookup this node to see if we already computed its cost.
2337 auto DTCostIt = DTCostMap.find(&N);
2338 if (DTCostIt != DTCostMap.end())
2339 return DTCostIt->second;
2340
2341 // If not, we have to compute it. We can't use insert above and update
2342 // because computing the cost may insert more things into the map.
2343 int Cost = std::accumulate(
2344 N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
2345 return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2346 });
2347 bool Inserted = DTCostMap.insert({&N, Cost}).second;
2348 (void)Inserted;
2349 assert(Inserted && "Should not insert a node while visiting children!");
2350 return Cost;
2351}
2352
Max Kazantsev619a8342018-10-26 14:20:11 +00002353/// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2354/// making the following replacement:
2355///
Simon Pilgrima1320162018-10-27 15:14:42 +00002356/// --code before guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002357/// call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
Simon Pilgrima1320162018-10-27 15:14:42 +00002358/// --code after guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002359///
2360/// into
2361///
Simon Pilgrima1320162018-10-27 15:14:42 +00002362/// --code before guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002363/// br i1 %cond, label %guarded, label %deopt
2364///
2365/// guarded:
Simon Pilgrima1320162018-10-27 15:14:42 +00002366/// --code after guard--
Max Kazantsev619a8342018-10-26 14:20:11 +00002367///
2368/// deopt:
2369/// call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2370/// unreachable
2371///
2372/// It also makes all relevant DT and LI updates, so that all structures are in
2373/// valid state after this transform.
2374static BranchInst *
2375turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2376 SmallVectorImpl<BasicBlock *> &ExitBlocks,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002377 DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Max Kazantsev619a8342018-10-26 14:20:11 +00002378 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2379 LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
2380 BasicBlock *CheckBB = GI->getParent();
2381
Alina Sbirlea797935f2018-12-04 14:43:24 +00002382 if (MSSAU && VerifyMemorySSA)
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002383 MSSAU->getMemorySSA()->verifyMemorySSA();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002384
Max Kazantsev619a8342018-10-26 14:20:11 +00002385 // Remove all CheckBB's successors from DomTree. A block can be seen among
2386 // successors more than once, but for DomTree it should be added only once.
2387 SmallPtrSet<BasicBlock *, 4> Successors;
2388 for (auto *Succ : successors(CheckBB))
2389 if (Successors.insert(Succ).second)
2390 DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
2391
2392 Instruction *DeoptBlockTerm =
2393 SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
2394 BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
2395 // SplitBlockAndInsertIfThen inserts control flow that branches to
2396 // DeoptBlockTerm if the condition is true. We want the opposite.
2397 CheckBI->swapSuccessors();
2398
2399 BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2400 GuardedBlock->setName("guarded");
2401 CheckBI->getSuccessor(1)->setName("deopt");
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002402 BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
Max Kazantsev619a8342018-10-26 14:20:11 +00002403
2404 // We now have a new exit block.
2405 ExitBlocks.push_back(CheckBI->getSuccessor(1));
2406
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002407 if (MSSAU)
2408 MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
2409
Max Kazantsev619a8342018-10-26 14:20:11 +00002410 GI->moveBefore(DeoptBlockTerm);
2411 GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
2412
2413 // Add new successors of CheckBB into DomTree.
2414 for (auto *Succ : successors(CheckBB))
2415 DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
2416
2417 // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2418 // successors.
2419 for (auto *Succ : Successors)
2420 DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
2421
2422 // Make proper changes to DT.
2423 DT.applyUpdates(DTUpdates);
2424 // Inform LI of a new loop block.
2425 L.addBasicBlockToLoop(GuardedBlock, LI);
2426
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002427 if (MSSAU) {
2428 MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
2429 MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::End);
2430 if (VerifyMemorySSA)
2431 MSSAU->getMemorySSA()->verifyMemorySSA();
2432 }
2433
Max Kazantsev619a8342018-10-26 14:20:11 +00002434 ++NumGuards;
2435 return CheckBI;
2436}
2437
Fedor Sergeev2e3e2242018-11-16 21:16:43 +00002438/// Cost multiplier is a way to limit potentially exponential behavior
2439/// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
2440/// candidates available. Also accounting for the number of "sibling" loops with
2441/// the idea to account for previous unswitches that already happened on this
2442/// cluster of loops. There was an attempt to keep this formula simple,
2443/// just enough to limit the worst case behavior. Even if it is not that simple
2444/// now it is still not an attempt to provide a detailed heuristic size
2445/// prediction.
2446///
2447/// TODO: Make a proper accounting of "explosion" effect for all kinds of
2448/// unswitch candidates, making adequate predictions instead of wild guesses.
2449/// That requires knowing not just the number of "remaining" candidates but
2450/// also costs of unswitching for each of these candidates.
2451static int calculateUnswitchCostMultiplier(
2452 Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT,
2453 ArrayRef<std::pair<Instruction *, TinyPtrVector<Value *>>>
2454 UnswitchCandidates) {
2455
2456 // Guards and other exiting conditions do not contribute to exponential
2457 // explosion as soon as they dominate the latch (otherwise there might be
2458 // another path to the latch remaining that does not allow to eliminate the
2459 // loop copy on unswitch).
2460 BasicBlock *Latch = L.getLoopLatch();
2461 BasicBlock *CondBlock = TI.getParent();
2462 if (DT.dominates(CondBlock, Latch) &&
2463 (isGuard(&TI) ||
2464 llvm::count_if(successors(&TI), [&L](BasicBlock *SuccBB) {
2465 return L.contains(SuccBB);
2466 }) <= 1)) {
2467 NumCostMultiplierSkipped++;
2468 return 1;
2469 }
2470
2471 auto *ParentL = L.getParentLoop();
2472 int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
2473 : std::distance(LI.begin(), LI.end()));
2474 // Count amount of clones that all the candidates might cause during
2475 // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
2476 int UnswitchedClones = 0;
2477 for (auto Candidate : UnswitchCandidates) {
2478 Instruction *CI = Candidate.first;
2479 BasicBlock *CondBlock = CI->getParent();
2480 bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
2481 if (isGuard(CI)) {
2482 if (!SkipExitingSuccessors)
2483 UnswitchedClones++;
2484 continue;
2485 }
2486 int NonExitingSuccessors = llvm::count_if(
2487 successors(CondBlock), [SkipExitingSuccessors, &L](BasicBlock *SuccBB) {
2488 return !SkipExitingSuccessors || L.contains(SuccBB);
2489 });
2490 UnswitchedClones += Log2_32(NonExitingSuccessors);
2491 }
2492
2493 // Ignore up to the "unscaled candidates" number of unswitch candidates
2494 // when calculating the power-of-two scaling of the cost. The main idea
2495 // with this control is to allow a small number of unswitches to happen
2496 // and rely more on siblings multiplier (see below) when the number
2497 // of candidates is small.
2498 unsigned ClonesPower =
2499 std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
2500
2501 // Allowing top-level loops to spread a bit more than nested ones.
2502 int SiblingsMultiplier =
2503 std::max((ParentL ? SiblingsCount
2504 : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
2505 1);
2506 // Compute the cost multiplier in a way that won't overflow by saturating
2507 // at an upper bound.
2508 int CostMultiplier;
2509 if (ClonesPower > Log2_32(UnswitchThreshold) ||
2510 SiblingsMultiplier > UnswitchThreshold)
2511 CostMultiplier = UnswitchThreshold;
2512 else
2513 CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
2514 (int)UnswitchThreshold);
2515
2516 LLVM_DEBUG(dbgs() << " Computed multiplier " << CostMultiplier
2517 << " (siblings " << SiblingsMultiplier << " * clones "
2518 << (1 << ClonesPower) << ")"
2519 << " for unswitch candidate: " << TI << "\n");
2520 return CostMultiplier;
2521}
2522
Chandler Carruth3897ded2018-07-03 09:13:27 +00002523static bool
2524unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
2525 AssumptionCache &AC, TargetTransformInfo &TTI,
2526 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002527 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002528 // Collect all invariant conditions within this loop (as opposed to an inner
2529 // loop which would be handled when visiting that inner loop).
Chandler Carruth60b2e052018-10-18 00:40:26 +00002530 SmallVector<std::pair<Instruction *, TinyPtrVector<Value *>>, 4>
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002531 UnswitchCandidates;
Max Kazantsev619a8342018-10-26 14:20:11 +00002532
2533 // Whether or not we should also collect guards in the loop.
2534 bool CollectGuards = false;
2535 if (UnswitchGuards) {
2536 auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
2537 Intrinsic::getName(Intrinsic::experimental_guard));
2538 if (GuardDecl && !GuardDecl->use_empty())
2539 CollectGuards = true;
2540 }
2541
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002542 for (auto *BB : L.blocks()) {
2543 if (LI.getLoopFor(BB) != &L)
2544 continue;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002545
Max Kazantsev619a8342018-10-26 14:20:11 +00002546 if (CollectGuards)
2547 for (auto &I : *BB)
2548 if (isGuard(&I)) {
2549 auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0);
2550 // TODO: Support AND, OR conditions and partial unswitching.
2551 if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
2552 UnswitchCandidates.push_back({&I, {Cond}});
2553 }
2554
Chandler Carruth16529962018-06-25 23:32:54 +00002555 if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2556 // We can only consider fully loop-invariant switch conditions as we need
2557 // to completely eliminate the switch after unswitching.
2558 if (!isa<Constant>(SI->getCondition()) &&
Serguei Katkovd000f8b2019-07-10 10:25:22 +00002559 L.isLoopInvariant(SI->getCondition()) && !BB->getUniqueSuccessor())
Chandler Carruth16529962018-06-25 23:32:54 +00002560 UnswitchCandidates.push_back({SI, {SI->getCondition()}});
2561 continue;
2562 }
2563
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002564 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002565 if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2566 BI->getSuccessor(0) == BI->getSuccessor(1))
2567 continue;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002568
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002569 if (L.isLoopInvariant(BI->getCondition())) {
2570 UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2571 continue;
2572 }
2573
2574 Instruction &CondI = *cast<Instruction>(BI->getCondition());
2575 if (CondI.getOpcode() != Instruction::And &&
2576 CondI.getOpcode() != Instruction::Or)
2577 continue;
2578
2579 TinyPtrVector<Value *> Invariants =
2580 collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2581 if (Invariants.empty())
2582 continue;
2583
2584 UnswitchCandidates.push_back({BI, std::move(Invariants)});
Chandler Carruth71fd2702018-05-30 02:46:45 +00002585 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002586
Chandler Carruth693eedb2017-11-17 19:58:36 +00002587 // If we didn't find any candidates, we're done.
2588 if (UnswitchCandidates.empty())
Chandler Carruth71fd2702018-05-30 02:46:45 +00002589 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002590
Chandler Carruth32e62f92018-04-19 18:44:25 +00002591 // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2592 // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2593 // irreducible control flow into reducible control flow and introduce new
2594 // loops "out of thin air". If we ever discover important use cases for doing
2595 // this, we can add support to loop unswitch, but it is a lot of complexity
Hiroshi Inouef2096492018-06-14 05:41:49 +00002596 // for what seems little or no real world benefit.
Chandler Carruth32e62f92018-04-19 18:44:25 +00002597 LoopBlocksRPO RPOT(&L);
2598 RPOT.perform(&LI);
2599 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
Chandler Carruth71fd2702018-05-30 02:46:45 +00002600 return false;
Chandler Carruth32e62f92018-04-19 18:44:25 +00002601
Max Kazantsevbde31002018-10-26 09:52:58 +00002602 SmallVector<BasicBlock *, 4> ExitBlocks;
2603 L.getUniqueExitBlocks(ExitBlocks);
2604
2605 // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
2606 // don't know how to split those exit blocks.
2607 // FIXME: We should teach SplitBlock to handle this and remove this
2608 // restriction.
2609 for (auto *ExitBB : ExitBlocks)
2610 if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI())) {
2611 dbgs() << "Cannot unswitch because of cleanuppad in exit block\n";
2612 return false;
2613 }
2614
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002615 LLVM_DEBUG(
2616 dbgs() << "Considering " << UnswitchCandidates.size()
2617 << " non-trivial loop invariant conditions for unswitching.\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002618
2619 // Given that unswitching these terminators will require duplicating parts of
2620 // the loop, so we need to be able to model that cost. Compute the ephemeral
2621 // values and set up a data structure to hold per-BB costs. We cache each
2622 // block's cost so that we don't recompute this when considering different
2623 // subsets of the loop for duplication during unswitching.
2624 SmallPtrSet<const Value *, 4> EphValues;
2625 CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2626 SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
2627
2628 // Compute the cost of each block, as well as the total loop cost. Also, bail
2629 // out if we see instructions which are incompatible with loop unswitching
2630 // (convergent, noduplicate, or cross-basic-block tokens).
2631 // FIXME: We might be able to safely handle some of these in non-duplicated
2632 // regions.
2633 int LoopCost = 0;
2634 for (auto *BB : L.blocks()) {
2635 int Cost = 0;
2636 for (auto &I : *BB) {
2637 if (EphValues.count(&I))
2638 continue;
2639
2640 if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
Chandler Carruth71fd2702018-05-30 02:46:45 +00002641 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002642 if (auto CS = CallSite(&I))
2643 if (CS.isConvergent() || CS.cannotDuplicate())
Chandler Carruth71fd2702018-05-30 02:46:45 +00002644 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002645
2646 Cost += TTI.getUserCost(&I);
2647 }
2648 assert(Cost >= 0 && "Must not have negative costs!");
2649 LoopCost += Cost;
2650 assert(LoopCost >= 0 && "Must not have negative loop costs!");
2651 BBCostMap[BB] = Cost;
2652 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002653 LLVM_DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002654
2655 // Now we find the best candidate by searching for the one with the following
2656 // properties in order:
2657 //
2658 // 1) An unswitching cost below the threshold
2659 // 2) The smallest number of duplicated unswitch candidates (to avoid
2660 // creating redundant subsequent unswitching)
2661 // 3) The smallest cost after unswitching.
2662 //
2663 // We prioritize reducing fanout of unswitch candidates provided the cost
2664 // remains below the threshold because this has a multiplicative effect.
2665 //
2666 // This requires memoizing each dominator subtree to avoid redundant work.
2667 //
2668 // FIXME: Need to actually do the number of candidates part above.
2669 SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
2670 // Given a terminator which might be unswitched, computes the non-duplicated
2671 // cost for that terminator.
Chandler Carruth60b2e052018-10-18 00:40:26 +00002672 auto ComputeUnswitchedCost = [&](Instruction &TI, bool FullUnswitch) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002673 BasicBlock &BB = *TI.getParent();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002674 SmallPtrSet<BasicBlock *, 4> Visited;
2675
2676 int Cost = LoopCost;
2677 for (BasicBlock *SuccBB : successors(&BB)) {
2678 // Don't count successors more than once.
2679 if (!Visited.insert(SuccBB).second)
2680 continue;
2681
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002682 // If this is a partial unswitch candidate, then it must be a conditional
2683 // branch with a condition of either `or` or `and`. In that case, one of
2684 // the successors is necessarily duplicated, so don't even try to remove
2685 // its cost.
2686 if (!FullUnswitch) {
2687 auto &BI = cast<BranchInst>(TI);
2688 if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2689 Instruction::And) {
2690 if (SuccBB == BI.getSuccessor(1))
2691 continue;
2692 } else {
2693 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2694 Instruction::Or &&
2695 "Only `and` and `or` conditions can result in a partial "
2696 "unswitch!");
2697 if (SuccBB == BI.getSuccessor(0))
2698 continue;
2699 }
2700 }
2701
Chandler Carruth693eedb2017-11-17 19:58:36 +00002702 // This successor's domtree will not need to be duplicated after
2703 // unswitching if the edge to the successor dominates it (and thus the
2704 // entire tree). This essentially means there is no other path into this
2705 // subtree and so it will end up live in only one clone of the loop.
2706 if (SuccBB->getUniquePredecessor() ||
2707 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2708 return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2709 })) {
2710 Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2711 assert(Cost >= 0 &&
2712 "Non-duplicated cost should never exceed total loop cost!");
2713 }
2714 }
2715
2716 // Now scale the cost by the number of unique successors minus one. We
2717 // subtract one because there is already at least one copy of the entire
2718 // loop. This is computing the new cost of unswitching a condition.
Max Kazantsev619a8342018-10-26 14:20:11 +00002719 // Note that guards always have 2 unique successors that are implicit and
2720 // will be materialized if we decide to unswitch it.
2721 int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
2722 assert(SuccessorsCount > 1 &&
Chandler Carruth693eedb2017-11-17 19:58:36 +00002723 "Cannot unswitch a condition without multiple distinct successors!");
Max Kazantsev619a8342018-10-26 14:20:11 +00002724 return Cost * (SuccessorsCount - 1);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002725 };
Chandler Carruth60b2e052018-10-18 00:40:26 +00002726 Instruction *BestUnswitchTI = nullptr;
Simon Pilgrimc598ef72019-10-16 10:38:18 +00002727 int BestUnswitchCost = 0;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002728 ArrayRef<Value *> BestUnswitchInvariants;
2729 for (auto &TerminatorAndInvariants : UnswitchCandidates) {
Chandler Carruth60b2e052018-10-18 00:40:26 +00002730 Instruction &TI = *TerminatorAndInvariants.first;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002731 ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2732 BranchInst *BI = dyn_cast<BranchInst>(&TI);
Chandler Carruth16529962018-06-25 23:32:54 +00002733 int CandidateCost = ComputeUnswitchedCost(
2734 TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
2735 Invariants[0] == BI->getCondition()));
Fedor Sergeev2e3e2242018-11-16 21:16:43 +00002736 // Calculate cost multiplier which is a tool to limit potentially
2737 // exponential behavior of loop-unswitch.
2738 if (EnableUnswitchCostMultiplier) {
2739 int CostMultiplier =
2740 calculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
2741 assert(
2742 (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
2743 "cost multiplier needs to be in the range of 1..UnswitchThreshold");
2744 CandidateCost *= CostMultiplier;
2745 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2746 << " (multiplier: " << CostMultiplier << ")"
2747 << " for unswitch candidate: " << TI << "\n");
2748 } else {
2749 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2750 << " for unswitch candidate: " << TI << "\n");
2751 }
2752
Chandler Carruth693eedb2017-11-17 19:58:36 +00002753 if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002754 BestUnswitchTI = &TI;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002755 BestUnswitchCost = CandidateCost;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002756 BestUnswitchInvariants = Invariants;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002757 }
2758 }
Simon Pilgrimc598ef72019-10-16 10:38:18 +00002759 assert(BestUnswitchTI && "Failed to find loop unswitch candidate");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002760
Chandler Carruth71fd2702018-05-30 02:46:45 +00002761 if (BestUnswitchCost >= UnswitchThreshold) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002762 LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
2763 << BestUnswitchCost << "\n");
Chandler Carruth71fd2702018-05-30 02:46:45 +00002764 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002765 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002766
Max Kazantsev619a8342018-10-26 14:20:11 +00002767 // If the best candidate is a guard, turn it into a branch.
2768 if (isGuard(BestUnswitchTI))
2769 BestUnswitchTI = turnGuardIntoBranch(cast<IntrinsicInst>(BestUnswitchTI), L,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002770 ExitBlocks, DT, LI, MSSAU);
Max Kazantsev619a8342018-10-26 14:20:11 +00002771
Max Kazantsevbde31002018-10-26 09:52:58 +00002772 LLVM_DEBUG(dbgs() << " Unswitching non-trivial (cost = "
Chandler Carruth16529962018-06-25 23:32:54 +00002773 << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
2774 << "\n");
Max Kazantsevbde31002018-10-26 09:52:58 +00002775 unswitchNontrivialInvariants(L, *BestUnswitchTI, BestUnswitchInvariants,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002776 ExitBlocks, DT, LI, AC, UnswitchCB, SE, MSSAU);
Max Kazantsevbde31002018-10-26 09:52:58 +00002777 return true;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002778}
2779
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002780/// Unswitch control flow predicated on loop invariant conditions.
2781///
2782/// This first hoists all branches or switches which are trivial (IE, do not
2783/// require duplicating any part of the loop) out of the loop body. It then
2784/// looks at other loop invariant control flows and tries to unswitch those as
2785/// well by cloning the loop if the result is small enough.
Chandler Carruth3897ded2018-07-03 09:13:27 +00002786///
2787/// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
2788/// updated based on the unswitch.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002789/// The `MSSA` analysis is also updated if valid (i.e. its use is enabled).
Chandler Carruth3897ded2018-07-03 09:13:27 +00002790///
2791/// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
2792/// true, we will attempt to do non-trivial unswitching as well as trivial
2793/// unswitching.
2794///
2795/// The `UnswitchCB` callback provided will be run after unswitching is
2796/// complete, with the first parameter set to `true` if the provided loop
2797/// remains a loop, and a list of new sibling loops created.
2798///
2799/// If `SE` is non-null, we will update that analysis based on the unswitching
2800/// done.
2801static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
2802 AssumptionCache &AC, TargetTransformInfo &TTI,
2803 bool NonTrivial,
2804 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002805 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002806 assert(L.isRecursivelyLCSSAForm(DT, LI) &&
2807 "Loops must be in LCSSA form before unswitching.");
2808 bool Changed = false;
2809
2810 // Must be in loop simplified form: we need a preheader and dedicated exits.
2811 if (!L.isLoopSimplifyForm())
2812 return false;
2813
2814 // Try trivial unswitch first before loop over other basic blocks in the loop.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002815 if (unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002816 // If we unswitched successfully we will want to clean up the loop before
2817 // processing it further so just mark it as unswitched and return.
2818 UnswitchCB(/*CurrentLoopValid*/ true, {});
2819 return true;
2820 }
2821
2822 // If we're not doing non-trivial unswitching, we're done. We both accept
2823 // a parameter but also check a local flag that can be used for testing
2824 // a debugging.
2825 if (!NonTrivial && !EnableNonTrivialUnswitch)
2826 return false;
2827
2828 // For non-trivial unswitching, because it often creates new loops, we rely on
2829 // the pass manager to iterate on the loops rather than trying to immediately
2830 // reach a fixed point. There is no substantial advantage to iterating
2831 // internally, and if any of the new loops are simplified enough to contain
2832 // trivial unswitching we want to prefer those.
2833
2834 // Try to unswitch the best invariant condition. We prefer this full unswitch to
2835 // a partial unswitch when possible below the threshold.
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002836 if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE, MSSAU))
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002837 return true;
2838
2839 // No other opportunities to unswitch.
2840 return Changed;
2841}
2842
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002843PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
2844 LoopStandardAnalysisResults &AR,
2845 LPMUpdater &U) {
2846 Function &F = *L.getHeader()->getParent();
2847 (void)F;
2848
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002849 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
2850 << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002851
Chandler Carruth693eedb2017-11-17 19:58:36 +00002852 // Save the current loop name in a variable so that we can report it even
2853 // after it has been deleted.
2854 std::string LoopName = L.getName();
2855
Chandler Carruth71fd2702018-05-30 02:46:45 +00002856 auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2857 ArrayRef<Loop *> NewLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002858 // If we did a non-trivial unswitch, we have added new (cloned) loops.
Chandler Carruth71fd2702018-05-30 02:46:45 +00002859 if (!NewLoops.empty())
2860 U.addSiblingLoops(NewLoops);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002861
2862 // If the current loop remains valid, we should revisit it to catch any
2863 // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2864 if (CurrentLoopValid)
2865 U.revisitCurrentLoop();
2866 else
2867 U.markLoopAsDeleted(L, LoopName);
2868 };
2869
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002870 Optional<MemorySSAUpdater> MSSAU;
2871 if (AR.MSSA) {
2872 MSSAU = MemorySSAUpdater(AR.MSSA);
2873 if (VerifyMemorySSA)
2874 AR.MSSA->verifyMemorySSA();
2875 }
Chandler Carruth3897ded2018-07-03 09:13:27 +00002876 if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB,
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002877 &AR.SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002878 return PreservedAnalyses::all();
2879
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002880 if (AR.MSSA && VerifyMemorySSA)
2881 AR.MSSA->verifyMemorySSA();
2882
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002883 // Historically this pass has had issues with the dominator tree so verify it
2884 // in asserts builds.
David Green7c35de12018-02-28 11:00:08 +00002885 assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
Alina Sbirlea3cef1f72019-06-11 18:27:49 +00002886
2887 auto PA = getLoopPassPreservedAnalyses();
Alina Sbirleaf92109d2019-08-17 01:02:12 +00002888 if (AR.MSSA)
Alina Sbirlea3cef1f72019-06-11 18:27:49 +00002889 PA.preserve<MemorySSAAnalysis>();
2890 return PA;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002891}
2892
2893namespace {
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002894
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002895class SimpleLoopUnswitchLegacyPass : public LoopPass {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002896 bool NonTrivial;
2897
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002898public:
2899 static char ID; // Pass ID, replacement for typeid
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002900
Chandler Carruth693eedb2017-11-17 19:58:36 +00002901 explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2902 : LoopPass(ID), NonTrivial(NonTrivial) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002903 initializeSimpleLoopUnswitchLegacyPassPass(
2904 *PassRegistry::getPassRegistry());
2905 }
2906
2907 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
2908
2909 void getAnalysisUsage(AnalysisUsage &AU) const override {
2910 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002911 AU.addRequired<TargetTransformInfoWrapperPass>();
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002912 if (EnableMSSALoopDependency) {
2913 AU.addRequired<MemorySSAWrapperPass>();
2914 AU.addPreserved<MemorySSAWrapperPass>();
2915 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002916 getLoopAnalysisUsage(AU);
2917 }
2918};
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002919
2920} // end anonymous namespace
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002921
2922bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
2923 if (skipLoop(L))
2924 return false;
2925
2926 Function &F = *L->getHeader()->getParent();
2927
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002928 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
2929 << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002930
2931 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2932 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2933 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002934 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002935 MemorySSA *MSSA = nullptr;
2936 Optional<MemorySSAUpdater> MSSAU;
2937 if (EnableMSSALoopDependency) {
2938 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
2939 MSSAU = MemorySSAUpdater(MSSA);
2940 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002941
Chandler Carruth3897ded2018-07-03 09:13:27 +00002942 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
2943 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
2944
Chandler Carruth71fd2702018-05-30 02:46:45 +00002945 auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2946 ArrayRef<Loop *> NewLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002947 // If we did a non-trivial unswitch, we have added new (cloned) loops.
2948 for (auto *NewL : NewLoops)
2949 LPM.addLoop(*NewL);
2950
2951 // If the current loop remains valid, re-add it to the queue. This is
2952 // a little wasteful as we'll finish processing the current loop as well,
2953 // but it is the best we can do in the old PM.
2954 if (CurrentLoopValid)
2955 LPM.addLoop(*L);
2956 else
2957 LPM.markLoopAsDeleted(*L);
2958 };
2959
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002960 if (MSSA && VerifyMemorySSA)
2961 MSSA->verifyMemorySSA();
2962
2963 bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE,
2964 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
2965
2966 if (MSSA && VerifyMemorySSA)
2967 MSSA->verifyMemorySSA();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002968
2969 // If anything was unswitched, also clear any cached information about this
2970 // loop.
2971 LPM.deleteSimpleAnalysisLoop(L);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002972
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002973 // Historically this pass has had issues with the dominator tree so verify it
2974 // in asserts builds.
David Green7c35de12018-02-28 11:00:08 +00002975 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2976
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002977 return Changed;
2978}
2979
2980char SimpleLoopUnswitchLegacyPass::ID = 0;
2981INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2982 "Simple unswitch loops", false, false)
2983INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth693eedb2017-11-17 19:58:36 +00002984INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2985INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002986INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirleaa2eebb82018-12-04 14:23:37 +00002987INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002988INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2989INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2990 "Simple unswitch loops", false, false)
2991
Chandler Carruth693eedb2017-11-17 19:58:36 +00002992Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
2993 return new SimpleLoopUnswitchLegacyPass(NonTrivial);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002994}