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