blob: 9c9ed2a02e35229b9d1bca3ff4a52bd56f00e87d [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
952 // Remove the cloned parent as a predecessor of the cloned continue successor
953 // if we did in fact clone it.
954 auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
955 if (auto *ClonedContinueSuccBB =
956 cast_or_null<BasicBlock>(VMap.lookup(ContinueSuccBB)))
957 ClonedContinueSuccBB->removePredecessor(ClonedParentBB,
958 /*DontDeleteUselessPHIs*/ true);
Chandler Carruthb5254242018-04-23 00:48:42 +0000959 // Replace the cloned branch with an unconditional branch to the cloned
Chandler Carruth693eedb2017-11-17 19:58:36 +0000960 // unswitched successor.
961 auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
962 ClonedParentBB->getTerminator()->eraseFromParent();
963 BranchInst::Create(ClonedSuccBB, ClonedParentBB);
964
965 // Update any PHI nodes in the cloned successors of the skipped blocks to not
966 // have spurious incoming values.
967 for (auto *LoopBB : L.blocks())
Chandler Carruth16529962018-06-25 23:32:54 +0000968 if (SkipBlock(LoopBB))
Chandler Carruth693eedb2017-11-17 19:58:36 +0000969 for (auto *SuccBB : successors(LoopBB))
970 if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
971 for (PHINode &PN : ClonedSuccBB->phis())
972 PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
973
Chandler Carruth69e68f82018-04-25 00:18:07 +0000974 // Record the domtree updates for the new blocks.
Chandler Carruth44aab922018-05-01 09:42:09 +0000975 SmallPtrSet<BasicBlock *, 4> SuccSet;
976 for (auto *ClonedBB : NewBlocks) {
Chandler Carruth69e68f82018-04-25 00:18:07 +0000977 for (auto *SuccBB : successors(ClonedBB))
Chandler Carruth44aab922018-05-01 09:42:09 +0000978 if (SuccSet.insert(SuccBB).second)
979 DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
980 SuccSet.clear();
981 }
Chandler Carruth69e68f82018-04-25 00:18:07 +0000982
Chandler Carruth693eedb2017-11-17 19:58:36 +0000983 return ClonedPH;
984}
985
986/// Recursively clone the specified loop and all of its children.
987///
988/// The target parent loop for the clone should be provided, or can be null if
989/// the clone is a top-level loop. While cloning, all the blocks are mapped
990/// with the provided value map. The entire original loop must be present in
991/// the value map. The cloned loop is returned.
992static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
993 const ValueToValueMapTy &VMap, LoopInfo &LI) {
994 auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
995 assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
996 ClonedL.reserveBlocks(OrigL.getNumBlocks());
997 for (auto *BB : OrigL.blocks()) {
998 auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
999 ClonedL.addBlockEntry(ClonedBB);
Chandler Carruth0ace1482018-04-24 03:27:00 +00001000 if (LI.getLoopFor(BB) == &OrigL)
Chandler Carruth693eedb2017-11-17 19:58:36 +00001001 LI.changeLoopFor(ClonedBB, &ClonedL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001002 }
1003 };
1004
1005 // We specially handle the first loop because it may get cloned into
1006 // a different parent and because we most commonly are cloning leaf loops.
1007 Loop *ClonedRootL = LI.AllocateLoop();
1008 if (RootParentL)
1009 RootParentL->addChildLoop(ClonedRootL);
1010 else
1011 LI.addTopLevelLoop(ClonedRootL);
1012 AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1013
1014 if (OrigRootL.empty())
1015 return ClonedRootL;
1016
1017 // If we have a nest, we can quickly clone the entire loop nest using an
1018 // iterative approach because it is a tree. We keep the cloned parent in the
1019 // data structure to avoid repeatedly querying through a map to find it.
1020 SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1021 // Build up the loops to clone in reverse order as we'll clone them from the
1022 // back.
1023 for (Loop *ChildL : llvm::reverse(OrigRootL))
1024 LoopsToClone.push_back({ClonedRootL, ChildL});
1025 do {
1026 Loop *ClonedParentL, *L;
1027 std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1028 Loop *ClonedL = LI.AllocateLoop();
1029 ClonedParentL->addChildLoop(ClonedL);
1030 AddClonedBlocksToLoop(*L, *ClonedL);
1031 for (Loop *ChildL : llvm::reverse(*L))
1032 LoopsToClone.push_back({ClonedL, ChildL});
1033 } while (!LoopsToClone.empty());
1034
1035 return ClonedRootL;
1036}
1037
1038/// Build the cloned loops of an original loop from unswitching.
1039///
1040/// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1041/// operation. We need to re-verify that there even is a loop (as the backedge
1042/// may not have been cloned), and even if there are remaining backedges the
1043/// backedge set may be different. However, we know that each child loop is
1044/// undisturbed, we only need to find where to place each child loop within
1045/// either any parent loop or within a cloned version of the original loop.
1046///
1047/// Because child loops may end up cloned outside of any cloned version of the
1048/// original loop, multiple cloned sibling loops may be created. All of them
1049/// are returned so that the newly introduced loop nest roots can be
1050/// identified.
Chandler Carruth92815032018-06-02 01:29:01 +00001051static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1052 const ValueToValueMapTy &VMap, LoopInfo &LI,
1053 SmallVectorImpl<Loop *> &NonChildClonedLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00001054 Loop *ClonedL = nullptr;
1055
1056 auto *OrigPH = OrigL.getLoopPreheader();
1057 auto *OrigHeader = OrigL.getHeader();
1058
1059 auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1060 auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1061
1062 // We need to know the loops of the cloned exit blocks to even compute the
1063 // accurate parent loop. If we only clone exits to some parent of the
1064 // original parent, we want to clone into that outer loop. We also keep track
1065 // of the loops that our cloned exit blocks participate in.
1066 Loop *ParentL = nullptr;
1067 SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1068 SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1069 ClonedExitsInLoops.reserve(ExitBlocks.size());
1070 for (auto *ExitBB : ExitBlocks)
1071 if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1072 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1073 ExitLoopMap[ClonedExitBB] = ExitL;
1074 ClonedExitsInLoops.push_back(ClonedExitBB);
1075 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1076 ParentL = ExitL;
1077 }
1078 assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1079 ParentL->contains(OrigL.getParentLoop())) &&
1080 "The computed parent loop should always contain (or be) the parent of "
1081 "the original loop.");
1082
1083 // We build the set of blocks dominated by the cloned header from the set of
1084 // cloned blocks out of the original loop. While not all of these will
1085 // necessarily be in the cloned loop, it is enough to establish that they
1086 // aren't in unreachable cycles, etc.
1087 SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1088 for (auto *BB : OrigL.blocks())
1089 if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1090 ClonedLoopBlocks.insert(ClonedBB);
1091
1092 // Rebuild the set of blocks that will end up in the cloned loop. We may have
1093 // skipped cloning some region of this loop which can in turn skip some of
1094 // the backedges so we have to rebuild the blocks in the loop based on the
1095 // backedges that remain after cloning.
1096 SmallVector<BasicBlock *, 16> Worklist;
1097 SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1098 for (auto *Pred : predecessors(ClonedHeader)) {
1099 // The only possible non-loop header predecessor is the preheader because
1100 // we know we cloned the loop in simplified form.
1101 if (Pred == ClonedPH)
1102 continue;
1103
1104 // Because the loop was in simplified form, the only non-loop predecessor
1105 // should be the preheader.
1106 assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1107 "header other than the preheader "
1108 "that is not part of the loop!");
1109
1110 // Insert this block into the loop set and on the first visit (and if it
1111 // isn't the header we're currently walking) put it into the worklist to
1112 // recurse through.
1113 if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1114 Worklist.push_back(Pred);
1115 }
1116
1117 // If we had any backedges then there *is* a cloned loop. Put the header into
1118 // the loop set and then walk the worklist backwards to find all the blocks
1119 // that remain within the loop after cloning.
1120 if (!BlocksInClonedLoop.empty()) {
1121 BlocksInClonedLoop.insert(ClonedHeader);
1122
1123 while (!Worklist.empty()) {
1124 BasicBlock *BB = Worklist.pop_back_val();
1125 assert(BlocksInClonedLoop.count(BB) &&
1126 "Didn't put block into the loop set!");
1127
1128 // Insert any predecessors that are in the possible set into the cloned
1129 // set, and if the insert is successful, add them to the worklist. Note
1130 // that we filter on the blocks that are definitely reachable via the
1131 // backedge to the loop header so we may prune out dead code within the
1132 // cloned loop.
1133 for (auto *Pred : predecessors(BB))
1134 if (ClonedLoopBlocks.count(Pred) &&
1135 BlocksInClonedLoop.insert(Pred).second)
1136 Worklist.push_back(Pred);
1137 }
1138
1139 ClonedL = LI.AllocateLoop();
1140 if (ParentL) {
1141 ParentL->addBasicBlockToLoop(ClonedPH, LI);
1142 ParentL->addChildLoop(ClonedL);
1143 } else {
1144 LI.addTopLevelLoop(ClonedL);
1145 }
Chandler Carruth92815032018-06-02 01:29:01 +00001146 NonChildClonedLoops.push_back(ClonedL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001147
1148 ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1149 // We don't want to just add the cloned loop blocks based on how we
1150 // discovered them. The original order of blocks was carefully built in
1151 // a way that doesn't rely on predecessor ordering. Rather than re-invent
1152 // that logic, we just re-walk the original blocks (and those of the child
1153 // loops) and filter them as we add them into the cloned loop.
1154 for (auto *BB : OrigL.blocks()) {
1155 auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1156 if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1157 continue;
1158
1159 // Directly add the blocks that are only in this loop.
1160 if (LI.getLoopFor(BB) == &OrigL) {
1161 ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1162 continue;
1163 }
1164
1165 // We want to manually add it to this loop and parents.
1166 // Registering it with LoopInfo will happen when we clone the top
1167 // loop for this block.
1168 for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1169 PL->addBlockEntry(ClonedBB);
1170 }
1171
1172 // Now add each child loop whose header remains within the cloned loop. All
1173 // of the blocks within the loop must satisfy the same constraints as the
1174 // header so once we pass the header checks we can just clone the entire
1175 // child loop nest.
1176 for (Loop *ChildL : OrigL) {
1177 auto *ClonedChildHeader =
1178 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1179 if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1180 continue;
1181
1182#ifndef NDEBUG
1183 // We should never have a cloned child loop header but fail to have
1184 // all of the blocks for that child loop.
1185 for (auto *ChildLoopBB : ChildL->blocks())
1186 assert(BlocksInClonedLoop.count(
1187 cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1188 "Child cloned loop has a header within the cloned outer "
1189 "loop but not all of its blocks!");
1190#endif
1191
1192 cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1193 }
1194 }
1195
1196 // Now that we've handled all the components of the original loop that were
1197 // cloned into a new loop, we still need to handle anything from the original
1198 // loop that wasn't in a cloned loop.
1199
1200 // Figure out what blocks are left to place within any loop nest containing
1201 // the unswitched loop. If we never formed a loop, the cloned PH is one of
1202 // them.
1203 SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1204 if (BlocksInClonedLoop.empty())
1205 UnloopedBlockSet.insert(ClonedPH);
1206 for (auto *ClonedBB : ClonedLoopBlocks)
1207 if (!BlocksInClonedLoop.count(ClonedBB))
1208 UnloopedBlockSet.insert(ClonedBB);
1209
1210 // Copy the cloned exits and sort them in ascending loop depth, we'll work
1211 // backwards across these to process them inside out. The order shouldn't
1212 // matter as we're just trying to build up the map from inside-out; we use
1213 // the map in a more stably ordered way below.
1214 auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
Chandler Carruth4da33312018-06-20 18:57:07 +00001215 llvm::sort(OrderedClonedExitsInLoops.begin(), OrderedClonedExitsInLoops.end(),
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +00001216 [&](BasicBlock *LHS, BasicBlock *RHS) {
1217 return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1218 ExitLoopMap.lookup(RHS)->getLoopDepth();
1219 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001220
1221 // Populate the existing ExitLoopMap with everything reachable from each
1222 // exit, starting from the inner most exit.
1223 while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1224 assert(Worklist.empty() && "Didn't clear worklist!");
1225
1226 BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1227 Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1228
1229 // Walk the CFG back until we hit the cloned PH adding everything reachable
1230 // and in the unlooped set to this exit block's loop.
1231 Worklist.push_back(ExitBB);
1232 do {
1233 BasicBlock *BB = Worklist.pop_back_val();
1234 // We can stop recursing at the cloned preheader (if we get there).
1235 if (BB == ClonedPH)
1236 continue;
1237
1238 for (BasicBlock *PredBB : predecessors(BB)) {
1239 // If this pred has already been moved to our set or is part of some
1240 // (inner) loop, no update needed.
1241 if (!UnloopedBlockSet.erase(PredBB)) {
1242 assert(
1243 (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1244 "Predecessor not mapped to a loop!");
1245 continue;
1246 }
1247
1248 // We just insert into the loop set here. We'll add these blocks to the
1249 // exit loop after we build up the set in an order that doesn't rely on
1250 // predecessor order (which in turn relies on use list order).
1251 bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1252 (void)Inserted;
1253 assert(Inserted && "Should only visit an unlooped block once!");
1254
1255 // And recurse through to its predecessors.
1256 Worklist.push_back(PredBB);
1257 }
1258 } while (!Worklist.empty());
1259 }
1260
1261 // Now that the ExitLoopMap gives as mapping for all the non-looping cloned
1262 // blocks to their outer loops, walk the cloned blocks and the cloned exits
1263 // in their original order adding them to the correct loop.
1264
1265 // We need a stable insertion order. We use the order of the original loop
1266 // order and map into the correct parent loop.
1267 for (auto *BB : llvm::concat<BasicBlock *const>(
1268 makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1269 if (Loop *OuterL = ExitLoopMap.lookup(BB))
1270 OuterL->addBasicBlockToLoop(BB, LI);
1271
1272#ifndef NDEBUG
1273 for (auto &BBAndL : ExitLoopMap) {
1274 auto *BB = BBAndL.first;
1275 auto *OuterL = BBAndL.second;
1276 assert(LI.getLoopFor(BB) == OuterL &&
1277 "Failed to put all blocks into outer loops!");
1278 }
1279#endif
1280
1281 // Now that all the blocks are placed into the correct containing loop in the
1282 // absence of child loops, find all the potentially cloned child loops and
1283 // clone them into whatever outer loop we placed their header into.
1284 for (Loop *ChildL : OrigL) {
1285 auto *ClonedChildHeader =
1286 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1287 if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1288 continue;
1289
1290#ifndef NDEBUG
1291 for (auto *ChildLoopBB : ChildL->blocks())
1292 assert(VMap.count(ChildLoopBB) &&
1293 "Cloned a child loop header but not all of that loops blocks!");
1294#endif
1295
1296 NonChildClonedLoops.push_back(cloneLoopNest(
1297 *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1298 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001299}
1300
Chandler Carruth69e68f82018-04-25 00:18:07 +00001301static void
Chandler Carruth16529962018-06-25 23:32:54 +00001302deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1303 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
1304 DominatorTree &DT) {
1305 // Find all the dead clones, and remove them from their successors.
1306 SmallVector<BasicBlock *, 16> DeadBlocks;
1307 for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1308 for (auto &VMap : VMaps)
1309 if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
1310 if (!DT.isReachableFromEntry(ClonedBB)) {
1311 for (BasicBlock *SuccBB : successors(ClonedBB))
1312 SuccBB->removePredecessor(ClonedBB);
1313 DeadBlocks.push_back(ClonedBB);
1314 }
1315
1316 // Drop any remaining references to break cycles.
1317 for (BasicBlock *BB : DeadBlocks)
1318 BB->dropAllReferences();
1319 // Erase them from the IR.
1320 for (BasicBlock *BB : DeadBlocks)
1321 BB->eraseFromParent();
1322}
1323
1324static void
Chandler Carruth69e68f82018-04-25 00:18:07 +00001325deleteDeadBlocksFromLoop(Loop &L,
Chandler Carruth69e68f82018-04-25 00:18:07 +00001326 SmallVectorImpl<BasicBlock *> &ExitBlocks,
1327 DominatorTree &DT, LoopInfo &LI) {
Chandler Carruth16529962018-06-25 23:32:54 +00001328 // Find all the dead blocks, and remove them from their successors.
1329 SmallVector<BasicBlock *, 16> DeadBlocks;
1330 for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1331 if (!DT.isReachableFromEntry(BB)) {
1332 for (BasicBlock *SuccBB : successors(BB))
1333 SuccBB->removePredecessor(BB);
1334 DeadBlocks.push_back(BB);
1335 }
1336
Chandler Carruth69e68f82018-04-25 00:18:07 +00001337 SmallPtrSet<BasicBlock *, 16> DeadBlockSet(DeadBlocks.begin(),
1338 DeadBlocks.end());
Chandler Carruth693eedb2017-11-17 19:58:36 +00001339
1340 // Filter out the dead blocks from the exit blocks list so that it can be
1341 // used in the caller.
1342 llvm::erase_if(ExitBlocks,
Chandler Carruth69e68f82018-04-25 00:18:07 +00001343 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001344
Chandler Carruth693eedb2017-11-17 19:58:36 +00001345 // Walk from this loop up through its parents removing all of the dead blocks.
1346 for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
1347 for (auto *BB : DeadBlocks)
1348 ParentL->getBlocksSet().erase(BB);
1349 llvm::erase_if(ParentL->getBlocksVector(),
Chandler Carruth69e68f82018-04-25 00:18:07 +00001350 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001351 }
1352
1353 // Now delete the dead child loops. This raw delete will clear them
1354 // recursively.
1355 llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001356 if (!DeadBlockSet.count(ChildL->getHeader()))
Chandler Carruth693eedb2017-11-17 19:58:36 +00001357 return false;
1358
1359 assert(llvm::all_of(ChildL->blocks(),
1360 [&](BasicBlock *ChildBB) {
Chandler Carruth69e68f82018-04-25 00:18:07 +00001361 return DeadBlockSet.count(ChildBB);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001362 }) &&
1363 "If the child loop header is dead all blocks in the child loop must "
1364 "be dead as well!");
1365 LI.destroy(ChildL);
1366 return true;
1367 });
1368
Chandler Carruth69e68f82018-04-25 00:18:07 +00001369 // Remove the loop mappings for the dead blocks and drop all the references
1370 // from these blocks to others to handle cyclic references as we start
1371 // deleting the blocks themselves.
1372 for (auto *BB : DeadBlocks) {
1373 // Check that the dominator tree has already been updated.
1374 assert(!DT.getNode(BB) && "Should already have cleared domtree!");
Chandler Carruth693eedb2017-11-17 19:58:36 +00001375 LI.changeLoopFor(BB, nullptr);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001376 BB->dropAllReferences();
Chandler Carruth693eedb2017-11-17 19:58:36 +00001377 }
Chandler Carruth69e68f82018-04-25 00:18:07 +00001378
1379 // Actually delete the blocks now that they've been fully unhooked from the
1380 // IR.
1381 for (auto *BB : DeadBlocks)
1382 BB->eraseFromParent();
Chandler Carruth693eedb2017-11-17 19:58:36 +00001383}
1384
1385/// Recompute the set of blocks in a loop after unswitching.
1386///
1387/// This walks from the original headers predecessors to rebuild the loop. We
1388/// take advantage of the fact that new blocks can't have been added, and so we
1389/// filter by the original loop's blocks. This also handles potentially
1390/// unreachable code that we don't want to explore but might be found examining
1391/// the predecessors of the header.
1392///
1393/// If the original loop is no longer a loop, this will return an empty set. If
1394/// it remains a loop, all the blocks within it will be added to the set
1395/// (including those blocks in inner loops).
1396static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1397 LoopInfo &LI) {
1398 SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1399
1400 auto *PH = L.getLoopPreheader();
1401 auto *Header = L.getHeader();
1402
1403 // A worklist to use while walking backwards from the header.
1404 SmallVector<BasicBlock *, 16> Worklist;
1405
1406 // First walk the predecessors of the header to find the backedges. This will
1407 // form the basis of our walk.
1408 for (auto *Pred : predecessors(Header)) {
1409 // Skip the preheader.
1410 if (Pred == PH)
1411 continue;
1412
1413 // Because the loop was in simplified form, the only non-loop predecessor
1414 // is the preheader.
1415 assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1416 "than the preheader that is not part of the "
1417 "loop!");
1418
1419 // Insert this block into the loop set and on the first visit and, if it
1420 // isn't the header we're currently walking, put it into the worklist to
1421 // recurse through.
1422 if (LoopBlockSet.insert(Pred).second && Pred != Header)
1423 Worklist.push_back(Pred);
1424 }
1425
1426 // If no backedges were found, we're done.
1427 if (LoopBlockSet.empty())
1428 return LoopBlockSet;
1429
Chandler Carruth693eedb2017-11-17 19:58:36 +00001430 // We found backedges, recurse through them to identify the loop blocks.
1431 while (!Worklist.empty()) {
1432 BasicBlock *BB = Worklist.pop_back_val();
1433 assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1434
Chandler Carruth43acdb32018-04-24 10:33:08 +00001435 // No need to walk past the header.
1436 if (BB == Header)
1437 continue;
1438
Chandler Carruth693eedb2017-11-17 19:58:36 +00001439 // Because we know the inner loop structure remains valid we can use the
1440 // loop structure to jump immediately across the entire nested loop.
1441 // Further, because it is in loop simplified form, we can directly jump
1442 // to its preheader afterward.
1443 if (Loop *InnerL = LI.getLoopFor(BB))
1444 if (InnerL != &L) {
1445 assert(L.contains(InnerL) &&
1446 "Should not reach a loop *outside* this loop!");
1447 // The preheader is the only possible predecessor of the loop so
1448 // insert it into the set and check whether it was already handled.
1449 auto *InnerPH = InnerL->getLoopPreheader();
1450 assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1451 "but not contain the inner loop "
1452 "preheader!");
1453 if (!LoopBlockSet.insert(InnerPH).second)
1454 // The only way to reach the preheader is through the loop body
1455 // itself so if it has been visited the loop is already handled.
1456 continue;
1457
1458 // Insert all of the blocks (other than those already present) into
Chandler Carruthbf7190a2018-04-23 06:58:36 +00001459 // the loop set. We expect at least the block that led us to find the
1460 // inner loop to be in the block set, but we may also have other loop
1461 // blocks if they were already enqueued as predecessors of some other
1462 // outer loop block.
Chandler Carruth693eedb2017-11-17 19:58:36 +00001463 for (auto *InnerBB : InnerL->blocks()) {
1464 if (InnerBB == BB) {
1465 assert(LoopBlockSet.count(InnerBB) &&
1466 "Block should already be in the set!");
1467 continue;
1468 }
1469
Chandler Carruthbf7190a2018-04-23 06:58:36 +00001470 LoopBlockSet.insert(InnerBB);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001471 }
1472
1473 // Add the preheader to the worklist so we will continue past the
1474 // loop body.
1475 Worklist.push_back(InnerPH);
1476 continue;
1477 }
1478
1479 // Insert any predecessors that were in the original loop into the new
1480 // set, and if the insert is successful, add them to the worklist.
1481 for (auto *Pred : predecessors(BB))
1482 if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1483 Worklist.push_back(Pred);
1484 }
1485
Chandler Carruth43acdb32018-04-24 10:33:08 +00001486 assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
1487
Chandler Carruth693eedb2017-11-17 19:58:36 +00001488 // We've found all the blocks participating in the loop, return our completed
1489 // set.
1490 return LoopBlockSet;
1491}
1492
1493/// Rebuild a loop after unswitching removes some subset of blocks and edges.
1494///
1495/// The removal may have removed some child loops entirely but cannot have
1496/// disturbed any remaining child loops. However, they may need to be hoisted
1497/// to the parent loop (or to be top-level loops). The original loop may be
1498/// completely removed.
1499///
1500/// The sibling loops resulting from this update are returned. If the original
1501/// loop remains a valid loop, it will be the first entry in this list with all
1502/// of the newly sibling loops following it.
1503///
1504/// Returns true if the loop remains a loop after unswitching, and false if it
1505/// is no longer a loop after unswitching (and should not continue to be
1506/// referenced).
1507static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1508 LoopInfo &LI,
1509 SmallVectorImpl<Loop *> &HoistedLoops) {
1510 auto *PH = L.getLoopPreheader();
1511
1512 // Compute the actual parent loop from the exit blocks. Because we may have
1513 // pruned some exits the loop may be different from the original parent.
1514 Loop *ParentL = nullptr;
1515 SmallVector<Loop *, 4> ExitLoops;
1516 SmallVector<BasicBlock *, 4> ExitsInLoops;
1517 ExitsInLoops.reserve(ExitBlocks.size());
1518 for (auto *ExitBB : ExitBlocks)
1519 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1520 ExitLoops.push_back(ExitL);
1521 ExitsInLoops.push_back(ExitBB);
1522 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1523 ParentL = ExitL;
1524 }
1525
1526 // Recompute the blocks participating in this loop. This may be empty if it
1527 // is no longer a loop.
1528 auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1529
1530 // If we still have a loop, we need to re-set the loop's parent as the exit
1531 // block set changing may have moved it within the loop nest. Note that this
1532 // can only happen when this loop has a parent as it can only hoist the loop
1533 // *up* the nest.
1534 if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1535 // Remove this loop's (original) blocks from all of the intervening loops.
1536 for (Loop *IL = L.getParentLoop(); IL != ParentL;
1537 IL = IL->getParentLoop()) {
1538 IL->getBlocksSet().erase(PH);
1539 for (auto *BB : L.blocks())
1540 IL->getBlocksSet().erase(BB);
1541 llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1542 return BB == PH || L.contains(BB);
1543 });
1544 }
1545
1546 LI.changeLoopFor(PH, ParentL);
1547 L.getParentLoop()->removeChildLoop(&L);
1548 if (ParentL)
1549 ParentL->addChildLoop(&L);
1550 else
1551 LI.addTopLevelLoop(&L);
1552 }
1553
1554 // Now we update all the blocks which are no longer within the loop.
1555 auto &Blocks = L.getBlocksVector();
1556 auto BlocksSplitI =
1557 LoopBlockSet.empty()
1558 ? Blocks.begin()
1559 : std::stable_partition(
1560 Blocks.begin(), Blocks.end(),
1561 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1562
1563 // Before we erase the list of unlooped blocks, build a set of them.
1564 SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1565 if (LoopBlockSet.empty())
1566 UnloopedBlocks.insert(PH);
1567
1568 // Now erase these blocks from the loop.
1569 for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1570 L.getBlocksSet().erase(BB);
1571 Blocks.erase(BlocksSplitI, Blocks.end());
1572
1573 // Sort the exits in ascending loop depth, we'll work backwards across these
1574 // to process them inside out.
1575 std::stable_sort(ExitsInLoops.begin(), ExitsInLoops.end(),
1576 [&](BasicBlock *LHS, BasicBlock *RHS) {
1577 return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1578 });
1579
1580 // We'll build up a set for each exit loop.
1581 SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1582 Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1583
1584 auto RemoveUnloopedBlocksFromLoop =
1585 [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1586 for (auto *BB : UnloopedBlocks)
1587 L.getBlocksSet().erase(BB);
1588 llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1589 return UnloopedBlocks.count(BB);
1590 });
1591 };
1592
1593 SmallVector<BasicBlock *, 16> Worklist;
1594 while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1595 assert(Worklist.empty() && "Didn't clear worklist!");
1596 assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1597
1598 // Grab the next exit block, in decreasing loop depth order.
1599 BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1600 Loop &ExitL = *LI.getLoopFor(ExitBB);
1601 assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1602
1603 // Erase all of the unlooped blocks from the loops between the previous
1604 // exit loop and this exit loop. This works because the ExitInLoops list is
1605 // sorted in increasing order of loop depth and thus we visit loops in
1606 // decreasing order of loop depth.
1607 for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1608 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1609
1610 // Walk the CFG back until we hit the cloned PH adding everything reachable
1611 // and in the unlooped set to this exit block's loop.
1612 Worklist.push_back(ExitBB);
1613 do {
1614 BasicBlock *BB = Worklist.pop_back_val();
1615 // We can stop recursing at the cloned preheader (if we get there).
1616 if (BB == PH)
1617 continue;
1618
1619 for (BasicBlock *PredBB : predecessors(BB)) {
1620 // If this pred has already been moved to our set or is part of some
1621 // (inner) loop, no update needed.
1622 if (!UnloopedBlocks.erase(PredBB)) {
1623 assert((NewExitLoopBlocks.count(PredBB) ||
1624 ExitL.contains(LI.getLoopFor(PredBB))) &&
1625 "Predecessor not in a nested loop (or already visited)!");
1626 continue;
1627 }
1628
1629 // We just insert into the loop set here. We'll add these blocks to the
1630 // exit loop after we build up the set in a deterministic order rather
1631 // than the predecessor-influenced visit order.
1632 bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1633 (void)Inserted;
1634 assert(Inserted && "Should only visit an unlooped block once!");
1635
1636 // And recurse through to its predecessors.
1637 Worklist.push_back(PredBB);
1638 }
1639 } while (!Worklist.empty());
1640
1641 // If blocks in this exit loop were directly part of the original loop (as
1642 // opposed to a child loop) update the map to point to this exit loop. This
1643 // just updates a map and so the fact that the order is unstable is fine.
1644 for (auto *BB : NewExitLoopBlocks)
1645 if (Loop *BBL = LI.getLoopFor(BB))
1646 if (BBL == &L || !L.contains(BBL))
1647 LI.changeLoopFor(BB, &ExitL);
1648
1649 // We will remove the remaining unlooped blocks from this loop in the next
1650 // iteration or below.
1651 NewExitLoopBlocks.clear();
1652 }
1653
1654 // Any remaining unlooped blocks are no longer part of any loop unless they
1655 // are part of some child loop.
1656 for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1657 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1658 for (auto *BB : UnloopedBlocks)
1659 if (Loop *BBL = LI.getLoopFor(BB))
1660 if (BBL == &L || !L.contains(BBL))
1661 LI.changeLoopFor(BB, nullptr);
1662
1663 // Sink all the child loops whose headers are no longer in the loop set to
1664 // the parent (or to be top level loops). We reach into the loop and directly
1665 // update its subloop vector to make this batch update efficient.
1666 auto &SubLoops = L.getSubLoopsVector();
1667 auto SubLoopsSplitI =
1668 LoopBlockSet.empty()
1669 ? SubLoops.begin()
1670 : std::stable_partition(
1671 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1672 return LoopBlockSet.count(SubL->getHeader());
1673 });
1674 for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1675 HoistedLoops.push_back(HoistedL);
1676 HoistedL->setParentLoop(nullptr);
1677
1678 // To compute the new parent of this hoisted loop we look at where we
1679 // placed the preheader above. We can't lookup the header itself because we
1680 // retained the mapping from the header to the hoisted loop. But the
1681 // preheader and header should have the exact same new parent computed
1682 // based on the set of exit blocks from the original loop as the preheader
1683 // is a predecessor of the header and so reached in the reverse walk. And
1684 // because the loops were all in simplified form the preheader of the
1685 // hoisted loop can't be part of some *other* loop.
1686 if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1687 NewParentL->addChildLoop(HoistedL);
1688 else
1689 LI.addTopLevelLoop(HoistedL);
1690 }
1691 SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1692
1693 // Actually delete the loop if nothing remained within it.
1694 if (Blocks.empty()) {
1695 assert(SubLoops.empty() &&
1696 "Failed to remove all subloops from the original loop!");
1697 if (Loop *ParentL = L.getParentLoop())
1698 ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1699 else
1700 LI.removeLoop(llvm::find(LI, &L));
1701 LI.destroy(&L);
1702 return false;
1703 }
1704
1705 return true;
1706}
1707
1708/// Helper to visit a dominator subtree, invoking a callable on each node.
1709///
1710/// Returning false at any point will stop walking past that node of the tree.
1711template <typename CallableT>
1712void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1713 SmallVector<DomTreeNode *, 4> DomWorklist;
1714 DomWorklist.push_back(DT[BB]);
1715#ifndef NDEBUG
1716 SmallPtrSet<DomTreeNode *, 4> Visited;
1717 Visited.insert(DT[BB]);
1718#endif
1719 do {
1720 DomTreeNode *N = DomWorklist.pop_back_val();
1721
1722 // Visit this node.
1723 if (!Callable(N->getBlock()))
1724 continue;
1725
1726 // Accumulate the child nodes.
1727 for (DomTreeNode *ChildN : *N) {
1728 assert(Visited.insert(ChildN).second &&
1729 "Cannot visit a node twice when walking a tree!");
1730 DomWorklist.push_back(ChildN);
1731 }
1732 } while (!DomWorklist.empty());
1733}
1734
Chandler Carruth16529962018-06-25 23:32:54 +00001735static bool unswitchNontrivialInvariants(
1736 Loop &L, TerminatorInst &TI, ArrayRef<Value *> Invariants,
1737 DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
Chandler Carruth3897ded2018-07-03 09:13:27 +00001738 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
1739 ScalarEvolution *SE) {
Chandler Carruth16529962018-06-25 23:32:54 +00001740 auto *ParentBB = TI.getParent();
1741 BranchInst *BI = dyn_cast<BranchInst>(&TI);
1742 SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001743
Chandler Carruth16529962018-06-25 23:32:54 +00001744 // We can only unswitch switches, conditional branches with an invariant
1745 // condition, or combining invariant conditions with an instruction.
1746 assert((SI || BI->isConditional()) &&
1747 "Can only unswitch switches and conditional branch!");
1748 bool FullUnswitch = SI || BI->getCondition() == Invariants[0];
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001749 if (FullUnswitch)
1750 assert(Invariants.size() == 1 &&
1751 "Cannot have other invariants with full unswitching!");
1752 else
Chandler Carruth16529962018-06-25 23:32:54 +00001753 assert(isa<Instruction>(BI->getCondition()) &&
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001754 "Partial unswitching requires an instruction as the condition!");
1755
1756 // Constant and BBs tracking the cloned and continuing successor. When we are
1757 // unswitching the entire condition, this can just be trivially chosen to
1758 // unswitch towards `true`. However, when we are unswitching a set of
1759 // invariants combined with `and` or `or`, the combining operation determines
1760 // the best direction to unswitch: we want to unswitch the direction that will
1761 // collapse the branch.
1762 bool Direction = true;
1763 int ClonedSucc = 0;
1764 if (!FullUnswitch) {
Chandler Carruth16529962018-06-25 23:32:54 +00001765 if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) {
1766 assert(cast<Instruction>(BI->getCondition())->getOpcode() ==
1767 Instruction::And &&
1768 "Only `or` and `and` instructions can combine invariants being "
1769 "unswitched.");
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001770 Direction = false;
1771 ClonedSucc = 1;
1772 }
1773 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001774
Chandler Carruth16529962018-06-25 23:32:54 +00001775 BasicBlock *RetainedSuccBB =
1776 BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
1777 SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
1778 if (BI)
1779 UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
1780 else
1781 for (auto Case : SI->cases())
1782 UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
1783
1784 assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
1785 "Should not unswitch the same successor we are retaining!");
Chandler Carruth693eedb2017-11-17 19:58:36 +00001786
1787 // The branch should be in this exact loop. Any inner loop's invariant branch
1788 // should be handled by unswitching that inner loop. The caller of this
1789 // routine should filter out any candidates that remain (but were skipped for
1790 // whatever reason).
1791 assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
1792
1793 SmallVector<BasicBlock *, 4> ExitBlocks;
1794 L.getUniqueExitBlocks(ExitBlocks);
1795
1796 // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
1797 // don't know how to split those exit blocks.
1798 // FIXME: We should teach SplitBlock to handle this and remove this
1799 // restriction.
1800 for (auto *ExitBB : ExitBlocks)
1801 if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI()))
1802 return false;
1803
Chandler Carruth693eedb2017-11-17 19:58:36 +00001804 // Compute the parent loop now before we start hacking on things.
1805 Loop *ParentL = L.getParentLoop();
1806
1807 // Compute the outer-most loop containing one of our exit blocks. This is the
1808 // furthest up our loopnest which can be mutated, which we will use below to
1809 // update things.
1810 Loop *OuterExitL = &L;
1811 for (auto *ExitBB : ExitBlocks) {
1812 Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
1813 if (!NewOuterExitL) {
1814 // We exited the entire nest with this block, so we're done.
1815 OuterExitL = nullptr;
1816 break;
1817 }
1818 if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
1819 OuterExitL = NewOuterExitL;
1820 }
1821
Chandler Carruth3897ded2018-07-03 09:13:27 +00001822 // At this point, we're definitely going to unswitch something so invalidate
1823 // any cached information in ScalarEvolution for the outer most loop
1824 // containing an exit block and all nested loops.
1825 if (SE) {
1826 if (OuterExitL)
1827 SE->forgetLoop(OuterExitL);
1828 else
1829 SE->forgetTopmostLoop(&L);
1830 }
1831
Chandler Carruth16529962018-06-25 23:32:54 +00001832 // If the edge from this terminator to a successor dominates that successor,
1833 // store a map from each block in its dominator subtree to it. This lets us
1834 // tell when cloning for a particular successor if a block is dominated by
1835 // some *other* successor with a single data structure. We use this to
1836 // significantly reduce cloning.
1837 SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
1838 for (auto *SuccBB : llvm::concat<BasicBlock *const>(
1839 makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
1840 if (SuccBB->getUniquePredecessor() ||
1841 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
1842 return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
1843 }))
1844 visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
1845 DominatingSucc[BB] = SuccBB;
1846 return true;
1847 });
Chandler Carruth693eedb2017-11-17 19:58:36 +00001848
1849 // Split the preheader, so that we know that there is a safe place to insert
1850 // the conditional branch. We will change the preheader to have a conditional
1851 // branch on LoopCond. The original preheader will become the split point
1852 // between the unswitched versions, and we will have a new preheader for the
1853 // original loop.
1854 BasicBlock *SplitBB = L.getLoopPreheader();
1855 BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI);
1856
Chandler Carruth69e68f82018-04-25 00:18:07 +00001857 // Keep track of the dominator tree updates needed.
1858 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
1859
Chandler Carruth16529962018-06-25 23:32:54 +00001860 // Clone the loop for each unswitched successor.
1861 SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
1862 VMaps.reserve(UnswitchedSuccBBs.size());
1863 SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
1864 for (auto *SuccBB : UnswitchedSuccBBs) {
1865 VMaps.emplace_back(new ValueToValueMapTy());
1866 ClonedPHs[SuccBB] = buildClonedLoopBlocks(
1867 L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
1868 DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI);
1869 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001870
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001871 // The stitching of the branched code back together depends on whether we're
1872 // doing full unswitching or not with the exception that we always want to
1873 // nuke the initial terminator placed in the split block.
Chandler Carruth693eedb2017-11-17 19:58:36 +00001874 SplitBB->getTerminator()->eraseFromParent();
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001875 if (FullUnswitch) {
Chandler Carruth16529962018-06-25 23:32:54 +00001876 for (BasicBlock *SuccBB : UnswitchedSuccBBs) {
1877 // Remove the parent as a predecessor of the unswitched successor.
1878 SuccBB->removePredecessor(ParentBB,
1879 /*DontDeleteUselessPHIs*/ true);
1880 DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
1881 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001882
Chandler Carruth16529962018-06-25 23:32:54 +00001883 // Now splice the terminator from the original loop and rewrite its
1884 // successors.
1885 SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
1886 if (BI) {
1887 assert(UnswitchedSuccBBs.size() == 1 &&
1888 "Only one possible unswitched block for a branch!");
1889 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
1890 BI->setSuccessor(ClonedSucc, ClonedPH);
1891 BI->setSuccessor(1 - ClonedSucc, LoopPH);
1892 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
1893 } else {
1894 assert(SI && "Must either be a branch or switch!");
1895
1896 // Walk the cases and directly update their successors.
1897 for (auto &Case : SI->cases())
1898 Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
1899 // We need to use the set to populate domtree updates as even when there
1900 // are multiple cases pointing at the same successor we only want to
1901 // insert one edge in the domtree.
1902 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
1903 DTUpdates.push_back(
1904 {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
1905
1906 SI->setDefaultDest(LoopPH);
1907 }
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001908
1909 // Create a new unconditional branch to the continuing block (as opposed to
1910 // the one cloned).
Chandler Carruth16529962018-06-25 23:32:54 +00001911 BranchInst::Create(RetainedSuccBB, ParentBB);
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001912 } else {
Chandler Carruth16529962018-06-25 23:32:54 +00001913 assert(BI && "Only branches have partial unswitching.");
1914 assert(UnswitchedSuccBBs.size() == 1 &&
1915 "Only one possible unswitched block for a branch!");
1916 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001917 // When doing a partial unswitch, we have to do a bit more work to build up
1918 // the branch in the split block.
1919 buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
1920 *ClonedPH, *LoopPH);
Chandler Carruth16529962018-06-25 23:32:54 +00001921 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001922 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00001923
Chandler Carruth16529962018-06-25 23:32:54 +00001924 // Apply the updates accumulated above to get an up-to-date dominator tree.
Chandler Carruth69e68f82018-04-25 00:18:07 +00001925 DT.applyUpdates(DTUpdates);
1926
Chandler Carruth16529962018-06-25 23:32:54 +00001927 // Now that we have an accurate dominator tree, first delete the dead cloned
1928 // blocks so that we can accurately build any cloned loops. It is important to
1929 // not delete the blocks from the original loop yet because we still want to
1930 // reference the original loop to understand the cloned loop's structure.
1931 deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT);
1932
Chandler Carruth69e68f82018-04-25 00:18:07 +00001933 // Build the cloned loop structure itself. This may be substantially
1934 // different from the original structure due to the simplified CFG. This also
1935 // handles inserting all the cloned blocks into the correct loops.
1936 SmallVector<Loop *, 4> NonChildClonedLoops;
Chandler Carruth16529962018-06-25 23:32:54 +00001937 for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
1938 buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
Chandler Carruth69e68f82018-04-25 00:18:07 +00001939
Chandler Carruth16529962018-06-25 23:32:54 +00001940 // Now that our cloned loops have been built, we can update the original loop.
1941 // First we delete the dead blocks from it and then we rebuild the loop
1942 // structure taking these deletions into account.
1943 deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI);
Chandler Carruth693eedb2017-11-17 19:58:36 +00001944 SmallVector<Loop *, 4> HoistedLoops;
1945 bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
1946
Chandler Carruth69e68f82018-04-25 00:18:07 +00001947 // This transformation has a high risk of corrupting the dominator tree, and
1948 // the below steps to rebuild loop structures will result in hard to debug
1949 // errors in that case so verify that the dominator tree is sane first.
1950 // FIXME: Remove this when the bugs stop showing up and rely on existing
1951 // verification steps.
1952 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruth693eedb2017-11-17 19:58:36 +00001953
Chandler Carruth16529962018-06-25 23:32:54 +00001954 if (BI) {
1955 // If we unswitched a branch which collapses the condition to a known
1956 // constant we want to replace all the uses of the invariants within both
1957 // the original and cloned blocks. We do this here so that we can use the
1958 // now updated dominator tree to identify which side the users are on.
1959 assert(UnswitchedSuccBBs.size() == 1 &&
1960 "Only one possible unswitched block for a branch!");
1961 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
1962 ConstantInt *UnswitchedReplacement =
1963 Direction ? ConstantInt::getTrue(BI->getContext())
1964 : ConstantInt::getFalse(BI->getContext());
1965 ConstantInt *ContinueReplacement =
1966 Direction ? ConstantInt::getFalse(BI->getContext())
1967 : ConstantInt::getTrue(BI->getContext());
1968 for (Value *Invariant : Invariants)
1969 for (auto UI = Invariant->use_begin(), UE = Invariant->use_end();
1970 UI != UE;) {
1971 // Grab the use and walk past it so we can clobber it in the use list.
1972 Use *U = &*UI++;
1973 Instruction *UserI = dyn_cast<Instruction>(U->getUser());
1974 if (!UserI)
1975 continue;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001976
Chandler Carruth16529962018-06-25 23:32:54 +00001977 // Replace it with the 'continue' side if in the main loop body, and the
1978 // unswitched if in the cloned blocks.
1979 if (DT.dominates(LoopPH, UserI->getParent()))
1980 U->set(ContinueReplacement);
1981 else if (DT.dominates(ClonedPH, UserI->getParent()))
1982 U->set(UnswitchedReplacement);
1983 }
1984 }
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00001985
Chandler Carruth693eedb2017-11-17 19:58:36 +00001986 // We can change which blocks are exit blocks of all the cloned sibling
1987 // loops, the current loop, and any parent loops which shared exit blocks
1988 // with the current loop. As a consequence, we need to re-form LCSSA for
1989 // them. But we shouldn't need to re-form LCSSA for any child loops.
1990 // FIXME: This could be made more efficient by tracking which exit blocks are
1991 // new, and focusing on them, but that isn't likely to be necessary.
1992 //
1993 // In order to reasonably rebuild LCSSA we need to walk inside-out across the
1994 // loop nest and update every loop that could have had its exits changed. We
1995 // also need to cover any intervening loops. We add all of these loops to
1996 // a list and sort them by loop depth to achieve this without updating
1997 // unnecessary loops.
Chandler Carruth92815032018-06-02 01:29:01 +00001998 auto UpdateLoop = [&](Loop &UpdateL) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00001999#ifndef NDEBUG
Chandler Carruth43acdb32018-04-24 10:33:08 +00002000 UpdateL.verifyLoop();
2001 for (Loop *ChildL : UpdateL) {
2002 ChildL->verifyLoop();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002003 assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2004 "Perturbed a child loop's LCSSA form!");
Chandler Carruth43acdb32018-04-24 10:33:08 +00002005 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002006#endif
Chandler Carruth92815032018-06-02 01:29:01 +00002007 // First build LCSSA for this loop so that we can preserve it when
2008 // forming dedicated exits. We don't want to perturb some other loop's
2009 // LCSSA while doing that CFG edit.
Chandler Carruth693eedb2017-11-17 19:58:36 +00002010 formLCSSA(UpdateL, DT, &LI, nullptr);
Chandler Carruth92815032018-06-02 01:29:01 +00002011
2012 // For loops reached by this loop's original exit blocks we may
2013 // introduced new, non-dedicated exits. At least try to re-form dedicated
2014 // exits for these loops. This may fail if they couldn't have dedicated
2015 // exits to start with.
2016 formDedicatedExitBlocks(&UpdateL, &DT, &LI, /*PreserveLCSSA*/ true);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002017 };
2018
2019 // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2020 // and we can do it in any order as they don't nest relative to each other.
Chandler Carruth92815032018-06-02 01:29:01 +00002021 //
2022 // Also check if any of the loops we have updated have become top-level loops
2023 // as that will necessitate widening the outer loop scope.
2024 for (Loop *UpdatedL :
2025 llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2026 UpdateLoop(*UpdatedL);
2027 if (!UpdatedL->getParentLoop())
2028 OuterExitL = nullptr;
2029 }
2030 if (IsStillLoop) {
2031 UpdateLoop(L);
2032 if (!L.getParentLoop())
2033 OuterExitL = nullptr;
2034 }
Chandler Carruth693eedb2017-11-17 19:58:36 +00002035
2036 // If the original loop had exit blocks, walk up through the outer most loop
2037 // of those exit blocks to update LCSSA and form updated dedicated exits.
Chandler Carruth92815032018-06-02 01:29:01 +00002038 if (OuterExitL != &L)
Chandler Carruth693eedb2017-11-17 19:58:36 +00002039 for (Loop *OuterL = ParentL; OuterL != OuterExitL;
2040 OuterL = OuterL->getParentLoop())
Chandler Carruth92815032018-06-02 01:29:01 +00002041 UpdateLoop(*OuterL);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002042
2043#ifndef NDEBUG
2044 // Verify the entire loop structure to catch any incorrect updates before we
2045 // progress in the pass pipeline.
2046 LI.verify(DT);
2047#endif
2048
2049 // Now that we've unswitched something, make callbacks to report the changes.
2050 // For that we need to merge together the updated loops and the cloned loops
2051 // and check whether the original loop survived.
2052 SmallVector<Loop *, 4> SibLoops;
2053 for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2054 if (UpdatedL->getParentLoop() == ParentL)
2055 SibLoops.push_back(UpdatedL);
Chandler Carruth71fd2702018-05-30 02:46:45 +00002056 UnswitchCB(IsStillLoop, SibLoops);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002057
2058 ++NumBranches;
2059 return true;
2060}
2061
2062/// Recursively compute the cost of a dominator subtree based on the per-block
2063/// cost map provided.
2064///
2065/// The recursive computation is memozied into the provided DT-indexed cost map
2066/// to allow querying it for most nodes in the domtree without it becoming
2067/// quadratic.
2068static int
2069computeDomSubtreeCost(DomTreeNode &N,
2070 const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
2071 SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
2072 // Don't accumulate cost (or recurse through) blocks not in our block cost
2073 // map and thus not part of the duplication cost being considered.
2074 auto BBCostIt = BBCostMap.find(N.getBlock());
2075 if (BBCostIt == BBCostMap.end())
2076 return 0;
2077
2078 // Lookup this node to see if we already computed its cost.
2079 auto DTCostIt = DTCostMap.find(&N);
2080 if (DTCostIt != DTCostMap.end())
2081 return DTCostIt->second;
2082
2083 // If not, we have to compute it. We can't use insert above and update
2084 // because computing the cost may insert more things into the map.
2085 int Cost = std::accumulate(
2086 N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
2087 return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2088 });
2089 bool Inserted = DTCostMap.insert({&N, Cost}).second;
2090 (void)Inserted;
2091 assert(Inserted && "Should not insert a node while visiting children!");
2092 return Cost;
2093}
2094
Chandler Carruth3897ded2018-07-03 09:13:27 +00002095static bool
2096unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
2097 AssumptionCache &AC, TargetTransformInfo &TTI,
2098 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2099 ScalarEvolution *SE) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002100 // Collect all invariant conditions within this loop (as opposed to an inner
2101 // loop which would be handled when visiting that inner loop).
2102 SmallVector<std::pair<TerminatorInst *, TinyPtrVector<Value *>>, 4>
2103 UnswitchCandidates;
2104 for (auto *BB : L.blocks()) {
2105 if (LI.getLoopFor(BB) != &L)
2106 continue;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002107
Chandler Carruth16529962018-06-25 23:32:54 +00002108 if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2109 // We can only consider fully loop-invariant switch conditions as we need
2110 // to completely eliminate the switch after unswitching.
2111 if (!isa<Constant>(SI->getCondition()) &&
2112 L.isLoopInvariant(SI->getCondition()))
2113 UnswitchCandidates.push_back({SI, {SI->getCondition()}});
2114 continue;
2115 }
2116
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002117 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002118 if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2119 BI->getSuccessor(0) == BI->getSuccessor(1))
2120 continue;
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002121
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002122 if (L.isLoopInvariant(BI->getCondition())) {
2123 UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2124 continue;
2125 }
2126
2127 Instruction &CondI = *cast<Instruction>(BI->getCondition());
2128 if (CondI.getOpcode() != Instruction::And &&
2129 CondI.getOpcode() != Instruction::Or)
2130 continue;
2131
2132 TinyPtrVector<Value *> Invariants =
2133 collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2134 if (Invariants.empty())
2135 continue;
2136
2137 UnswitchCandidates.push_back({BI, std::move(Invariants)});
Chandler Carruth71fd2702018-05-30 02:46:45 +00002138 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002139
Chandler Carruth693eedb2017-11-17 19:58:36 +00002140 // If we didn't find any candidates, we're done.
2141 if (UnswitchCandidates.empty())
Chandler Carruth71fd2702018-05-30 02:46:45 +00002142 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002143
Chandler Carruth32e62f92018-04-19 18:44:25 +00002144 // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2145 // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2146 // irreducible control flow into reducible control flow and introduce new
2147 // loops "out of thin air". If we ever discover important use cases for doing
2148 // this, we can add support to loop unswitch, but it is a lot of complexity
Hiroshi Inouef2096492018-06-14 05:41:49 +00002149 // for what seems little or no real world benefit.
Chandler Carruth32e62f92018-04-19 18:44:25 +00002150 LoopBlocksRPO RPOT(&L);
2151 RPOT.perform(&LI);
2152 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
Chandler Carruth71fd2702018-05-30 02:46:45 +00002153 return false;
Chandler Carruth32e62f92018-04-19 18:44:25 +00002154
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002155 LLVM_DEBUG(
2156 dbgs() << "Considering " << UnswitchCandidates.size()
2157 << " non-trivial loop invariant conditions for unswitching.\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002158
2159 // Given that unswitching these terminators will require duplicating parts of
2160 // the loop, so we need to be able to model that cost. Compute the ephemeral
2161 // values and set up a data structure to hold per-BB costs. We cache each
2162 // block's cost so that we don't recompute this when considering different
2163 // subsets of the loop for duplication during unswitching.
2164 SmallPtrSet<const Value *, 4> EphValues;
2165 CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2166 SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
2167
2168 // Compute the cost of each block, as well as the total loop cost. Also, bail
2169 // out if we see instructions which are incompatible with loop unswitching
2170 // (convergent, noduplicate, or cross-basic-block tokens).
2171 // FIXME: We might be able to safely handle some of these in non-duplicated
2172 // regions.
2173 int LoopCost = 0;
2174 for (auto *BB : L.blocks()) {
2175 int Cost = 0;
2176 for (auto &I : *BB) {
2177 if (EphValues.count(&I))
2178 continue;
2179
2180 if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
Chandler Carruth71fd2702018-05-30 02:46:45 +00002181 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002182 if (auto CS = CallSite(&I))
2183 if (CS.isConvergent() || CS.cannotDuplicate())
Chandler Carruth71fd2702018-05-30 02:46:45 +00002184 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002185
2186 Cost += TTI.getUserCost(&I);
2187 }
2188 assert(Cost >= 0 && "Must not have negative costs!");
2189 LoopCost += Cost;
2190 assert(LoopCost >= 0 && "Must not have negative loop costs!");
2191 BBCostMap[BB] = Cost;
2192 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002193 LLVM_DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002194
2195 // Now we find the best candidate by searching for the one with the following
2196 // properties in order:
2197 //
2198 // 1) An unswitching cost below the threshold
2199 // 2) The smallest number of duplicated unswitch candidates (to avoid
2200 // creating redundant subsequent unswitching)
2201 // 3) The smallest cost after unswitching.
2202 //
2203 // We prioritize reducing fanout of unswitch candidates provided the cost
2204 // remains below the threshold because this has a multiplicative effect.
2205 //
2206 // This requires memoizing each dominator subtree to avoid redundant work.
2207 //
2208 // FIXME: Need to actually do the number of candidates part above.
2209 SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
2210 // Given a terminator which might be unswitched, computes the non-duplicated
2211 // cost for that terminator.
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002212 auto ComputeUnswitchedCost = [&](TerminatorInst &TI, bool FullUnswitch) {
2213 BasicBlock &BB = *TI.getParent();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002214 SmallPtrSet<BasicBlock *, 4> Visited;
2215
2216 int Cost = LoopCost;
2217 for (BasicBlock *SuccBB : successors(&BB)) {
2218 // Don't count successors more than once.
2219 if (!Visited.insert(SuccBB).second)
2220 continue;
2221
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002222 // If this is a partial unswitch candidate, then it must be a conditional
2223 // branch with a condition of either `or` or `and`. In that case, one of
2224 // the successors is necessarily duplicated, so don't even try to remove
2225 // its cost.
2226 if (!FullUnswitch) {
2227 auto &BI = cast<BranchInst>(TI);
2228 if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2229 Instruction::And) {
2230 if (SuccBB == BI.getSuccessor(1))
2231 continue;
2232 } else {
2233 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2234 Instruction::Or &&
2235 "Only `and` and `or` conditions can result in a partial "
2236 "unswitch!");
2237 if (SuccBB == BI.getSuccessor(0))
2238 continue;
2239 }
2240 }
2241
Chandler Carruth693eedb2017-11-17 19:58:36 +00002242 // This successor's domtree will not need to be duplicated after
2243 // unswitching if the edge to the successor dominates it (and thus the
2244 // entire tree). This essentially means there is no other path into this
2245 // subtree and so it will end up live in only one clone of the loop.
2246 if (SuccBB->getUniquePredecessor() ||
2247 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2248 return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2249 })) {
2250 Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2251 assert(Cost >= 0 &&
2252 "Non-duplicated cost should never exceed total loop cost!");
2253 }
2254 }
2255
2256 // Now scale the cost by the number of unique successors minus one. We
2257 // subtract one because there is already at least one copy of the entire
2258 // loop. This is computing the new cost of unswitching a condition.
2259 assert(Visited.size() > 1 &&
2260 "Cannot unswitch a condition without multiple distinct successors!");
2261 return Cost * (Visited.size() - 1);
2262 };
2263 TerminatorInst *BestUnswitchTI = nullptr;
2264 int BestUnswitchCost;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002265 ArrayRef<Value *> BestUnswitchInvariants;
2266 for (auto &TerminatorAndInvariants : UnswitchCandidates) {
2267 TerminatorInst &TI = *TerminatorAndInvariants.first;
2268 ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2269 BranchInst *BI = dyn_cast<BranchInst>(&TI);
Chandler Carruth16529962018-06-25 23:32:54 +00002270 int CandidateCost = ComputeUnswitchedCost(
2271 TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
2272 Invariants[0] == BI->getCondition()));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002273 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002274 << " for unswitch candidate: " << TI << "\n");
Chandler Carruth693eedb2017-11-17 19:58:36 +00002275 if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002276 BestUnswitchTI = &TI;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002277 BestUnswitchCost = CandidateCost;
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002278 BestUnswitchInvariants = Invariants;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002279 }
2280 }
2281
Chandler Carruth71fd2702018-05-30 02:46:45 +00002282 if (BestUnswitchCost >= UnswitchThreshold) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002283 LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
2284 << BestUnswitchCost << "\n");
Chandler Carruth71fd2702018-05-30 02:46:45 +00002285 return false;
Chandler Carruth693eedb2017-11-17 19:58:36 +00002286 }
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002287
Chandler Carruth71fd2702018-05-30 02:46:45 +00002288 LLVM_DEBUG(dbgs() << " Trying to unswitch non-trivial (cost = "
Chandler Carruth16529962018-06-25 23:32:54 +00002289 << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
2290 << "\n");
2291 return unswitchNontrivialInvariants(
Chandler Carruth3897ded2018-07-03 09:13:27 +00002292 L, *BestUnswitchTI, BestUnswitchInvariants, DT, LI, AC, UnswitchCB, SE);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002293}
2294
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002295/// Unswitch control flow predicated on loop invariant conditions.
2296///
2297/// This first hoists all branches or switches which are trivial (IE, do not
2298/// require duplicating any part of the loop) out of the loop body. It then
2299/// looks at other loop invariant control flows and tries to unswitch those as
2300/// well by cloning the loop if the result is small enough.
Chandler Carruth3897ded2018-07-03 09:13:27 +00002301///
2302/// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
2303/// updated based on the unswitch.
2304///
2305/// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
2306/// true, we will attempt to do non-trivial unswitching as well as trivial
2307/// unswitching.
2308///
2309/// The `UnswitchCB` callback provided will be run after unswitching is
2310/// complete, with the first parameter set to `true` if the provided loop
2311/// remains a loop, and a list of new sibling loops created.
2312///
2313/// If `SE` is non-null, we will update that analysis based on the unswitching
2314/// done.
2315static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
2316 AssumptionCache &AC, TargetTransformInfo &TTI,
2317 bool NonTrivial,
2318 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2319 ScalarEvolution *SE) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002320 assert(L.isRecursivelyLCSSAForm(DT, LI) &&
2321 "Loops must be in LCSSA form before unswitching.");
2322 bool Changed = false;
2323
2324 // Must be in loop simplified form: we need a preheader and dedicated exits.
2325 if (!L.isLoopSimplifyForm())
2326 return false;
2327
2328 // Try trivial unswitch first before loop over other basic blocks in the loop.
Chandler Carruth3897ded2018-07-03 09:13:27 +00002329 if (unswitchAllTrivialConditions(L, DT, LI, SE)) {
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002330 // If we unswitched successfully we will want to clean up the loop before
2331 // processing it further so just mark it as unswitched and return.
2332 UnswitchCB(/*CurrentLoopValid*/ true, {});
2333 return true;
2334 }
2335
2336 // If we're not doing non-trivial unswitching, we're done. We both accept
2337 // a parameter but also check a local flag that can be used for testing
2338 // a debugging.
2339 if (!NonTrivial && !EnableNonTrivialUnswitch)
2340 return false;
2341
2342 // For non-trivial unswitching, because it often creates new loops, we rely on
2343 // the pass manager to iterate on the loops rather than trying to immediately
2344 // reach a fixed point. There is no substantial advantage to iterating
2345 // internally, and if any of the new loops are simplified enough to contain
2346 // trivial unswitching we want to prefer those.
2347
2348 // Try to unswitch the best invariant condition. We prefer this full unswitch to
2349 // a partial unswitch when possible below the threshold.
Chandler Carruth3897ded2018-07-03 09:13:27 +00002350 if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE))
Chandler Carruthd1dab0c2018-06-21 06:14:03 +00002351 return true;
2352
2353 // No other opportunities to unswitch.
2354 return Changed;
2355}
2356
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002357PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
2358 LoopStandardAnalysisResults &AR,
2359 LPMUpdater &U) {
2360 Function &F = *L.getHeader()->getParent();
2361 (void)F;
2362
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002363 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
2364 << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002365
Chandler Carruth693eedb2017-11-17 19:58:36 +00002366 // Save the current loop name in a variable so that we can report it even
2367 // after it has been deleted.
2368 std::string LoopName = L.getName();
2369
Chandler Carruth71fd2702018-05-30 02:46:45 +00002370 auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2371 ArrayRef<Loop *> NewLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002372 // If we did a non-trivial unswitch, we have added new (cloned) loops.
Chandler Carruth71fd2702018-05-30 02:46:45 +00002373 if (!NewLoops.empty())
2374 U.addSiblingLoops(NewLoops);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002375
2376 // If the current loop remains valid, we should revisit it to catch any
2377 // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2378 if (CurrentLoopValid)
2379 U.revisitCurrentLoop();
2380 else
2381 U.markLoopAsDeleted(L, LoopName);
2382 };
2383
Chandler Carruth3897ded2018-07-03 09:13:27 +00002384 if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB,
2385 &AR.SE))
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002386 return PreservedAnalyses::all();
2387
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002388 // Historically this pass has had issues with the dominator tree so verify it
2389 // in asserts builds.
David Green7c35de12018-02-28 11:00:08 +00002390 assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002391 return getLoopPassPreservedAnalyses();
2392}
2393
2394namespace {
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002395
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002396class SimpleLoopUnswitchLegacyPass : public LoopPass {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002397 bool NonTrivial;
2398
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002399public:
2400 static char ID; // Pass ID, replacement for typeid
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002401
Chandler Carruth693eedb2017-11-17 19:58:36 +00002402 explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2403 : LoopPass(ID), NonTrivial(NonTrivial) {
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002404 initializeSimpleLoopUnswitchLegacyPassPass(
2405 *PassRegistry::getPassRegistry());
2406 }
2407
2408 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
2409
2410 void getAnalysisUsage(AnalysisUsage &AU) const override {
2411 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth693eedb2017-11-17 19:58:36 +00002412 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002413 getLoopAnalysisUsage(AU);
2414 }
2415};
Eugene Zelenkoa369a452017-05-16 23:10:25 +00002416
2417} // end anonymous namespace
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002418
2419bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
2420 if (skipLoop(L))
2421 return false;
2422
2423 Function &F = *L->getHeader()->getParent();
2424
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002425 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
2426 << "\n");
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002427
2428 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2429 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2430 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002431 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002432
Chandler Carruth3897ded2018-07-03 09:13:27 +00002433 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
2434 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
2435
Chandler Carruth71fd2702018-05-30 02:46:45 +00002436 auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2437 ArrayRef<Loop *> NewLoops) {
Chandler Carruth693eedb2017-11-17 19:58:36 +00002438 // If we did a non-trivial unswitch, we have added new (cloned) loops.
2439 for (auto *NewL : NewLoops)
2440 LPM.addLoop(*NewL);
2441
2442 // If the current loop remains valid, re-add it to the queue. This is
2443 // a little wasteful as we'll finish processing the current loop as well,
2444 // but it is the best we can do in the old PM.
2445 if (CurrentLoopValid)
2446 LPM.addLoop(*L);
2447 else
2448 LPM.markLoopAsDeleted(*L);
2449 };
2450
Chandler Carruth3897ded2018-07-03 09:13:27 +00002451 bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE);
Chandler Carruth693eedb2017-11-17 19:58:36 +00002452
2453 // If anything was unswitched, also clear any cached information about this
2454 // loop.
2455 LPM.deleteSimpleAnalysisLoop(L);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002456
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002457 // Historically this pass has had issues with the dominator tree so verify it
2458 // in asserts builds.
David Green7c35de12018-02-28 11:00:08 +00002459 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2460
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002461 return Changed;
2462}
2463
2464char SimpleLoopUnswitchLegacyPass::ID = 0;
2465INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2466 "Simple unswitch loops", false, false)
2467INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth693eedb2017-11-17 19:58:36 +00002468INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2469INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002470INITIALIZE_PASS_DEPENDENCY(LoopPass)
2471INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2472INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2473 "Simple unswitch loops", false, false)
2474
Chandler Carruth693eedb2017-11-17 19:58:36 +00002475Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
2476 return new SimpleLoopUnswitchLegacyPass(NonTrivial);
Chandler Carruth1353f9a2017-04-27 18:45:20 +00002477}