blob: 1f3ac8af86ccd5aae5194e5250a76dafc4a654ed [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//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Chandler Carruth6bda14b2017-06-06 11:49:48 +000010#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000011#include "llvm/ADT/DenseMap.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000012#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000013#include "llvm/ADT/Sequence.h"
14#include "llvm/ADT/SetVector.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000015#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000016#include "llvm/ADT/SmallVector.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000017#include "llvm/ADT/Statistic.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000018#include "llvm/ADT/Twine.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000019#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth32e62f92018-04-19 18:44:25 +000020#include "llvm/Analysis/CFG.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000021#include "llvm/Analysis/CodeMetrics.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"
Chandler Carruth4da33312018-06-20 18:57:07 +000027#include "llvm/Analysis/Utils/Local.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000028#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/Constant.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000030#include "llvm/IR/Constants.h"
31#include "llvm/IR/Dominators.h"
32#include "llvm/IR/Function.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000033#include "llvm/IR/InstrTypes.h"
34#include "llvm/IR/Instruction.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000035#include "llvm/IR/Instructions.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000036#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000037#include "llvm/IR/Use.h"
38#include "llvm/IR/Value.h"
39#include "llvm/Pass.h"
40#include "llvm/Support/Casting.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000041#include "llvm/Support/Debug.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000042#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/GenericDomTree.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000044#include "llvm/Support/raw_ostream.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000045#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000047#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruth1353f9a2017-04-27 18:45:20 +000048#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruth693eedb2017-11-17 19:58:36 +000049#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenkoa369a452017-05-16 23:10:25 +000050#include <algorithm>
51#include <cassert>
52#include <iterator>
Chandler Carruth693eedb2017-11-17 19:58:36 +000053#include <numeric>
Eugene Zelenkoa369a452017-05-16 23:10:25 +000054#include <utility>
Chandler Carruth1353f9a2017-04-27 18:45:20 +000055
56#define DEBUG_TYPE "simple-loop-unswitch"
57
58using namespace llvm;
59
60STATISTIC(NumBranches, "Number of branches unswitched");
61STATISTIC(NumSwitches, "Number of switches unswitched");
62STATISTIC(NumTrivial, "Number of unswitches that are trivial");
63
Chandler Carruth693eedb2017-11-17 19:58:36 +000064static cl::opt<bool> EnableNonTrivialUnswitch(
65 "enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
66 cl::desc("Forcibly enables non-trivial loop unswitching rather than "
67 "following the configuration passed into the pass."));
68
69static cl::opt<int>
70 UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
71 cl::desc("The cost threshold for unswitching a loop."));
72
Chandler Carruth4da33312018-06-20 18:57:07 +000073/// Collect all of the loop invariant input values transitively used by the
74/// homogeneous instruction graph from a given root.
75///
76/// This essentially walks from a root recursively through loop variant operands
77/// which have the exact same opcode and finds all inputs which are loop
78/// invariant. For some operations these can be re-associated and unswitched out
79/// of the loop entirely.
Chandler Carruthd1dab0c2018-06-21 06:14:03 +000080static TinyPtrVector<Value *>
Chandler Carruth4da33312018-06-20 18:57:07 +000081collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root,
82 LoopInfo &LI) {
Chandler Carruth4da33312018-06-20 18:57:07 +000083 assert(!L.isLoopInvariant(&Root) &&
84 "Only need to walk the graph if root itself is not invariant.");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +000085 TinyPtrVector<Value *> Invariants;
Chandler Carruth4da33312018-06-20 18:57:07 +000086
87 // Build a worklist and recurse through operators collecting invariants.
88 SmallVector<Instruction *, 4> Worklist;
89 SmallPtrSet<Instruction *, 8> Visited;
90 Worklist.push_back(&Root);
91 Visited.insert(&Root);
92 do {
93 Instruction &I = *Worklist.pop_back_val();
94 for (Value *OpV : I.operand_values()) {
95 // Skip constants as unswitching isn't interesting for them.
96 if (isa<Constant>(OpV))
97 continue;
98
99 // Add it to our result if loop invariant.
100 if (L.isLoopInvariant(OpV)) {
101 Invariants.push_back(OpV);
102 continue;
103 }
104
105 // If not an instruction with the same opcode, nothing we can do.
106 Instruction *OpI = dyn_cast<Instruction>(OpV);
107 if (!OpI || OpI->getOpcode() != Root.getOpcode())
108 continue;
109
110 // Visit this operand.
111 if (Visited.insert(OpI).second)
112 Worklist.push_back(OpI);
113 }
114 } while (!Worklist.empty());
115
116 return Invariants;
117}
118
119static void replaceLoopInvariantUses(Loop &L, Value *Invariant,
120 Constant &Replacement) {
121 assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000122
123 // Replace uses of LIC in the loop with the given constant.
Chandler Carruth4da33312018-06-20 18:57:07 +0000124 for (auto UI = Invariant->use_begin(), UE = Invariant->use_end(); UI != UE;) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000125 // Grab the use and walk past it so we can clobber it in the use list.
126 Use *U = &*UI++;
127 Instruction *UserI = dyn_cast<Instruction>(U->getUser());
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000128
129 // Replace this use within the loop body.
Chandler Carruth4da33312018-06-20 18:57:07 +0000130 if (UserI && L.contains(UserI))
131 U->set(&Replacement);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000132 }
133}
134
Chandler Carruthd869b182017-05-12 02:19:59 +0000135/// Check that all the LCSSA PHI nodes in the loop exit block have trivial
136/// incoming values along this edge.
137static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB,
138 BasicBlock &ExitBB) {
139 for (Instruction &I : ExitBB) {
140 auto *PN = dyn_cast<PHINode>(&I);
141 if (!PN)
142 // No more PHIs to check.
143 return true;
144
145 // If the incoming value for this edge isn't loop invariant the unswitch
146 // won't be trivial.
147 if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
148 return false;
149 }
150 llvm_unreachable("Basic blocks should never be empty!");
151}
152
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000153/// Insert code to test a set of loop invariant values, and conditionally branch
154/// on them.
155static void buildPartialUnswitchConditionalBranch(BasicBlock &BB,
156 ArrayRef<Value *> Invariants,
157 bool Direction,
158 BasicBlock &UnswitchedSucc,
159 BasicBlock &NormalSucc) {
160 IRBuilder<> IRB(&BB);
161 Value *Cond = Invariants.front();
162 for (Value *Invariant :
163 make_range(std::next(Invariants.begin()), Invariants.end()))
164 if (Direction)
165 Cond = IRB.CreateOr(Cond, Invariant);
166 else
167 Cond = IRB.CreateAnd(Cond, Invariant);
168
169 IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
170 Direction ? &NormalSucc : &UnswitchedSucc);
171}
172
Chandler Carruthd869b182017-05-12 02:19:59 +0000173/// Rewrite the PHI nodes in an unswitched loop exit basic block.
174///
175/// Requires that the loop exit and unswitched basic block are the same, and
176/// that the exiting block was a unique predecessor of that block. Rewrites the
177/// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
178/// PHI nodes from the old preheader that now contains the unswitched
179/// terminator.
180static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
181 BasicBlock &OldExitingBB,
182 BasicBlock &OldPH) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000183 for (PHINode &PN : UnswitchedBB.phis()) {
Chandler Carruthd869b182017-05-12 02:19:59 +0000184 // When the loop exit is directly unswitched we just need to update the
185 // incoming basic block. We loop to handle weird cases with repeated
186 // incoming blocks, but expect to typically only have one operand here.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000187 for (auto i : seq<int>(0, PN.getNumOperands())) {
188 assert(PN.getIncomingBlock(i) == &OldExitingBB &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000189 "Found incoming block different from unique predecessor!");
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000190 PN.setIncomingBlock(i, &OldPH);
Chandler Carruthd869b182017-05-12 02:19:59 +0000191 }
192 }
193}
194
195/// Rewrite the PHI nodes in the loop exit basic block and the split off
196/// unswitched block.
197///
198/// Because the exit block remains an exit from the loop, this rewrites the
199/// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
200/// nodes into the unswitched basic block to select between the value in the
201/// old preheader and the loop exit.
202static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
203 BasicBlock &UnswitchedBB,
204 BasicBlock &OldExitingBB,
Chandler Carruth4da33312018-06-20 18:57:07 +0000205 BasicBlock &OldPH,
206 bool FullUnswitch) {
Chandler Carruthd869b182017-05-12 02:19:59 +0000207 assert(&ExitBB != &UnswitchedBB &&
208 "Must have different loop exit and unswitched blocks!");
209 Instruction *InsertPt = &*UnswitchedBB.begin();
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000210 for (PHINode &PN : ExitBB.phis()) {
211 auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
212 PN.getName() + ".split", InsertPt);
Chandler Carruthd869b182017-05-12 02:19:59 +0000213
214 // Walk backwards over the old PHI node's inputs to minimize the cost of
215 // removing each one. We have to do this weird loop manually so that we
216 // create the same number of new incoming edges in the new PHI as we expect
217 // each case-based edge to be included in the unswitched switch in some
218 // cases.
219 // FIXME: This is really, really gross. It would be much cleaner if LLVM
220 // allowed us to create a single entry for a predecessor block without
221 // having separate entries for each "edge" even though these edges are
222 // required to produce identical results.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000223 for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
224 if (PN.getIncomingBlock(i) != &OldExitingBB)
Chandler Carruthd869b182017-05-12 02:19:59 +0000225 continue;
226
Chandler Carruth4da33312018-06-20 18:57:07 +0000227 Value *Incoming = PN.getIncomingValue(i);
228 if (FullUnswitch)
229 // No more edge from the old exiting block to the exit block.
230 PN.removeIncomingValue(i);
231
Chandler Carruthd869b182017-05-12 02:19:59 +0000232 NewPN->addIncoming(Incoming, &OldPH);
233 }
234
235 // Now replace the old PHI with the new one and wire the old one in as an
236 // input to the new one.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000237 PN.replaceAllUsesWith(NewPN);
238 NewPN->addIncoming(&PN, &ExitBB);
Chandler Carruthd869b182017-05-12 02:19:59 +0000239 }
240}
241
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000242/// Hoist the current loop up to the innermost loop containing a remaining exit.
243///
244/// Because we've removed an exit from the loop, we may have changed the set of
245/// loops reachable and need to move the current loop up the loop nest or even
246/// to an entirely separate nest.
247static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
248 DominatorTree &DT, LoopInfo &LI) {
249 // If the loop is already at the top level, we can't hoist it anywhere.
250 Loop *OldParentL = L.getParentLoop();
251 if (!OldParentL)
252 return;
253
254 SmallVector<BasicBlock *, 4> Exits;
255 L.getExitBlocks(Exits);
256 Loop *NewParentL = nullptr;
257 for (auto *ExitBB : Exits)
258 if (Loop *ExitL = LI.getLoopFor(ExitBB))
259 if (!NewParentL || NewParentL->contains(ExitL))
260 NewParentL = ExitL;
261
262 if (NewParentL == OldParentL)
263 return;
264
265 // The new parent loop (if different) should always contain the old one.
266 if (NewParentL)
267 assert(NewParentL->contains(OldParentL) &&
268 "Can only hoist this loop up the nest!");
269
270 // The preheader will need to move with the body of this loop. However,
271 // because it isn't in this loop we also need to update the primary loop map.
272 assert(OldParentL == LI.getLoopFor(&Preheader) &&
273 "Parent loop of this loop should contain this loop's preheader!");
274 LI.changeLoopFor(&Preheader, NewParentL);
275
276 // Remove this loop from its old parent.
277 OldParentL->removeChildLoop(&L);
278
279 // Add the loop either to the new parent or as a top-level loop.
280 if (NewParentL)
281 NewParentL->addChildLoop(&L);
282 else
283 LI.addTopLevelLoop(&L);
284
285 // Remove this loops blocks from the old parent and every other loop up the
286 // nest until reaching the new parent. Also update all of these
287 // no-longer-containing loops to reflect the nesting change.
288 for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
289 OldContainingL = OldContainingL->getParentLoop()) {
290 llvm::erase_if(OldContainingL->getBlocksVector(),
291 [&](const BasicBlock *BB) {
292 return BB == &Preheader || L.contains(BB);
293 });
294
295 OldContainingL->getBlocksSet().erase(&Preheader);
296 for (BasicBlock *BB : L.blocks())
297 OldContainingL->getBlocksSet().erase(BB);
298
299 // Because we just hoisted a loop out of this one, we have essentially
300 // created new exit paths from it. That means we need to form LCSSA PHI
301 // nodes for values used in the no-longer-nested loop.
302 formLCSSA(*OldContainingL, DT, &LI, nullptr);
303
304 // We shouldn't need to form dedicated exits because the exit introduced
305 // here is the (just split by unswitching) preheader. As such, it is
306 // necessarily dedicated.
307 assert(OldContainingL->hasDedicatedExits() &&
308 "Unexpected predecessor of hoisted loop preheader!");
309 }
310}
311
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000312/// Unswitch a trivial branch if the condition is loop invariant.
313///
314/// This routine should only be called when loop code leading to the branch has
315/// been validated as trivial (no side effects). This routine checks if the
316/// condition is invariant and one of the successors is a loop exit. This
317/// allows us to unswitch without duplicating the loop, making it trivial.
318///
319/// If this routine fails to unswitch the branch it returns false.
320///
321/// If the branch can be unswitched, this routine splits the preheader and
322/// hoists the branch above that split. Preserves loop simplified form
323/// (splitting the exit block as necessary). It simplifies the branch within
324/// the loop to an unconditional branch but doesn't remove it entirely. Further
325/// cleanup can be done with some simplify-cfg like pass.
Chandler Carruth3897ded2018-07-03 09:13:27 +0000326///
327/// If `SE` is not null, it will be updated based on the potential loop SCEVs
328/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000329static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
Chandler Carruth3897ded2018-07-03 09:13:27 +0000330 LoopInfo &LI, ScalarEvolution *SE) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000331 assert(BI.isConditional() && "Can only unswitch a conditional branch!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000332 LLVM_DEBUG(dbgs() << " Trying to unswitch branch: " << BI << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000333
Chandler Carruth4da33312018-06-20 18:57:07 +0000334 // The loop invariant values that we want to unswitch.
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000335 TinyPtrVector<Value *> Invariants;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000336
Chandler Carruth4da33312018-06-20 18:57:07 +0000337 // When true, we're fully unswitching the branch rather than just unswitching
338 // some input conditions to the branch.
339 bool FullUnswitch = false;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000340
Chandler Carruth4da33312018-06-20 18:57:07 +0000341 if (L.isLoopInvariant(BI.getCondition())) {
342 Invariants.push_back(BI.getCondition());
343 FullUnswitch = true;
344 } else {
345 if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition()))
346 Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
347 if (Invariants.empty())
348 // Couldn't find invariant inputs!
349 return false;
350 }
351
352 // Check that one of the branch's successors exits, and which one.
353 bool ExitDirection = true;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000354 int LoopExitSuccIdx = 0;
355 auto *LoopExitBB = BI.getSuccessor(0);
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000356 if (L.contains(LoopExitBB)) {
Chandler Carruth4da33312018-06-20 18:57:07 +0000357 ExitDirection = false;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000358 LoopExitSuccIdx = 1;
359 LoopExitBB = BI.getSuccessor(1);
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000360 if (L.contains(LoopExitBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000361 return false;
362 }
363 auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
Chandler Carruthd869b182017-05-12 02:19:59 +0000364 auto *ParentBB = BI.getParent();
365 if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000366 return false;
367
Chandler Carruth4da33312018-06-20 18:57:07 +0000368 // When unswitching only part of the branch's condition, we need the exit
369 // block to be reached directly from the partially unswitched input. This can
370 // be done when the exit block is along the true edge and the branch condition
371 // is a graph of `or` operations, or the exit block is along the false edge
372 // and the condition is a graph of `and` operations.
373 if (!FullUnswitch) {
374 if (ExitDirection) {
375 if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::Or)
376 return false;
377 } else {
378 if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::And)
379 return false;
380 }
381 }
382
383 LLVM_DEBUG({
384 dbgs() << " unswitching trivial invariant conditions for: " << BI
385 << "\n";
386 for (Value *Invariant : Invariants) {
387 dbgs() << " " << *Invariant << " == true";
388 if (Invariant != Invariants.back())
389 dbgs() << " ||";
390 dbgs() << "\n";
391 }
392 });
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000393
Chandler Carruth3897ded2018-07-03 09:13:27 +0000394 // If we have scalar evolutions, we need to invalidate them including this
395 // loop and the loop containing the exit block.
396 if (SE) {
397 if (Loop *ExitL = LI.getLoopFor(LoopExitBB))
398 SE->forgetLoop(ExitL);
399 else
400 // Forget the entire nest as this exits the entire nest.
401 SE->forgetTopmostLoop(&L);
402 }
403
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000404 // Split the preheader, so that we know that there is a safe place to insert
405 // the conditional branch. We will change the preheader to have a conditional
406 // branch on LoopCond.
407 BasicBlock *OldPH = L.getLoopPreheader();
408 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI);
409
410 // Now that we have a place to insert the conditional branch, create a place
411 // to branch to: this is the exit block out of the loop that we are
412 // unswitching. We need to split this if there are other loop predecessors.
413 // Because the loop is in simplified form, *any* other predecessor is enough.
414 BasicBlock *UnswitchedBB;
Chandler Carruth4da33312018-06-20 18:57:07 +0000415 if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
416 assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000417 "A branch's parent isn't a predecessor!");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000418 UnswitchedBB = LoopExitBB;
419 } else {
420 UnswitchedBB = SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI);
421 }
422
Chandler Carruth4da33312018-06-20 18:57:07 +0000423 // Actually move the invariant uses into the unswitched position. If possible,
424 // we do this by moving the instructions, but when doing partial unswitching
425 // we do it by building a new merge of the values in the unswitched position.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000426 OldPH->getTerminator()->eraseFromParent();
Chandler Carruth4da33312018-06-20 18:57:07 +0000427 if (FullUnswitch) {
428 // If fully unswitching, we can use the existing branch instruction.
429 // Splice it into the old PH to gate reaching the new preheader and re-point
430 // its successors.
431 OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
432 BI);
433 BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
434 BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000435
Chandler Carruth4da33312018-06-20 18:57:07 +0000436 // Create a new unconditional branch that will continue the loop as a new
437 // terminator.
438 BranchInst::Create(ContinueBB, ParentBB);
439 } else {
440 // Only unswitching a subset of inputs to the condition, so we will need to
441 // build a new branch that merges the invariant inputs.
Chandler Carruth4da33312018-06-20 18:57:07 +0000442 if (ExitDirection)
443 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
444 Instruction::Or &&
445 "Must have an `or` of `i1`s for the condition!");
446 else
447 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
448 Instruction::And &&
449 "Must have an `and` of `i1`s for the condition!");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +0000450 buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection,
451 *UnswitchedBB, *NewPH);
Chandler Carruth4da33312018-06-20 18:57:07 +0000452 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000453
Chandler Carruthd869b182017-05-12 02:19:59 +0000454 // Rewrite the relevant PHI nodes.
455 if (UnswitchedBB == LoopExitBB)
456 rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
457 else
458 rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
Chandler Carruth4da33312018-06-20 18:57:07 +0000459 *ParentBB, *OldPH, FullUnswitch);
Chandler Carruthd869b182017-05-12 02:19:59 +0000460
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000461 // Now we need to update the dominator tree.
Chandler Carruth4da33312018-06-20 18:57:07 +0000462 DT.insertEdge(OldPH, UnswitchedBB);
463 if (FullUnswitch)
464 DT.deleteEdge(ParentBB, UnswitchedBB);
465
466 // The constant we can replace all of our invariants with inside the loop
467 // body. If any of the invariants have a value other than this the loop won't
468 // be entered.
469 ConstantInt *Replacement = ExitDirection
470 ? ConstantInt::getFalse(BI.getContext())
471 : ConstantInt::getTrue(BI.getContext());
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000472
473 // Since this is an i1 condition we can also trivially replace uses of it
474 // within the loop with a constant.
Chandler Carruth4da33312018-06-20 18:57:07 +0000475 for (Value *Invariant : Invariants)
476 replaceLoopInvariantUses(L, Invariant, *Replacement);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000477
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000478 // If this was full unswitching, we may have changed the nesting relationship
479 // for this loop so hoist it to its correct parent if needed.
480 if (FullUnswitch)
481 hoistLoopToNewParent(L, *NewPH, DT, LI);
482
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000483 ++NumTrivial;
484 ++NumBranches;
485 return true;
486}
487
488/// Unswitch a trivial switch if the condition is loop invariant.
489///
490/// This routine should only be called when loop code leading to the switch has
491/// been validated as trivial (no side effects). This routine checks if the
492/// condition is invariant and that at least one of the successors is a loop
493/// exit. This allows us to unswitch without duplicating the loop, making it
494/// trivial.
495///
496/// If this routine fails to unswitch the switch it returns false.
497///
498/// If the switch can be unswitched, this routine splits the preheader and
499/// copies the switch above that split. If the default case is one of the
500/// exiting cases, it copies the non-exiting cases and points them at the new
501/// preheader. If the default case is not exiting, it copies the exiting cases
502/// and points the default at the preheader. It preserves loop simplified form
503/// (splitting the exit blocks as necessary). It simplifies the switch within
504/// the loop by removing now-dead cases. If the default case is one of those
505/// unswitched, it replaces its destination with a new basic block containing
506/// only unreachable. Such basic blocks, while technically loop exits, are not
507/// considered for unswitching so this is a stable transform and the same
508/// switch will not be revisited. If after unswitching there is only a single
509/// in-loop successor, the switch is further simplified to an unconditional
510/// branch. Still more cleanup can be done with some simplify-cfg like pass.
Chandler Carruth3897ded2018-07-03 09:13:27 +0000511///
512/// If `SE` is not null, it will be updated based on the potential loop SCEVs
513/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000514static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
Chandler Carruth3897ded2018-07-03 09:13:27 +0000515 LoopInfo &LI, ScalarEvolution *SE) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000516 LLVM_DEBUG(dbgs() << " Trying to unswitch switch: " << SI << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000517 Value *LoopCond = SI.getCondition();
518
519 // If this isn't switching on an invariant condition, we can't unswitch it.
520 if (!L.isLoopInvariant(LoopCond))
521 return false;
522
Chandler Carruthd869b182017-05-12 02:19:59 +0000523 auto *ParentBB = SI.getParent();
524
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000525 SmallVector<int, 4> ExitCaseIndices;
526 for (auto Case : SI.cases()) {
527 auto *SuccBB = Case.getCaseSuccessor();
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000528 if (!L.contains(SuccBB) &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000529 areLoopExitPHIsLoopInvariant(L, *ParentBB, *SuccBB))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000530 ExitCaseIndices.push_back(Case.getCaseIndex());
531 }
532 BasicBlock *DefaultExitBB = nullptr;
Chandler Carruthbaf045f2018-05-10 17:33:20 +0000533 if (!L.contains(SI.getDefaultDest()) &&
Chandler Carruthd869b182017-05-12 02:19:59 +0000534 areLoopExitPHIsLoopInvariant(L, *ParentBB, *SI.getDefaultDest()) &&
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000535 !isa<UnreachableInst>(SI.getDefaultDest()->getTerminator()))
536 DefaultExitBB = SI.getDefaultDest();
537 else if (ExitCaseIndices.empty())
538 return false;
539
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000540 LLVM_DEBUG(dbgs() << " unswitching trivial cases...\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000541
Chandler Carruth3897ded2018-07-03 09:13:27 +0000542 // We may need to invalidate SCEVs for the outermost loop reached by any of
543 // the exits.
544 Loop *OuterL = &L;
545
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000546 SmallVector<std::pair<ConstantInt *, BasicBlock *>, 4> ExitCases;
547 ExitCases.reserve(ExitCaseIndices.size());
548 // We walk the case indices backwards so that we remove the last case first
549 // and don't disrupt the earlier indices.
550 for (unsigned Index : reverse(ExitCaseIndices)) {
551 auto CaseI = SI.case_begin() + Index;
Chandler Carruth3897ded2018-07-03 09:13:27 +0000552 // Compute the outer loop from this exit.
553 Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor());
554 if (!ExitL || ExitL->contains(OuterL))
555 OuterL = ExitL;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000556 // Save the value of this case.
557 ExitCases.push_back({CaseI->getCaseValue(), CaseI->getCaseSuccessor()});
558 // Delete the unswitched cases.
559 SI.removeCase(CaseI);
560 }
561
Chandler Carruth3897ded2018-07-03 09:13:27 +0000562 if (SE) {
563 if (OuterL)
564 SE->forgetLoop(OuterL);
565 else
566 SE->forgetTopmostLoop(&L);
567 }
568
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000569 // Check if after this all of the remaining cases point at the same
570 // successor.
571 BasicBlock *CommonSuccBB = nullptr;
572 if (SI.getNumCases() > 0 &&
573 std::all_of(std::next(SI.case_begin()), SI.case_end(),
574 [&SI](const SwitchInst::CaseHandle &Case) {
575 return Case.getCaseSuccessor() ==
576 SI.case_begin()->getCaseSuccessor();
577 }))
578 CommonSuccBB = SI.case_begin()->getCaseSuccessor();
579
580 if (DefaultExitBB) {
581 // We can't remove the default edge so replace it with an edge to either
582 // the single common remaining successor (if we have one) or an unreachable
583 // block.
584 if (CommonSuccBB) {
585 SI.setDefaultDest(CommonSuccBB);
586 } else {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000587 BasicBlock *UnreachableBB = BasicBlock::Create(
588 ParentBB->getContext(),
589 Twine(ParentBB->getName()) + ".unreachable_default",
590 ParentBB->getParent());
591 new UnreachableInst(ParentBB->getContext(), UnreachableBB);
592 SI.setDefaultDest(UnreachableBB);
593 DT.addNewBlock(UnreachableBB, ParentBB);
594 }
595 } else {
596 // If we're not unswitching the default, we need it to match any cases to
597 // have a common successor or if we have no cases it is the common
598 // successor.
599 if (SI.getNumCases() == 0)
600 CommonSuccBB = SI.getDefaultDest();
601 else if (SI.getDefaultDest() != CommonSuccBB)
602 CommonSuccBB = nullptr;
603 }
604
605 // Split the preheader, so that we know that there is a safe place to insert
606 // the switch.
607 BasicBlock *OldPH = L.getLoopPreheader();
608 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI);
609 OldPH->getTerminator()->eraseFromParent();
610
611 // Now add the unswitched switch.
612 auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
613
Chandler Carruthd869b182017-05-12 02:19:59 +0000614 // Rewrite the IR for the unswitched basic blocks. This requires two steps.
615 // First, we split any exit blocks with remaining in-loop predecessors. Then
616 // we update the PHIs in one of two ways depending on if there was a split.
617 // We walk in reverse so that we split in the same order as the cases
618 // appeared. This is purely for convenience of reading the resulting IR, but
619 // it doesn't cost anything really.
620 SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000621 SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
622 // Handle the default exit if necessary.
623 // FIXME: It'd be great if we could merge this with the loop below but LLVM's
624 // ranges aren't quite powerful enough yet.
Chandler Carruthd869b182017-05-12 02:19:59 +0000625 if (DefaultExitBB) {
626 if (pred_empty(DefaultExitBB)) {
627 UnswitchedExitBBs.insert(DefaultExitBB);
628 rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
629 } else {
630 auto *SplitBB =
631 SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI);
Chandler Carruth4da33312018-06-20 18:57:07 +0000632 rewritePHINodesForExitAndUnswitchedBlocks(
633 *DefaultExitBB, *SplitBB, *ParentBB, *OldPH, /*FullUnswitch*/ true);
Chandler Carruthd869b182017-05-12 02:19:59 +0000634 DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
635 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000636 }
637 // Note that we must use a reference in the for loop so that we update the
638 // container.
639 for (auto &CasePair : reverse(ExitCases)) {
640 // Grab a reference to the exit block in the pair so that we can update it.
Chandler Carruthd869b182017-05-12 02:19:59 +0000641 BasicBlock *ExitBB = CasePair.second;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000642
643 // If this case is the last edge into the exit block, we can simply reuse it
644 // as it will no longer be a loop exit. No mapping necessary.
Chandler Carruthd869b182017-05-12 02:19:59 +0000645 if (pred_empty(ExitBB)) {
646 // Only rewrite once.
647 if (UnswitchedExitBBs.insert(ExitBB).second)
648 rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000649 continue;
Chandler Carruthd869b182017-05-12 02:19:59 +0000650 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000651
652 // Otherwise we need to split the exit block so that we retain an exit
653 // block from the loop and a target for the unswitched condition.
654 BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
655 if (!SplitExitBB) {
656 // If this is the first time we see this, do the split and remember it.
657 SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI);
Chandler Carruth4da33312018-06-20 18:57:07 +0000658 rewritePHINodesForExitAndUnswitchedBlocks(
659 *ExitBB, *SplitExitBB, *ParentBB, *OldPH, /*FullUnswitch*/ true);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000660 }
Chandler Carruthd869b182017-05-12 02:19:59 +0000661 // Update the case pair to point to the split block.
662 CasePair.second = SplitExitBB;
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000663 }
664
665 // Now add the unswitched cases. We do this in reverse order as we built them
666 // in reverse order.
667 for (auto CasePair : reverse(ExitCases)) {
668 ConstantInt *CaseVal = CasePair.first;
669 BasicBlock *UnswitchedBB = CasePair.second;
670
671 NewSI->addCase(CaseVal, UnswitchedBB);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000672 }
673
674 // If the default was unswitched, re-point it and add explicit cases for
675 // entering the loop.
676 if (DefaultExitBB) {
677 NewSI->setDefaultDest(DefaultExitBB);
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000678
679 // We removed all the exit cases, so we just copy the cases to the
680 // unswitched switch.
681 for (auto Case : SI.cases())
682 NewSI->addCase(Case.getCaseValue(), NewPH);
683 }
684
685 // If we ended up with a common successor for every path through the switch
686 // after unswitching, rewrite it to an unconditional branch to make it easy
687 // to recognize. Otherwise we potentially have to recognize the default case
688 // pointing at unreachable and other complexity.
689 if (CommonSuccBB) {
690 BasicBlock *BB = SI.getParent();
691 SI.eraseFromParent();
692 BranchInst::Create(CommonSuccBB, BB);
693 }
694
Chandler Carruth2c85a232018-05-01 09:54:39 +0000695 // Walk the unswitched exit blocks and the unswitched split blocks and update
696 // the dominator tree based on the CFG edits. While we are walking unordered
697 // containers here, the API for applyUpdates takes an unordered list of
698 // updates and requires them to not contain duplicates.
699 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
700 for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
701 DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
702 DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
703 }
704 for (auto SplitUnswitchedPair : SplitExitBBMap) {
705 auto *UnswitchedBB = SplitUnswitchedPair.second;
706 DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedBB});
707 DTUpdates.push_back({DT.Insert, OldPH, UnswitchedBB});
708 }
709 DT.applyUpdates(DTUpdates);
David Green7c35de12018-02-28 11:00:08 +0000710 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruthd8b0c8c2018-07-07 01:12:56 +0000711
712 // We may have changed the nesting relationship for this loop so hoist it to
713 // its correct parent if needed.
714 hoistLoopToNewParent(L, *NewPH, DT, LI);
715
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000716 ++NumTrivial;
717 ++NumSwitches;
718 return true;
719}
720
721/// This routine scans the loop to find a branch or switch which occurs before
722/// any side effects occur. These can potentially be unswitched without
723/// duplicating the loop. If a branch or switch is successfully unswitched the
724/// scanning continues to see if subsequent branches or switches have become
725/// trivial. Once all trivial candidates have been unswitched, this routine
726/// returns.
727///
728/// The return value indicates whether anything was unswitched (and therefore
729/// changed).
Chandler Carruth3897ded2018-07-03 09:13:27 +0000730///
731/// If `SE` is not null, it will be updated based on the potential loop SCEVs
732/// invalidated by this.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000733static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
Chandler Carruth3897ded2018-07-03 09:13:27 +0000734 LoopInfo &LI, ScalarEvolution *SE) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000735 bool Changed = false;
736
737 // If loop header has only one reachable successor we should keep looking for
738 // trivial condition candidates in the successor as well. An alternative is
739 // to constant fold conditions and merge successors into loop header (then we
740 // only need to check header's terminator). The reason for not doing this in
741 // LoopUnswitch pass is that it could potentially break LoopPassManager's
742 // invariants. Folding dead branches could either eliminate the current loop
743 // or make other loops unreachable. LCSSA form might also not be preserved
744 // after deleting branches. The following code keeps traversing loop header's
745 // successors until it finds the trivial condition candidate (condition that
746 // is not a constant). Since unswitching generates branches with constant
747 // conditions, this scenario could be very common in practice.
748 BasicBlock *CurrentBB = L.getHeader();
749 SmallPtrSet<BasicBlock *, 8> Visited;
750 Visited.insert(CurrentBB);
751 do {
752 // Check if there are any side-effecting instructions (e.g. stores, calls,
753 // volatile loads) in the part of the loop that the code *would* execute
754 // without unswitching.
755 if (llvm::any_of(*CurrentBB,
756 [](Instruction &I) { return I.mayHaveSideEffects(); }))
757 return Changed;
758
759 TerminatorInst *CurrentTerm = CurrentBB->getTerminator();
760
761 if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
762 // Don't bother trying to unswitch past a switch with a constant
763 // condition. This should be removed prior to running this pass by
764 // simplify-cfg.
765 if (isa<Constant>(SI->getCondition()))
766 return Changed;
767
Chandler Carruth3897ded2018-07-03 09:13:27 +0000768 if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE))
Hiroshi Inouef2096492018-06-14 05:41:49 +0000769 // Couldn't unswitch this one so we're done.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000770 return Changed;
771
772 // Mark that we managed to unswitch something.
773 Changed = true;
774
775 // If unswitching turned the terminator into an unconditional branch then
776 // we can continue. The unswitching logic specifically works to fold any
777 // cases it can into an unconditional branch to make it easier to
778 // recognize here.
779 auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
780 if (!BI || BI->isConditional())
781 return Changed;
782
783 CurrentBB = BI->getSuccessor(0);
784 continue;
785 }
786
787 auto *BI = dyn_cast<BranchInst>(CurrentTerm);
788 if (!BI)
789 // We do not understand other terminator instructions.
790 return Changed;
791
792 // Don't bother trying to unswitch past an unconditional branch or a branch
793 // with a constant value. These should be removed by simplify-cfg prior to
794 // running this pass.
795 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
796 return Changed;
797
798 // Found a trivial condition candidate: non-foldable conditional branch. If
799 // we fail to unswitch this, we can't do anything else that is trivial.
Chandler Carruth3897ded2018-07-03 09:13:27 +0000800 if (!unswitchTrivialBranch(L, *BI, DT, LI, SE))
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000801 return Changed;
802
803 // Mark that we managed to unswitch something.
804 Changed = true;
805
Chandler Carruth4da33312018-06-20 18:57:07 +0000806 // If we only unswitched some of the conditions feeding the branch, we won't
807 // have collapsed it to a single successor.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000808 BI = cast<BranchInst>(CurrentBB->getTerminator());
Chandler Carruth4da33312018-06-20 18:57:07 +0000809 if (BI->isConditional())
810 return Changed;
811
812 // Follow the newly unconditional branch into its successor.
Chandler Carruth1353f9a2017-04-27 18:45:20 +0000813 CurrentBB = BI->getSuccessor(0);
814
815 // When continuing, if we exit the loop or reach a previous visited block,
816 // then we can not reach any trivial condition candidates (unfoldable
817 // branch instructions or switch instructions) and no unswitch can happen.
818 } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
819
820 return Changed;
821}
822
Chandler Carruth693eedb2017-11-17 19:58:36 +0000823/// Build the cloned blocks for an unswitched copy of the given loop.
824///
825/// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
826/// after the split block (`SplitBB`) that will be used to select between the
827/// cloned and original loop.
828///
829/// This routine handles cloning all of the necessary loop blocks and exit
830/// blocks including rewriting their instructions and the relevant PHI nodes.
Chandler Carruth16529962018-06-25 23:32:54 +0000831/// Any loop blocks or exit blocks which are dominated by a different successor
832/// than the one for this clone of the loop blocks can be trivially skipped. We
833/// use the `DominatingSucc` map to determine whether a block satisfies that
834/// property with a simple map lookup.
835///
836/// It also correctly creates the unconditional branch in the cloned
Chandler Carruth693eedb2017-11-17 19:58:36 +0000837/// unswitched parent block to only point at the unswitched successor.
838///
839/// This does not handle most of the necessary updates to `LoopInfo`. Only exit
840/// block splitting is correctly reflected in `LoopInfo`, essentially all of
841/// the cloned blocks (and their loops) are left without full `LoopInfo`
842/// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
843/// blocks to them but doesn't create the cloned `DominatorTree` structure and
844/// instead the caller must recompute an accurate DT. It *does* correctly
845/// update the `AssumptionCache` provided in `AC`.
846static BasicBlock *buildClonedLoopBlocks(
847 Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
848 ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
849 BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
Chandler Carruth16529962018-06-25 23:32:54 +0000850 const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
Chandler Carruth69e68f82018-04-25 00:18:07 +0000851 ValueToValueMapTy &VMap,
852 SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
853 DominatorTree &DT, LoopInfo &LI) {
Chandler Carruth693eedb2017-11-17 19:58:36 +0000854 SmallVector<BasicBlock *, 4> NewBlocks;
855 NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
856
857 // We will need to clone a bunch of blocks, wrap up the clone operation in
858 // a helper.
859 auto CloneBlock = [&](BasicBlock *OldBB) {
860 // Clone the basic block and insert it before the new preheader.
861 BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
862 NewBB->moveBefore(LoopPH);
863
864 // Record this block and the mapping.
865 NewBlocks.push_back(NewBB);
866 VMap[OldBB] = NewBB;
867
Chandler Carruth693eedb2017-11-17 19:58:36 +0000868 return NewBB;
869 };
870
Chandler Carruth16529962018-06-25 23:32:54 +0000871 // We skip cloning blocks when they have a dominating succ that is not the
872 // succ we are cloning for.
873 auto SkipBlock = [&](BasicBlock *BB) {
874 auto It = DominatingSucc.find(BB);
875 return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
876 };
877
Chandler Carruth693eedb2017-11-17 19:58:36 +0000878 // First, clone the preheader.
879 auto *ClonedPH = CloneBlock(LoopPH);
880
881 // Then clone all the loop blocks, skipping the ones that aren't necessary.
882 for (auto *LoopBB : L.blocks())
Chandler Carruth16529962018-06-25 23:32:54 +0000883 if (!SkipBlock(LoopBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +0000884 CloneBlock(LoopBB);
885
886 // Split all the loop exit edges so that when we clone the exit blocks, if
887 // any of the exit blocks are *also* a preheader for some other loop, we
888 // don't create multiple predecessors entering the loop header.
889 for (auto *ExitBB : ExitBlocks) {
Chandler Carruth16529962018-06-25 23:32:54 +0000890 if (SkipBlock(ExitBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +0000891 continue;
892
893 // When we are going to clone an exit, we don't need to clone all the
894 // instructions in the exit block and we want to ensure we have an easy
895 // place to merge the CFG, so split the exit first. This is always safe to
896 // do because there cannot be any non-loop predecessors of a loop exit in
897 // loop simplified form.
898 auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI);
899
900 // Rearrange the names to make it easier to write test cases by having the
901 // exit block carry the suffix rather than the merge block carrying the
902 // suffix.
903 MergeBB->takeName(ExitBB);
904 ExitBB->setName(Twine(MergeBB->getName()) + ".split");
905
906 // Now clone the original exit block.
907 auto *ClonedExitBB = CloneBlock(ExitBB);
908 assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
909 "Exit block should have been split to have one successor!");
910 assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
911 "Cloned exit block has the wrong successor!");
912
Chandler Carruth693eedb2017-11-17 19:58:36 +0000913 // Remap any cloned instructions and create a merge phi node for them.
914 for (auto ZippedInsts : llvm::zip_first(
915 llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
916 llvm::make_range(ClonedExitBB->begin(),
917 std::prev(ClonedExitBB->end())))) {
918 Instruction &I = std::get<0>(ZippedInsts);
919 Instruction &ClonedI = std::get<1>(ZippedInsts);
920
921 // The only instructions in the exit block should be PHI nodes and
922 // potentially a landing pad.
923 assert(
924 (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
925 "Bad instruction in exit block!");
926 // We should have a value map between the instruction and its clone.
927 assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
928
929 auto *MergePN =
930 PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
931 &*MergeBB->getFirstInsertionPt());
932 I.replaceAllUsesWith(MergePN);
933 MergePN->addIncoming(&I, ExitBB);
934 MergePN->addIncoming(&ClonedI, ClonedExitBB);
935 }
936 }
937
938 // Rewrite the instructions in the cloned blocks to refer to the instructions
939 // in the cloned blocks. We have to do this as a second pass so that we have
940 // everything available. Also, we have inserted new instructions which may
941 // include assume intrinsics, so we update the assumption cache while
942 // processing this.
943 for (auto *ClonedBB : NewBlocks)
944 for (Instruction &I : *ClonedBB) {
945 RemapInstruction(&I, VMap,
946 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
947 if (auto *II = dyn_cast<IntrinsicInst>(&I))
948 if (II->getIntrinsicID() == Intrinsic::assume)
949 AC.registerAssumption(II);
950 }
951
Chandler Carruth693eedb2017-11-17 19:58:36 +0000952 // Update any PHI nodes in the cloned successors of the skipped blocks to not
953 // have spurious incoming values.
954 for (auto *LoopBB : L.blocks())
Chandler Carruth16529962018-06-25 23:32:54 +0000955 if (SkipBlock(LoopBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +0000956 for (auto *SuccBB : successors(LoopBB))
957 if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
958 for (PHINode &PN : ClonedSuccBB->phis())
959 PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
960
Chandler Carruthed296542018-07-09 10:30:48 +0000961 // Remove the cloned parent as a predecessor of any successor we ended up
962 // cloning other than the unswitched one.
963 auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
964 for (auto *SuccBB : successors(ParentBB)) {
965 if (SuccBB == UnswitchedSuccBB)
966 continue;
967
968 auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
969 if (!ClonedSuccBB)
970 continue;
971
972 ClonedSuccBB->removePredecessor(ClonedParentBB,
973 /*DontDeleteUselessPHIs*/ true);
974 }
975
976 // Replace the cloned branch with an unconditional branch to the cloned
977 // unswitched successor.
978 auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
979 ClonedParentBB->getTerminator()->eraseFromParent();
980 BranchInst::Create(ClonedSuccBB, ClonedParentBB);
981
982 // If there are duplicate entries in the PHI nodes because of multiple edges
983 // to the unswitched successor, we need to nuke all but one as we replaced it
984 // with a direct branch.
985 for (PHINode &PN : ClonedSuccBB->phis()) {
986 bool Found = false;
987 // Loop over the incoming operands backwards so we can easily delete as we
988 // go without invalidating the index.
989 for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
990 if (PN.getIncomingBlock(i) != ClonedParentBB)
991 continue;
992 if (!Found) {
993 Found = true;
994 continue;
995 }
996 PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
997 }
998 }
999
Chandler Carruth69e68f82018-04-25 00:18:07 +00001000 // Record the domtree updates for the new blocks.
Chandler Carruth44aab922018-05-01 09:42:09 +00001001 SmallPtrSet<BasicBlock *, 4> SuccSet;
1002 for (auto *ClonedBB : NewBlocks) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001003 for (auto *SuccBB : successors(ClonedBB))
Chandler Carruth44aab922018-05-01 09:42:09 +00001004 if (SuccSet.insert(SuccBB).second)
1005 DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
1006 SuccSet.clear();
1007 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00001008
Chandler Carruth693eedb2017-11-17 19:58:36 +00001009 return ClonedPH;
1010}
1011
1012/// Recursively clone the specified loop and all of its children.
1013///
1014/// The target parent loop for the clone should be provided, or can be null if
1015/// the clone is a top-level loop. While cloning, all the blocks are mapped
1016/// with the provided value map. The entire original loop must be present in
1017/// the value map. The cloned loop is returned.
1018static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
1019 const ValueToValueMapTy &VMap, LoopInfo &LI) {
1020 auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
1021 assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
1022 ClonedL.reserveBlocks(OrigL.getNumBlocks());
1023 for (auto *BB : OrigL.blocks()) {
1024 auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
1025 ClonedL.addBlockEntry(ClonedBB);
Chandler Carruth0ace1482018-04-24 03:27:00 +00001026 if (LI.getLoopFor(BB) == &OrigL)
Chandler Carruth693eedb2017-11-17 19:58:36 +00001027 LI.changeLoopFor(ClonedBB, &ClonedL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001028 }
1029 };
1030
1031 // We specially handle the first loop because it may get cloned into
1032 // a different parent and because we most commonly are cloning leaf loops.
1033 Loop *ClonedRootL = LI.AllocateLoop();
1034 if (RootParentL)
1035 RootParentL->addChildLoop(ClonedRootL);
1036 else
1037 LI.addTopLevelLoop(ClonedRootL);
1038 AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1039
1040 if (OrigRootL.empty())
1041 return ClonedRootL;
1042
1043 // If we have a nest, we can quickly clone the entire loop nest using an
1044 // iterative approach because it is a tree. We keep the cloned parent in the
1045 // data structure to avoid repeatedly querying through a map to find it.
1046 SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1047 // Build up the loops to clone in reverse order as we'll clone them from the
1048 // back.
1049 for (Loop *ChildL : llvm::reverse(OrigRootL))
1050 LoopsToClone.push_back({ClonedRootL, ChildL});
1051 do {
1052 Loop *ClonedParentL, *L;
1053 std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1054 Loop *ClonedL = LI.AllocateLoop();
1055 ClonedParentL->addChildLoop(ClonedL);
1056 AddClonedBlocksToLoop(*L, *ClonedL);
1057 for (Loop *ChildL : llvm::reverse(*L))
1058 LoopsToClone.push_back({ClonedL, ChildL});
1059 } while (!LoopsToClone.empty());
1060
1061 return ClonedRootL;
1062}
1063
1064/// Build the cloned loops of an original loop from unswitching.
1065///
1066/// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1067/// operation. We need to re-verify that there even is a loop (as the backedge
1068/// may not have been cloned), and even if there are remaining backedges the
1069/// backedge set may be different. However, we know that each child loop is
1070/// undisturbed, we only need to find where to place each child loop within
1071/// either any parent loop or within a cloned version of the original loop.
1072///
1073/// Because child loops may end up cloned outside of any cloned version of the
1074/// original loop, multiple cloned sibling loops may be created. All of them
1075/// are returned so that the newly introduced loop nest roots can be
1076/// identified.
Chandler Carruth92815032018-06-02 01:29:01 +00001077static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1078 const ValueToValueMapTy &VMap, LoopInfo &LI,
1079 SmallVectorImpl<Loop *> &NonChildClonedLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00001080 Loop *ClonedL = nullptr;
1081
1082 auto *OrigPH = OrigL.getLoopPreheader();
1083 auto *OrigHeader = OrigL.getHeader();
1084
1085 auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1086 auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1087
1088 // We need to know the loops of the cloned exit blocks to even compute the
1089 // accurate parent loop. If we only clone exits to some parent of the
1090 // original parent, we want to clone into that outer loop. We also keep track
1091 // of the loops that our cloned exit blocks participate in.
1092 Loop *ParentL = nullptr;
1093 SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1094 SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1095 ClonedExitsInLoops.reserve(ExitBlocks.size());
1096 for (auto *ExitBB : ExitBlocks)
1097 if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1098 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1099 ExitLoopMap[ClonedExitBB] = ExitL;
1100 ClonedExitsInLoops.push_back(ClonedExitBB);
1101 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1102 ParentL = ExitL;
1103 }
1104 assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1105 ParentL->contains(OrigL.getParentLoop())) &&
1106 "The computed parent loop should always contain (or be) the parent of "
1107 "the original loop.");
1108
1109 // We build the set of blocks dominated by the cloned header from the set of
1110 // cloned blocks out of the original loop. While not all of these will
1111 // necessarily be in the cloned loop, it is enough to establish that they
1112 // aren't in unreachable cycles, etc.
1113 SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1114 for (auto *BB : OrigL.blocks())
1115 if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1116 ClonedLoopBlocks.insert(ClonedBB);
1117
1118 // Rebuild the set of blocks that will end up in the cloned loop. We may have
1119 // skipped cloning some region of this loop which can in turn skip some of
1120 // the backedges so we have to rebuild the blocks in the loop based on the
1121 // backedges that remain after cloning.
1122 SmallVector<BasicBlock *, 16> Worklist;
1123 SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1124 for (auto *Pred : predecessors(ClonedHeader)) {
1125 // The only possible non-loop header predecessor is the preheader because
1126 // we know we cloned the loop in simplified form.
1127 if (Pred == ClonedPH)
1128 continue;
1129
1130 // Because the loop was in simplified form, the only non-loop predecessor
1131 // should be the preheader.
1132 assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1133 "header other than the preheader "
1134 "that is not part of the loop!");
1135
1136 // Insert this block into the loop set and on the first visit (and if it
1137 // isn't the header we're currently walking) put it into the worklist to
1138 // recurse through.
1139 if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1140 Worklist.push_back(Pred);
1141 }
1142
1143 // If we had any backedges then there *is* a cloned loop. Put the header into
1144 // the loop set and then walk the worklist backwards to find all the blocks
1145 // that remain within the loop after cloning.
1146 if (!BlocksInClonedLoop.empty()) {
1147 BlocksInClonedLoop.insert(ClonedHeader);
1148
1149 while (!Worklist.empty()) {
1150 BasicBlock *BB = Worklist.pop_back_val();
1151 assert(BlocksInClonedLoop.count(BB) &&
1152 "Didn't put block into the loop set!");
1153
1154 // Insert any predecessors that are in the possible set into the cloned
1155 // set, and if the insert is successful, add them to the worklist. Note
1156 // that we filter on the blocks that are definitely reachable via the
1157 // backedge to the loop header so we may prune out dead code within the
1158 // cloned loop.
1159 for (auto *Pred : predecessors(BB))
1160 if (ClonedLoopBlocks.count(Pred) &&
1161 BlocksInClonedLoop.insert(Pred).second)
1162 Worklist.push_back(Pred);
1163 }
1164
1165 ClonedL = LI.AllocateLoop();
1166 if (ParentL) {
1167 ParentL->addBasicBlockToLoop(ClonedPH, LI);
1168 ParentL->addChildLoop(ClonedL);
1169 } else {
1170 LI.addTopLevelLoop(ClonedL);
1171 }
Chandler Carruth92815032018-06-02 01:29:01 +00001172 NonChildClonedLoops.push_back(ClonedL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001173
1174 ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1175 // We don't want to just add the cloned loop blocks based on how we
1176 // discovered them. The original order of blocks was carefully built in
1177 // a way that doesn't rely on predecessor ordering. Rather than re-invent
1178 // that logic, we just re-walk the original blocks (and those of the child
1179 // loops) and filter them as we add them into the cloned loop.
1180 for (auto *BB : OrigL.blocks()) {
1181 auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1182 if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1183 continue;
1184
1185 // Directly add the blocks that are only in this loop.
1186 if (LI.getLoopFor(BB) == &OrigL) {
1187 ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1188 continue;
1189 }
1190
1191 // We want to manually add it to this loop and parents.
1192 // Registering it with LoopInfo will happen when we clone the top
1193 // loop for this block.
1194 for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1195 PL->addBlockEntry(ClonedBB);
1196 }
1197
1198 // Now add each child loop whose header remains within the cloned loop. All
1199 // of the blocks within the loop must satisfy the same constraints as the
1200 // header so once we pass the header checks we can just clone the entire
1201 // child loop nest.
1202 for (Loop *ChildL : OrigL) {
1203 auto *ClonedChildHeader =
1204 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1205 if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1206 continue;
1207
1208#ifndef NDEBUG
1209 // We should never have a cloned child loop header but fail to have
1210 // all of the blocks for that child loop.
1211 for (auto *ChildLoopBB : ChildL->blocks())
1212 assert(BlocksInClonedLoop.count(
1213 cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1214 "Child cloned loop has a header within the cloned outer "
1215 "loop but not all of its blocks!");
1216#endif
1217
1218 cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1219 }
1220 }
1221
1222 // Now that we've handled all the components of the original loop that were
1223 // cloned into a new loop, we still need to handle anything from the original
1224 // loop that wasn't in a cloned loop.
1225
1226 // Figure out what blocks are left to place within any loop nest containing
1227 // the unswitched loop. If we never formed a loop, the cloned PH is one of
1228 // them.
1229 SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1230 if (BlocksInClonedLoop.empty())
1231 UnloopedBlockSet.insert(ClonedPH);
1232 for (auto *ClonedBB : ClonedLoopBlocks)
1233 if (!BlocksInClonedLoop.count(ClonedBB))
1234 UnloopedBlockSet.insert(ClonedBB);
1235
1236 // Copy the cloned exits and sort them in ascending loop depth, we'll work
1237 // backwards across these to process them inside out. The order shouldn't
1238 // matter as we're just trying to build up the map from inside-out; we use
1239 // the map in a more stably ordered way below.
1240 auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
Chandler Carruth4da33312018-06-20 18:57:07 +00001241 llvm::sort(OrderedClonedExitsInLoops.begin(), OrderedClonedExitsInLoops.end(),
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +00001242 [&](BasicBlock *LHS, BasicBlock *RHS) {
1243 return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1244 ExitLoopMap.lookup(RHS)->getLoopDepth();
1245 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001246
1247 // Populate the existing ExitLoopMap with everything reachable from each
1248 // exit, starting from the inner most exit.
1249 while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1250 assert(Worklist.empty() && "Didn't clear worklist!");
1251
1252 BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1253 Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1254
1255 // Walk the CFG back until we hit the cloned PH adding everything reachable
1256 // and in the unlooped set to this exit block's loop.
1257 Worklist.push_back(ExitBB);
1258 do {
1259 BasicBlock *BB = Worklist.pop_back_val();
1260 // We can stop recursing at the cloned preheader (if we get there).
1261 if (BB == ClonedPH)
1262 continue;
1263
1264 for (BasicBlock *PredBB : predecessors(BB)) {
1265 // If this pred has already been moved to our set or is part of some
1266 // (inner) loop, no update needed.
1267 if (!UnloopedBlockSet.erase(PredBB)) {
1268 assert(
1269 (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1270 "Predecessor not mapped to a loop!");
1271 continue;
1272 }
1273
1274 // We just insert into the loop set here. We'll add these blocks to the
1275 // exit loop after we build up the set in an order that doesn't rely on
1276 // predecessor order (which in turn relies on use list order).
1277 bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1278 (void)Inserted;
1279 assert(Inserted && "Should only visit an unlooped block once!");
1280
1281 // And recurse through to its predecessors.
1282 Worklist.push_back(PredBB);
1283 }
1284 } while (!Worklist.empty());
1285 }
1286
1287 // Now that the ExitLoopMap gives as mapping for all the non-looping cloned
1288 // blocks to their outer loops, walk the cloned blocks and the cloned exits
1289 // in their original order adding them to the correct loop.
1290
1291 // We need a stable insertion order. We use the order of the original loop
1292 // order and map into the correct parent loop.
1293 for (auto *BB : llvm::concat<BasicBlock *const>(
1294 makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1295 if (Loop *OuterL = ExitLoopMap.lookup(BB))
1296 OuterL->addBasicBlockToLoop(BB, LI);
1297
1298#ifndef NDEBUG
1299 for (auto &BBAndL : ExitLoopMap) {
1300 auto *BB = BBAndL.first;
1301 auto *OuterL = BBAndL.second;
1302 assert(LI.getLoopFor(BB) == OuterL &&
1303 "Failed to put all blocks into outer loops!");
1304 }
1305#endif
1306
1307 // Now that all the blocks are placed into the correct containing loop in the
1308 // absence of child loops, find all the potentially cloned child loops and
1309 // clone them into whatever outer loop we placed their header into.
1310 for (Loop *ChildL : OrigL) {
1311 auto *ClonedChildHeader =
1312 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1313 if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1314 continue;
1315
1316#ifndef NDEBUG
1317 for (auto *ChildLoopBB : ChildL->blocks())
1318 assert(VMap.count(ChildLoopBB) &&
1319 "Cloned a child loop header but not all of that loops blocks!");
1320#endif
1321
1322 NonChildClonedLoops.push_back(cloneLoopNest(
1323 *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1324 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001325}
1326
Chandler Carruth69e68f82018-04-25 00:18:07 +00001327static void
Chandler Carruth16529962018-06-25 23:32:54 +00001328deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1329 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
1330 DominatorTree &DT) {
1331 // Find all the dead clones, and remove them from their successors.
1332 SmallVector<BasicBlock *, 16> DeadBlocks;
1333 for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1334 for (auto &VMap : VMaps)
1335 if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
1336 if (!DT.isReachableFromEntry(ClonedBB)) {
1337 for (BasicBlock *SuccBB : successors(ClonedBB))
1338 SuccBB->removePredecessor(ClonedBB);
1339 DeadBlocks.push_back(ClonedBB);
1340 }
1341
1342 // Drop any remaining references to break cycles.
1343 for (BasicBlock *BB : DeadBlocks)
1344 BB->dropAllReferences();
1345 // Erase them from the IR.
1346 for (BasicBlock *BB : DeadBlocks)
1347 BB->eraseFromParent();
1348}
1349
1350static void
Chandler Carruth69e68f82018-04-25 00:18:07 +00001351deleteDeadBlocksFromLoop(Loop &L,
Chandler Carruth69e68f82018-04-25 00:18:07 +00001352 SmallVectorImpl<BasicBlock *> &ExitBlocks,
1353 DominatorTree &DT, LoopInfo &LI) {
Chandler Carruth16529962018-06-25 23:32:54 +00001354 // Find all the dead blocks, and remove them from their successors.
1355 SmallVector<BasicBlock *, 16> DeadBlocks;
1356 for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1357 if (!DT.isReachableFromEntry(BB)) {
1358 for (BasicBlock *SuccBB : successors(BB))
1359 SuccBB->removePredecessor(BB);
1360 DeadBlocks.push_back(BB);
1361 }
1362
Chandler Carruth69e68f82018-04-25 00:18:07 +00001363 SmallPtrSet<BasicBlock *, 16> DeadBlockSet(DeadBlocks.begin(),
1364 DeadBlocks.end());
Chandler Carruth693eedb2017-11-17 19:58:36 +00001365
1366 // Filter out the dead blocks from the exit blocks list so that it can be
1367 // used in the caller.
1368 llvm::erase_if(ExitBlocks,
Chandler Carruth69e68f82018-04-25 00:18:07 +00001369 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001370
Chandler Carruth693eedb2017-11-17 19:58:36 +00001371 // Walk from this loop up through its parents removing all of the dead blocks.
1372 for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
1373 for (auto *BB : DeadBlocks)
1374 ParentL->getBlocksSet().erase(BB);
1375 llvm::erase_if(ParentL->getBlocksVector(),
Chandler Carruth69e68f82018-04-25 00:18:07 +00001376 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001377 }
1378
1379 // Now delete the dead child loops. This raw delete will clear them
1380 // recursively.
1381 llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001382 if (!DeadBlockSet.count(ChildL->getHeader()))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001383 return false;
1384
1385 assert(llvm::all_of(ChildL->blocks(),
1386 [&](BasicBlock *ChildBB) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001387 return DeadBlockSet.count(ChildBB);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001388 }) &&
1389 "If the child loop header is dead all blocks in the child loop must "
1390 "be dead as well!");
1391 LI.destroy(ChildL);
1392 return true;
1393 });
1394
Chandler Carruth69e68f82018-04-25 00:18:07 +00001395 // Remove the loop mappings for the dead blocks and drop all the references
1396 // from these blocks to others to handle cyclic references as we start
1397 // deleting the blocks themselves.
1398 for (auto *BB : DeadBlocks) {
1399 // Check that the dominator tree has already been updated.
1400 assert(!DT.getNode(BB) && "Should already have cleared domtree!");
Chandler Carruth693eedb2017-11-17 19:58:36 +00001401 LI.changeLoopFor(BB, nullptr);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001402 BB->dropAllReferences();
Chandler Carruth693eedb2017-11-17 19:58:36 +00001403 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00001404
1405 // Actually delete the blocks now that they've been fully unhooked from the
1406 // IR.
1407 for (auto *BB : DeadBlocks)
1408 BB->eraseFromParent();
Chandler Carruth693eedb2017-11-17 19:58:36 +00001409}
1410
1411/// Recompute the set of blocks in a loop after unswitching.
1412///
1413/// This walks from the original headers predecessors to rebuild the loop. We
1414/// take advantage of the fact that new blocks can't have been added, and so we
1415/// filter by the original loop's blocks. This also handles potentially
1416/// unreachable code that we don't want to explore but might be found examining
1417/// the predecessors of the header.
1418///
1419/// If the original loop is no longer a loop, this will return an empty set. If
1420/// it remains a loop, all the blocks within it will be added to the set
1421/// (including those blocks in inner loops).
1422static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1423 LoopInfo &LI) {
1424 SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1425
1426 auto *PH = L.getLoopPreheader();
1427 auto *Header = L.getHeader();
1428
1429 // A worklist to use while walking backwards from the header.
1430 SmallVector<BasicBlock *, 16> Worklist;
1431
1432 // First walk the predecessors of the header to find the backedges. This will
1433 // form the basis of our walk.
1434 for (auto *Pred : predecessors(Header)) {
1435 // Skip the preheader.
1436 if (Pred == PH)
1437 continue;
1438
1439 // Because the loop was in simplified form, the only non-loop predecessor
1440 // is the preheader.
1441 assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1442 "than the preheader that is not part of the "
1443 "loop!");
1444
1445 // Insert this block into the loop set and on the first visit and, if it
1446 // isn't the header we're currently walking, put it into the worklist to
1447 // recurse through.
1448 if (LoopBlockSet.insert(Pred).second && Pred != Header)
1449 Worklist.push_back(Pred);
1450 }
1451
1452 // If no backedges were found, we're done.
1453 if (LoopBlockSet.empty())
1454 return LoopBlockSet;
1455
Chandler Carruth693eedb2017-11-17 19:58:36 +00001456 // We found backedges, recurse through them to identify the loop blocks.
1457 while (!Worklist.empty()) {
1458 BasicBlock *BB = Worklist.pop_back_val();
1459 assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1460
Chandler Carruth43acdb32018-04-24 10:33:08 +00001461 // No need to walk past the header.
1462 if (BB == Header)
1463 continue;
1464
Chandler Carruth693eedb2017-11-17 19:58:36 +00001465 // Because we know the inner loop structure remains valid we can use the
1466 // loop structure to jump immediately across the entire nested loop.
1467 // Further, because it is in loop simplified form, we can directly jump
1468 // to its preheader afterward.
1469 if (Loop *InnerL = LI.getLoopFor(BB))
1470 if (InnerL != &L) {
1471 assert(L.contains(InnerL) &&
1472 "Should not reach a loop *outside* this loop!");
1473 // The preheader is the only possible predecessor of the loop so
1474 // insert it into the set and check whether it was already handled.
1475 auto *InnerPH = InnerL->getLoopPreheader();
1476 assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1477 "but not contain the inner loop "
1478 "preheader!");
1479 if (!LoopBlockSet.insert(InnerPH).second)
1480 // The only way to reach the preheader is through the loop body
1481 // itself so if it has been visited the loop is already handled.
1482 continue;
1483
1484 // Insert all of the blocks (other than those already present) into
Chandler Carruthbf7190a2018-04-23 06:58:36 +00001485 // the loop set. We expect at least the block that led us to find the
1486 // inner loop to be in the block set, but we may also have other loop
1487 // blocks if they were already enqueued as predecessors of some other
1488 // outer loop block.
Chandler Carruth693eedb2017-11-17 19:58:36 +00001489 for (auto *InnerBB : InnerL->blocks()) {
1490 if (InnerBB == BB) {
1491 assert(LoopBlockSet.count(InnerBB) &&
1492 "Block should already be in the set!");
1493 continue;
1494 }
1495
Chandler Carruthbf7190a2018-04-23 06:58:36 +00001496 LoopBlockSet.insert(InnerBB);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001497 }
1498
1499 // Add the preheader to the worklist so we will continue past the
1500 // loop body.
1501 Worklist.push_back(InnerPH);
1502 continue;
1503 }
1504
1505 // Insert any predecessors that were in the original loop into the new
1506 // set, and if the insert is successful, add them to the worklist.
1507 for (auto *Pred : predecessors(BB))
1508 if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1509 Worklist.push_back(Pred);
1510 }
1511
Chandler Carruth43acdb32018-04-24 10:33:08 +00001512 assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
1513
Chandler Carruth693eedb2017-11-17 19:58:36 +00001514 // We've found all the blocks participating in the loop, return our completed
1515 // set.
1516 return LoopBlockSet;
1517}
1518
1519/// Rebuild a loop after unswitching removes some subset of blocks and edges.
1520///
1521/// The removal may have removed some child loops entirely but cannot have
1522/// disturbed any remaining child loops. However, they may need to be hoisted
1523/// to the parent loop (or to be top-level loops). The original loop may be
1524/// completely removed.
1525///
1526/// The sibling loops resulting from this update are returned. If the original
1527/// loop remains a valid loop, it will be the first entry in this list with all
1528/// of the newly sibling loops following it.
1529///
1530/// Returns true if the loop remains a loop after unswitching, and false if it
1531/// is no longer a loop after unswitching (and should not continue to be
1532/// referenced).
1533static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1534 LoopInfo &LI,
1535 SmallVectorImpl<Loop *> &HoistedLoops) {
1536 auto *PH = L.getLoopPreheader();
1537
1538 // Compute the actual parent loop from the exit blocks. Because we may have
1539 // pruned some exits the loop may be different from the original parent.
1540 Loop *ParentL = nullptr;
1541 SmallVector<Loop *, 4> ExitLoops;
1542 SmallVector<BasicBlock *, 4> ExitsInLoops;
1543 ExitsInLoops.reserve(ExitBlocks.size());
1544 for (auto *ExitBB : ExitBlocks)
1545 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1546 ExitLoops.push_back(ExitL);
1547 ExitsInLoops.push_back(ExitBB);
1548 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1549 ParentL = ExitL;
1550 }
1551
1552 // Recompute the blocks participating in this loop. This may be empty if it
1553 // is no longer a loop.
1554 auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1555
1556 // If we still have a loop, we need to re-set the loop's parent as the exit
1557 // block set changing may have moved it within the loop nest. Note that this
1558 // can only happen when this loop has a parent as it can only hoist the loop
1559 // *up* the nest.
1560 if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1561 // Remove this loop's (original) blocks from all of the intervening loops.
1562 for (Loop *IL = L.getParentLoop(); IL != ParentL;
1563 IL = IL->getParentLoop()) {
1564 IL->getBlocksSet().erase(PH);
1565 for (auto *BB : L.blocks())
1566 IL->getBlocksSet().erase(BB);
1567 llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1568 return BB == PH || L.contains(BB);
1569 });
1570 }
1571
1572 LI.changeLoopFor(PH, ParentL);
1573 L.getParentLoop()->removeChildLoop(&L);
1574 if (ParentL)
1575 ParentL->addChildLoop(&L);
1576 else
1577 LI.addTopLevelLoop(&L);
1578 }
1579
1580 // Now we update all the blocks which are no longer within the loop.
1581 auto &Blocks = L.getBlocksVector();
1582 auto BlocksSplitI =
1583 LoopBlockSet.empty()
1584 ? Blocks.begin()
1585 : std::stable_partition(
1586 Blocks.begin(), Blocks.end(),
1587 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1588
1589 // Before we erase the list of unlooped blocks, build a set of them.
1590 SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1591 if (LoopBlockSet.empty())
1592 UnloopedBlocks.insert(PH);
1593
1594 // Now erase these blocks from the loop.
1595 for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1596 L.getBlocksSet().erase(BB);
1597 Blocks.erase(BlocksSplitI, Blocks.end());
1598
1599 // Sort the exits in ascending loop depth, we'll work backwards across these
1600 // to process them inside out.
1601 std::stable_sort(ExitsInLoops.begin(), ExitsInLoops.end(),
1602 [&](BasicBlock *LHS, BasicBlock *RHS) {
1603 return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1604 });
1605
1606 // We'll build up a set for each exit loop.
1607 SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1608 Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1609
1610 auto RemoveUnloopedBlocksFromLoop =
1611 [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1612 for (auto *BB : UnloopedBlocks)
1613 L.getBlocksSet().erase(BB);
1614 llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1615 return UnloopedBlocks.count(BB);
1616 });
1617 };
1618
1619 SmallVector<BasicBlock *, 16> Worklist;
1620 while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1621 assert(Worklist.empty() && "Didn't clear worklist!");
1622 assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1623
1624 // Grab the next exit block, in decreasing loop depth order.
1625 BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1626 Loop &ExitL = *LI.getLoopFor(ExitBB);
1627 assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1628
1629 // Erase all of the unlooped blocks from the loops between the previous
1630 // exit loop and this exit loop. This works because the ExitInLoops list is
1631 // sorted in increasing order of loop depth and thus we visit loops in
1632 // decreasing order of loop depth.
1633 for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1634 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1635
1636 // Walk the CFG back until we hit the cloned PH adding everything reachable
1637 // and in the unlooped set to this exit block's loop.
1638 Worklist.push_back(ExitBB);
1639 do {
1640 BasicBlock *BB = Worklist.pop_back_val();
1641 // We can stop recursing at the cloned preheader (if we get there).
1642 if (BB == PH)
1643 continue;
1644
1645 for (BasicBlock *PredBB : predecessors(BB)) {
1646 // If this pred has already been moved to our set or is part of some
1647 // (inner) loop, no update needed.
1648 if (!UnloopedBlocks.erase(PredBB)) {
1649 assert((NewExitLoopBlocks.count(PredBB) ||
1650 ExitL.contains(LI.getLoopFor(PredBB))) &&
1651 "Predecessor not in a nested loop (or already visited)!");
1652 continue;
1653 }
1654
1655 // We just insert into the loop set here. We'll add these blocks to the
1656 // exit loop after we build up the set in a deterministic order rather
1657 // than the predecessor-influenced visit order.
1658 bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1659 (void)Inserted;
1660 assert(Inserted && "Should only visit an unlooped block once!");
1661
1662 // And recurse through to its predecessors.
1663 Worklist.push_back(PredBB);
1664 }
1665 } while (!Worklist.empty());
1666
1667 // If blocks in this exit loop were directly part of the original loop (as
1668 // opposed to a child loop) update the map to point to this exit loop. This
1669 // just updates a map and so the fact that the order is unstable is fine.
1670 for (auto *BB : NewExitLoopBlocks)
1671 if (Loop *BBL = LI.getLoopFor(BB))
1672 if (BBL == &L || !L.contains(BBL))
1673 LI.changeLoopFor(BB, &ExitL);
1674
1675 // We will remove the remaining unlooped blocks from this loop in the next
1676 // iteration or below.
1677 NewExitLoopBlocks.clear();
1678 }
1679
1680 // Any remaining unlooped blocks are no longer part of any loop unless they
1681 // are part of some child loop.
1682 for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1683 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1684 for (auto *BB : UnloopedBlocks)
1685 if (Loop *BBL = LI.getLoopFor(BB))
1686 if (BBL == &L || !L.contains(BBL))
1687 LI.changeLoopFor(BB, nullptr);
1688
1689 // Sink all the child loops whose headers are no longer in the loop set to
1690 // the parent (or to be top level loops). We reach into the loop and directly
1691 // update its subloop vector to make this batch update efficient.
1692 auto &SubLoops = L.getSubLoopsVector();
1693 auto SubLoopsSplitI =
1694 LoopBlockSet.empty()
1695 ? SubLoops.begin()
1696 : std::stable_partition(
1697 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1698 return LoopBlockSet.count(SubL->getHeader());
1699 });
1700 for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1701 HoistedLoops.push_back(HoistedL);
1702 HoistedL->setParentLoop(nullptr);
1703
1704 // To compute the new parent of this hoisted loop we look at where we
1705 // placed the preheader above. We can't lookup the header itself because we
1706 // retained the mapping from the header to the hoisted loop. But the
1707 // preheader and header should have the exact same new parent computed
1708 // based on the set of exit blocks from the original loop as the preheader
1709 // is a predecessor of the header and so reached in the reverse walk. And
1710 // because the loops were all in simplified form the preheader of the
1711 // hoisted loop can't be part of some *other* loop.
1712 if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1713 NewParentL->addChildLoop(HoistedL);
1714 else
1715 LI.addTopLevelLoop(HoistedL);
1716 }
1717 SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1718
1719 // Actually delete the loop if nothing remained within it.
1720 if (Blocks.empty()) {
1721 assert(SubLoops.empty() &&
1722 "Failed to remove all subloops from the original loop!");
1723 if (Loop *ParentL = L.getParentLoop())
1724 ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1725 else
1726 LI.removeLoop(llvm::find(LI, &L));
1727 LI.destroy(&L);
1728 return false;
1729 }
1730
1731 return true;
1732}
1733
1734/// Helper to visit a dominator subtree, invoking a callable on each node.
1735///
1736/// Returning false at any point will stop walking past that node of the tree.
1737template <typename CallableT>
1738void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1739 SmallVector<DomTreeNode *, 4> DomWorklist;
1740 DomWorklist.push_back(DT[BB]);
1741#ifndef NDEBUG
1742 SmallPtrSet<DomTreeNode *, 4> Visited;
1743 Visited.insert(DT[BB]);
1744#endif
1745 do {
1746 DomTreeNode *N = DomWorklist.pop_back_val();
1747
1748 // Visit this node.
1749 if (!Callable(N->getBlock()))
1750 continue;
1751
1752 // Accumulate the child nodes.
1753 for (DomTreeNode *ChildN : *N) {
1754 assert(Visited.insert(ChildN).second &&
1755 "Cannot visit a node twice when walking a tree!");
1756 DomWorklist.push_back(ChildN);
1757 }
1758 } while (!DomWorklist.empty());
1759}
1760
Chandler Carruth16529962018-06-25 23:32:54 +00001761static bool unswitchNontrivialInvariants(
1762 Loop &L, TerminatorInst &TI, ArrayRef<Value *> Invariants,
1763 DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
Chandler Carruth3897ded2018-07-03 09:13:27 +00001764 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
1765 ScalarEvolution *SE) {
Chandler Carruth16529962018-06-25 23:32:54 +00001766 auto *ParentBB = TI.getParent();
1767 BranchInst *BI = dyn_cast<BranchInst>(&TI);
1768 SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001769
Chandler Carruth16529962018-06-25 23:32:54 +00001770 // We can only unswitch switches, conditional branches with an invariant
1771 // condition, or combining invariant conditions with an instruction.
1772 assert((SI || BI->isConditional()) &&
1773 "Can only unswitch switches and conditional branch!");
1774 bool FullUnswitch = SI || BI->getCondition() == Invariants[0];
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001775 if (FullUnswitch)
1776 assert(Invariants.size() == 1 &&
1777 "Cannot have other invariants with full unswitching!");
1778 else
Chandler Carruth16529962018-06-25 23:32:54 +00001779 assert(isa<Instruction>(BI->getCondition()) &&
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001780 "Partial unswitching requires an instruction as the condition!");
1781
1782 // Constant and BBs tracking the cloned and continuing successor. When we are
1783 // unswitching the entire condition, this can just be trivially chosen to
1784 // unswitch towards `true`. However, when we are unswitching a set of
1785 // invariants combined with `and` or `or`, the combining operation determines
1786 // the best direction to unswitch: we want to unswitch the direction that will
1787 // collapse the branch.
1788 bool Direction = true;
1789 int ClonedSucc = 0;
1790 if (!FullUnswitch) {
Chandler Carruth16529962018-06-25 23:32:54 +00001791 if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) {
1792 assert(cast<Instruction>(BI->getCondition())->getOpcode() ==
1793 Instruction::And &&
1794 "Only `or` and `and` instructions can combine invariants being "
1795 "unswitched.");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001796 Direction = false;
1797 ClonedSucc = 1;
1798 }
1799 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001800
Chandler Carruth16529962018-06-25 23:32:54 +00001801 BasicBlock *RetainedSuccBB =
1802 BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
1803 SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
1804 if (BI)
1805 UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
1806 else
1807 for (auto Case : SI->cases())
Chandler Carruthed296542018-07-09 10:30:48 +00001808 if (Case.getCaseSuccessor() != RetainedSuccBB)
1809 UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
Chandler Carruth16529962018-06-25 23:32:54 +00001810
1811 assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
1812 "Should not unswitch the same successor we are retaining!");
Chandler Carruth693eedb2017-11-17 19:58:36 +00001813
1814 // The branch should be in this exact loop. Any inner loop's invariant branch
1815 // should be handled by unswitching that inner loop. The caller of this
1816 // routine should filter out any candidates that remain (but were skipped for
1817 // whatever reason).
1818 assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
1819
1820 SmallVector<BasicBlock *, 4> ExitBlocks;
1821 L.getUniqueExitBlocks(ExitBlocks);
1822
1823 // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
1824 // don't know how to split those exit blocks.
1825 // FIXME: We should teach SplitBlock to handle this and remove this
1826 // restriction.
1827 for (auto *ExitBB : ExitBlocks)
1828 if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI()))
1829 return false;
1830
Chandler Carruth693eedb2017-11-17 19:58:36 +00001831 // Compute the parent loop now before we start hacking on things.
1832 Loop *ParentL = L.getParentLoop();
1833
1834 // Compute the outer-most loop containing one of our exit blocks. This is the
1835 // furthest up our loopnest which can be mutated, which we will use below to
1836 // update things.
1837 Loop *OuterExitL = &L;
1838 for (auto *ExitBB : ExitBlocks) {
1839 Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
1840 if (!NewOuterExitL) {
1841 // We exited the entire nest with this block, so we're done.
1842 OuterExitL = nullptr;
1843 break;
1844 }
1845 if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
1846 OuterExitL = NewOuterExitL;
1847 }
1848
Chandler Carruth3897ded2018-07-03 09:13:27 +00001849 // At this point, we're definitely going to unswitch something so invalidate
1850 // any cached information in ScalarEvolution for the outer most loop
1851 // containing an exit block and all nested loops.
1852 if (SE) {
1853 if (OuterExitL)
1854 SE->forgetLoop(OuterExitL);
1855 else
1856 SE->forgetTopmostLoop(&L);
1857 }
1858
Chandler Carruth16529962018-06-25 23:32:54 +00001859 // If the edge from this terminator to a successor dominates that successor,
1860 // store a map from each block in its dominator subtree to it. This lets us
1861 // tell when cloning for a particular successor if a block is dominated by
1862 // some *other* successor with a single data structure. We use this to
1863 // significantly reduce cloning.
1864 SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
1865 for (auto *SuccBB : llvm::concat<BasicBlock *const>(
1866 makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
1867 if (SuccBB->getUniquePredecessor() ||
1868 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
1869 return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
1870 }))
1871 visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
1872 DominatingSucc[BB] = SuccBB;
1873 return true;
1874 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001875
1876 // Split the preheader, so that we know that there is a safe place to insert
1877 // the conditional branch. We will change the preheader to have a conditional
1878 // branch on LoopCond. The original preheader will become the split point
1879 // between the unswitched versions, and we will have a new preheader for the
1880 // original loop.
1881 BasicBlock *SplitBB = L.getLoopPreheader();
1882 BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI);
1883
Chandler Carruth69e68f82018-04-25 00:18:07 +00001884 // Keep track of the dominator tree updates needed.
1885 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
1886
Chandler Carruth16529962018-06-25 23:32:54 +00001887 // Clone the loop for each unswitched successor.
1888 SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
1889 VMaps.reserve(UnswitchedSuccBBs.size());
1890 SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
1891 for (auto *SuccBB : UnswitchedSuccBBs) {
1892 VMaps.emplace_back(new ValueToValueMapTy());
1893 ClonedPHs[SuccBB] = buildClonedLoopBlocks(
1894 L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
1895 DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI);
1896 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001897
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001898 // The stitching of the branched code back together depends on whether we're
1899 // doing full unswitching or not with the exception that we always want to
1900 // nuke the initial terminator placed in the split block.
Chandler Carruth693eedb2017-11-17 19:58:36 +00001901 SplitBB->getTerminator()->eraseFromParent();
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001902 if (FullUnswitch) {
Chandler Carruthed296542018-07-09 10:30:48 +00001903 // First we need to unhook the successor relationship as we'll be replacing
1904 // the terminator with a direct branch. This is much simpler for branches
1905 // than switches so we handle those first.
Chandler Carruth16529962018-06-25 23:32:54 +00001906 if (BI) {
Chandler Carruthed296542018-07-09 10:30:48 +00001907 // Remove the parent as a predecessor of the unswitched successor.
Chandler Carruth16529962018-06-25 23:32:54 +00001908 assert(UnswitchedSuccBBs.size() == 1 &&
1909 "Only one possible unswitched block for a branch!");
Chandler Carruthed296542018-07-09 10:30:48 +00001910 BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
1911 UnswitchedSuccBB->removePredecessor(ParentBB,
1912 /*DontDeleteUselessPHIs*/ true);
1913 DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
1914 } else {
1915 // Note that we actually want to remove the parent block as a predecessor
1916 // of *every* case successor. The case successor is either unswitched,
1917 // completely eliminating an edge from the parent to that successor, or it
1918 // is a duplicate edge to the retained successor as the retained successor
1919 // is always the default successor and as we'll replace this with a direct
1920 // branch we no longer need the duplicate entries in the PHI nodes.
1921 assert(SI->getDefaultDest() == RetainedSuccBB &&
1922 "Not retaining default successor!");
1923 for (auto &Case : SI->cases())
1924 Case.getCaseSuccessor()->removePredecessor(
1925 ParentBB,
1926 /*DontDeleteUselessPHIs*/ true);
1927
1928 // We need to use the set to populate domtree updates as even when there
1929 // are multiple cases pointing at the same successor we only want to
1930 // remove and insert one edge in the domtree.
1931 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
1932 DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
1933 }
1934
1935 // Now that we've unhooked the successor relationship, splice the terminator
1936 // from the original loop to the split.
1937 SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
1938
1939 // Now wire up the terminator to the preheaders.
1940 if (BI) {
Chandler Carruth16529962018-06-25 23:32:54 +00001941 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
1942 BI->setSuccessor(ClonedSucc, ClonedPH);
1943 BI->setSuccessor(1 - ClonedSucc, LoopPH);
1944 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
1945 } else {
1946 assert(SI && "Must either be a branch or switch!");
1947
1948 // Walk the cases and directly update their successors.
Chandler Carruthed296542018-07-09 10:30:48 +00001949 SI->setDefaultDest(LoopPH);
Chandler Carruth16529962018-06-25 23:32:54 +00001950 for (auto &Case : SI->cases())
Chandler Carruthed296542018-07-09 10:30:48 +00001951 if (Case.getCaseSuccessor() == RetainedSuccBB)
1952 Case.setSuccessor(LoopPH);
1953 else
1954 Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
1955
Chandler Carruth16529962018-06-25 23:32:54 +00001956 // We need to use the set to populate domtree updates as even when there
1957 // are multiple cases pointing at the same successor we only want to
Chandler Carruthed296542018-07-09 10:30:48 +00001958 // remove and insert one edge in the domtree.
Chandler Carruth16529962018-06-25 23:32:54 +00001959 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
1960 DTUpdates.push_back(
1961 {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
Chandler Carruth16529962018-06-25 23:32:54 +00001962 }
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001963
1964 // Create a new unconditional branch to the continuing block (as opposed to
1965 // the one cloned).
Chandler Carruth16529962018-06-25 23:32:54 +00001966 BranchInst::Create(RetainedSuccBB, ParentBB);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001967 } else {
Chandler Carruth16529962018-06-25 23:32:54 +00001968 assert(BI && "Only branches have partial unswitching.");
1969 assert(UnswitchedSuccBBs.size() == 1 &&
1970 "Only one possible unswitched block for a branch!");
1971 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001972 // When doing a partial unswitch, we have to do a bit more work to build up
1973 // the branch in the split block.
1974 buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
1975 *ClonedPH, *LoopPH);
Chandler Carruth16529962018-06-25 23:32:54 +00001976 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001977 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001978
Chandler Carruth16529962018-06-25 23:32:54 +00001979 // Apply the updates accumulated above to get an up-to-date dominator tree.
Chandler Carruth69e68f82018-04-25 00:18:07 +00001980 DT.applyUpdates(DTUpdates);
1981
Chandler Carruth16529962018-06-25 23:32:54 +00001982 // Now that we have an accurate dominator tree, first delete the dead cloned
1983 // blocks so that we can accurately build any cloned loops. It is important to
1984 // not delete the blocks from the original loop yet because we still want to
1985 // reference the original loop to understand the cloned loop's structure.
1986 deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT);
1987
Chandler Carruth69e68f82018-04-25 00:18:07 +00001988 // Build the cloned loop structure itself. This may be substantially
1989 // different from the original structure due to the simplified CFG. This also
1990 // handles inserting all the cloned blocks into the correct loops.
1991 SmallVector<Loop *, 4> NonChildClonedLoops;
Chandler Carruth16529962018-06-25 23:32:54 +00001992 for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
1993 buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
Chandler Carruth69e68f82018-04-25 00:18:07 +00001994
Chandler Carruth16529962018-06-25 23:32:54 +00001995 // Now that our cloned loops have been built, we can update the original loop.
1996 // First we delete the dead blocks from it and then we rebuild the loop
1997 // structure taking these deletions into account.
1998 deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001999 SmallVector<Loop *, 4> HoistedLoops;
2000 bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
2001
Chandler Carruth69e68f82018-04-25 00:18:07 +00002002 // This transformation has a high risk of corrupting the dominator tree, and
2003 // the below steps to rebuild loop structures will result in hard to debug
2004 // errors in that case so verify that the dominator tree is sane first.
2005 // FIXME: Remove this when the bugs stop showing up and rely on existing
2006 // verification steps.
2007 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruth693eedb2017-11-17 19:58:36 +00002008
Chandler Carruth16529962018-06-25 23:32:54 +00002009 if (BI) {
2010 // If we unswitched a branch which collapses the condition to a known
2011 // constant we want to replace all the uses of the invariants within both
2012 // the original and cloned blocks. We do this here so that we can use the
2013 // now updated dominator tree to identify which side the users are on.
2014 assert(UnswitchedSuccBBs.size() == 1 &&
2015 "Only one possible unswitched block for a branch!");
2016 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2017 ConstantInt *UnswitchedReplacement =
2018 Direction ? ConstantInt::getTrue(BI->getContext())
2019 : ConstantInt::getFalse(BI->getContext());
2020 ConstantInt *ContinueReplacement =
2021 Direction ? ConstantInt::getFalse(BI->getContext())
2022 : ConstantInt::getTrue(BI->getContext());
2023 for (Value *Invariant : Invariants)
2024 for (auto UI = Invariant->use_begin(), UE = Invariant->use_end();
2025 UI != UE;) {
2026 // Grab the use and walk past it so we can clobber it in the use list.
2027 Use *U = &*UI++;
2028 Instruction *UserI = dyn_cast<Instruction>(U->getUser());
2029 if (!UserI)
2030 continue;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002031
Chandler Carruth16529962018-06-25 23:32:54 +00002032 // Replace it with the 'continue' side if in the main loop body, and the
2033 // unswitched if in the cloned blocks.
2034 if (DT.dominates(LoopPH, UserI->getParent()))
2035 U->set(ContinueReplacement);
2036 else if (DT.dominates(ClonedPH, UserI->getParent()))
2037 U->set(UnswitchedReplacement);
2038 }
2039 }
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002040
Chandler Carruth693eedb2017-11-17 19:58:36 +00002041 // We can change which blocks are exit blocks of all the cloned sibling
2042 // loops, the current loop, and any parent loops which shared exit blocks
2043 // with the current loop. As a consequence, we need to re-form LCSSA for
2044 // them. But we shouldn't need to re-form LCSSA for any child loops.
2045 // FIXME: This could be made more efficient by tracking which exit blocks are
2046 // new, and focusing on them, but that isn't likely to be necessary.
2047 //
2048 // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2049 // loop nest and update every loop that could have had its exits changed. We
2050 // also need to cover any intervening loops. We add all of these loops to
2051 // a list and sort them by loop depth to achieve this without updating
2052 // unnecessary loops.
Chandler Carruth92815032018-06-02 01:29:01 +00002053 auto UpdateLoop = [&](Loop &UpdateL) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002054#ifndef NDEBUG
Chandler Carruth43acdb32018-04-24 10:33:08 +00002055 UpdateL.verifyLoop();
2056 for (Loop *ChildL : UpdateL) {
2057 ChildL->verifyLoop();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002058 assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2059 "Perturbed a child loop's LCSSA form!");
Chandler Carruth43acdb32018-04-24 10:33:08 +00002060 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002061#endif
Chandler Carruth92815032018-06-02 01:29:01 +00002062 // First build LCSSA for this loop so that we can preserve it when
2063 // forming dedicated exits. We don't want to perturb some other loop's
2064 // LCSSA while doing that CFG edit.
Chandler Carruth693eedb2017-11-17 19:58:36 +00002065 formLCSSA(UpdateL, DT, &LI, nullptr);
Chandler Carruth92815032018-06-02 01:29:01 +00002066
2067 // For loops reached by this loop's original exit blocks we may
2068 // introduced new, non-dedicated exits. At least try to re-form dedicated
2069 // exits for these loops. This may fail if they couldn't have dedicated
2070 // exits to start with.
2071 formDedicatedExitBlocks(&UpdateL, &DT, &LI, /*PreserveLCSSA*/ true);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002072 };
2073
2074 // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2075 // and we can do it in any order as they don't nest relative to each other.
Chandler Carruth92815032018-06-02 01:29:01 +00002076 //
2077 // Also check if any of the loops we have updated have become top-level loops
2078 // as that will necessitate widening the outer loop scope.
2079 for (Loop *UpdatedL :
2080 llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2081 UpdateLoop(*UpdatedL);
2082 if (!UpdatedL->getParentLoop())
2083 OuterExitL = nullptr;
2084 }
2085 if (IsStillLoop) {
2086 UpdateLoop(L);
2087 if (!L.getParentLoop())
2088 OuterExitL = nullptr;
2089 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002090
2091 // If the original loop had exit blocks, walk up through the outer most loop
2092 // of those exit blocks to update LCSSA and form updated dedicated exits.
Chandler Carruth92815032018-06-02 01:29:01 +00002093 if (OuterExitL != &L)
Chandler Carruth693eedb2017-11-17 19:58:36 +00002094 for (Loop *OuterL = ParentL; OuterL != OuterExitL;
2095 OuterL = OuterL->getParentLoop())
Chandler Carruth92815032018-06-02 01:29:01 +00002096 UpdateLoop(*OuterL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002097
2098#ifndef NDEBUG
2099 // Verify the entire loop structure to catch any incorrect updates before we
2100 // progress in the pass pipeline.
2101 LI.verify(DT);
2102#endif
2103
2104 // Now that we've unswitched something, make callbacks to report the changes.
2105 // For that we need to merge together the updated loops and the cloned loops
2106 // and check whether the original loop survived.
2107 SmallVector<Loop *, 4> SibLoops;
2108 for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2109 if (UpdatedL->getParentLoop() == ParentL)
2110 SibLoops.push_back(UpdatedL);
Chandler Carruth71fd2702018-05-30 02:46:45 +00002111 UnswitchCB(IsStillLoop, SibLoops);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002112
2113 ++NumBranches;
2114 return true;
2115}
2116
2117/// Recursively compute the cost of a dominator subtree based on the per-block
2118/// cost map provided.
2119///
2120/// The recursive computation is memozied into the provided DT-indexed cost map
2121/// to allow querying it for most nodes in the domtree without it becoming
2122/// quadratic.
2123static int
2124computeDomSubtreeCost(DomTreeNode &N,
2125 const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
2126 SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
2127 // Don't accumulate cost (or recurse through) blocks not in our block cost
2128 // map and thus not part of the duplication cost being considered.
2129 auto BBCostIt = BBCostMap.find(N.getBlock());
2130 if (BBCostIt == BBCostMap.end())
2131 return 0;
2132
2133 // Lookup this node to see if we already computed its cost.
2134 auto DTCostIt = DTCostMap.find(&N);
2135 if (DTCostIt != DTCostMap.end())
2136 return DTCostIt->second;
2137
2138 // If not, we have to compute it. We can't use insert above and update
2139 // because computing the cost may insert more things into the map.
2140 int Cost = std::accumulate(
2141 N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
2142 return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2143 });
2144 bool Inserted = DTCostMap.insert({&N, Cost}).second;
2145 (void)Inserted;
2146 assert(Inserted && "Should not insert a node while visiting children!");
2147 return Cost;
2148}
2149
Chandler Carruth3897ded2018-07-03 09:13:27 +00002150static bool
2151unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
2152 AssumptionCache &AC, TargetTransformInfo &TTI,
2153 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2154 ScalarEvolution *SE) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002155 // Collect all invariant conditions within this loop (as opposed to an inner
2156 // loop which would be handled when visiting that inner loop).
2157 SmallVector<std::pair<TerminatorInst *, TinyPtrVector<Value *>>, 4>
2158 UnswitchCandidates;
2159 for (auto *BB : L.blocks()) {
2160 if (LI.getLoopFor(BB) != &L)
2161 continue;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002162
Chandler Carruth16529962018-06-25 23:32:54 +00002163 if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2164 // We can only consider fully loop-invariant switch conditions as we need
2165 // to completely eliminate the switch after unswitching.
2166 if (!isa<Constant>(SI->getCondition()) &&
2167 L.isLoopInvariant(SI->getCondition()))
2168 UnswitchCandidates.push_back({SI, {SI->getCondition()}});
2169 continue;
2170 }
2171
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002172 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002173 if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2174 BI->getSuccessor(0) == BI->getSuccessor(1))
2175 continue;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002176
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002177 if (L.isLoopInvariant(BI->getCondition())) {
2178 UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2179 continue;
2180 }
2181
2182 Instruction &CondI = *cast<Instruction>(BI->getCondition());
2183 if (CondI.getOpcode() != Instruction::And &&
2184 CondI.getOpcode() != Instruction::Or)
2185 continue;
2186
2187 TinyPtrVector<Value *> Invariants =
2188 collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2189 if (Invariants.empty())
2190 continue;
2191
2192 UnswitchCandidates.push_back({BI, std::move(Invariants)});
Chandler Carruth71fd2702018-05-30 02:46:45 +00002193 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002194
Chandler Carruth693eedb2017-11-17 19:58:36 +00002195 // If we didn't find any candidates, we're done.
2196 if (UnswitchCandidates.empty())
Chandler Carruth71fd2702018-05-30 02:46:45 +00002197 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002198
Chandler Carruth32e62f92018-04-19 18:44:25 +00002199 // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2200 // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2201 // irreducible control flow into reducible control flow and introduce new
2202 // loops "out of thin air". If we ever discover important use cases for doing
2203 // this, we can add support to loop unswitch, but it is a lot of complexity
Hiroshi Inouef2096492018-06-14 05:41:49 +00002204 // for what seems little or no real world benefit.
Chandler Carruth32e62f92018-04-19 18:44:25 +00002205 LoopBlocksRPO RPOT(&L);
2206 RPOT.perform(&LI);
2207 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
Chandler Carruth71fd2702018-05-30 02:46:45 +00002208 return false;
Chandler Carruth32e62f92018-04-19 18:44:25 +00002209
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002210 LLVM_DEBUG(
2211 dbgs() << "Considering " << UnswitchCandidates.size()
2212 << " non-trivial loop invariant conditions for unswitching.\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002213
2214 // Given that unswitching these terminators will require duplicating parts of
2215 // the loop, so we need to be able to model that cost. Compute the ephemeral
2216 // values and set up a data structure to hold per-BB costs. We cache each
2217 // block's cost so that we don't recompute this when considering different
2218 // subsets of the loop for duplication during unswitching.
2219 SmallPtrSet<const Value *, 4> EphValues;
2220 CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2221 SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
2222
2223 // Compute the cost of each block, as well as the total loop cost. Also, bail
2224 // out if we see instructions which are incompatible with loop unswitching
2225 // (convergent, noduplicate, or cross-basic-block tokens).
2226 // FIXME: We might be able to safely handle some of these in non-duplicated
2227 // regions.
2228 int LoopCost = 0;
2229 for (auto *BB : L.blocks()) {
2230 int Cost = 0;
2231 for (auto &I : *BB) {
2232 if (EphValues.count(&I))
2233 continue;
2234
2235 if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
Chandler Carruth71fd2702018-05-30 02:46:45 +00002236 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002237 if (auto CS = CallSite(&I))
2238 if (CS.isConvergent() || CS.cannotDuplicate())
Chandler Carruth71fd2702018-05-30 02:46:45 +00002239 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002240
2241 Cost += TTI.getUserCost(&I);
2242 }
2243 assert(Cost >= 0 && "Must not have negative costs!");
2244 LoopCost += Cost;
2245 assert(LoopCost >= 0 && "Must not have negative loop costs!");
2246 BBCostMap[BB] = Cost;
2247 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002248 LLVM_DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002249
2250 // Now we find the best candidate by searching for the one with the following
2251 // properties in order:
2252 //
2253 // 1) An unswitching cost below the threshold
2254 // 2) The smallest number of duplicated unswitch candidates (to avoid
2255 // creating redundant subsequent unswitching)
2256 // 3) The smallest cost after unswitching.
2257 //
2258 // We prioritize reducing fanout of unswitch candidates provided the cost
2259 // remains below the threshold because this has a multiplicative effect.
2260 //
2261 // This requires memoizing each dominator subtree to avoid redundant work.
2262 //
2263 // FIXME: Need to actually do the number of candidates part above.
2264 SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
2265 // Given a terminator which might be unswitched, computes the non-duplicated
2266 // cost for that terminator.
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002267 auto ComputeUnswitchedCost = [&](TerminatorInst &TI, bool FullUnswitch) {
2268 BasicBlock &BB = *TI.getParent();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002269 SmallPtrSet<BasicBlock *, 4> Visited;
2270
2271 int Cost = LoopCost;
2272 for (BasicBlock *SuccBB : successors(&BB)) {
2273 // Don't count successors more than once.
2274 if (!Visited.insert(SuccBB).second)
2275 continue;
2276
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002277 // If this is a partial unswitch candidate, then it must be a conditional
2278 // branch with a condition of either `or` or `and`. In that case, one of
2279 // the successors is necessarily duplicated, so don't even try to remove
2280 // its cost.
2281 if (!FullUnswitch) {
2282 auto &BI = cast<BranchInst>(TI);
2283 if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2284 Instruction::And) {
2285 if (SuccBB == BI.getSuccessor(1))
2286 continue;
2287 } else {
2288 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2289 Instruction::Or &&
2290 "Only `and` and `or` conditions can result in a partial "
2291 "unswitch!");
2292 if (SuccBB == BI.getSuccessor(0))
2293 continue;
2294 }
2295 }
2296
Chandler Carruth693eedb2017-11-17 19:58:36 +00002297 // This successor's domtree will not need to be duplicated after
2298 // unswitching if the edge to the successor dominates it (and thus the
2299 // entire tree). This essentially means there is no other path into this
2300 // subtree and so it will end up live in only one clone of the loop.
2301 if (SuccBB->getUniquePredecessor() ||
2302 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2303 return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2304 })) {
2305 Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2306 assert(Cost >= 0 &&
2307 "Non-duplicated cost should never exceed total loop cost!");
2308 }
2309 }
2310
2311 // Now scale the cost by the number of unique successors minus one. We
2312 // subtract one because there is already at least one copy of the entire
2313 // loop. This is computing the new cost of unswitching a condition.
2314 assert(Visited.size() > 1 &&
2315 "Cannot unswitch a condition without multiple distinct successors!");
2316 return Cost * (Visited.size() - 1);
2317 };
2318 TerminatorInst *BestUnswitchTI = nullptr;
2319 int BestUnswitchCost;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002320 ArrayRef<Value *> BestUnswitchInvariants;
2321 for (auto &TerminatorAndInvariants : UnswitchCandidates) {
2322 TerminatorInst &TI = *TerminatorAndInvariants.first;
2323 ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2324 BranchInst *BI = dyn_cast<BranchInst>(&TI);
Chandler Carruth16529962018-06-25 23:32:54 +00002325 int CandidateCost = ComputeUnswitchedCost(
2326 TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
2327 Invariants[0] == BI->getCondition()));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002328 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002329 << " for unswitch candidate: " << TI << "\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002330 if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002331 BestUnswitchTI = &TI;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002332 BestUnswitchCost = CandidateCost;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002333 BestUnswitchInvariants = Invariants;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002334 }
2335 }
2336
Chandler Carruth71fd2702018-05-30 02:46:45 +00002337 if (BestUnswitchCost >= UnswitchThreshold) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002338 LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
2339 << BestUnswitchCost << "\n");
Chandler Carruth71fd2702018-05-30 02:46:45 +00002340 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002341 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002342
Chandler Carruth71fd2702018-05-30 02:46:45 +00002343 LLVM_DEBUG(dbgs() << " Trying to unswitch non-trivial (cost = "
Chandler Carruth16529962018-06-25 23:32:54 +00002344 << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
2345 << "\n");
2346 return unswitchNontrivialInvariants(
Chandler Carruth3897ded2018-07-03 09:13:27 +00002347 L, *BestUnswitchTI, BestUnswitchInvariants, DT, LI, AC, UnswitchCB, SE);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002348}
2349
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002350/// Unswitch control flow predicated on loop invariant conditions.
2351///
2352/// This first hoists all branches or switches which are trivial (IE, do not
2353/// require duplicating any part of the loop) out of the loop body. It then
2354/// looks at other loop invariant control flows and tries to unswitch those as
2355/// well by cloning the loop if the result is small enough.
Chandler Carruth3897ded2018-07-03 09:13:27 +00002356///
2357/// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
2358/// updated based on the unswitch.
2359///
2360/// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
2361/// true, we will attempt to do non-trivial unswitching as well as trivial
2362/// unswitching.
2363///
2364/// The `UnswitchCB` callback provided will be run after unswitching is
2365/// complete, with the first parameter set to `true` if the provided loop
2366/// remains a loop, and a list of new sibling loops created.
2367///
2368/// If `SE` is non-null, we will update that analysis based on the unswitching
2369/// done.
2370static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
2371 AssumptionCache &AC, TargetTransformInfo &TTI,
2372 bool NonTrivial,
2373 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2374 ScalarEvolution *SE) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002375 assert(L.isRecursivelyLCSSAForm(DT, LI) &&
2376 "Loops must be in LCSSA form before unswitching.");
2377 bool Changed = false;
2378
2379 // Must be in loop simplified form: we need a preheader and dedicated exits.
2380 if (!L.isLoopSimplifyForm())
2381 return false;
2382
2383 // Try trivial unswitch first before loop over other basic blocks in the loop.
Chandler Carruth3897ded2018-07-03 09:13:27 +00002384 if (unswitchAllTrivialConditions(L, DT, LI, SE)) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002385 // If we unswitched successfully we will want to clean up the loop before
2386 // processing it further so just mark it as unswitched and return.
2387 UnswitchCB(/*CurrentLoopValid*/ true, {});
2388 return true;
2389 }
2390
2391 // If we're not doing non-trivial unswitching, we're done. We both accept
2392 // a parameter but also check a local flag that can be used for testing
2393 // a debugging.
2394 if (!NonTrivial && !EnableNonTrivialUnswitch)
2395 return false;
2396
2397 // For non-trivial unswitching, because it often creates new loops, we rely on
2398 // the pass manager to iterate on the loops rather than trying to immediately
2399 // reach a fixed point. There is no substantial advantage to iterating
2400 // internally, and if any of the new loops are simplified enough to contain
2401 // trivial unswitching we want to prefer those.
2402
2403 // Try to unswitch the best invariant condition. We prefer this full unswitch to
2404 // a partial unswitch when possible below the threshold.
Chandler Carruth3897ded2018-07-03 09:13:27 +00002405 if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE))
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002406 return true;
2407
2408 // No other opportunities to unswitch.
2409 return Changed;
2410}
2411
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002412PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
2413 LoopStandardAnalysisResults &AR,
2414 LPMUpdater &U) {
2415 Function &F = *L.getHeader()->getParent();
2416 (void)F;
2417
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002418 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
2419 << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002420
Chandler Carruth693eedb2017-11-17 19:58:36 +00002421 // Save the current loop name in a variable so that we can report it even
2422 // after it has been deleted.
2423 std::string LoopName = L.getName();
2424
Chandler Carruth71fd2702018-05-30 02:46:45 +00002425 auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2426 ArrayRef<Loop *> NewLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002427 // If we did a non-trivial unswitch, we have added new (cloned) loops.
Chandler Carruth71fd2702018-05-30 02:46:45 +00002428 if (!NewLoops.empty())
2429 U.addSiblingLoops(NewLoops);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002430
2431 // If the current loop remains valid, we should revisit it to catch any
2432 // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2433 if (CurrentLoopValid)
2434 U.revisitCurrentLoop();
2435 else
2436 U.markLoopAsDeleted(L, LoopName);
2437 };
2438
Chandler Carruth3897ded2018-07-03 09:13:27 +00002439 if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB,
2440 &AR.SE))
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002441 return PreservedAnalyses::all();
2442
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002443 // Historically this pass has had issues with the dominator tree so verify it
2444 // in asserts builds.
David Green7c35de12018-02-28 11:00:08 +00002445 assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002446 return getLoopPassPreservedAnalyses();
2447}
2448
2449namespace {
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002450
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002451class SimpleLoopUnswitchLegacyPass : public LoopPass {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002452 bool NonTrivial;
2453
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002454public:
2455 static char ID; // Pass ID, replacement for typeid
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002456
Chandler Carruth693eedb2017-11-17 19:58:36 +00002457 explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2458 : LoopPass(ID), NonTrivial(NonTrivial) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002459 initializeSimpleLoopUnswitchLegacyPassPass(
2460 *PassRegistry::getPassRegistry());
2461 }
2462
2463 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
2464
2465 void getAnalysisUsage(AnalysisUsage &AU) const override {
2466 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002467 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002468 getLoopAnalysisUsage(AU);
2469 }
2470};
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002471
2472} // end anonymous namespace
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002473
2474bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
2475 if (skipLoop(L))
2476 return false;
2477
2478 Function &F = *L->getHeader()->getParent();
2479
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002480 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
2481 << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002482
2483 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2484 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2485 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002486 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002487
Chandler Carruth3897ded2018-07-03 09:13:27 +00002488 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
2489 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
2490
Chandler Carruth71fd2702018-05-30 02:46:45 +00002491 auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2492 ArrayRef<Loop *> NewLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002493 // If we did a non-trivial unswitch, we have added new (cloned) loops.
2494 for (auto *NewL : NewLoops)
2495 LPM.addLoop(*NewL);
2496
2497 // If the current loop remains valid, re-add it to the queue. This is
2498 // a little wasteful as we'll finish processing the current loop as well,
2499 // but it is the best we can do in the old PM.
2500 if (CurrentLoopValid)
2501 LPM.addLoop(*L);
2502 else
2503 LPM.markLoopAsDeleted(*L);
2504 };
2505
Chandler Carruth3897ded2018-07-03 09:13:27 +00002506 bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002507
2508 // If anything was unswitched, also clear any cached information about this
2509 // loop.
2510 LPM.deleteSimpleAnalysisLoop(L);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002511
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002512 // Historically this pass has had issues with the dominator tree so verify it
2513 // in asserts builds.
David Green7c35de12018-02-28 11:00:08 +00002514 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2515
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002516 return Changed;
2517}
2518
2519char SimpleLoopUnswitchLegacyPass::ID = 0;
2520INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2521 "Simple unswitch loops", false, false)
2522INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth693eedb2017-11-17 19:58:36 +00002523INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2524INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002525INITIALIZE_PASS_DEPENDENCY(LoopPass)
2526INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2527INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2528 "Simple unswitch loops", false, false)
2529
Chandler Carruth693eedb2017-11-17 19:58:36 +00002530Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
2531 return new SimpleLoopUnswitchLegacyPass(NonTrivial);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002532}