[llvm-exegesis] [NFC] Fixing typo.
[llvm-complete.git] / lib / Transforms / Scalar / SimpleLoopUnswitch.cpp
blobdb7da8edd51bd5dada117349d00a22b37f9ae052
1 ///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
10 #include "llvm/ADT/DenseMap.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/Sequence.h"
13 #include "llvm/ADT/SetVector.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/CFG.h"
20 #include "llvm/Analysis/CodeMetrics.h"
21 #include "llvm/Analysis/GuardUtils.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/LoopAnalysisManager.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/LoopIterator.h"
26 #include "llvm/Analysis/LoopPass.h"
27 #include "llvm/Analysis/MemorySSA.h"
28 #include "llvm/Analysis/MemorySSAUpdater.h"
29 #include "llvm/Analysis/Utils/Local.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/Constant.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/InstrTypes.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Use.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/GenericDomTree.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Cloning.h"
50 #include "llvm/Transforms/Utils/LoopUtils.h"
51 #include "llvm/Transforms/Utils/ValueMapper.h"
52 #include <algorithm>
53 #include <cassert>
54 #include <iterator>
55 #include <numeric>
56 #include <utility>
58 #define DEBUG_TYPE "simple-loop-unswitch"
60 using namespace llvm;
62 STATISTIC(NumBranches, "Number of branches unswitched");
63 STATISTIC(NumSwitches, "Number of switches unswitched");
64 STATISTIC(NumGuards, "Number of guards turned into branches for unswitching");
65 STATISTIC(NumTrivial, "Number of unswitches that are trivial");
66 STATISTIC(
67 NumCostMultiplierSkipped,
68 "Number of unswitch candidates that had their cost multiplier skipped");
70 static cl::opt<bool> EnableNonTrivialUnswitch(
71 "enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
72 cl::desc("Forcibly enables non-trivial loop unswitching rather than "
73 "following the configuration passed into the pass."));
75 static cl::opt<int>
76 UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
77 cl::desc("The cost threshold for unswitching a loop."));
79 static cl::opt<bool> EnableUnswitchCostMultiplier(
80 "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden,
81 cl::desc("Enable unswitch cost multiplier that prohibits exponential "
82 "explosion in nontrivial unswitch."));
83 static cl::opt<int> UnswitchSiblingsToplevelDiv(
84 "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden,
85 cl::desc("Toplevel siblings divisor for cost multiplier."));
86 static cl::opt<int> UnswitchNumInitialUnscaledCandidates(
87 "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden,
88 cl::desc("Number of unswitch candidates that are ignored when calculating "
89 "cost multiplier."));
90 static cl::opt<bool> UnswitchGuards(
91 "simple-loop-unswitch-guards", cl::init(true), cl::Hidden,
92 cl::desc("If enabled, simple loop unswitching will also consider "
93 "llvm.experimental.guard intrinsics as unswitch candidates."));
95 /// Collect all of the loop invariant input values transitively used by the
96 /// homogeneous instruction graph from a given root.
97 ///
98 /// This essentially walks from a root recursively through loop variant operands
99 /// which have the exact same opcode and finds all inputs which are loop
100 /// invariant. For some operations these can be re-associated and unswitched out
101 /// of the loop entirely.
102 static TinyPtrVector<Value *>
103 collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root,
104 LoopInfo &LI) {
105 assert(!L.isLoopInvariant(&Root) &&
106 "Only need to walk the graph if root itself is not invariant.");
107 TinyPtrVector<Value *> Invariants;
109 // Build a worklist and recurse through operators collecting invariants.
110 SmallVector<Instruction *, 4> Worklist;
111 SmallPtrSet<Instruction *, 8> Visited;
112 Worklist.push_back(&Root);
113 Visited.insert(&Root);
114 do {
115 Instruction &I = *Worklist.pop_back_val();
116 for (Value *OpV : I.operand_values()) {
117 // Skip constants as unswitching isn't interesting for them.
118 if (isa<Constant>(OpV))
119 continue;
121 // Add it to our result if loop invariant.
122 if (L.isLoopInvariant(OpV)) {
123 Invariants.push_back(OpV);
124 continue;
127 // If not an instruction with the same opcode, nothing we can do.
128 Instruction *OpI = dyn_cast<Instruction>(OpV);
129 if (!OpI || OpI->getOpcode() != Root.getOpcode())
130 continue;
132 // Visit this operand.
133 if (Visited.insert(OpI).second)
134 Worklist.push_back(OpI);
136 } while (!Worklist.empty());
138 return Invariants;
141 static void replaceLoopInvariantUses(Loop &L, Value *Invariant,
142 Constant &Replacement) {
143 assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
145 // Replace uses of LIC in the loop with the given constant.
146 for (auto UI = Invariant->use_begin(), UE = Invariant->use_end(); UI != UE;) {
147 // Grab the use and walk past it so we can clobber it in the use list.
148 Use *U = &*UI++;
149 Instruction *UserI = dyn_cast<Instruction>(U->getUser());
151 // Replace this use within the loop body.
152 if (UserI && L.contains(UserI))
153 U->set(&Replacement);
157 /// Check that all the LCSSA PHI nodes in the loop exit block have trivial
158 /// incoming values along this edge.
159 static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB,
160 BasicBlock &ExitBB) {
161 for (Instruction &I : ExitBB) {
162 auto *PN = dyn_cast<PHINode>(&I);
163 if (!PN)
164 // No more PHIs to check.
165 return true;
167 // If the incoming value for this edge isn't loop invariant the unswitch
168 // won't be trivial.
169 if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
170 return false;
172 llvm_unreachable("Basic blocks should never be empty!");
175 /// Insert code to test a set of loop invariant values, and conditionally branch
176 /// on them.
177 static void buildPartialUnswitchConditionalBranch(BasicBlock &BB,
178 ArrayRef<Value *> Invariants,
179 bool Direction,
180 BasicBlock &UnswitchedSucc,
181 BasicBlock &NormalSucc) {
182 IRBuilder<> IRB(&BB);
183 Value *Cond = Invariants.front();
184 for (Value *Invariant :
185 make_range(std::next(Invariants.begin()), Invariants.end()))
186 if (Direction)
187 Cond = IRB.CreateOr(Cond, Invariant);
188 else
189 Cond = IRB.CreateAnd(Cond, Invariant);
191 IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
192 Direction ? &NormalSucc : &UnswitchedSucc);
195 /// Rewrite the PHI nodes in an unswitched loop exit basic block.
197 /// Requires that the loop exit and unswitched basic block are the same, and
198 /// that the exiting block was a unique predecessor of that block. Rewrites the
199 /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
200 /// PHI nodes from the old preheader that now contains the unswitched
201 /// terminator.
202 static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
203 BasicBlock &OldExitingBB,
204 BasicBlock &OldPH) {
205 for (PHINode &PN : UnswitchedBB.phis()) {
206 // When the loop exit is directly unswitched we just need to update the
207 // incoming basic block. We loop to handle weird cases with repeated
208 // incoming blocks, but expect to typically only have one operand here.
209 for (auto i : seq<int>(0, PN.getNumOperands())) {
210 assert(PN.getIncomingBlock(i) == &OldExitingBB &&
211 "Found incoming block different from unique predecessor!");
212 PN.setIncomingBlock(i, &OldPH);
217 /// Rewrite the PHI nodes in the loop exit basic block and the split off
218 /// unswitched block.
220 /// Because the exit block remains an exit from the loop, this rewrites the
221 /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
222 /// nodes into the unswitched basic block to select between the value in the
223 /// old preheader and the loop exit.
224 static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
225 BasicBlock &UnswitchedBB,
226 BasicBlock &OldExitingBB,
227 BasicBlock &OldPH,
228 bool FullUnswitch) {
229 assert(&ExitBB != &UnswitchedBB &&
230 "Must have different loop exit and unswitched blocks!");
231 Instruction *InsertPt = &*UnswitchedBB.begin();
232 for (PHINode &PN : ExitBB.phis()) {
233 auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
234 PN.getName() + ".split", InsertPt);
236 // Walk backwards over the old PHI node's inputs to minimize the cost of
237 // removing each one. We have to do this weird loop manually so that we
238 // create the same number of new incoming edges in the new PHI as we expect
239 // each case-based edge to be included in the unswitched switch in some
240 // cases.
241 // FIXME: This is really, really gross. It would be much cleaner if LLVM
242 // allowed us to create a single entry for a predecessor block without
243 // having separate entries for each "edge" even though these edges are
244 // required to produce identical results.
245 for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
246 if (PN.getIncomingBlock(i) != &OldExitingBB)
247 continue;
249 Value *Incoming = PN.getIncomingValue(i);
250 if (FullUnswitch)
251 // No more edge from the old exiting block to the exit block.
252 PN.removeIncomingValue(i);
254 NewPN->addIncoming(Incoming, &OldPH);
257 // Now replace the old PHI with the new one and wire the old one in as an
258 // input to the new one.
259 PN.replaceAllUsesWith(NewPN);
260 NewPN->addIncoming(&PN, &ExitBB);
264 /// Hoist the current loop up to the innermost loop containing a remaining exit.
266 /// Because we've removed an exit from the loop, we may have changed the set of
267 /// loops reachable and need to move the current loop up the loop nest or even
268 /// to an entirely separate nest.
269 static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
270 DominatorTree &DT, LoopInfo &LI) {
271 // If the loop is already at the top level, we can't hoist it anywhere.
272 Loop *OldParentL = L.getParentLoop();
273 if (!OldParentL)
274 return;
276 SmallVector<BasicBlock *, 4> Exits;
277 L.getExitBlocks(Exits);
278 Loop *NewParentL = nullptr;
279 for (auto *ExitBB : Exits)
280 if (Loop *ExitL = LI.getLoopFor(ExitBB))
281 if (!NewParentL || NewParentL->contains(ExitL))
282 NewParentL = ExitL;
284 if (NewParentL == OldParentL)
285 return;
287 // The new parent loop (if different) should always contain the old one.
288 if (NewParentL)
289 assert(NewParentL->contains(OldParentL) &&
290 "Can only hoist this loop up the nest!");
292 // The preheader will need to move with the body of this loop. However,
293 // because it isn't in this loop we also need to update the primary loop map.
294 assert(OldParentL == LI.getLoopFor(&Preheader) &&
295 "Parent loop of this loop should contain this loop's preheader!");
296 LI.changeLoopFor(&Preheader, NewParentL);
298 // Remove this loop from its old parent.
299 OldParentL->removeChildLoop(&L);
301 // Add the loop either to the new parent or as a top-level loop.
302 if (NewParentL)
303 NewParentL->addChildLoop(&L);
304 else
305 LI.addTopLevelLoop(&L);
307 // Remove this loops blocks from the old parent and every other loop up the
308 // nest until reaching the new parent. Also update all of these
309 // no-longer-containing loops to reflect the nesting change.
310 for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
311 OldContainingL = OldContainingL->getParentLoop()) {
312 llvm::erase_if(OldContainingL->getBlocksVector(),
313 [&](const BasicBlock *BB) {
314 return BB == &Preheader || L.contains(BB);
317 OldContainingL->getBlocksSet().erase(&Preheader);
318 for (BasicBlock *BB : L.blocks())
319 OldContainingL->getBlocksSet().erase(BB);
321 // Because we just hoisted a loop out of this one, we have essentially
322 // created new exit paths from it. That means we need to form LCSSA PHI
323 // nodes for values used in the no-longer-nested loop.
324 formLCSSA(*OldContainingL, DT, &LI, nullptr);
326 // We shouldn't need to form dedicated exits because the exit introduced
327 // here is the (just split by unswitching) preheader. However, after trivial
328 // unswitching it is possible to get new non-dedicated exits out of parent
329 // loop so let's conservatively form dedicated exit blocks and figure out
330 // if we can optimize later.
331 formDedicatedExitBlocks(OldContainingL, &DT, &LI, /*PreserveLCSSA*/ true);
335 /// Unswitch a trivial branch if the condition is loop invariant.
337 /// This routine should only be called when loop code leading to the branch has
338 /// been validated as trivial (no side effects). This routine checks if the
339 /// condition is invariant and one of the successors is a loop exit. This
340 /// allows us to unswitch without duplicating the loop, making it trivial.
342 /// If this routine fails to unswitch the branch it returns false.
344 /// If the branch can be unswitched, this routine splits the preheader and
345 /// hoists the branch above that split. Preserves loop simplified form
346 /// (splitting the exit block as necessary). It simplifies the branch within
347 /// the loop to an unconditional branch but doesn't remove it entirely. Further
348 /// cleanup can be done with some simplify-cfg like pass.
350 /// If `SE` is not null, it will be updated based on the potential loop SCEVs
351 /// invalidated by this.
352 static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
353 LoopInfo &LI, ScalarEvolution *SE,
354 MemorySSAUpdater *MSSAU) {
355 assert(BI.isConditional() && "Can only unswitch a conditional branch!");
356 LLVM_DEBUG(dbgs() << " Trying to unswitch branch: " << BI << "\n");
358 // The loop invariant values that we want to unswitch.
359 TinyPtrVector<Value *> Invariants;
361 // When true, we're fully unswitching the branch rather than just unswitching
362 // some input conditions to the branch.
363 bool FullUnswitch = false;
365 if (L.isLoopInvariant(BI.getCondition())) {
366 Invariants.push_back(BI.getCondition());
367 FullUnswitch = true;
368 } else {
369 if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition()))
370 Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
371 if (Invariants.empty())
372 // Couldn't find invariant inputs!
373 return false;
376 // Check that one of the branch's successors exits, and which one.
377 bool ExitDirection = true;
378 int LoopExitSuccIdx = 0;
379 auto *LoopExitBB = BI.getSuccessor(0);
380 if (L.contains(LoopExitBB)) {
381 ExitDirection = false;
382 LoopExitSuccIdx = 1;
383 LoopExitBB = BI.getSuccessor(1);
384 if (L.contains(LoopExitBB))
385 return false;
387 auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
388 auto *ParentBB = BI.getParent();
389 if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB))
390 return false;
392 // When unswitching only part of the branch's condition, we need the exit
393 // block to be reached directly from the partially unswitched input. This can
394 // be done when the exit block is along the true edge and the branch condition
395 // is a graph of `or` operations, or the exit block is along the false edge
396 // and the condition is a graph of `and` operations.
397 if (!FullUnswitch) {
398 if (ExitDirection) {
399 if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::Or)
400 return false;
401 } else {
402 if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::And)
403 return false;
407 LLVM_DEBUG({
408 dbgs() << " unswitching trivial invariant conditions for: " << BI
409 << "\n";
410 for (Value *Invariant : Invariants) {
411 dbgs() << " " << *Invariant << " == true";
412 if (Invariant != Invariants.back())
413 dbgs() << " ||";
414 dbgs() << "\n";
418 // If we have scalar evolutions, we need to invalidate them including this
419 // loop and the loop containing the exit block.
420 if (SE) {
421 if (Loop *ExitL = LI.getLoopFor(LoopExitBB))
422 SE->forgetLoop(ExitL);
423 else
424 // Forget the entire nest as this exits the entire nest.
425 SE->forgetTopmostLoop(&L);
428 if (MSSAU && VerifyMemorySSA)
429 MSSAU->getMemorySSA()->verifyMemorySSA();
431 // Split the preheader, so that we know that there is a safe place to insert
432 // the conditional branch. We will change the preheader to have a conditional
433 // branch on LoopCond.
434 BasicBlock *OldPH = L.getLoopPreheader();
435 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
437 // Now that we have a place to insert the conditional branch, create a place
438 // to branch to: this is the exit block out of the loop that we are
439 // unswitching. We need to split this if there are other loop predecessors.
440 // Because the loop is in simplified form, *any* other predecessor is enough.
441 BasicBlock *UnswitchedBB;
442 if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
443 assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
444 "A branch's parent isn't a predecessor!");
445 UnswitchedBB = LoopExitBB;
446 } else {
447 UnswitchedBB =
448 SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
451 if (MSSAU && VerifyMemorySSA)
452 MSSAU->getMemorySSA()->verifyMemorySSA();
454 // Actually move the invariant uses into the unswitched position. If possible,
455 // we do this by moving the instructions, but when doing partial unswitching
456 // we do it by building a new merge of the values in the unswitched position.
457 OldPH->getTerminator()->eraseFromParent();
458 if (FullUnswitch) {
459 // If fully unswitching, we can use the existing branch instruction.
460 // Splice it into the old PH to gate reaching the new preheader and re-point
461 // its successors.
462 OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
463 BI);
464 if (MSSAU) {
465 // Temporarily clone the terminator, to make MSSA update cheaper by
466 // separating "insert edge" updates from "remove edge" ones.
467 ParentBB->getInstList().push_back(BI.clone());
468 } else {
469 // Create a new unconditional branch that will continue the loop as a new
470 // terminator.
471 BranchInst::Create(ContinueBB, ParentBB);
473 BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
474 BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
475 } else {
476 // Only unswitching a subset of inputs to the condition, so we will need to
477 // build a new branch that merges the invariant inputs.
478 if (ExitDirection)
479 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
480 Instruction::Or &&
481 "Must have an `or` of `i1`s for the condition!");
482 else
483 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
484 Instruction::And &&
485 "Must have an `and` of `i1`s for the condition!");
486 buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection,
487 *UnswitchedBB, *NewPH);
490 // Update the dominator tree with the added edge.
491 DT.insertEdge(OldPH, UnswitchedBB);
493 // After the dominator tree was updated with the added edge, update MemorySSA
494 // if available.
495 if (MSSAU) {
496 SmallVector<CFGUpdate, 1> Updates;
497 Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
498 MSSAU->applyInsertUpdates(Updates, DT);
501 // Finish updating dominator tree and memory ssa for full unswitch.
502 if (FullUnswitch) {
503 if (MSSAU) {
504 // Remove the cloned branch instruction.
505 ParentBB->getTerminator()->eraseFromParent();
506 // Create unconditional branch now.
507 BranchInst::Create(ContinueBB, ParentBB);
508 MSSAU->removeEdge(ParentBB, LoopExitBB);
510 DT.deleteEdge(ParentBB, LoopExitBB);
513 if (MSSAU && VerifyMemorySSA)
514 MSSAU->getMemorySSA()->verifyMemorySSA();
516 // Rewrite the relevant PHI nodes.
517 if (UnswitchedBB == LoopExitBB)
518 rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
519 else
520 rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
521 *ParentBB, *OldPH, FullUnswitch);
523 // The constant we can replace all of our invariants with inside the loop
524 // body. If any of the invariants have a value other than this the loop won't
525 // be entered.
526 ConstantInt *Replacement = ExitDirection
527 ? ConstantInt::getFalse(BI.getContext())
528 : ConstantInt::getTrue(BI.getContext());
530 // Since this is an i1 condition we can also trivially replace uses of it
531 // within the loop with a constant.
532 for (Value *Invariant : Invariants)
533 replaceLoopInvariantUses(L, Invariant, *Replacement);
535 // If this was full unswitching, we may have changed the nesting relationship
536 // for this loop so hoist it to its correct parent if needed.
537 if (FullUnswitch)
538 hoistLoopToNewParent(L, *NewPH, DT, LI);
540 LLVM_DEBUG(dbgs() << " done: unswitching trivial branch...\n");
541 ++NumTrivial;
542 ++NumBranches;
543 return true;
546 /// Unswitch a trivial switch if the condition is loop invariant.
548 /// This routine should only be called when loop code leading to the switch has
549 /// been validated as trivial (no side effects). This routine checks if the
550 /// condition is invariant and that at least one of the successors is a loop
551 /// exit. This allows us to unswitch without duplicating the loop, making it
552 /// trivial.
554 /// If this routine fails to unswitch the switch it returns false.
556 /// If the switch can be unswitched, this routine splits the preheader and
557 /// copies the switch above that split. If the default case is one of the
558 /// exiting cases, it copies the non-exiting cases and points them at the new
559 /// preheader. If the default case is not exiting, it copies the exiting cases
560 /// and points the default at the preheader. It preserves loop simplified form
561 /// (splitting the exit blocks as necessary). It simplifies the switch within
562 /// the loop by removing now-dead cases. If the default case is one of those
563 /// unswitched, it replaces its destination with a new basic block containing
564 /// only unreachable. Such basic blocks, while technically loop exits, are not
565 /// considered for unswitching so this is a stable transform and the same
566 /// switch will not be revisited. If after unswitching there is only a single
567 /// in-loop successor, the switch is further simplified to an unconditional
568 /// branch. Still more cleanup can be done with some simplify-cfg like pass.
570 /// If `SE` is not null, it will be updated based on the potential loop SCEVs
571 /// invalidated by this.
572 static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
573 LoopInfo &LI, ScalarEvolution *SE,
574 MemorySSAUpdater *MSSAU) {
575 LLVM_DEBUG(dbgs() << " Trying to unswitch switch: " << SI << "\n");
576 Value *LoopCond = SI.getCondition();
578 // If this isn't switching on an invariant condition, we can't unswitch it.
579 if (!L.isLoopInvariant(LoopCond))
580 return false;
582 auto *ParentBB = SI.getParent();
584 SmallVector<int, 4> ExitCaseIndices;
585 for (auto Case : SI.cases()) {
586 auto *SuccBB = Case.getCaseSuccessor();
587 if (!L.contains(SuccBB) &&
588 areLoopExitPHIsLoopInvariant(L, *ParentBB, *SuccBB))
589 ExitCaseIndices.push_back(Case.getCaseIndex());
591 BasicBlock *DefaultExitBB = nullptr;
592 if (!L.contains(SI.getDefaultDest()) &&
593 areLoopExitPHIsLoopInvariant(L, *ParentBB, *SI.getDefaultDest()) &&
594 !isa<UnreachableInst>(SI.getDefaultDest()->getTerminator()))
595 DefaultExitBB = SI.getDefaultDest();
596 else if (ExitCaseIndices.empty())
597 return false;
599 LLVM_DEBUG(dbgs() << " unswitching trivial switch...\n");
601 if (MSSAU && VerifyMemorySSA)
602 MSSAU->getMemorySSA()->verifyMemorySSA();
604 // We may need to invalidate SCEVs for the outermost loop reached by any of
605 // the exits.
606 Loop *OuterL = &L;
608 if (DefaultExitBB) {
609 // Clear out the default destination temporarily to allow accurate
610 // predecessor lists to be examined below.
611 SI.setDefaultDest(nullptr);
612 // Check the loop containing this exit.
613 Loop *ExitL = LI.getLoopFor(DefaultExitBB);
614 if (!ExitL || ExitL->contains(OuterL))
615 OuterL = ExitL;
618 // Store the exit cases into a separate data structure and remove them from
619 // the switch.
620 SmallVector<std::pair<ConstantInt *, BasicBlock *>, 4> ExitCases;
621 ExitCases.reserve(ExitCaseIndices.size());
622 // We walk the case indices backwards so that we remove the last case first
623 // and don't disrupt the earlier indices.
624 for (unsigned Index : reverse(ExitCaseIndices)) {
625 auto CaseI = SI.case_begin() + Index;
626 // Compute the outer loop from this exit.
627 Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor());
628 if (!ExitL || ExitL->contains(OuterL))
629 OuterL = ExitL;
630 // Save the value of this case.
631 ExitCases.push_back({CaseI->getCaseValue(), CaseI->getCaseSuccessor()});
632 // Delete the unswitched cases.
633 SI.removeCase(CaseI);
636 if (SE) {
637 if (OuterL)
638 SE->forgetLoop(OuterL);
639 else
640 SE->forgetTopmostLoop(&L);
643 // Check if after this all of the remaining cases point at the same
644 // successor.
645 BasicBlock *CommonSuccBB = nullptr;
646 if (SI.getNumCases() > 0 &&
647 std::all_of(std::next(SI.case_begin()), SI.case_end(),
648 [&SI](const SwitchInst::CaseHandle &Case) {
649 return Case.getCaseSuccessor() ==
650 SI.case_begin()->getCaseSuccessor();
652 CommonSuccBB = SI.case_begin()->getCaseSuccessor();
653 if (!DefaultExitBB) {
654 // If we're not unswitching the default, we need it to match any cases to
655 // have a common successor or if we have no cases it is the common
656 // successor.
657 if (SI.getNumCases() == 0)
658 CommonSuccBB = SI.getDefaultDest();
659 else if (SI.getDefaultDest() != CommonSuccBB)
660 CommonSuccBB = nullptr;
663 // Split the preheader, so that we know that there is a safe place to insert
664 // the switch.
665 BasicBlock *OldPH = L.getLoopPreheader();
666 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
667 OldPH->getTerminator()->eraseFromParent();
669 // Now add the unswitched switch.
670 auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
672 // Rewrite the IR for the unswitched basic blocks. This requires two steps.
673 // First, we split any exit blocks with remaining in-loop predecessors. Then
674 // we update the PHIs in one of two ways depending on if there was a split.
675 // We walk in reverse so that we split in the same order as the cases
676 // appeared. This is purely for convenience of reading the resulting IR, but
677 // it doesn't cost anything really.
678 SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
679 SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
680 // Handle the default exit if necessary.
681 // FIXME: It'd be great if we could merge this with the loop below but LLVM's
682 // ranges aren't quite powerful enough yet.
683 if (DefaultExitBB) {
684 if (pred_empty(DefaultExitBB)) {
685 UnswitchedExitBBs.insert(DefaultExitBB);
686 rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
687 } else {
688 auto *SplitBB =
689 SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU);
690 rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
691 *ParentBB, *OldPH,
692 /*FullUnswitch*/ true);
693 DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
696 // Note that we must use a reference in the for loop so that we update the
697 // container.
698 for (auto &CasePair : reverse(ExitCases)) {
699 // Grab a reference to the exit block in the pair so that we can update it.
700 BasicBlock *ExitBB = CasePair.second;
702 // If this case is the last edge into the exit block, we can simply reuse it
703 // as it will no longer be a loop exit. No mapping necessary.
704 if (pred_empty(ExitBB)) {
705 // Only rewrite once.
706 if (UnswitchedExitBBs.insert(ExitBB).second)
707 rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
708 continue;
711 // Otherwise we need to split the exit block so that we retain an exit
712 // block from the loop and a target for the unswitched condition.
713 BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
714 if (!SplitExitBB) {
715 // If this is the first time we see this, do the split and remember it.
716 SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
717 rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
718 *ParentBB, *OldPH,
719 /*FullUnswitch*/ true);
721 // Update the case pair to point to the split block.
722 CasePair.second = SplitExitBB;
725 // Now add the unswitched cases. We do this in reverse order as we built them
726 // in reverse order.
727 for (auto CasePair : reverse(ExitCases)) {
728 ConstantInt *CaseVal = CasePair.first;
729 BasicBlock *UnswitchedBB = CasePair.second;
731 NewSI->addCase(CaseVal, UnswitchedBB);
734 // If the default was unswitched, re-point it and add explicit cases for
735 // entering the loop.
736 if (DefaultExitBB) {
737 NewSI->setDefaultDest(DefaultExitBB);
739 // We removed all the exit cases, so we just copy the cases to the
740 // unswitched switch.
741 for (auto Case : SI.cases())
742 NewSI->addCase(Case.getCaseValue(), NewPH);
745 // If we ended up with a common successor for every path through the switch
746 // after unswitching, rewrite it to an unconditional branch to make it easy
747 // to recognize. Otherwise we potentially have to recognize the default case
748 // pointing at unreachable and other complexity.
749 if (CommonSuccBB) {
750 BasicBlock *BB = SI.getParent();
751 // We may have had multiple edges to this common successor block, so remove
752 // them as predecessors. We skip the first one, either the default or the
753 // actual first case.
754 bool SkippedFirst = DefaultExitBB == nullptr;
755 for (auto Case : SI.cases()) {
756 assert(Case.getCaseSuccessor() == CommonSuccBB &&
757 "Non-common successor!");
758 (void)Case;
759 if (!SkippedFirst) {
760 SkippedFirst = true;
761 continue;
763 CommonSuccBB->removePredecessor(BB,
764 /*KeepOneInputPHIs*/ true);
766 // Now nuke the switch and replace it with a direct branch.
767 SI.eraseFromParent();
768 BranchInst::Create(CommonSuccBB, BB);
769 } else if (DefaultExitBB) {
770 assert(SI.getNumCases() > 0 &&
771 "If we had no cases we'd have a common successor!");
772 // Move the last case to the default successor. This is valid as if the
773 // default got unswitched it cannot be reached. This has the advantage of
774 // being simple and keeping the number of edges from this switch to
775 // successors the same, and avoiding any PHI update complexity.
776 auto LastCaseI = std::prev(SI.case_end());
777 SI.setDefaultDest(LastCaseI->getCaseSuccessor());
778 SI.removeCase(LastCaseI);
781 // Walk the unswitched exit blocks and the unswitched split blocks and update
782 // the dominator tree based on the CFG edits. While we are walking unordered
783 // containers here, the API for applyUpdates takes an unordered list of
784 // updates and requires them to not contain duplicates.
785 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
786 for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
787 DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
788 DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
790 for (auto SplitUnswitchedPair : SplitExitBBMap) {
791 auto *UnswitchedBB = SplitUnswitchedPair.second;
792 DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedBB});
793 DTUpdates.push_back({DT.Insert, OldPH, UnswitchedBB});
795 DT.applyUpdates(DTUpdates);
797 if (MSSAU) {
798 MSSAU->applyUpdates(DTUpdates, DT);
799 if (VerifyMemorySSA)
800 MSSAU->getMemorySSA()->verifyMemorySSA();
803 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
805 // We may have changed the nesting relationship for this loop so hoist it to
806 // its correct parent if needed.
807 hoistLoopToNewParent(L, *NewPH, DT, LI);
809 ++NumTrivial;
810 ++NumSwitches;
811 LLVM_DEBUG(dbgs() << " done: unswitching trivial switch...\n");
812 return true;
815 /// This routine scans the loop to find a branch or switch which occurs before
816 /// any side effects occur. These can potentially be unswitched without
817 /// duplicating the loop. If a branch or switch is successfully unswitched the
818 /// scanning continues to see if subsequent branches or switches have become
819 /// trivial. Once all trivial candidates have been unswitched, this routine
820 /// returns.
822 /// The return value indicates whether anything was unswitched (and therefore
823 /// changed).
825 /// If `SE` is not null, it will be updated based on the potential loop SCEVs
826 /// invalidated by this.
827 static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
828 LoopInfo &LI, ScalarEvolution *SE,
829 MemorySSAUpdater *MSSAU) {
830 bool Changed = false;
832 // If loop header has only one reachable successor we should keep looking for
833 // trivial condition candidates in the successor as well. An alternative is
834 // to constant fold conditions and merge successors into loop header (then we
835 // only need to check header's terminator). The reason for not doing this in
836 // LoopUnswitch pass is that it could potentially break LoopPassManager's
837 // invariants. Folding dead branches could either eliminate the current loop
838 // or make other loops unreachable. LCSSA form might also not be preserved
839 // after deleting branches. The following code keeps traversing loop header's
840 // successors until it finds the trivial condition candidate (condition that
841 // is not a constant). Since unswitching generates branches with constant
842 // conditions, this scenario could be very common in practice.
843 BasicBlock *CurrentBB = L.getHeader();
844 SmallPtrSet<BasicBlock *, 8> Visited;
845 Visited.insert(CurrentBB);
846 do {
847 // Check if there are any side-effecting instructions (e.g. stores, calls,
848 // volatile loads) in the part of the loop that the code *would* execute
849 // without unswitching.
850 if (MSSAU) // Possible early exit with MSSA
851 if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB))
852 if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
853 return Changed;
854 if (llvm::any_of(*CurrentBB,
855 [](Instruction &I) { return I.mayHaveSideEffects(); }))
856 return Changed;
858 Instruction *CurrentTerm = CurrentBB->getTerminator();
860 if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
861 // Don't bother trying to unswitch past a switch with a constant
862 // condition. This should be removed prior to running this pass by
863 // simplify-cfg.
864 if (isa<Constant>(SI->getCondition()))
865 return Changed;
867 if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
868 // Couldn't unswitch this one so we're done.
869 return Changed;
871 // Mark that we managed to unswitch something.
872 Changed = true;
874 // If unswitching turned the terminator into an unconditional branch then
875 // we can continue. The unswitching logic specifically works to fold any
876 // cases it can into an unconditional branch to make it easier to
877 // recognize here.
878 auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
879 if (!BI || BI->isConditional())
880 return Changed;
882 CurrentBB = BI->getSuccessor(0);
883 continue;
886 auto *BI = dyn_cast<BranchInst>(CurrentTerm);
887 if (!BI)
888 // We do not understand other terminator instructions.
889 return Changed;
891 // Don't bother trying to unswitch past an unconditional branch or a branch
892 // with a constant value. These should be removed by simplify-cfg prior to
893 // running this pass.
894 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
895 return Changed;
897 // Found a trivial condition candidate: non-foldable conditional branch. If
898 // we fail to unswitch this, we can't do anything else that is trivial.
899 if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU))
900 return Changed;
902 // Mark that we managed to unswitch something.
903 Changed = true;
905 // If we only unswitched some of the conditions feeding the branch, we won't
906 // have collapsed it to a single successor.
907 BI = cast<BranchInst>(CurrentBB->getTerminator());
908 if (BI->isConditional())
909 return Changed;
911 // Follow the newly unconditional branch into its successor.
912 CurrentBB = BI->getSuccessor(0);
914 // When continuing, if we exit the loop or reach a previous visited block,
915 // then we can not reach any trivial condition candidates (unfoldable
916 // branch instructions or switch instructions) and no unswitch can happen.
917 } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
919 return Changed;
922 /// Build the cloned blocks for an unswitched copy of the given loop.
924 /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
925 /// after the split block (`SplitBB`) that will be used to select between the
926 /// cloned and original loop.
928 /// This routine handles cloning all of the necessary loop blocks and exit
929 /// blocks including rewriting their instructions and the relevant PHI nodes.
930 /// Any loop blocks or exit blocks which are dominated by a different successor
931 /// than the one for this clone of the loop blocks can be trivially skipped. We
932 /// use the `DominatingSucc` map to determine whether a block satisfies that
933 /// property with a simple map lookup.
935 /// It also correctly creates the unconditional branch in the cloned
936 /// unswitched parent block to only point at the unswitched successor.
938 /// This does not handle most of the necessary updates to `LoopInfo`. Only exit
939 /// block splitting is correctly reflected in `LoopInfo`, essentially all of
940 /// the cloned blocks (and their loops) are left without full `LoopInfo`
941 /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
942 /// blocks to them but doesn't create the cloned `DominatorTree` structure and
943 /// instead the caller must recompute an accurate DT. It *does* correctly
944 /// update the `AssumptionCache` provided in `AC`.
945 static BasicBlock *buildClonedLoopBlocks(
946 Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
947 ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
948 BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
949 const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
950 ValueToValueMapTy &VMap,
951 SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
952 DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
953 SmallVector<BasicBlock *, 4> NewBlocks;
954 NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
956 // We will need to clone a bunch of blocks, wrap up the clone operation in
957 // a helper.
958 auto CloneBlock = [&](BasicBlock *OldBB) {
959 // Clone the basic block and insert it before the new preheader.
960 BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
961 NewBB->moveBefore(LoopPH);
963 // Record this block and the mapping.
964 NewBlocks.push_back(NewBB);
965 VMap[OldBB] = NewBB;
967 return NewBB;
970 // We skip cloning blocks when they have a dominating succ that is not the
971 // succ we are cloning for.
972 auto SkipBlock = [&](BasicBlock *BB) {
973 auto It = DominatingSucc.find(BB);
974 return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
977 // First, clone the preheader.
978 auto *ClonedPH = CloneBlock(LoopPH);
980 // Then clone all the loop blocks, skipping the ones that aren't necessary.
981 for (auto *LoopBB : L.blocks())
982 if (!SkipBlock(LoopBB))
983 CloneBlock(LoopBB);
985 // Split all the loop exit edges so that when we clone the exit blocks, if
986 // any of the exit blocks are *also* a preheader for some other loop, we
987 // don't create multiple predecessors entering the loop header.
988 for (auto *ExitBB : ExitBlocks) {
989 if (SkipBlock(ExitBB))
990 continue;
992 // When we are going to clone an exit, we don't need to clone all the
993 // instructions in the exit block and we want to ensure we have an easy
994 // place to merge the CFG, so split the exit first. This is always safe to
995 // do because there cannot be any non-loop predecessors of a loop exit in
996 // loop simplified form.
997 auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
999 // Rearrange the names to make it easier to write test cases by having the
1000 // exit block carry the suffix rather than the merge block carrying the
1001 // suffix.
1002 MergeBB->takeName(ExitBB);
1003 ExitBB->setName(Twine(MergeBB->getName()) + ".split");
1005 // Now clone the original exit block.
1006 auto *ClonedExitBB = CloneBlock(ExitBB);
1007 assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
1008 "Exit block should have been split to have one successor!");
1009 assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
1010 "Cloned exit block has the wrong successor!");
1012 // Remap any cloned instructions and create a merge phi node for them.
1013 for (auto ZippedInsts : llvm::zip_first(
1014 llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
1015 llvm::make_range(ClonedExitBB->begin(),
1016 std::prev(ClonedExitBB->end())))) {
1017 Instruction &I = std::get<0>(ZippedInsts);
1018 Instruction &ClonedI = std::get<1>(ZippedInsts);
1020 // The only instructions in the exit block should be PHI nodes and
1021 // potentially a landing pad.
1022 assert(
1023 (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
1024 "Bad instruction in exit block!");
1025 // We should have a value map between the instruction and its clone.
1026 assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
1028 auto *MergePN =
1029 PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
1030 &*MergeBB->getFirstInsertionPt());
1031 I.replaceAllUsesWith(MergePN);
1032 MergePN->addIncoming(&I, ExitBB);
1033 MergePN->addIncoming(&ClonedI, ClonedExitBB);
1037 // Rewrite the instructions in the cloned blocks to refer to the instructions
1038 // in the cloned blocks. We have to do this as a second pass so that we have
1039 // everything available. Also, we have inserted new instructions which may
1040 // include assume intrinsics, so we update the assumption cache while
1041 // processing this.
1042 for (auto *ClonedBB : NewBlocks)
1043 for (Instruction &I : *ClonedBB) {
1044 RemapInstruction(&I, VMap,
1045 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1046 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1047 if (II->getIntrinsicID() == Intrinsic::assume)
1048 AC.registerAssumption(II);
1051 // Update any PHI nodes in the cloned successors of the skipped blocks to not
1052 // have spurious incoming values.
1053 for (auto *LoopBB : L.blocks())
1054 if (SkipBlock(LoopBB))
1055 for (auto *SuccBB : successors(LoopBB))
1056 if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
1057 for (PHINode &PN : ClonedSuccBB->phis())
1058 PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
1060 // Remove the cloned parent as a predecessor of any successor we ended up
1061 // cloning other than the unswitched one.
1062 auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
1063 for (auto *SuccBB : successors(ParentBB)) {
1064 if (SuccBB == UnswitchedSuccBB)
1065 continue;
1067 auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
1068 if (!ClonedSuccBB)
1069 continue;
1071 ClonedSuccBB->removePredecessor(ClonedParentBB,
1072 /*KeepOneInputPHIs*/ true);
1075 // Replace the cloned branch with an unconditional branch to the cloned
1076 // unswitched successor.
1077 auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
1078 ClonedParentBB->getTerminator()->eraseFromParent();
1079 BranchInst::Create(ClonedSuccBB, ClonedParentBB);
1081 // If there are duplicate entries in the PHI nodes because of multiple edges
1082 // to the unswitched successor, we need to nuke all but one as we replaced it
1083 // with a direct branch.
1084 for (PHINode &PN : ClonedSuccBB->phis()) {
1085 bool Found = false;
1086 // Loop over the incoming operands backwards so we can easily delete as we
1087 // go without invalidating the index.
1088 for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
1089 if (PN.getIncomingBlock(i) != ClonedParentBB)
1090 continue;
1091 if (!Found) {
1092 Found = true;
1093 continue;
1095 PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
1099 // Record the domtree updates for the new blocks.
1100 SmallPtrSet<BasicBlock *, 4> SuccSet;
1101 for (auto *ClonedBB : NewBlocks) {
1102 for (auto *SuccBB : successors(ClonedBB))
1103 if (SuccSet.insert(SuccBB).second)
1104 DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
1105 SuccSet.clear();
1108 return ClonedPH;
1111 /// Recursively clone the specified loop and all of its children.
1113 /// The target parent loop for the clone should be provided, or can be null if
1114 /// the clone is a top-level loop. While cloning, all the blocks are mapped
1115 /// with the provided value map. The entire original loop must be present in
1116 /// the value map. The cloned loop is returned.
1117 static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
1118 const ValueToValueMapTy &VMap, LoopInfo &LI) {
1119 auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
1120 assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
1121 ClonedL.reserveBlocks(OrigL.getNumBlocks());
1122 for (auto *BB : OrigL.blocks()) {
1123 auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
1124 ClonedL.addBlockEntry(ClonedBB);
1125 if (LI.getLoopFor(BB) == &OrigL)
1126 LI.changeLoopFor(ClonedBB, &ClonedL);
1130 // We specially handle the first loop because it may get cloned into
1131 // a different parent and because we most commonly are cloning leaf loops.
1132 Loop *ClonedRootL = LI.AllocateLoop();
1133 if (RootParentL)
1134 RootParentL->addChildLoop(ClonedRootL);
1135 else
1136 LI.addTopLevelLoop(ClonedRootL);
1137 AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1139 if (OrigRootL.empty())
1140 return ClonedRootL;
1142 // If we have a nest, we can quickly clone the entire loop nest using an
1143 // iterative approach because it is a tree. We keep the cloned parent in the
1144 // data structure to avoid repeatedly querying through a map to find it.
1145 SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1146 // Build up the loops to clone in reverse order as we'll clone them from the
1147 // back.
1148 for (Loop *ChildL : llvm::reverse(OrigRootL))
1149 LoopsToClone.push_back({ClonedRootL, ChildL});
1150 do {
1151 Loop *ClonedParentL, *L;
1152 std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1153 Loop *ClonedL = LI.AllocateLoop();
1154 ClonedParentL->addChildLoop(ClonedL);
1155 AddClonedBlocksToLoop(*L, *ClonedL);
1156 for (Loop *ChildL : llvm::reverse(*L))
1157 LoopsToClone.push_back({ClonedL, ChildL});
1158 } while (!LoopsToClone.empty());
1160 return ClonedRootL;
1163 /// Build the cloned loops of an original loop from unswitching.
1165 /// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1166 /// operation. We need to re-verify that there even is a loop (as the backedge
1167 /// may not have been cloned), and even if there are remaining backedges the
1168 /// backedge set may be different. However, we know that each child loop is
1169 /// undisturbed, we only need to find where to place each child loop within
1170 /// either any parent loop or within a cloned version of the original loop.
1172 /// Because child loops may end up cloned outside of any cloned version of the
1173 /// original loop, multiple cloned sibling loops may be created. All of them
1174 /// are returned so that the newly introduced loop nest roots can be
1175 /// identified.
1176 static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1177 const ValueToValueMapTy &VMap, LoopInfo &LI,
1178 SmallVectorImpl<Loop *> &NonChildClonedLoops) {
1179 Loop *ClonedL = nullptr;
1181 auto *OrigPH = OrigL.getLoopPreheader();
1182 auto *OrigHeader = OrigL.getHeader();
1184 auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1185 auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1187 // We need to know the loops of the cloned exit blocks to even compute the
1188 // accurate parent loop. If we only clone exits to some parent of the
1189 // original parent, we want to clone into that outer loop. We also keep track
1190 // of the loops that our cloned exit blocks participate in.
1191 Loop *ParentL = nullptr;
1192 SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1193 SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1194 ClonedExitsInLoops.reserve(ExitBlocks.size());
1195 for (auto *ExitBB : ExitBlocks)
1196 if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1197 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1198 ExitLoopMap[ClonedExitBB] = ExitL;
1199 ClonedExitsInLoops.push_back(ClonedExitBB);
1200 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1201 ParentL = ExitL;
1203 assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1204 ParentL->contains(OrigL.getParentLoop())) &&
1205 "The computed parent loop should always contain (or be) the parent of "
1206 "the original loop.");
1208 // We build the set of blocks dominated by the cloned header from the set of
1209 // cloned blocks out of the original loop. While not all of these will
1210 // necessarily be in the cloned loop, it is enough to establish that they
1211 // aren't in unreachable cycles, etc.
1212 SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1213 for (auto *BB : OrigL.blocks())
1214 if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1215 ClonedLoopBlocks.insert(ClonedBB);
1217 // Rebuild the set of blocks that will end up in the cloned loop. We may have
1218 // skipped cloning some region of this loop which can in turn skip some of
1219 // the backedges so we have to rebuild the blocks in the loop based on the
1220 // backedges that remain after cloning.
1221 SmallVector<BasicBlock *, 16> Worklist;
1222 SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1223 for (auto *Pred : predecessors(ClonedHeader)) {
1224 // The only possible non-loop header predecessor is the preheader because
1225 // we know we cloned the loop in simplified form.
1226 if (Pred == ClonedPH)
1227 continue;
1229 // Because the loop was in simplified form, the only non-loop predecessor
1230 // should be the preheader.
1231 assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1232 "header other than the preheader "
1233 "that is not part of the loop!");
1235 // Insert this block into the loop set and on the first visit (and if it
1236 // isn't the header we're currently walking) put it into the worklist to
1237 // recurse through.
1238 if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1239 Worklist.push_back(Pred);
1242 // If we had any backedges then there *is* a cloned loop. Put the header into
1243 // the loop set and then walk the worklist backwards to find all the blocks
1244 // that remain within the loop after cloning.
1245 if (!BlocksInClonedLoop.empty()) {
1246 BlocksInClonedLoop.insert(ClonedHeader);
1248 while (!Worklist.empty()) {
1249 BasicBlock *BB = Worklist.pop_back_val();
1250 assert(BlocksInClonedLoop.count(BB) &&
1251 "Didn't put block into the loop set!");
1253 // Insert any predecessors that are in the possible set into the cloned
1254 // set, and if the insert is successful, add them to the worklist. Note
1255 // that we filter on the blocks that are definitely reachable via the
1256 // backedge to the loop header so we may prune out dead code within the
1257 // cloned loop.
1258 for (auto *Pred : predecessors(BB))
1259 if (ClonedLoopBlocks.count(Pred) &&
1260 BlocksInClonedLoop.insert(Pred).second)
1261 Worklist.push_back(Pred);
1264 ClonedL = LI.AllocateLoop();
1265 if (ParentL) {
1266 ParentL->addBasicBlockToLoop(ClonedPH, LI);
1267 ParentL->addChildLoop(ClonedL);
1268 } else {
1269 LI.addTopLevelLoop(ClonedL);
1271 NonChildClonedLoops.push_back(ClonedL);
1273 ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1274 // We don't want to just add the cloned loop blocks based on how we
1275 // discovered them. The original order of blocks was carefully built in
1276 // a way that doesn't rely on predecessor ordering. Rather than re-invent
1277 // that logic, we just re-walk the original blocks (and those of the child
1278 // loops) and filter them as we add them into the cloned loop.
1279 for (auto *BB : OrigL.blocks()) {
1280 auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1281 if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1282 continue;
1284 // Directly add the blocks that are only in this loop.
1285 if (LI.getLoopFor(BB) == &OrigL) {
1286 ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1287 continue;
1290 // We want to manually add it to this loop and parents.
1291 // Registering it with LoopInfo will happen when we clone the top
1292 // loop for this block.
1293 for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1294 PL->addBlockEntry(ClonedBB);
1297 // Now add each child loop whose header remains within the cloned loop. All
1298 // of the blocks within the loop must satisfy the same constraints as the
1299 // header so once we pass the header checks we can just clone the entire
1300 // child loop nest.
1301 for (Loop *ChildL : OrigL) {
1302 auto *ClonedChildHeader =
1303 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1304 if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1305 continue;
1307 #ifndef NDEBUG
1308 // We should never have a cloned child loop header but fail to have
1309 // all of the blocks for that child loop.
1310 for (auto *ChildLoopBB : ChildL->blocks())
1311 assert(BlocksInClonedLoop.count(
1312 cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1313 "Child cloned loop has a header within the cloned outer "
1314 "loop but not all of its blocks!");
1315 #endif
1317 cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1321 // Now that we've handled all the components of the original loop that were
1322 // cloned into a new loop, we still need to handle anything from the original
1323 // loop that wasn't in a cloned loop.
1325 // Figure out what blocks are left to place within any loop nest containing
1326 // the unswitched loop. If we never formed a loop, the cloned PH is one of
1327 // them.
1328 SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1329 if (BlocksInClonedLoop.empty())
1330 UnloopedBlockSet.insert(ClonedPH);
1331 for (auto *ClonedBB : ClonedLoopBlocks)
1332 if (!BlocksInClonedLoop.count(ClonedBB))
1333 UnloopedBlockSet.insert(ClonedBB);
1335 // Copy the cloned exits and sort them in ascending loop depth, we'll work
1336 // backwards across these to process them inside out. The order shouldn't
1337 // matter as we're just trying to build up the map from inside-out; we use
1338 // the map in a more stably ordered way below.
1339 auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
1340 llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1341 return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1342 ExitLoopMap.lookup(RHS)->getLoopDepth();
1345 // Populate the existing ExitLoopMap with everything reachable from each
1346 // exit, starting from the inner most exit.
1347 while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1348 assert(Worklist.empty() && "Didn't clear worklist!");
1350 BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1351 Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1353 // Walk the CFG back until we hit the cloned PH adding everything reachable
1354 // and in the unlooped set to this exit block's loop.
1355 Worklist.push_back(ExitBB);
1356 do {
1357 BasicBlock *BB = Worklist.pop_back_val();
1358 // We can stop recursing at the cloned preheader (if we get there).
1359 if (BB == ClonedPH)
1360 continue;
1362 for (BasicBlock *PredBB : predecessors(BB)) {
1363 // If this pred has already been moved to our set or is part of some
1364 // (inner) loop, no update needed.
1365 if (!UnloopedBlockSet.erase(PredBB)) {
1366 assert(
1367 (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1368 "Predecessor not mapped to a loop!");
1369 continue;
1372 // We just insert into the loop set here. We'll add these blocks to the
1373 // exit loop after we build up the set in an order that doesn't rely on
1374 // predecessor order (which in turn relies on use list order).
1375 bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1376 (void)Inserted;
1377 assert(Inserted && "Should only visit an unlooped block once!");
1379 // And recurse through to its predecessors.
1380 Worklist.push_back(PredBB);
1382 } while (!Worklist.empty());
1385 // Now that the ExitLoopMap gives as mapping for all the non-looping cloned
1386 // blocks to their outer loops, walk the cloned blocks and the cloned exits
1387 // in their original order adding them to the correct loop.
1389 // We need a stable insertion order. We use the order of the original loop
1390 // order and map into the correct parent loop.
1391 for (auto *BB : llvm::concat<BasicBlock *const>(
1392 makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1393 if (Loop *OuterL = ExitLoopMap.lookup(BB))
1394 OuterL->addBasicBlockToLoop(BB, LI);
1396 #ifndef NDEBUG
1397 for (auto &BBAndL : ExitLoopMap) {
1398 auto *BB = BBAndL.first;
1399 auto *OuterL = BBAndL.second;
1400 assert(LI.getLoopFor(BB) == OuterL &&
1401 "Failed to put all blocks into outer loops!");
1403 #endif
1405 // Now that all the blocks are placed into the correct containing loop in the
1406 // absence of child loops, find all the potentially cloned child loops and
1407 // clone them into whatever outer loop we placed their header into.
1408 for (Loop *ChildL : OrigL) {
1409 auto *ClonedChildHeader =
1410 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1411 if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1412 continue;
1414 #ifndef NDEBUG
1415 for (auto *ChildLoopBB : ChildL->blocks())
1416 assert(VMap.count(ChildLoopBB) &&
1417 "Cloned a child loop header but not all of that loops blocks!");
1418 #endif
1420 NonChildClonedLoops.push_back(cloneLoopNest(
1421 *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1425 static void
1426 deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1427 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
1428 DominatorTree &DT, MemorySSAUpdater *MSSAU) {
1429 // Find all the dead clones, and remove them from their successors.
1430 SmallVector<BasicBlock *, 16> DeadBlocks;
1431 for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1432 for (auto &VMap : VMaps)
1433 if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
1434 if (!DT.isReachableFromEntry(ClonedBB)) {
1435 for (BasicBlock *SuccBB : successors(ClonedBB))
1436 SuccBB->removePredecessor(ClonedBB);
1437 DeadBlocks.push_back(ClonedBB);
1440 // Remove all MemorySSA in the dead blocks
1441 if (MSSAU) {
1442 SmallPtrSet<BasicBlock *, 16> DeadBlockSet(DeadBlocks.begin(),
1443 DeadBlocks.end());
1444 MSSAU->removeBlocks(DeadBlockSet);
1447 // Drop any remaining references to break cycles.
1448 for (BasicBlock *BB : DeadBlocks)
1449 BB->dropAllReferences();
1450 // Erase them from the IR.
1451 for (BasicBlock *BB : DeadBlocks)
1452 BB->eraseFromParent();
1455 static void deleteDeadBlocksFromLoop(Loop &L,
1456 SmallVectorImpl<BasicBlock *> &ExitBlocks,
1457 DominatorTree &DT, LoopInfo &LI,
1458 MemorySSAUpdater *MSSAU) {
1459 // Find all the dead blocks tied to this loop, and remove them from their
1460 // successors.
1461 SmallPtrSet<BasicBlock *, 16> DeadBlockSet;
1463 // Start with loop/exit blocks and get a transitive closure of reachable dead
1464 // blocks.
1465 SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(),
1466 ExitBlocks.end());
1467 DeathCandidates.append(L.blocks().begin(), L.blocks().end());
1468 while (!DeathCandidates.empty()) {
1469 auto *BB = DeathCandidates.pop_back_val();
1470 if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) {
1471 for (BasicBlock *SuccBB : successors(BB)) {
1472 SuccBB->removePredecessor(BB);
1473 DeathCandidates.push_back(SuccBB);
1475 DeadBlockSet.insert(BB);
1479 // Remove all MemorySSA in the dead blocks
1480 if (MSSAU)
1481 MSSAU->removeBlocks(DeadBlockSet);
1483 // Filter out the dead blocks from the exit blocks list so that it can be
1484 // used in the caller.
1485 llvm::erase_if(ExitBlocks,
1486 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1488 // Walk from this loop up through its parents removing all of the dead blocks.
1489 for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
1490 for (auto *BB : DeadBlockSet)
1491 ParentL->getBlocksSet().erase(BB);
1492 llvm::erase_if(ParentL->getBlocksVector(),
1493 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1496 // Now delete the dead child loops. This raw delete will clear them
1497 // recursively.
1498 llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
1499 if (!DeadBlockSet.count(ChildL->getHeader()))
1500 return false;
1502 assert(llvm::all_of(ChildL->blocks(),
1503 [&](BasicBlock *ChildBB) {
1504 return DeadBlockSet.count(ChildBB);
1505 }) &&
1506 "If the child loop header is dead all blocks in the child loop must "
1507 "be dead as well!");
1508 LI.destroy(ChildL);
1509 return true;
1512 // Remove the loop mappings for the dead blocks and drop all the references
1513 // from these blocks to others to handle cyclic references as we start
1514 // deleting the blocks themselves.
1515 for (auto *BB : DeadBlockSet) {
1516 // Check that the dominator tree has already been updated.
1517 assert(!DT.getNode(BB) && "Should already have cleared domtree!");
1518 LI.changeLoopFor(BB, nullptr);
1519 BB->dropAllReferences();
1522 // Actually delete the blocks now that they've been fully unhooked from the
1523 // IR.
1524 for (auto *BB : DeadBlockSet)
1525 BB->eraseFromParent();
1528 /// Recompute the set of blocks in a loop after unswitching.
1530 /// This walks from the original headers predecessors to rebuild the loop. We
1531 /// take advantage of the fact that new blocks can't have been added, and so we
1532 /// filter by the original loop's blocks. This also handles potentially
1533 /// unreachable code that we don't want to explore but might be found examining
1534 /// the predecessors of the header.
1536 /// If the original loop is no longer a loop, this will return an empty set. If
1537 /// it remains a loop, all the blocks within it will be added to the set
1538 /// (including those blocks in inner loops).
1539 static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1540 LoopInfo &LI) {
1541 SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1543 auto *PH = L.getLoopPreheader();
1544 auto *Header = L.getHeader();
1546 // A worklist to use while walking backwards from the header.
1547 SmallVector<BasicBlock *, 16> Worklist;
1549 // First walk the predecessors of the header to find the backedges. This will
1550 // form the basis of our walk.
1551 for (auto *Pred : predecessors(Header)) {
1552 // Skip the preheader.
1553 if (Pred == PH)
1554 continue;
1556 // Because the loop was in simplified form, the only non-loop predecessor
1557 // is the preheader.
1558 assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1559 "than the preheader that is not part of the "
1560 "loop!");
1562 // Insert this block into the loop set and on the first visit and, if it
1563 // isn't the header we're currently walking, put it into the worklist to
1564 // recurse through.
1565 if (LoopBlockSet.insert(Pred).second && Pred != Header)
1566 Worklist.push_back(Pred);
1569 // If no backedges were found, we're done.
1570 if (LoopBlockSet.empty())
1571 return LoopBlockSet;
1573 // We found backedges, recurse through them to identify the loop blocks.
1574 while (!Worklist.empty()) {
1575 BasicBlock *BB = Worklist.pop_back_val();
1576 assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1578 // No need to walk past the header.
1579 if (BB == Header)
1580 continue;
1582 // Because we know the inner loop structure remains valid we can use the
1583 // loop structure to jump immediately across the entire nested loop.
1584 // Further, because it is in loop simplified form, we can directly jump
1585 // to its preheader afterward.
1586 if (Loop *InnerL = LI.getLoopFor(BB))
1587 if (InnerL != &L) {
1588 assert(L.contains(InnerL) &&
1589 "Should not reach a loop *outside* this loop!");
1590 // The preheader is the only possible predecessor of the loop so
1591 // insert it into the set and check whether it was already handled.
1592 auto *InnerPH = InnerL->getLoopPreheader();
1593 assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1594 "but not contain the inner loop "
1595 "preheader!");
1596 if (!LoopBlockSet.insert(InnerPH).second)
1597 // The only way to reach the preheader is through the loop body
1598 // itself so if it has been visited the loop is already handled.
1599 continue;
1601 // Insert all of the blocks (other than those already present) into
1602 // the loop set. We expect at least the block that led us to find the
1603 // inner loop to be in the block set, but we may also have other loop
1604 // blocks if they were already enqueued as predecessors of some other
1605 // outer loop block.
1606 for (auto *InnerBB : InnerL->blocks()) {
1607 if (InnerBB == BB) {
1608 assert(LoopBlockSet.count(InnerBB) &&
1609 "Block should already be in the set!");
1610 continue;
1613 LoopBlockSet.insert(InnerBB);
1616 // Add the preheader to the worklist so we will continue past the
1617 // loop body.
1618 Worklist.push_back(InnerPH);
1619 continue;
1622 // Insert any predecessors that were in the original loop into the new
1623 // set, and if the insert is successful, add them to the worklist.
1624 for (auto *Pred : predecessors(BB))
1625 if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1626 Worklist.push_back(Pred);
1629 assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
1631 // We've found all the blocks participating in the loop, return our completed
1632 // set.
1633 return LoopBlockSet;
1636 /// Rebuild a loop after unswitching removes some subset of blocks and edges.
1638 /// The removal may have removed some child loops entirely but cannot have
1639 /// disturbed any remaining child loops. However, they may need to be hoisted
1640 /// to the parent loop (or to be top-level loops). The original loop may be
1641 /// completely removed.
1643 /// The sibling loops resulting from this update are returned. If the original
1644 /// loop remains a valid loop, it will be the first entry in this list with all
1645 /// of the newly sibling loops following it.
1647 /// Returns true if the loop remains a loop after unswitching, and false if it
1648 /// is no longer a loop after unswitching (and should not continue to be
1649 /// referenced).
1650 static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1651 LoopInfo &LI,
1652 SmallVectorImpl<Loop *> &HoistedLoops) {
1653 auto *PH = L.getLoopPreheader();
1655 // Compute the actual parent loop from the exit blocks. Because we may have
1656 // pruned some exits the loop may be different from the original parent.
1657 Loop *ParentL = nullptr;
1658 SmallVector<Loop *, 4> ExitLoops;
1659 SmallVector<BasicBlock *, 4> ExitsInLoops;
1660 ExitsInLoops.reserve(ExitBlocks.size());
1661 for (auto *ExitBB : ExitBlocks)
1662 if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1663 ExitLoops.push_back(ExitL);
1664 ExitsInLoops.push_back(ExitBB);
1665 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1666 ParentL = ExitL;
1669 // Recompute the blocks participating in this loop. This may be empty if it
1670 // is no longer a loop.
1671 auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1673 // If we still have a loop, we need to re-set the loop's parent as the exit
1674 // block set changing may have moved it within the loop nest. Note that this
1675 // can only happen when this loop has a parent as it can only hoist the loop
1676 // *up* the nest.
1677 if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1678 // Remove this loop's (original) blocks from all of the intervening loops.
1679 for (Loop *IL = L.getParentLoop(); IL != ParentL;
1680 IL = IL->getParentLoop()) {
1681 IL->getBlocksSet().erase(PH);
1682 for (auto *BB : L.blocks())
1683 IL->getBlocksSet().erase(BB);
1684 llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1685 return BB == PH || L.contains(BB);
1689 LI.changeLoopFor(PH, ParentL);
1690 L.getParentLoop()->removeChildLoop(&L);
1691 if (ParentL)
1692 ParentL->addChildLoop(&L);
1693 else
1694 LI.addTopLevelLoop(&L);
1697 // Now we update all the blocks which are no longer within the loop.
1698 auto &Blocks = L.getBlocksVector();
1699 auto BlocksSplitI =
1700 LoopBlockSet.empty()
1701 ? Blocks.begin()
1702 : std::stable_partition(
1703 Blocks.begin(), Blocks.end(),
1704 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1706 // Before we erase the list of unlooped blocks, build a set of them.
1707 SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1708 if (LoopBlockSet.empty())
1709 UnloopedBlocks.insert(PH);
1711 // Now erase these blocks from the loop.
1712 for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1713 L.getBlocksSet().erase(BB);
1714 Blocks.erase(BlocksSplitI, Blocks.end());
1716 // Sort the exits in ascending loop depth, we'll work backwards across these
1717 // to process them inside out.
1718 std::stable_sort(ExitsInLoops.begin(), ExitsInLoops.end(),
1719 [&](BasicBlock *LHS, BasicBlock *RHS) {
1720 return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1723 // We'll build up a set for each exit loop.
1724 SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1725 Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1727 auto RemoveUnloopedBlocksFromLoop =
1728 [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1729 for (auto *BB : UnloopedBlocks)
1730 L.getBlocksSet().erase(BB);
1731 llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1732 return UnloopedBlocks.count(BB);
1736 SmallVector<BasicBlock *, 16> Worklist;
1737 while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1738 assert(Worklist.empty() && "Didn't clear worklist!");
1739 assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1741 // Grab the next exit block, in decreasing loop depth order.
1742 BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1743 Loop &ExitL = *LI.getLoopFor(ExitBB);
1744 assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1746 // Erase all of the unlooped blocks from the loops between the previous
1747 // exit loop and this exit loop. This works because the ExitInLoops list is
1748 // sorted in increasing order of loop depth and thus we visit loops in
1749 // decreasing order of loop depth.
1750 for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1751 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1753 // Walk the CFG back until we hit the cloned PH adding everything reachable
1754 // and in the unlooped set to this exit block's loop.
1755 Worklist.push_back(ExitBB);
1756 do {
1757 BasicBlock *BB = Worklist.pop_back_val();
1758 // We can stop recursing at the cloned preheader (if we get there).
1759 if (BB == PH)
1760 continue;
1762 for (BasicBlock *PredBB : predecessors(BB)) {
1763 // If this pred has already been moved to our set or is part of some
1764 // (inner) loop, no update needed.
1765 if (!UnloopedBlocks.erase(PredBB)) {
1766 assert((NewExitLoopBlocks.count(PredBB) ||
1767 ExitL.contains(LI.getLoopFor(PredBB))) &&
1768 "Predecessor not in a nested loop (or already visited)!");
1769 continue;
1772 // We just insert into the loop set here. We'll add these blocks to the
1773 // exit loop after we build up the set in a deterministic order rather
1774 // than the predecessor-influenced visit order.
1775 bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1776 (void)Inserted;
1777 assert(Inserted && "Should only visit an unlooped block once!");
1779 // And recurse through to its predecessors.
1780 Worklist.push_back(PredBB);
1782 } while (!Worklist.empty());
1784 // If blocks in this exit loop were directly part of the original loop (as
1785 // opposed to a child loop) update the map to point to this exit loop. This
1786 // just updates a map and so the fact that the order is unstable is fine.
1787 for (auto *BB : NewExitLoopBlocks)
1788 if (Loop *BBL = LI.getLoopFor(BB))
1789 if (BBL == &L || !L.contains(BBL))
1790 LI.changeLoopFor(BB, &ExitL);
1792 // We will remove the remaining unlooped blocks from this loop in the next
1793 // iteration or below.
1794 NewExitLoopBlocks.clear();
1797 // Any remaining unlooped blocks are no longer part of any loop unless they
1798 // are part of some child loop.
1799 for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1800 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1801 for (auto *BB : UnloopedBlocks)
1802 if (Loop *BBL = LI.getLoopFor(BB))
1803 if (BBL == &L || !L.contains(BBL))
1804 LI.changeLoopFor(BB, nullptr);
1806 // Sink all the child loops whose headers are no longer in the loop set to
1807 // the parent (or to be top level loops). We reach into the loop and directly
1808 // update its subloop vector to make this batch update efficient.
1809 auto &SubLoops = L.getSubLoopsVector();
1810 auto SubLoopsSplitI =
1811 LoopBlockSet.empty()
1812 ? SubLoops.begin()
1813 : std::stable_partition(
1814 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1815 return LoopBlockSet.count(SubL->getHeader());
1817 for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1818 HoistedLoops.push_back(HoistedL);
1819 HoistedL->setParentLoop(nullptr);
1821 // To compute the new parent of this hoisted loop we look at where we
1822 // placed the preheader above. We can't lookup the header itself because we
1823 // retained the mapping from the header to the hoisted loop. But the
1824 // preheader and header should have the exact same new parent computed
1825 // based on the set of exit blocks from the original loop as the preheader
1826 // is a predecessor of the header and so reached in the reverse walk. And
1827 // because the loops were all in simplified form the preheader of the
1828 // hoisted loop can't be part of some *other* loop.
1829 if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1830 NewParentL->addChildLoop(HoistedL);
1831 else
1832 LI.addTopLevelLoop(HoistedL);
1834 SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1836 // Actually delete the loop if nothing remained within it.
1837 if (Blocks.empty()) {
1838 assert(SubLoops.empty() &&
1839 "Failed to remove all subloops from the original loop!");
1840 if (Loop *ParentL = L.getParentLoop())
1841 ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1842 else
1843 LI.removeLoop(llvm::find(LI, &L));
1844 LI.destroy(&L);
1845 return false;
1848 return true;
1851 /// Helper to visit a dominator subtree, invoking a callable on each node.
1853 /// Returning false at any point will stop walking past that node of the tree.
1854 template <typename CallableT>
1855 void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1856 SmallVector<DomTreeNode *, 4> DomWorklist;
1857 DomWorklist.push_back(DT[BB]);
1858 #ifndef NDEBUG
1859 SmallPtrSet<DomTreeNode *, 4> Visited;
1860 Visited.insert(DT[BB]);
1861 #endif
1862 do {
1863 DomTreeNode *N = DomWorklist.pop_back_val();
1865 // Visit this node.
1866 if (!Callable(N->getBlock()))
1867 continue;
1869 // Accumulate the child nodes.
1870 for (DomTreeNode *ChildN : *N) {
1871 assert(Visited.insert(ChildN).second &&
1872 "Cannot visit a node twice when walking a tree!");
1873 DomWorklist.push_back(ChildN);
1875 } while (!DomWorklist.empty());
1878 static void unswitchNontrivialInvariants(
1879 Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
1880 SmallVectorImpl<BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI,
1881 AssumptionCache &AC, function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
1882 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
1883 auto *ParentBB = TI.getParent();
1884 BranchInst *BI = dyn_cast<BranchInst>(&TI);
1885 SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
1887 // We can only unswitch switches, conditional branches with an invariant
1888 // condition, or combining invariant conditions with an instruction.
1889 assert((SI || BI->isConditional()) &&
1890 "Can only unswitch switches and conditional branch!");
1891 bool FullUnswitch = SI || BI->getCondition() == Invariants[0];
1892 if (FullUnswitch)
1893 assert(Invariants.size() == 1 &&
1894 "Cannot have other invariants with full unswitching!");
1895 else
1896 assert(isa<Instruction>(BI->getCondition()) &&
1897 "Partial unswitching requires an instruction as the condition!");
1899 if (MSSAU && VerifyMemorySSA)
1900 MSSAU->getMemorySSA()->verifyMemorySSA();
1902 // Constant and BBs tracking the cloned and continuing successor. When we are
1903 // unswitching the entire condition, this can just be trivially chosen to
1904 // unswitch towards `true`. However, when we are unswitching a set of
1905 // invariants combined with `and` or `or`, the combining operation determines
1906 // the best direction to unswitch: we want to unswitch the direction that will
1907 // collapse the branch.
1908 bool Direction = true;
1909 int ClonedSucc = 0;
1910 if (!FullUnswitch) {
1911 if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) {
1912 assert(cast<Instruction>(BI->getCondition())->getOpcode() ==
1913 Instruction::And &&
1914 "Only `or` and `and` instructions can combine invariants being "
1915 "unswitched.");
1916 Direction = false;
1917 ClonedSucc = 1;
1921 BasicBlock *RetainedSuccBB =
1922 BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
1923 SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
1924 if (BI)
1925 UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
1926 else
1927 for (auto Case : SI->cases())
1928 if (Case.getCaseSuccessor() != RetainedSuccBB)
1929 UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
1931 assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
1932 "Should not unswitch the same successor we are retaining!");
1934 // The branch should be in this exact loop. Any inner loop's invariant branch
1935 // should be handled by unswitching that inner loop. The caller of this
1936 // routine should filter out any candidates that remain (but were skipped for
1937 // whatever reason).
1938 assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
1940 // Compute the parent loop now before we start hacking on things.
1941 Loop *ParentL = L.getParentLoop();
1942 // Get blocks in RPO order for MSSA update, before changing the CFG.
1943 LoopBlocksRPO LBRPO(&L);
1944 if (MSSAU)
1945 LBRPO.perform(&LI);
1947 // Compute the outer-most loop containing one of our exit blocks. This is the
1948 // furthest up our loopnest which can be mutated, which we will use below to
1949 // update things.
1950 Loop *OuterExitL = &L;
1951 for (auto *ExitBB : ExitBlocks) {
1952 Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
1953 if (!NewOuterExitL) {
1954 // We exited the entire nest with this block, so we're done.
1955 OuterExitL = nullptr;
1956 break;
1958 if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
1959 OuterExitL = NewOuterExitL;
1962 // At this point, we're definitely going to unswitch something so invalidate
1963 // any cached information in ScalarEvolution for the outer most loop
1964 // containing an exit block and all nested loops.
1965 if (SE) {
1966 if (OuterExitL)
1967 SE->forgetLoop(OuterExitL);
1968 else
1969 SE->forgetTopmostLoop(&L);
1972 // If the edge from this terminator to a successor dominates that successor,
1973 // store a map from each block in its dominator subtree to it. This lets us
1974 // tell when cloning for a particular successor if a block is dominated by
1975 // some *other* successor with a single data structure. We use this to
1976 // significantly reduce cloning.
1977 SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
1978 for (auto *SuccBB : llvm::concat<BasicBlock *const>(
1979 makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
1980 if (SuccBB->getUniquePredecessor() ||
1981 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
1982 return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
1984 visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
1985 DominatingSucc[BB] = SuccBB;
1986 return true;
1989 // Split the preheader, so that we know that there is a safe place to insert
1990 // the conditional branch. We will change the preheader to have a conditional
1991 // branch on LoopCond. The original preheader will become the split point
1992 // between the unswitched versions, and we will have a new preheader for the
1993 // original loop.
1994 BasicBlock *SplitBB = L.getLoopPreheader();
1995 BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
1997 // Keep track of the dominator tree updates needed.
1998 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2000 // Clone the loop for each unswitched successor.
2001 SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
2002 VMaps.reserve(UnswitchedSuccBBs.size());
2003 SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
2004 for (auto *SuccBB : UnswitchedSuccBBs) {
2005 VMaps.emplace_back(new ValueToValueMapTy());
2006 ClonedPHs[SuccBB] = buildClonedLoopBlocks(
2007 L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
2008 DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU);
2011 // The stitching of the branched code back together depends on whether we're
2012 // doing full unswitching or not with the exception that we always want to
2013 // nuke the initial terminator placed in the split block.
2014 SplitBB->getTerminator()->eraseFromParent();
2015 if (FullUnswitch) {
2016 // Splice the terminator from the original loop and rewrite its
2017 // successors.
2018 SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
2020 // Keep a clone of the terminator for MSSA updates.
2021 Instruction *NewTI = TI.clone();
2022 ParentBB->getInstList().push_back(NewTI);
2024 // First wire up the moved terminator to the preheaders.
2025 if (BI) {
2026 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2027 BI->setSuccessor(ClonedSucc, ClonedPH);
2028 BI->setSuccessor(1 - ClonedSucc, LoopPH);
2029 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2030 } else {
2031 assert(SI && "Must either be a branch or switch!");
2033 // Walk the cases and directly update their successors.
2034 assert(SI->getDefaultDest() == RetainedSuccBB &&
2035 "Not retaining default successor!");
2036 SI->setDefaultDest(LoopPH);
2037 for (auto &Case : SI->cases())
2038 if (Case.getCaseSuccessor() == RetainedSuccBB)
2039 Case.setSuccessor(LoopPH);
2040 else
2041 Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
2043 // We need to use the set to populate domtree updates as even when there
2044 // are multiple cases pointing at the same successor we only want to
2045 // remove and insert one edge in the domtree.
2046 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2047 DTUpdates.push_back(
2048 {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
2051 if (MSSAU) {
2052 DT.applyUpdates(DTUpdates);
2053 DTUpdates.clear();
2055 // Remove all but one edge to the retained block and all unswitched
2056 // blocks. This is to avoid having duplicate entries in the cloned Phis,
2057 // when we know we only keep a single edge for each case.
2058 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
2059 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2060 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
2062 for (auto &VMap : VMaps)
2063 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2064 /*IgnoreIncomingWithNoClones=*/true);
2065 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2067 // Remove all edges to unswitched blocks.
2068 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2069 MSSAU->removeEdge(ParentBB, SuccBB);
2072 // Now unhook the successor relationship as we'll be replacing
2073 // the terminator with a direct branch. This is much simpler for branches
2074 // than switches so we handle those first.
2075 if (BI) {
2076 // Remove the parent as a predecessor of the unswitched successor.
2077 assert(UnswitchedSuccBBs.size() == 1 &&
2078 "Only one possible unswitched block for a branch!");
2079 BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
2080 UnswitchedSuccBB->removePredecessor(ParentBB,
2081 /*KeepOneInputPHIs*/ true);
2082 DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
2083 } else {
2084 // Note that we actually want to remove the parent block as a predecessor
2085 // of *every* case successor. The case successor is either unswitched,
2086 // completely eliminating an edge from the parent to that successor, or it
2087 // is a duplicate edge to the retained successor as the retained successor
2088 // is always the default successor and as we'll replace this with a direct
2089 // branch we no longer need the duplicate entries in the PHI nodes.
2090 SwitchInst *NewSI = cast<SwitchInst>(NewTI);
2091 assert(NewSI->getDefaultDest() == RetainedSuccBB &&
2092 "Not retaining default successor!");
2093 for (auto &Case : NewSI->cases())
2094 Case.getCaseSuccessor()->removePredecessor(
2095 ParentBB,
2096 /*KeepOneInputPHIs*/ true);
2098 // We need to use the set to populate domtree updates as even when there
2099 // are multiple cases pointing at the same successor we only want to
2100 // remove and insert one edge in the domtree.
2101 for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2102 DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
2105 // After MSSAU update, remove the cloned terminator instruction NewTI.
2106 ParentBB->getTerminator()->eraseFromParent();
2108 // Create a new unconditional branch to the continuing block (as opposed to
2109 // the one cloned).
2110 BranchInst::Create(RetainedSuccBB, ParentBB);
2111 } else {
2112 assert(BI && "Only branches have partial unswitching.");
2113 assert(UnswitchedSuccBBs.size() == 1 &&
2114 "Only one possible unswitched block for a branch!");
2115 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2116 // When doing a partial unswitch, we have to do a bit more work to build up
2117 // the branch in the split block.
2118 buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
2119 *ClonedPH, *LoopPH);
2120 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2123 // Apply the updates accumulated above to get an up-to-date dominator tree.
2124 DT.applyUpdates(DTUpdates);
2125 if (!FullUnswitch && MSSAU) {
2126 // Update MSSA for partial unswitch, after DT update.
2127 SmallVector<CFGUpdate, 1> Updates;
2128 Updates.push_back(
2129 {cfg::UpdateKind::Insert, SplitBB, ClonedPHs.begin()->second});
2130 MSSAU->applyInsertUpdates(Updates, DT);
2133 // Now that we have an accurate dominator tree, first delete the dead cloned
2134 // blocks so that we can accurately build any cloned loops. It is important to
2135 // not delete the blocks from the original loop yet because we still want to
2136 // reference the original loop to understand the cloned loop's structure.
2137 deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
2139 // Build the cloned loop structure itself. This may be substantially
2140 // different from the original structure due to the simplified CFG. This also
2141 // handles inserting all the cloned blocks into the correct loops.
2142 SmallVector<Loop *, 4> NonChildClonedLoops;
2143 for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2144 buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
2146 // Now that our cloned loops have been built, we can update the original loop.
2147 // First we delete the dead blocks from it and then we rebuild the loop
2148 // structure taking these deletions into account.
2149 deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU);
2151 if (MSSAU && VerifyMemorySSA)
2152 MSSAU->getMemorySSA()->verifyMemorySSA();
2154 SmallVector<Loop *, 4> HoistedLoops;
2155 bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
2157 if (MSSAU && VerifyMemorySSA)
2158 MSSAU->getMemorySSA()->verifyMemorySSA();
2160 // This transformation has a high risk of corrupting the dominator tree, and
2161 // the below steps to rebuild loop structures will result in hard to debug
2162 // errors in that case so verify that the dominator tree is sane first.
2163 // FIXME: Remove this when the bugs stop showing up and rely on existing
2164 // verification steps.
2165 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2167 if (BI) {
2168 // If we unswitched a branch which collapses the condition to a known
2169 // constant we want to replace all the uses of the invariants within both
2170 // the original and cloned blocks. We do this here so that we can use the
2171 // now updated dominator tree to identify which side the users are on.
2172 assert(UnswitchedSuccBBs.size() == 1 &&
2173 "Only one possible unswitched block for a branch!");
2174 BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2176 // When considering multiple partially-unswitched invariants
2177 // we cant just go replace them with constants in both branches.
2179 // For 'AND' we infer that true branch ("continue") means true
2180 // for each invariant operand.
2181 // For 'OR' we can infer that false branch ("continue") means false
2182 // for each invariant operand.
2183 // So it happens that for multiple-partial case we dont replace
2184 // in the unswitched branch.
2185 bool ReplaceUnswitched = FullUnswitch || (Invariants.size() == 1);
2187 ConstantInt *UnswitchedReplacement =
2188 Direction ? ConstantInt::getTrue(BI->getContext())
2189 : ConstantInt::getFalse(BI->getContext());
2190 ConstantInt *ContinueReplacement =
2191 Direction ? ConstantInt::getFalse(BI->getContext())
2192 : ConstantInt::getTrue(BI->getContext());
2193 for (Value *Invariant : Invariants)
2194 for (auto UI = Invariant->use_begin(), UE = Invariant->use_end();
2195 UI != UE;) {
2196 // Grab the use and walk past it so we can clobber it in the use list.
2197 Use *U = &*UI++;
2198 Instruction *UserI = dyn_cast<Instruction>(U->getUser());
2199 if (!UserI)
2200 continue;
2202 // Replace it with the 'continue' side if in the main loop body, and the
2203 // unswitched if in the cloned blocks.
2204 if (DT.dominates(LoopPH, UserI->getParent()))
2205 U->set(ContinueReplacement);
2206 else if (ReplaceUnswitched &&
2207 DT.dominates(ClonedPH, UserI->getParent()))
2208 U->set(UnswitchedReplacement);
2212 // We can change which blocks are exit blocks of all the cloned sibling
2213 // loops, the current loop, and any parent loops which shared exit blocks
2214 // with the current loop. As a consequence, we need to re-form LCSSA for
2215 // them. But we shouldn't need to re-form LCSSA for any child loops.
2216 // FIXME: This could be made more efficient by tracking which exit blocks are
2217 // new, and focusing on them, but that isn't likely to be necessary.
2219 // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2220 // loop nest and update every loop that could have had its exits changed. We
2221 // also need to cover any intervening loops. We add all of these loops to
2222 // a list and sort them by loop depth to achieve this without updating
2223 // unnecessary loops.
2224 auto UpdateLoop = [&](Loop &UpdateL) {
2225 #ifndef NDEBUG
2226 UpdateL.verifyLoop();
2227 for (Loop *ChildL : UpdateL) {
2228 ChildL->verifyLoop();
2229 assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2230 "Perturbed a child loop's LCSSA form!");
2232 #endif
2233 // First build LCSSA for this loop so that we can preserve it when
2234 // forming dedicated exits. We don't want to perturb some other loop's
2235 // LCSSA while doing that CFG edit.
2236 formLCSSA(UpdateL, DT, &LI, nullptr);
2238 // For loops reached by this loop's original exit blocks we may
2239 // introduced new, non-dedicated exits. At least try to re-form dedicated
2240 // exits for these loops. This may fail if they couldn't have dedicated
2241 // exits to start with.
2242 formDedicatedExitBlocks(&UpdateL, &DT, &LI, /*PreserveLCSSA*/ true);
2245 // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2246 // and we can do it in any order as they don't nest relative to each other.
2248 // Also check if any of the loops we have updated have become top-level loops
2249 // as that will necessitate widening the outer loop scope.
2250 for (Loop *UpdatedL :
2251 llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2252 UpdateLoop(*UpdatedL);
2253 if (!UpdatedL->getParentLoop())
2254 OuterExitL = nullptr;
2256 if (IsStillLoop) {
2257 UpdateLoop(L);
2258 if (!L.getParentLoop())
2259 OuterExitL = nullptr;
2262 // If the original loop had exit blocks, walk up through the outer most loop
2263 // of those exit blocks to update LCSSA and form updated dedicated exits.
2264 if (OuterExitL != &L)
2265 for (Loop *OuterL = ParentL; OuterL != OuterExitL;
2266 OuterL = OuterL->getParentLoop())
2267 UpdateLoop(*OuterL);
2269 #ifndef NDEBUG
2270 // Verify the entire loop structure to catch any incorrect updates before we
2271 // progress in the pass pipeline.
2272 LI.verify(DT);
2273 #endif
2275 // Now that we've unswitched something, make callbacks to report the changes.
2276 // For that we need to merge together the updated loops and the cloned loops
2277 // and check whether the original loop survived.
2278 SmallVector<Loop *, 4> SibLoops;
2279 for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2280 if (UpdatedL->getParentLoop() == ParentL)
2281 SibLoops.push_back(UpdatedL);
2282 UnswitchCB(IsStillLoop, SibLoops);
2284 if (MSSAU && VerifyMemorySSA)
2285 MSSAU->getMemorySSA()->verifyMemorySSA();
2287 if (BI)
2288 ++NumBranches;
2289 else
2290 ++NumSwitches;
2293 /// Recursively compute the cost of a dominator subtree based on the per-block
2294 /// cost map provided.
2296 /// The recursive computation is memozied into the provided DT-indexed cost map
2297 /// to allow querying it for most nodes in the domtree without it becoming
2298 /// quadratic.
2299 static int
2300 computeDomSubtreeCost(DomTreeNode &N,
2301 const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
2302 SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
2303 // Don't accumulate cost (or recurse through) blocks not in our block cost
2304 // map and thus not part of the duplication cost being considered.
2305 auto BBCostIt = BBCostMap.find(N.getBlock());
2306 if (BBCostIt == BBCostMap.end())
2307 return 0;
2309 // Lookup this node to see if we already computed its cost.
2310 auto DTCostIt = DTCostMap.find(&N);
2311 if (DTCostIt != DTCostMap.end())
2312 return DTCostIt->second;
2314 // If not, we have to compute it. We can't use insert above and update
2315 // because computing the cost may insert more things into the map.
2316 int Cost = std::accumulate(
2317 N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
2318 return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2320 bool Inserted = DTCostMap.insert({&N, Cost}).second;
2321 (void)Inserted;
2322 assert(Inserted && "Should not insert a node while visiting children!");
2323 return Cost;
2326 /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2327 /// making the following replacement:
2329 /// --code before guard--
2330 /// call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
2331 /// --code after guard--
2333 /// into
2335 /// --code before guard--
2336 /// br i1 %cond, label %guarded, label %deopt
2338 /// guarded:
2339 /// --code after guard--
2341 /// deopt:
2342 /// call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2343 /// unreachable
2345 /// It also makes all relevant DT and LI updates, so that all structures are in
2346 /// valid state after this transform.
2347 static BranchInst *
2348 turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2349 SmallVectorImpl<BasicBlock *> &ExitBlocks,
2350 DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) {
2351 SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2352 LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
2353 BasicBlock *CheckBB = GI->getParent();
2355 if (MSSAU && VerifyMemorySSA)
2356 MSSAU->getMemorySSA()->verifyMemorySSA();
2358 // Remove all CheckBB's successors from DomTree. A block can be seen among
2359 // successors more than once, but for DomTree it should be added only once.
2360 SmallPtrSet<BasicBlock *, 4> Successors;
2361 for (auto *Succ : successors(CheckBB))
2362 if (Successors.insert(Succ).second)
2363 DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
2365 Instruction *DeoptBlockTerm =
2366 SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
2367 BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
2368 // SplitBlockAndInsertIfThen inserts control flow that branches to
2369 // DeoptBlockTerm if the condition is true. We want the opposite.
2370 CheckBI->swapSuccessors();
2372 BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2373 GuardedBlock->setName("guarded");
2374 CheckBI->getSuccessor(1)->setName("deopt");
2375 BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
2377 // We now have a new exit block.
2378 ExitBlocks.push_back(CheckBI->getSuccessor(1));
2380 if (MSSAU)
2381 MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
2383 GI->moveBefore(DeoptBlockTerm);
2384 GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
2386 // Add new successors of CheckBB into DomTree.
2387 for (auto *Succ : successors(CheckBB))
2388 DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
2390 // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2391 // successors.
2392 for (auto *Succ : Successors)
2393 DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
2395 // Make proper changes to DT.
2396 DT.applyUpdates(DTUpdates);
2397 // Inform LI of a new loop block.
2398 L.addBasicBlockToLoop(GuardedBlock, LI);
2400 if (MSSAU) {
2401 MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
2402 MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::End);
2403 if (VerifyMemorySSA)
2404 MSSAU->getMemorySSA()->verifyMemorySSA();
2407 ++NumGuards;
2408 return CheckBI;
2411 /// Cost multiplier is a way to limit potentially exponential behavior
2412 /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
2413 /// candidates available. Also accounting for the number of "sibling" loops with
2414 /// the idea to account for previous unswitches that already happened on this
2415 /// cluster of loops. There was an attempt to keep this formula simple,
2416 /// just enough to limit the worst case behavior. Even if it is not that simple
2417 /// now it is still not an attempt to provide a detailed heuristic size
2418 /// prediction.
2420 /// TODO: Make a proper accounting of "explosion" effect for all kinds of
2421 /// unswitch candidates, making adequate predictions instead of wild guesses.
2422 /// That requires knowing not just the number of "remaining" candidates but
2423 /// also costs of unswitching for each of these candidates.
2424 static int calculateUnswitchCostMultiplier(
2425 Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT,
2426 ArrayRef<std::pair<Instruction *, TinyPtrVector<Value *>>>
2427 UnswitchCandidates) {
2429 // Guards and other exiting conditions do not contribute to exponential
2430 // explosion as soon as they dominate the latch (otherwise there might be
2431 // another path to the latch remaining that does not allow to eliminate the
2432 // loop copy on unswitch).
2433 BasicBlock *Latch = L.getLoopLatch();
2434 BasicBlock *CondBlock = TI.getParent();
2435 if (DT.dominates(CondBlock, Latch) &&
2436 (isGuard(&TI) ||
2437 llvm::count_if(successors(&TI), [&L](BasicBlock *SuccBB) {
2438 return L.contains(SuccBB);
2439 }) <= 1)) {
2440 NumCostMultiplierSkipped++;
2441 return 1;
2444 auto *ParentL = L.getParentLoop();
2445 int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
2446 : std::distance(LI.begin(), LI.end()));
2447 // Count amount of clones that all the candidates might cause during
2448 // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
2449 int UnswitchedClones = 0;
2450 for (auto Candidate : UnswitchCandidates) {
2451 Instruction *CI = Candidate.first;
2452 BasicBlock *CondBlock = CI->getParent();
2453 bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
2454 if (isGuard(CI)) {
2455 if (!SkipExitingSuccessors)
2456 UnswitchedClones++;
2457 continue;
2459 int NonExitingSuccessors = llvm::count_if(
2460 successors(CondBlock), [SkipExitingSuccessors, &L](BasicBlock *SuccBB) {
2461 return !SkipExitingSuccessors || L.contains(SuccBB);
2463 UnswitchedClones += Log2_32(NonExitingSuccessors);
2466 // Ignore up to the "unscaled candidates" number of unswitch candidates
2467 // when calculating the power-of-two scaling of the cost. The main idea
2468 // with this control is to allow a small number of unswitches to happen
2469 // and rely more on siblings multiplier (see below) when the number
2470 // of candidates is small.
2471 unsigned ClonesPower =
2472 std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
2474 // Allowing top-level loops to spread a bit more than nested ones.
2475 int SiblingsMultiplier =
2476 std::max((ParentL ? SiblingsCount
2477 : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
2479 // Compute the cost multiplier in a way that won't overflow by saturating
2480 // at an upper bound.
2481 int CostMultiplier;
2482 if (ClonesPower > Log2_32(UnswitchThreshold) ||
2483 SiblingsMultiplier > UnswitchThreshold)
2484 CostMultiplier = UnswitchThreshold;
2485 else
2486 CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
2487 (int)UnswitchThreshold);
2489 LLVM_DEBUG(dbgs() << " Computed multiplier " << CostMultiplier
2490 << " (siblings " << SiblingsMultiplier << " * clones "
2491 << (1 << ClonesPower) << ")"
2492 << " for unswitch candidate: " << TI << "\n");
2493 return CostMultiplier;
2496 static bool
2497 unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
2498 AssumptionCache &AC, TargetTransformInfo &TTI,
2499 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2500 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
2501 // Collect all invariant conditions within this loop (as opposed to an inner
2502 // loop which would be handled when visiting that inner loop).
2503 SmallVector<std::pair<Instruction *, TinyPtrVector<Value *>>, 4>
2504 UnswitchCandidates;
2506 // Whether or not we should also collect guards in the loop.
2507 bool CollectGuards = false;
2508 if (UnswitchGuards) {
2509 auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
2510 Intrinsic::getName(Intrinsic::experimental_guard));
2511 if (GuardDecl && !GuardDecl->use_empty())
2512 CollectGuards = true;
2515 for (auto *BB : L.blocks()) {
2516 if (LI.getLoopFor(BB) != &L)
2517 continue;
2519 if (CollectGuards)
2520 for (auto &I : *BB)
2521 if (isGuard(&I)) {
2522 auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0);
2523 // TODO: Support AND, OR conditions and partial unswitching.
2524 if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
2525 UnswitchCandidates.push_back({&I, {Cond}});
2528 if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2529 // We can only consider fully loop-invariant switch conditions as we need
2530 // to completely eliminate the switch after unswitching.
2531 if (!isa<Constant>(SI->getCondition()) &&
2532 L.isLoopInvariant(SI->getCondition()))
2533 UnswitchCandidates.push_back({SI, {SI->getCondition()}});
2534 continue;
2537 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
2538 if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2539 BI->getSuccessor(0) == BI->getSuccessor(1))
2540 continue;
2542 if (L.isLoopInvariant(BI->getCondition())) {
2543 UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2544 continue;
2547 Instruction &CondI = *cast<Instruction>(BI->getCondition());
2548 if (CondI.getOpcode() != Instruction::And &&
2549 CondI.getOpcode() != Instruction::Or)
2550 continue;
2552 TinyPtrVector<Value *> Invariants =
2553 collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2554 if (Invariants.empty())
2555 continue;
2557 UnswitchCandidates.push_back({BI, std::move(Invariants)});
2560 // If we didn't find any candidates, we're done.
2561 if (UnswitchCandidates.empty())
2562 return false;
2564 // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2565 // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2566 // irreducible control flow into reducible control flow and introduce new
2567 // loops "out of thin air". If we ever discover important use cases for doing
2568 // this, we can add support to loop unswitch, but it is a lot of complexity
2569 // for what seems little or no real world benefit.
2570 LoopBlocksRPO RPOT(&L);
2571 RPOT.perform(&LI);
2572 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
2573 return false;
2575 SmallVector<BasicBlock *, 4> ExitBlocks;
2576 L.getUniqueExitBlocks(ExitBlocks);
2578 // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
2579 // don't know how to split those exit blocks.
2580 // FIXME: We should teach SplitBlock to handle this and remove this
2581 // restriction.
2582 for (auto *ExitBB : ExitBlocks)
2583 if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI())) {
2584 dbgs() << "Cannot unswitch because of cleanuppad in exit block\n";
2585 return false;
2588 LLVM_DEBUG(
2589 dbgs() << "Considering " << UnswitchCandidates.size()
2590 << " non-trivial loop invariant conditions for unswitching.\n");
2592 // Given that unswitching these terminators will require duplicating parts of
2593 // the loop, so we need to be able to model that cost. Compute the ephemeral
2594 // values and set up a data structure to hold per-BB costs. We cache each
2595 // block's cost so that we don't recompute this when considering different
2596 // subsets of the loop for duplication during unswitching.
2597 SmallPtrSet<const Value *, 4> EphValues;
2598 CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2599 SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
2601 // Compute the cost of each block, as well as the total loop cost. Also, bail
2602 // out if we see instructions which are incompatible with loop unswitching
2603 // (convergent, noduplicate, or cross-basic-block tokens).
2604 // FIXME: We might be able to safely handle some of these in non-duplicated
2605 // regions.
2606 int LoopCost = 0;
2607 for (auto *BB : L.blocks()) {
2608 int Cost = 0;
2609 for (auto &I : *BB) {
2610 if (EphValues.count(&I))
2611 continue;
2613 if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
2614 return false;
2615 if (auto CS = CallSite(&I))
2616 if (CS.isConvergent() || CS.cannotDuplicate())
2617 return false;
2619 Cost += TTI.getUserCost(&I);
2621 assert(Cost >= 0 && "Must not have negative costs!");
2622 LoopCost += Cost;
2623 assert(LoopCost >= 0 && "Must not have negative loop costs!");
2624 BBCostMap[BB] = Cost;
2626 LLVM_DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n");
2628 // Now we find the best candidate by searching for the one with the following
2629 // properties in order:
2631 // 1) An unswitching cost below the threshold
2632 // 2) The smallest number of duplicated unswitch candidates (to avoid
2633 // creating redundant subsequent unswitching)
2634 // 3) The smallest cost after unswitching.
2636 // We prioritize reducing fanout of unswitch candidates provided the cost
2637 // remains below the threshold because this has a multiplicative effect.
2639 // This requires memoizing each dominator subtree to avoid redundant work.
2641 // FIXME: Need to actually do the number of candidates part above.
2642 SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
2643 // Given a terminator which might be unswitched, computes the non-duplicated
2644 // cost for that terminator.
2645 auto ComputeUnswitchedCost = [&](Instruction &TI, bool FullUnswitch) {
2646 BasicBlock &BB = *TI.getParent();
2647 SmallPtrSet<BasicBlock *, 4> Visited;
2649 int Cost = LoopCost;
2650 for (BasicBlock *SuccBB : successors(&BB)) {
2651 // Don't count successors more than once.
2652 if (!Visited.insert(SuccBB).second)
2653 continue;
2655 // If this is a partial unswitch candidate, then it must be a conditional
2656 // branch with a condition of either `or` or `and`. In that case, one of
2657 // the successors is necessarily duplicated, so don't even try to remove
2658 // its cost.
2659 if (!FullUnswitch) {
2660 auto &BI = cast<BranchInst>(TI);
2661 if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2662 Instruction::And) {
2663 if (SuccBB == BI.getSuccessor(1))
2664 continue;
2665 } else {
2666 assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2667 Instruction::Or &&
2668 "Only `and` and `or` conditions can result in a partial "
2669 "unswitch!");
2670 if (SuccBB == BI.getSuccessor(0))
2671 continue;
2675 // This successor's domtree will not need to be duplicated after
2676 // unswitching if the edge to the successor dominates it (and thus the
2677 // entire tree). This essentially means there is no other path into this
2678 // subtree and so it will end up live in only one clone of the loop.
2679 if (SuccBB->getUniquePredecessor() ||
2680 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2681 return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2682 })) {
2683 Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2684 assert(Cost >= 0 &&
2685 "Non-duplicated cost should never exceed total loop cost!");
2689 // Now scale the cost by the number of unique successors minus one. We
2690 // subtract one because there is already at least one copy of the entire
2691 // loop. This is computing the new cost of unswitching a condition.
2692 // Note that guards always have 2 unique successors that are implicit and
2693 // will be materialized if we decide to unswitch it.
2694 int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
2695 assert(SuccessorsCount > 1 &&
2696 "Cannot unswitch a condition without multiple distinct successors!");
2697 return Cost * (SuccessorsCount - 1);
2699 Instruction *BestUnswitchTI = nullptr;
2700 int BestUnswitchCost;
2701 ArrayRef<Value *> BestUnswitchInvariants;
2702 for (auto &TerminatorAndInvariants : UnswitchCandidates) {
2703 Instruction &TI = *TerminatorAndInvariants.first;
2704 ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2705 BranchInst *BI = dyn_cast<BranchInst>(&TI);
2706 int CandidateCost = ComputeUnswitchedCost(
2707 TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
2708 Invariants[0] == BI->getCondition()));
2709 // Calculate cost multiplier which is a tool to limit potentially
2710 // exponential behavior of loop-unswitch.
2711 if (EnableUnswitchCostMultiplier) {
2712 int CostMultiplier =
2713 calculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
2714 assert(
2715 (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
2716 "cost multiplier needs to be in the range of 1..UnswitchThreshold");
2717 CandidateCost *= CostMultiplier;
2718 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2719 << " (multiplier: " << CostMultiplier << ")"
2720 << " for unswitch candidate: " << TI << "\n");
2721 } else {
2722 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost
2723 << " for unswitch candidate: " << TI << "\n");
2726 if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
2727 BestUnswitchTI = &TI;
2728 BestUnswitchCost = CandidateCost;
2729 BestUnswitchInvariants = Invariants;
2733 if (BestUnswitchCost >= UnswitchThreshold) {
2734 LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
2735 << BestUnswitchCost << "\n");
2736 return false;
2739 // If the best candidate is a guard, turn it into a branch.
2740 if (isGuard(BestUnswitchTI))
2741 BestUnswitchTI = turnGuardIntoBranch(cast<IntrinsicInst>(BestUnswitchTI), L,
2742 ExitBlocks, DT, LI, MSSAU);
2744 LLVM_DEBUG(dbgs() << " Unswitching non-trivial (cost = "
2745 << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
2746 << "\n");
2747 unswitchNontrivialInvariants(L, *BestUnswitchTI, BestUnswitchInvariants,
2748 ExitBlocks, DT, LI, AC, UnswitchCB, SE, MSSAU);
2749 return true;
2752 /// Unswitch control flow predicated on loop invariant conditions.
2754 /// This first hoists all branches or switches which are trivial (IE, do not
2755 /// require duplicating any part of the loop) out of the loop body. It then
2756 /// looks at other loop invariant control flows and tries to unswitch those as
2757 /// well by cloning the loop if the result is small enough.
2759 /// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
2760 /// updated based on the unswitch.
2761 /// The `MSSA` analysis is also updated if valid (i.e. its use is enabled).
2763 /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
2764 /// true, we will attempt to do non-trivial unswitching as well as trivial
2765 /// unswitching.
2767 /// The `UnswitchCB` callback provided will be run after unswitching is
2768 /// complete, with the first parameter set to `true` if the provided loop
2769 /// remains a loop, and a list of new sibling loops created.
2771 /// If `SE` is non-null, we will update that analysis based on the unswitching
2772 /// done.
2773 static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
2774 AssumptionCache &AC, TargetTransformInfo &TTI,
2775 bool NonTrivial,
2776 function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2777 ScalarEvolution *SE, MemorySSAUpdater *MSSAU) {
2778 assert(L.isRecursivelyLCSSAForm(DT, LI) &&
2779 "Loops must be in LCSSA form before unswitching.");
2780 bool Changed = false;
2782 // Must be in loop simplified form: we need a preheader and dedicated exits.
2783 if (!L.isLoopSimplifyForm())
2784 return false;
2786 // Try trivial unswitch first before loop over other basic blocks in the loop.
2787 if (unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
2788 // If we unswitched successfully we will want to clean up the loop before
2789 // processing it further so just mark it as unswitched and return.
2790 UnswitchCB(/*CurrentLoopValid*/ true, {});
2791 return true;
2794 // If we're not doing non-trivial unswitching, we're done. We both accept
2795 // a parameter but also check a local flag that can be used for testing
2796 // a debugging.
2797 if (!NonTrivial && !EnableNonTrivialUnswitch)
2798 return false;
2800 // For non-trivial unswitching, because it often creates new loops, we rely on
2801 // the pass manager to iterate on the loops rather than trying to immediately
2802 // reach a fixed point. There is no substantial advantage to iterating
2803 // internally, and if any of the new loops are simplified enough to contain
2804 // trivial unswitching we want to prefer those.
2806 // Try to unswitch the best invariant condition. We prefer this full unswitch to
2807 // a partial unswitch when possible below the threshold.
2808 if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE, MSSAU))
2809 return true;
2811 // No other opportunities to unswitch.
2812 return Changed;
2815 PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
2816 LoopStandardAnalysisResults &AR,
2817 LPMUpdater &U) {
2818 Function &F = *L.getHeader()->getParent();
2819 (void)F;
2821 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
2822 << "\n");
2824 // Save the current loop name in a variable so that we can report it even
2825 // after it has been deleted.
2826 std::string LoopName = L.getName();
2828 auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2829 ArrayRef<Loop *> NewLoops) {
2830 // If we did a non-trivial unswitch, we have added new (cloned) loops.
2831 if (!NewLoops.empty())
2832 U.addSiblingLoops(NewLoops);
2834 // If the current loop remains valid, we should revisit it to catch any
2835 // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2836 if (CurrentLoopValid)
2837 U.revisitCurrentLoop();
2838 else
2839 U.markLoopAsDeleted(L, LoopName);
2842 Optional<MemorySSAUpdater> MSSAU;
2843 if (AR.MSSA) {
2844 MSSAU = MemorySSAUpdater(AR.MSSA);
2845 if (VerifyMemorySSA)
2846 AR.MSSA->verifyMemorySSA();
2848 if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB,
2849 &AR.SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
2850 return PreservedAnalyses::all();
2852 if (AR.MSSA && VerifyMemorySSA)
2853 AR.MSSA->verifyMemorySSA();
2855 // Historically this pass has had issues with the dominator tree so verify it
2856 // in asserts builds.
2857 assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
2858 return getLoopPassPreservedAnalyses();
2861 namespace {
2863 class SimpleLoopUnswitchLegacyPass : public LoopPass {
2864 bool NonTrivial;
2866 public:
2867 static char ID; // Pass ID, replacement for typeid
2869 explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2870 : LoopPass(ID), NonTrivial(NonTrivial) {
2871 initializeSimpleLoopUnswitchLegacyPassPass(
2872 *PassRegistry::getPassRegistry());
2875 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
2877 void getAnalysisUsage(AnalysisUsage &AU) const override {
2878 AU.addRequired<AssumptionCacheTracker>();
2879 AU.addRequired<TargetTransformInfoWrapperPass>();
2880 if (EnableMSSALoopDependency) {
2881 AU.addRequired<MemorySSAWrapperPass>();
2882 AU.addPreserved<MemorySSAWrapperPass>();
2884 getLoopAnalysisUsage(AU);
2888 } // end anonymous namespace
2890 bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
2891 if (skipLoop(L))
2892 return false;
2894 Function &F = *L->getHeader()->getParent();
2896 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
2897 << "\n");
2899 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2900 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2901 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2902 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2903 MemorySSA *MSSA = nullptr;
2904 Optional<MemorySSAUpdater> MSSAU;
2905 if (EnableMSSALoopDependency) {
2906 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
2907 MSSAU = MemorySSAUpdater(MSSA);
2910 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
2911 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
2913 auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2914 ArrayRef<Loop *> NewLoops) {
2915 // If we did a non-trivial unswitch, we have added new (cloned) loops.
2916 for (auto *NewL : NewLoops)
2917 LPM.addLoop(*NewL);
2919 // If the current loop remains valid, re-add it to the queue. This is
2920 // a little wasteful as we'll finish processing the current loop as well,
2921 // but it is the best we can do in the old PM.
2922 if (CurrentLoopValid)
2923 LPM.addLoop(*L);
2924 else
2925 LPM.markLoopAsDeleted(*L);
2928 if (MSSA && VerifyMemorySSA)
2929 MSSA->verifyMemorySSA();
2931 bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE,
2932 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
2934 if (MSSA && VerifyMemorySSA)
2935 MSSA->verifyMemorySSA();
2937 // If anything was unswitched, also clear any cached information about this
2938 // loop.
2939 LPM.deleteSimpleAnalysisLoop(L);
2941 // Historically this pass has had issues with the dominator tree so verify it
2942 // in asserts builds.
2943 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2945 return Changed;
2948 char SimpleLoopUnswitchLegacyPass::ID = 0;
2949 INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2950 "Simple unswitch loops", false, false)
2951 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2952 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2953 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
2954 INITIALIZE_PASS_DEPENDENCY(LoopPass)
2955 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
2956 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2957 INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2958 "Simple unswitch loops", false, false)
2960 Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
2961 return new SimpleLoopUnswitchLegacyPass(NonTrivial);