1*d8b0c8ceSChandler Carruth ///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===//
21353f9a4SChandler Carruth //
31353f9a4SChandler Carruth //                     The LLVM Compiler Infrastructure
41353f9a4SChandler Carruth //
51353f9a4SChandler Carruth // This file is distributed under the University of Illinois Open Source
61353f9a4SChandler Carruth // License. See LICENSE.TXT for details.
71353f9a4SChandler Carruth //
81353f9a4SChandler Carruth //===----------------------------------------------------------------------===//
91353f9a4SChandler Carruth 
106bda14b3SChandler Carruth #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
11a369a457SEugene Zelenko #include "llvm/ADT/DenseMap.h"
126bda14b3SChandler Carruth #include "llvm/ADT/STLExtras.h"
13a369a457SEugene Zelenko #include "llvm/ADT/Sequence.h"
14a369a457SEugene Zelenko #include "llvm/ADT/SetVector.h"
151353f9a4SChandler Carruth #include "llvm/ADT/SmallPtrSet.h"
16a369a457SEugene Zelenko #include "llvm/ADT/SmallVector.h"
171353f9a4SChandler Carruth #include "llvm/ADT/Statistic.h"
18a369a457SEugene Zelenko #include "llvm/ADT/Twine.h"
191353f9a4SChandler Carruth #include "llvm/Analysis/AssumptionCache.h"
2032e62f9cSChandler Carruth #include "llvm/Analysis/CFG.h"
21693eedb1SChandler Carruth #include "llvm/Analysis/CodeMetrics.h"
224da3331dSChandler Carruth #include "llvm/Analysis/InstructionSimplify.h"
23a369a457SEugene Zelenko #include "llvm/Analysis/LoopAnalysisManager.h"
241353f9a4SChandler Carruth #include "llvm/Analysis/LoopInfo.h"
2532e62f9cSChandler Carruth #include "llvm/Analysis/LoopIterator.h"
261353f9a4SChandler Carruth #include "llvm/Analysis/LoopPass.h"
274da3331dSChandler Carruth #include "llvm/Analysis/Utils/Local.h"
28a369a457SEugene Zelenko #include "llvm/IR/BasicBlock.h"
29a369a457SEugene Zelenko #include "llvm/IR/Constant.h"
301353f9a4SChandler Carruth #include "llvm/IR/Constants.h"
311353f9a4SChandler Carruth #include "llvm/IR/Dominators.h"
321353f9a4SChandler Carruth #include "llvm/IR/Function.h"
33a369a457SEugene Zelenko #include "llvm/IR/InstrTypes.h"
34a369a457SEugene Zelenko #include "llvm/IR/Instruction.h"
351353f9a4SChandler Carruth #include "llvm/IR/Instructions.h"
36693eedb1SChandler Carruth #include "llvm/IR/IntrinsicInst.h"
37a369a457SEugene Zelenko #include "llvm/IR/Use.h"
38a369a457SEugene Zelenko #include "llvm/IR/Value.h"
39a369a457SEugene Zelenko #include "llvm/Pass.h"
40a369a457SEugene Zelenko #include "llvm/Support/Casting.h"
411353f9a4SChandler Carruth #include "llvm/Support/Debug.h"
42a369a457SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
43a369a457SEugene Zelenko #include "llvm/Support/GenericDomTree.h"
441353f9a4SChandler Carruth #include "llvm/Support/raw_ostream.h"
45693eedb1SChandler Carruth #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
461353f9a4SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47693eedb1SChandler Carruth #include "llvm/Transforms/Utils/Cloning.h"
481353f9a4SChandler Carruth #include "llvm/Transforms/Utils/LoopUtils.h"
49693eedb1SChandler Carruth #include "llvm/Transforms/Utils/ValueMapper.h"
50a369a457SEugene Zelenko #include <algorithm>
51a369a457SEugene Zelenko #include <cassert>
52a369a457SEugene Zelenko #include <iterator>
53693eedb1SChandler Carruth #include <numeric>
54a369a457SEugene Zelenko #include <utility>
551353f9a4SChandler Carruth 
561353f9a4SChandler Carruth #define DEBUG_TYPE "simple-loop-unswitch"
571353f9a4SChandler Carruth 
581353f9a4SChandler Carruth using namespace llvm;
591353f9a4SChandler Carruth 
601353f9a4SChandler Carruth STATISTIC(NumBranches, "Number of branches unswitched");
611353f9a4SChandler Carruth STATISTIC(NumSwitches, "Number of switches unswitched");
621353f9a4SChandler Carruth STATISTIC(NumTrivial, "Number of unswitches that are trivial");
631353f9a4SChandler Carruth 
64693eedb1SChandler Carruth static cl::opt<bool> EnableNonTrivialUnswitch(
65693eedb1SChandler Carruth     "enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
66693eedb1SChandler Carruth     cl::desc("Forcibly enables non-trivial loop unswitching rather than "
67693eedb1SChandler Carruth              "following the configuration passed into the pass."));
68693eedb1SChandler Carruth 
69693eedb1SChandler Carruth static cl::opt<int>
70693eedb1SChandler Carruth     UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
71693eedb1SChandler Carruth                       cl::desc("The cost threshold for unswitching a loop."));
72693eedb1SChandler Carruth 
734da3331dSChandler Carruth /// Collect all of the loop invariant input values transitively used by the
744da3331dSChandler Carruth /// homogeneous instruction graph from a given root.
754da3331dSChandler Carruth ///
764da3331dSChandler Carruth /// This essentially walks from a root recursively through loop variant operands
774da3331dSChandler Carruth /// which have the exact same opcode and finds all inputs which are loop
784da3331dSChandler Carruth /// invariant. For some operations these can be re-associated and unswitched out
794da3331dSChandler Carruth /// of the loop entirely.
80d1dab0c3SChandler Carruth static TinyPtrVector<Value *>
814da3331dSChandler Carruth collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root,
824da3331dSChandler Carruth                                          LoopInfo &LI) {
834da3331dSChandler Carruth   assert(!L.isLoopInvariant(&Root) &&
844da3331dSChandler Carruth          "Only need to walk the graph if root itself is not invariant.");
85d1dab0c3SChandler Carruth   TinyPtrVector<Value *> Invariants;
864da3331dSChandler Carruth 
874da3331dSChandler Carruth   // Build a worklist and recurse through operators collecting invariants.
884da3331dSChandler Carruth   SmallVector<Instruction *, 4> Worklist;
894da3331dSChandler Carruth   SmallPtrSet<Instruction *, 8> Visited;
904da3331dSChandler Carruth   Worklist.push_back(&Root);
914da3331dSChandler Carruth   Visited.insert(&Root);
924da3331dSChandler Carruth   do {
934da3331dSChandler Carruth     Instruction &I = *Worklist.pop_back_val();
944da3331dSChandler Carruth     for (Value *OpV : I.operand_values()) {
954da3331dSChandler Carruth       // Skip constants as unswitching isn't interesting for them.
964da3331dSChandler Carruth       if (isa<Constant>(OpV))
974da3331dSChandler Carruth         continue;
984da3331dSChandler Carruth 
994da3331dSChandler Carruth       // Add it to our result if loop invariant.
1004da3331dSChandler Carruth       if (L.isLoopInvariant(OpV)) {
1014da3331dSChandler Carruth         Invariants.push_back(OpV);
1024da3331dSChandler Carruth         continue;
1034da3331dSChandler Carruth       }
1044da3331dSChandler Carruth 
1054da3331dSChandler Carruth       // If not an instruction with the same opcode, nothing we can do.
1064da3331dSChandler Carruth       Instruction *OpI = dyn_cast<Instruction>(OpV);
1074da3331dSChandler Carruth       if (!OpI || OpI->getOpcode() != Root.getOpcode())
1084da3331dSChandler Carruth         continue;
1094da3331dSChandler Carruth 
1104da3331dSChandler Carruth       // Visit this operand.
1114da3331dSChandler Carruth       if (Visited.insert(OpI).second)
1124da3331dSChandler Carruth         Worklist.push_back(OpI);
1134da3331dSChandler Carruth     }
1144da3331dSChandler Carruth   } while (!Worklist.empty());
1154da3331dSChandler Carruth 
1164da3331dSChandler Carruth   return Invariants;
1174da3331dSChandler Carruth }
1184da3331dSChandler Carruth 
1194da3331dSChandler Carruth static void replaceLoopInvariantUses(Loop &L, Value *Invariant,
1201353f9a4SChandler Carruth                                      Constant &Replacement) {
1214da3331dSChandler Carruth   assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
1221353f9a4SChandler Carruth 
1231353f9a4SChandler Carruth   // Replace uses of LIC in the loop with the given constant.
1244da3331dSChandler Carruth   for (auto UI = Invariant->use_begin(), UE = Invariant->use_end(); UI != UE;) {
1251353f9a4SChandler Carruth     // Grab the use and walk past it so we can clobber it in the use list.
1261353f9a4SChandler Carruth     Use *U = &*UI++;
1271353f9a4SChandler Carruth     Instruction *UserI = dyn_cast<Instruction>(U->getUser());
1281353f9a4SChandler Carruth 
1291353f9a4SChandler Carruth     // Replace this use within the loop body.
1304da3331dSChandler Carruth     if (UserI && L.contains(UserI))
1314da3331dSChandler Carruth       U->set(&Replacement);
1321353f9a4SChandler Carruth   }
1331353f9a4SChandler Carruth }
1341353f9a4SChandler Carruth 
135d869b188SChandler Carruth /// Check that all the LCSSA PHI nodes in the loop exit block have trivial
136d869b188SChandler Carruth /// incoming values along this edge.
137d869b188SChandler Carruth static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB,
138d869b188SChandler Carruth                                          BasicBlock &ExitBB) {
139d869b188SChandler Carruth   for (Instruction &I : ExitBB) {
140d869b188SChandler Carruth     auto *PN = dyn_cast<PHINode>(&I);
141d869b188SChandler Carruth     if (!PN)
142d869b188SChandler Carruth       // No more PHIs to check.
143d869b188SChandler Carruth       return true;
144d869b188SChandler Carruth 
145d869b188SChandler Carruth     // If the incoming value for this edge isn't loop invariant the unswitch
146d869b188SChandler Carruth     // won't be trivial.
147d869b188SChandler Carruth     if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
148d869b188SChandler Carruth       return false;
149d869b188SChandler Carruth   }
150d869b188SChandler Carruth   llvm_unreachable("Basic blocks should never be empty!");
151d869b188SChandler Carruth }
152d869b188SChandler Carruth 
153d1dab0c3SChandler Carruth /// Insert code to test a set of loop invariant values, and conditionally branch
154d1dab0c3SChandler Carruth /// on them.
155d1dab0c3SChandler Carruth static void buildPartialUnswitchConditionalBranch(BasicBlock &BB,
156d1dab0c3SChandler Carruth                                                   ArrayRef<Value *> Invariants,
157d1dab0c3SChandler Carruth                                                   bool Direction,
158d1dab0c3SChandler Carruth                                                   BasicBlock &UnswitchedSucc,
159d1dab0c3SChandler Carruth                                                   BasicBlock &NormalSucc) {
160d1dab0c3SChandler Carruth   IRBuilder<> IRB(&BB);
161d1dab0c3SChandler Carruth   Value *Cond = Invariants.front();
162d1dab0c3SChandler Carruth   for (Value *Invariant :
163d1dab0c3SChandler Carruth        make_range(std::next(Invariants.begin()), Invariants.end()))
164d1dab0c3SChandler Carruth     if (Direction)
165d1dab0c3SChandler Carruth       Cond = IRB.CreateOr(Cond, Invariant);
166d1dab0c3SChandler Carruth     else
167d1dab0c3SChandler Carruth       Cond = IRB.CreateAnd(Cond, Invariant);
168d1dab0c3SChandler Carruth 
169d1dab0c3SChandler Carruth   IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
170d1dab0c3SChandler Carruth                    Direction ? &NormalSucc : &UnswitchedSucc);
171d1dab0c3SChandler Carruth }
172d1dab0c3SChandler Carruth 
173d869b188SChandler Carruth /// Rewrite the PHI nodes in an unswitched loop exit basic block.
174d869b188SChandler Carruth ///
175d869b188SChandler Carruth /// Requires that the loop exit and unswitched basic block are the same, and
176d869b188SChandler Carruth /// that the exiting block was a unique predecessor of that block. Rewrites the
177d869b188SChandler Carruth /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
178d869b188SChandler Carruth /// PHI nodes from the old preheader that now contains the unswitched
179d869b188SChandler Carruth /// terminator.
180d869b188SChandler Carruth static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
181d869b188SChandler Carruth                                                   BasicBlock &OldExitingBB,
182d869b188SChandler Carruth                                                   BasicBlock &OldPH) {
183c7fc81e6SBenjamin Kramer   for (PHINode &PN : UnswitchedBB.phis()) {
184d869b188SChandler Carruth     // When the loop exit is directly unswitched we just need to update the
185d869b188SChandler Carruth     // incoming basic block. We loop to handle weird cases with repeated
186d869b188SChandler Carruth     // incoming blocks, but expect to typically only have one operand here.
187c7fc81e6SBenjamin Kramer     for (auto i : seq<int>(0, PN.getNumOperands())) {
188c7fc81e6SBenjamin Kramer       assert(PN.getIncomingBlock(i) == &OldExitingBB &&
189d869b188SChandler Carruth              "Found incoming block different from unique predecessor!");
190c7fc81e6SBenjamin Kramer       PN.setIncomingBlock(i, &OldPH);
191d869b188SChandler Carruth     }
192d869b188SChandler Carruth   }
193d869b188SChandler Carruth }
194d869b188SChandler Carruth 
195d869b188SChandler Carruth /// Rewrite the PHI nodes in the loop exit basic block and the split off
196d869b188SChandler Carruth /// unswitched block.
197d869b188SChandler Carruth ///
198d869b188SChandler Carruth /// Because the exit block remains an exit from the loop, this rewrites the
199d869b188SChandler Carruth /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
200d869b188SChandler Carruth /// nodes into the unswitched basic block to select between the value in the
201d869b188SChandler Carruth /// old preheader and the loop exit.
202d869b188SChandler Carruth static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
203d869b188SChandler Carruth                                                       BasicBlock &UnswitchedBB,
204d869b188SChandler Carruth                                                       BasicBlock &OldExitingBB,
2054da3331dSChandler Carruth                                                       BasicBlock &OldPH,
2064da3331dSChandler Carruth                                                       bool FullUnswitch) {
207d869b188SChandler Carruth   assert(&ExitBB != &UnswitchedBB &&
208d869b188SChandler Carruth          "Must have different loop exit and unswitched blocks!");
209d869b188SChandler Carruth   Instruction *InsertPt = &*UnswitchedBB.begin();
210c7fc81e6SBenjamin Kramer   for (PHINode &PN : ExitBB.phis()) {
211c7fc81e6SBenjamin Kramer     auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
212c7fc81e6SBenjamin Kramer                                   PN.getName() + ".split", InsertPt);
213d869b188SChandler Carruth 
214d869b188SChandler Carruth     // Walk backwards over the old PHI node's inputs to minimize the cost of
215d869b188SChandler Carruth     // removing each one. We have to do this weird loop manually so that we
216d869b188SChandler Carruth     // create the same number of new incoming edges in the new PHI as we expect
217d869b188SChandler Carruth     // each case-based edge to be included in the unswitched switch in some
218d869b188SChandler Carruth     // cases.
219d869b188SChandler Carruth     // FIXME: This is really, really gross. It would be much cleaner if LLVM
220d869b188SChandler Carruth     // allowed us to create a single entry for a predecessor block without
221d869b188SChandler Carruth     // having separate entries for each "edge" even though these edges are
222d869b188SChandler Carruth     // required to produce identical results.
223c7fc81e6SBenjamin Kramer     for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
224c7fc81e6SBenjamin Kramer       if (PN.getIncomingBlock(i) != &OldExitingBB)
225d869b188SChandler Carruth         continue;
226d869b188SChandler Carruth 
2274da3331dSChandler Carruth       Value *Incoming = PN.getIncomingValue(i);
2284da3331dSChandler Carruth       if (FullUnswitch)
2294da3331dSChandler Carruth         // No more edge from the old exiting block to the exit block.
2304da3331dSChandler Carruth         PN.removeIncomingValue(i);
2314da3331dSChandler Carruth 
232d869b188SChandler Carruth       NewPN->addIncoming(Incoming, &OldPH);
233d869b188SChandler Carruth     }
234d869b188SChandler Carruth 
235d869b188SChandler Carruth     // Now replace the old PHI with the new one and wire the old one in as an
236d869b188SChandler Carruth     // input to the new one.
237c7fc81e6SBenjamin Kramer     PN.replaceAllUsesWith(NewPN);
238c7fc81e6SBenjamin Kramer     NewPN->addIncoming(&PN, &ExitBB);
239d869b188SChandler Carruth   }
240d869b188SChandler Carruth }
241d869b188SChandler Carruth 
242*d8b0c8ceSChandler Carruth /// Hoist the current loop up to the innermost loop containing a remaining exit.
243*d8b0c8ceSChandler Carruth ///
244*d8b0c8ceSChandler Carruth /// Because we've removed an exit from the loop, we may have changed the set of
245*d8b0c8ceSChandler Carruth /// loops reachable and need to move the current loop up the loop nest or even
246*d8b0c8ceSChandler Carruth /// to an entirely separate nest.
247*d8b0c8ceSChandler Carruth static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
248*d8b0c8ceSChandler Carruth                                  DominatorTree &DT, LoopInfo &LI) {
249*d8b0c8ceSChandler Carruth   // If the loop is already at the top level, we can't hoist it anywhere.
250*d8b0c8ceSChandler Carruth   Loop *OldParentL = L.getParentLoop();
251*d8b0c8ceSChandler Carruth   if (!OldParentL)
252*d8b0c8ceSChandler Carruth     return;
253*d8b0c8ceSChandler Carruth 
254*d8b0c8ceSChandler Carruth   SmallVector<BasicBlock *, 4> Exits;
255*d8b0c8ceSChandler Carruth   L.getExitBlocks(Exits);
256*d8b0c8ceSChandler Carruth   Loop *NewParentL = nullptr;
257*d8b0c8ceSChandler Carruth   for (auto *ExitBB : Exits)
258*d8b0c8ceSChandler Carruth     if (Loop *ExitL = LI.getLoopFor(ExitBB))
259*d8b0c8ceSChandler Carruth       if (!NewParentL || NewParentL->contains(ExitL))
260*d8b0c8ceSChandler Carruth         NewParentL = ExitL;
261*d8b0c8ceSChandler Carruth 
262*d8b0c8ceSChandler Carruth   if (NewParentL == OldParentL)
263*d8b0c8ceSChandler Carruth     return;
264*d8b0c8ceSChandler Carruth 
265*d8b0c8ceSChandler Carruth   // The new parent loop (if different) should always contain the old one.
266*d8b0c8ceSChandler Carruth   if (NewParentL)
267*d8b0c8ceSChandler Carruth     assert(NewParentL->contains(OldParentL) &&
268*d8b0c8ceSChandler Carruth            "Can only hoist this loop up the nest!");
269*d8b0c8ceSChandler Carruth 
270*d8b0c8ceSChandler Carruth   // The preheader will need to move with the body of this loop. However,
271*d8b0c8ceSChandler Carruth   // because it isn't in this loop we also need to update the primary loop map.
272*d8b0c8ceSChandler Carruth   assert(OldParentL == LI.getLoopFor(&Preheader) &&
273*d8b0c8ceSChandler Carruth          "Parent loop of this loop should contain this loop's preheader!");
274*d8b0c8ceSChandler Carruth   LI.changeLoopFor(&Preheader, NewParentL);
275*d8b0c8ceSChandler Carruth 
276*d8b0c8ceSChandler Carruth   // Remove this loop from its old parent.
277*d8b0c8ceSChandler Carruth   OldParentL->removeChildLoop(&L);
278*d8b0c8ceSChandler Carruth 
279*d8b0c8ceSChandler Carruth   // Add the loop either to the new parent or as a top-level loop.
280*d8b0c8ceSChandler Carruth   if (NewParentL)
281*d8b0c8ceSChandler Carruth     NewParentL->addChildLoop(&L);
282*d8b0c8ceSChandler Carruth   else
283*d8b0c8ceSChandler Carruth     LI.addTopLevelLoop(&L);
284*d8b0c8ceSChandler Carruth 
285*d8b0c8ceSChandler Carruth   // Remove this loops blocks from the old parent and every other loop up the
286*d8b0c8ceSChandler Carruth   // nest until reaching the new parent. Also update all of these
287*d8b0c8ceSChandler Carruth   // no-longer-containing loops to reflect the nesting change.
288*d8b0c8ceSChandler Carruth   for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
289*d8b0c8ceSChandler Carruth        OldContainingL = OldContainingL->getParentLoop()) {
290*d8b0c8ceSChandler Carruth     llvm::erase_if(OldContainingL->getBlocksVector(),
291*d8b0c8ceSChandler Carruth                    [&](const BasicBlock *BB) {
292*d8b0c8ceSChandler Carruth                      return BB == &Preheader || L.contains(BB);
293*d8b0c8ceSChandler Carruth                    });
294*d8b0c8ceSChandler Carruth 
295*d8b0c8ceSChandler Carruth     OldContainingL->getBlocksSet().erase(&Preheader);
296*d8b0c8ceSChandler Carruth     for (BasicBlock *BB : L.blocks())
297*d8b0c8ceSChandler Carruth       OldContainingL->getBlocksSet().erase(BB);
298*d8b0c8ceSChandler Carruth 
299*d8b0c8ceSChandler Carruth     // Because we just hoisted a loop out of this one, we have essentially
300*d8b0c8ceSChandler Carruth     // created new exit paths from it. That means we need to form LCSSA PHI
301*d8b0c8ceSChandler Carruth     // nodes for values used in the no-longer-nested loop.
302*d8b0c8ceSChandler Carruth     formLCSSA(*OldContainingL, DT, &LI, nullptr);
303*d8b0c8ceSChandler Carruth 
304*d8b0c8ceSChandler Carruth     // We shouldn't need to form dedicated exits because the exit introduced
305*d8b0c8ceSChandler Carruth     // here is the (just split by unswitching) preheader. As such, it is
306*d8b0c8ceSChandler Carruth     // necessarily dedicated.
307*d8b0c8ceSChandler Carruth     assert(OldContainingL->hasDedicatedExits() &&
308*d8b0c8ceSChandler Carruth            "Unexpected predecessor of hoisted loop preheader!");
309*d8b0c8ceSChandler Carruth   }
310*d8b0c8ceSChandler Carruth }
311*d8b0c8ceSChandler Carruth 
3121353f9a4SChandler Carruth /// Unswitch a trivial branch if the condition is loop invariant.
3131353f9a4SChandler Carruth ///
3141353f9a4SChandler Carruth /// This routine should only be called when loop code leading to the branch has
3151353f9a4SChandler Carruth /// been validated as trivial (no side effects). This routine checks if the
3161353f9a4SChandler Carruth /// condition is invariant and one of the successors is a loop exit. This
3171353f9a4SChandler Carruth /// allows us to unswitch without duplicating the loop, making it trivial.
3181353f9a4SChandler Carruth ///
3191353f9a4SChandler Carruth /// If this routine fails to unswitch the branch it returns false.
3201353f9a4SChandler Carruth ///
3211353f9a4SChandler Carruth /// If the branch can be unswitched, this routine splits the preheader and
3221353f9a4SChandler Carruth /// hoists the branch above that split. Preserves loop simplified form
3231353f9a4SChandler Carruth /// (splitting the exit block as necessary). It simplifies the branch within
3241353f9a4SChandler Carruth /// the loop to an unconditional branch but doesn't remove it entirely. Further
3251353f9a4SChandler Carruth /// cleanup can be done with some simplify-cfg like pass.
3263897ded6SChandler Carruth ///
3273897ded6SChandler Carruth /// If `SE` is not null, it will be updated based on the potential loop SCEVs
3283897ded6SChandler Carruth /// invalidated by this.
3291353f9a4SChandler Carruth static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
3303897ded6SChandler Carruth                                   LoopInfo &LI, ScalarEvolution *SE) {
3311353f9a4SChandler Carruth   assert(BI.isConditional() && "Can only unswitch a conditional branch!");
332d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  Trying to unswitch branch: " << BI << "\n");
3331353f9a4SChandler Carruth 
3344da3331dSChandler Carruth   // The loop invariant values that we want to unswitch.
335d1dab0c3SChandler Carruth   TinyPtrVector<Value *> Invariants;
3361353f9a4SChandler Carruth 
3374da3331dSChandler Carruth   // When true, we're fully unswitching the branch rather than just unswitching
3384da3331dSChandler Carruth   // some input conditions to the branch.
3394da3331dSChandler Carruth   bool FullUnswitch = false;
3404da3331dSChandler Carruth 
3414da3331dSChandler Carruth   if (L.isLoopInvariant(BI.getCondition())) {
3424da3331dSChandler Carruth     Invariants.push_back(BI.getCondition());
3434da3331dSChandler Carruth     FullUnswitch = true;
3444da3331dSChandler Carruth   } else {
3454da3331dSChandler Carruth     if (auto *CondInst = dyn_cast<Instruction>(BI.getCondition()))
3464da3331dSChandler Carruth       Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
3474da3331dSChandler Carruth     if (Invariants.empty())
3484da3331dSChandler Carruth       // Couldn't find invariant inputs!
3491353f9a4SChandler Carruth       return false;
3504da3331dSChandler Carruth   }
3511353f9a4SChandler Carruth 
3524da3331dSChandler Carruth   // Check that one of the branch's successors exits, and which one.
3534da3331dSChandler Carruth   bool ExitDirection = true;
3541353f9a4SChandler Carruth   int LoopExitSuccIdx = 0;
3551353f9a4SChandler Carruth   auto *LoopExitBB = BI.getSuccessor(0);
356baf045fbSChandler Carruth   if (L.contains(LoopExitBB)) {
3574da3331dSChandler Carruth     ExitDirection = false;
3581353f9a4SChandler Carruth     LoopExitSuccIdx = 1;
3591353f9a4SChandler Carruth     LoopExitBB = BI.getSuccessor(1);
360baf045fbSChandler Carruth     if (L.contains(LoopExitBB))
3611353f9a4SChandler Carruth       return false;
3621353f9a4SChandler Carruth   }
3631353f9a4SChandler Carruth   auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
364d869b188SChandler Carruth   auto *ParentBB = BI.getParent();
365d869b188SChandler Carruth   if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB))
3661353f9a4SChandler Carruth     return false;
3671353f9a4SChandler Carruth 
3684da3331dSChandler Carruth   // When unswitching only part of the branch's condition, we need the exit
3694da3331dSChandler Carruth   // block to be reached directly from the partially unswitched input. This can
3704da3331dSChandler Carruth   // be done when the exit block is along the true edge and the branch condition
3714da3331dSChandler Carruth   // is a graph of `or` operations, or the exit block is along the false edge
3724da3331dSChandler Carruth   // and the condition is a graph of `and` operations.
3734da3331dSChandler Carruth   if (!FullUnswitch) {
3744da3331dSChandler Carruth     if (ExitDirection) {
3754da3331dSChandler Carruth       if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::Or)
3764da3331dSChandler Carruth         return false;
3774da3331dSChandler Carruth     } else {
3784da3331dSChandler Carruth       if (cast<Instruction>(BI.getCondition())->getOpcode() != Instruction::And)
3794da3331dSChandler Carruth         return false;
3804da3331dSChandler Carruth     }
3814da3331dSChandler Carruth   }
3824da3331dSChandler Carruth 
3834da3331dSChandler Carruth   LLVM_DEBUG({
3844da3331dSChandler Carruth     dbgs() << "    unswitching trivial invariant conditions for: " << BI
3854da3331dSChandler Carruth            << "\n";
3864da3331dSChandler Carruth     for (Value *Invariant : Invariants) {
3874da3331dSChandler Carruth       dbgs() << "      " << *Invariant << " == true";
3884da3331dSChandler Carruth       if (Invariant != Invariants.back())
3894da3331dSChandler Carruth         dbgs() << " ||";
3904da3331dSChandler Carruth       dbgs() << "\n";
3914da3331dSChandler Carruth     }
3924da3331dSChandler Carruth   });
3931353f9a4SChandler Carruth 
3943897ded6SChandler Carruth   // If we have scalar evolutions, we need to invalidate them including this
3953897ded6SChandler Carruth   // loop and the loop containing the exit block.
3963897ded6SChandler Carruth   if (SE) {
3973897ded6SChandler Carruth     if (Loop *ExitL = LI.getLoopFor(LoopExitBB))
3983897ded6SChandler Carruth       SE->forgetLoop(ExitL);
3993897ded6SChandler Carruth     else
4003897ded6SChandler Carruth       // Forget the entire nest as this exits the entire nest.
4013897ded6SChandler Carruth       SE->forgetTopmostLoop(&L);
4023897ded6SChandler Carruth   }
4033897ded6SChandler Carruth 
4041353f9a4SChandler Carruth   // Split the preheader, so that we know that there is a safe place to insert
4051353f9a4SChandler Carruth   // the conditional branch. We will change the preheader to have a conditional
4061353f9a4SChandler Carruth   // branch on LoopCond.
4071353f9a4SChandler Carruth   BasicBlock *OldPH = L.getLoopPreheader();
4081353f9a4SChandler Carruth   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI);
4091353f9a4SChandler Carruth 
4101353f9a4SChandler Carruth   // Now that we have a place to insert the conditional branch, create a place
4111353f9a4SChandler Carruth   // to branch to: this is the exit block out of the loop that we are
4121353f9a4SChandler Carruth   // unswitching. We need to split this if there are other loop predecessors.
4131353f9a4SChandler Carruth   // Because the loop is in simplified form, *any* other predecessor is enough.
4141353f9a4SChandler Carruth   BasicBlock *UnswitchedBB;
4154da3331dSChandler Carruth   if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
4164da3331dSChandler Carruth     assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
417d869b188SChandler Carruth            "A branch's parent isn't a predecessor!");
4181353f9a4SChandler Carruth     UnswitchedBB = LoopExitBB;
4191353f9a4SChandler Carruth   } else {
4201353f9a4SChandler Carruth     UnswitchedBB = SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI);
4211353f9a4SChandler Carruth   }
4221353f9a4SChandler Carruth 
4234da3331dSChandler Carruth   // Actually move the invariant uses into the unswitched position. If possible,
4244da3331dSChandler Carruth   // we do this by moving the instructions, but when doing partial unswitching
4254da3331dSChandler Carruth   // we do it by building a new merge of the values in the unswitched position.
4261353f9a4SChandler Carruth   OldPH->getTerminator()->eraseFromParent();
4274da3331dSChandler Carruth   if (FullUnswitch) {
4284da3331dSChandler Carruth     // If fully unswitching, we can use the existing branch instruction.
4294da3331dSChandler Carruth     // Splice it into the old PH to gate reaching the new preheader and re-point
4304da3331dSChandler Carruth     // its successors.
4314da3331dSChandler Carruth     OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(),
4324da3331dSChandler Carruth                                 BI);
4331353f9a4SChandler Carruth     BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
4341353f9a4SChandler Carruth     BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
4351353f9a4SChandler Carruth 
4361353f9a4SChandler Carruth     // Create a new unconditional branch that will continue the loop as a new
4371353f9a4SChandler Carruth     // terminator.
4381353f9a4SChandler Carruth     BranchInst::Create(ContinueBB, ParentBB);
4394da3331dSChandler Carruth   } else {
4404da3331dSChandler Carruth     // Only unswitching a subset of inputs to the condition, so we will need to
4414da3331dSChandler Carruth     // build a new branch that merges the invariant inputs.
4424da3331dSChandler Carruth     if (ExitDirection)
4434da3331dSChandler Carruth       assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
4444da3331dSChandler Carruth                  Instruction::Or &&
4454da3331dSChandler Carruth              "Must have an `or` of `i1`s for the condition!");
4464da3331dSChandler Carruth     else
4474da3331dSChandler Carruth       assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
4484da3331dSChandler Carruth                  Instruction::And &&
4494da3331dSChandler Carruth              "Must have an `and` of `i1`s for the condition!");
450d1dab0c3SChandler Carruth     buildPartialUnswitchConditionalBranch(*OldPH, Invariants, ExitDirection,
451d1dab0c3SChandler Carruth                                           *UnswitchedBB, *NewPH);
4524da3331dSChandler Carruth   }
4531353f9a4SChandler Carruth 
454d869b188SChandler Carruth   // Rewrite the relevant PHI nodes.
455d869b188SChandler Carruth   if (UnswitchedBB == LoopExitBB)
456d869b188SChandler Carruth     rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
457d869b188SChandler Carruth   else
458d869b188SChandler Carruth     rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
4594da3331dSChandler Carruth                                               *ParentBB, *OldPH, FullUnswitch);
460d869b188SChandler Carruth 
4611353f9a4SChandler Carruth   // Now we need to update the dominator tree.
4624da3331dSChandler Carruth   DT.insertEdge(OldPH, UnswitchedBB);
4634da3331dSChandler Carruth   if (FullUnswitch)
4644da3331dSChandler Carruth     DT.deleteEdge(ParentBB, UnswitchedBB);
4654da3331dSChandler Carruth 
4664da3331dSChandler Carruth   // The constant we can replace all of our invariants with inside the loop
4674da3331dSChandler Carruth   // body. If any of the invariants have a value other than this the loop won't
4684da3331dSChandler Carruth   // be entered.
4694da3331dSChandler Carruth   ConstantInt *Replacement = ExitDirection
4704da3331dSChandler Carruth                                  ? ConstantInt::getFalse(BI.getContext())
4714da3331dSChandler Carruth                                  : ConstantInt::getTrue(BI.getContext());
4721353f9a4SChandler Carruth 
4731353f9a4SChandler Carruth   // Since this is an i1 condition we can also trivially replace uses of it
4741353f9a4SChandler Carruth   // within the loop with a constant.
4754da3331dSChandler Carruth   for (Value *Invariant : Invariants)
4764da3331dSChandler Carruth     replaceLoopInvariantUses(L, Invariant, *Replacement);
4771353f9a4SChandler Carruth 
478*d8b0c8ceSChandler Carruth   // If this was full unswitching, we may have changed the nesting relationship
479*d8b0c8ceSChandler Carruth   // for this loop so hoist it to its correct parent if needed.
480*d8b0c8ceSChandler Carruth   if (FullUnswitch)
481*d8b0c8ceSChandler Carruth     hoistLoopToNewParent(L, *NewPH, DT, LI);
482*d8b0c8ceSChandler Carruth 
4831353f9a4SChandler Carruth   ++NumTrivial;
4841353f9a4SChandler Carruth   ++NumBranches;
4851353f9a4SChandler Carruth   return true;
4861353f9a4SChandler Carruth }
4871353f9a4SChandler Carruth 
4881353f9a4SChandler Carruth /// Unswitch a trivial switch if the condition is loop invariant.
4891353f9a4SChandler Carruth ///
4901353f9a4SChandler Carruth /// This routine should only be called when loop code leading to the switch has
4911353f9a4SChandler Carruth /// been validated as trivial (no side effects). This routine checks if the
4921353f9a4SChandler Carruth /// condition is invariant and that at least one of the successors is a loop
4931353f9a4SChandler Carruth /// exit. This allows us to unswitch without duplicating the loop, making it
4941353f9a4SChandler Carruth /// trivial.
4951353f9a4SChandler Carruth ///
4961353f9a4SChandler Carruth /// If this routine fails to unswitch the switch it returns false.
4971353f9a4SChandler Carruth ///
4981353f9a4SChandler Carruth /// If the switch can be unswitched, this routine splits the preheader and
4991353f9a4SChandler Carruth /// copies the switch above that split. If the default case is one of the
5001353f9a4SChandler Carruth /// exiting cases, it copies the non-exiting cases and points them at the new
5011353f9a4SChandler Carruth /// preheader. If the default case is not exiting, it copies the exiting cases
5021353f9a4SChandler Carruth /// and points the default at the preheader. It preserves loop simplified form
5031353f9a4SChandler Carruth /// (splitting the exit blocks as necessary). It simplifies the switch within
5041353f9a4SChandler Carruth /// the loop by removing now-dead cases. If the default case is one of those
5051353f9a4SChandler Carruth /// unswitched, it replaces its destination with a new basic block containing
5061353f9a4SChandler Carruth /// only unreachable. Such basic blocks, while technically loop exits, are not
5071353f9a4SChandler Carruth /// considered for unswitching so this is a stable transform and the same
5081353f9a4SChandler Carruth /// switch will not be revisited. If after unswitching there is only a single
5091353f9a4SChandler Carruth /// in-loop successor, the switch is further simplified to an unconditional
5101353f9a4SChandler Carruth /// branch. Still more cleanup can be done with some simplify-cfg like pass.
5113897ded6SChandler Carruth ///
5123897ded6SChandler Carruth /// If `SE` is not null, it will be updated based on the potential loop SCEVs
5133897ded6SChandler Carruth /// invalidated by this.
5141353f9a4SChandler Carruth static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
5153897ded6SChandler Carruth                                   LoopInfo &LI, ScalarEvolution *SE) {
516d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  Trying to unswitch switch: " << SI << "\n");
5171353f9a4SChandler Carruth   Value *LoopCond = SI.getCondition();
5181353f9a4SChandler Carruth 
5191353f9a4SChandler Carruth   // If this isn't switching on an invariant condition, we can't unswitch it.
5201353f9a4SChandler Carruth   if (!L.isLoopInvariant(LoopCond))
5211353f9a4SChandler Carruth     return false;
5221353f9a4SChandler Carruth 
523d869b188SChandler Carruth   auto *ParentBB = SI.getParent();
524d869b188SChandler Carruth 
5251353f9a4SChandler Carruth   SmallVector<int, 4> ExitCaseIndices;
5261353f9a4SChandler Carruth   for (auto Case : SI.cases()) {
5271353f9a4SChandler Carruth     auto *SuccBB = Case.getCaseSuccessor();
528baf045fbSChandler Carruth     if (!L.contains(SuccBB) &&
529d869b188SChandler Carruth         areLoopExitPHIsLoopInvariant(L, *ParentBB, *SuccBB))
5301353f9a4SChandler Carruth       ExitCaseIndices.push_back(Case.getCaseIndex());
5311353f9a4SChandler Carruth   }
5321353f9a4SChandler Carruth   BasicBlock *DefaultExitBB = nullptr;
533baf045fbSChandler Carruth   if (!L.contains(SI.getDefaultDest()) &&
534d869b188SChandler Carruth       areLoopExitPHIsLoopInvariant(L, *ParentBB, *SI.getDefaultDest()) &&
5351353f9a4SChandler Carruth       !isa<UnreachableInst>(SI.getDefaultDest()->getTerminator()))
5361353f9a4SChandler Carruth     DefaultExitBB = SI.getDefaultDest();
5371353f9a4SChandler Carruth   else if (ExitCaseIndices.empty())
5381353f9a4SChandler Carruth     return false;
5391353f9a4SChandler Carruth 
540d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "    unswitching trivial cases...\n");
5411353f9a4SChandler Carruth 
5423897ded6SChandler Carruth   // We may need to invalidate SCEVs for the outermost loop reached by any of
5433897ded6SChandler Carruth   // the exits.
5443897ded6SChandler Carruth   Loop *OuterL = &L;
5453897ded6SChandler Carruth 
5461353f9a4SChandler Carruth   SmallVector<std::pair<ConstantInt *, BasicBlock *>, 4> ExitCases;
5471353f9a4SChandler Carruth   ExitCases.reserve(ExitCaseIndices.size());
5481353f9a4SChandler Carruth   // We walk the case indices backwards so that we remove the last case first
5491353f9a4SChandler Carruth   // and don't disrupt the earlier indices.
5501353f9a4SChandler Carruth   for (unsigned Index : reverse(ExitCaseIndices)) {
5511353f9a4SChandler Carruth     auto CaseI = SI.case_begin() + Index;
5523897ded6SChandler Carruth     // Compute the outer loop from this exit.
5533897ded6SChandler Carruth     Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor());
5543897ded6SChandler Carruth     if (!ExitL || ExitL->contains(OuterL))
5553897ded6SChandler Carruth       OuterL = ExitL;
5561353f9a4SChandler Carruth     // Save the value of this case.
5571353f9a4SChandler Carruth     ExitCases.push_back({CaseI->getCaseValue(), CaseI->getCaseSuccessor()});
5581353f9a4SChandler Carruth     // Delete the unswitched cases.
5591353f9a4SChandler Carruth     SI.removeCase(CaseI);
5601353f9a4SChandler Carruth   }
5611353f9a4SChandler Carruth 
5623897ded6SChandler Carruth   if (SE) {
5633897ded6SChandler Carruth     if (OuterL)
5643897ded6SChandler Carruth       SE->forgetLoop(OuterL);
5653897ded6SChandler Carruth     else
5663897ded6SChandler Carruth       SE->forgetTopmostLoop(&L);
5673897ded6SChandler Carruth   }
5683897ded6SChandler Carruth 
5691353f9a4SChandler Carruth   // Check if after this all of the remaining cases point at the same
5701353f9a4SChandler Carruth   // successor.
5711353f9a4SChandler Carruth   BasicBlock *CommonSuccBB = nullptr;
5721353f9a4SChandler Carruth   if (SI.getNumCases() > 0 &&
5731353f9a4SChandler Carruth       std::all_of(std::next(SI.case_begin()), SI.case_end(),
5741353f9a4SChandler Carruth                   [&SI](const SwitchInst::CaseHandle &Case) {
5751353f9a4SChandler Carruth                     return Case.getCaseSuccessor() ==
5761353f9a4SChandler Carruth                            SI.case_begin()->getCaseSuccessor();
5771353f9a4SChandler Carruth                   }))
5781353f9a4SChandler Carruth     CommonSuccBB = SI.case_begin()->getCaseSuccessor();
5791353f9a4SChandler Carruth 
5801353f9a4SChandler Carruth   if (DefaultExitBB) {
5811353f9a4SChandler Carruth     // We can't remove the default edge so replace it with an edge to either
5821353f9a4SChandler Carruth     // the single common remaining successor (if we have one) or an unreachable
5831353f9a4SChandler Carruth     // block.
5841353f9a4SChandler Carruth     if (CommonSuccBB) {
5851353f9a4SChandler Carruth       SI.setDefaultDest(CommonSuccBB);
5861353f9a4SChandler Carruth     } else {
5871353f9a4SChandler Carruth       BasicBlock *UnreachableBB = BasicBlock::Create(
5881353f9a4SChandler Carruth           ParentBB->getContext(),
5891353f9a4SChandler Carruth           Twine(ParentBB->getName()) + ".unreachable_default",
5901353f9a4SChandler Carruth           ParentBB->getParent());
5911353f9a4SChandler Carruth       new UnreachableInst(ParentBB->getContext(), UnreachableBB);
5921353f9a4SChandler Carruth       SI.setDefaultDest(UnreachableBB);
5931353f9a4SChandler Carruth       DT.addNewBlock(UnreachableBB, ParentBB);
5941353f9a4SChandler Carruth     }
5951353f9a4SChandler Carruth   } else {
5961353f9a4SChandler Carruth     // If we're not unswitching the default, we need it to match any cases to
5971353f9a4SChandler Carruth     // have a common successor or if we have no cases it is the common
5981353f9a4SChandler Carruth     // successor.
5991353f9a4SChandler Carruth     if (SI.getNumCases() == 0)
6001353f9a4SChandler Carruth       CommonSuccBB = SI.getDefaultDest();
6011353f9a4SChandler Carruth     else if (SI.getDefaultDest() != CommonSuccBB)
6021353f9a4SChandler Carruth       CommonSuccBB = nullptr;
6031353f9a4SChandler Carruth   }
6041353f9a4SChandler Carruth 
6051353f9a4SChandler Carruth   // Split the preheader, so that we know that there is a safe place to insert
6061353f9a4SChandler Carruth   // the switch.
6071353f9a4SChandler Carruth   BasicBlock *OldPH = L.getLoopPreheader();
6081353f9a4SChandler Carruth   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI);
6091353f9a4SChandler Carruth   OldPH->getTerminator()->eraseFromParent();
6101353f9a4SChandler Carruth 
6111353f9a4SChandler Carruth   // Now add the unswitched switch.
6121353f9a4SChandler Carruth   auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
6131353f9a4SChandler Carruth 
614d869b188SChandler Carruth   // Rewrite the IR for the unswitched basic blocks. This requires two steps.
615d869b188SChandler Carruth   // First, we split any exit blocks with remaining in-loop predecessors. Then
616d869b188SChandler Carruth   // we update the PHIs in one of two ways depending on if there was a split.
617d869b188SChandler Carruth   // We walk in reverse so that we split in the same order as the cases
618d869b188SChandler Carruth   // appeared. This is purely for convenience of reading the resulting IR, but
619d869b188SChandler Carruth   // it doesn't cost anything really.
620d869b188SChandler Carruth   SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
6211353f9a4SChandler Carruth   SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
6221353f9a4SChandler Carruth   // Handle the default exit if necessary.
6231353f9a4SChandler Carruth   // FIXME: It'd be great if we could merge this with the loop below but LLVM's
6241353f9a4SChandler Carruth   // ranges aren't quite powerful enough yet.
625d869b188SChandler Carruth   if (DefaultExitBB) {
626d869b188SChandler Carruth     if (pred_empty(DefaultExitBB)) {
627d869b188SChandler Carruth       UnswitchedExitBBs.insert(DefaultExitBB);
628d869b188SChandler Carruth       rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
629d869b188SChandler Carruth     } else {
6301353f9a4SChandler Carruth       auto *SplitBB =
6311353f9a4SChandler Carruth           SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI);
6324da3331dSChandler Carruth       rewritePHINodesForExitAndUnswitchedBlocks(
6334da3331dSChandler Carruth           *DefaultExitBB, *SplitBB, *ParentBB, *OldPH, /*FullUnswitch*/ true);
6341353f9a4SChandler Carruth       DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
6351353f9a4SChandler Carruth     }
636d869b188SChandler Carruth   }
6371353f9a4SChandler Carruth   // Note that we must use a reference in the for loop so that we update the
6381353f9a4SChandler Carruth   // container.
6391353f9a4SChandler Carruth   for (auto &CasePair : reverse(ExitCases)) {
6401353f9a4SChandler Carruth     // Grab a reference to the exit block in the pair so that we can update it.
641d869b188SChandler Carruth     BasicBlock *ExitBB = CasePair.second;
6421353f9a4SChandler Carruth 
6431353f9a4SChandler Carruth     // If this case is the last edge into the exit block, we can simply reuse it
6441353f9a4SChandler Carruth     // as it will no longer be a loop exit. No mapping necessary.
645d869b188SChandler Carruth     if (pred_empty(ExitBB)) {
646d869b188SChandler Carruth       // Only rewrite once.
647d869b188SChandler Carruth       if (UnswitchedExitBBs.insert(ExitBB).second)
648d869b188SChandler Carruth         rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
6491353f9a4SChandler Carruth       continue;
650d869b188SChandler Carruth     }
6511353f9a4SChandler Carruth 
6521353f9a4SChandler Carruth     // Otherwise we need to split the exit block so that we retain an exit
6531353f9a4SChandler Carruth     // block from the loop and a target for the unswitched condition.
6541353f9a4SChandler Carruth     BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
6551353f9a4SChandler Carruth     if (!SplitExitBB) {
6561353f9a4SChandler Carruth       // If this is the first time we see this, do the split and remember it.
6571353f9a4SChandler Carruth       SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI);
6584da3331dSChandler Carruth       rewritePHINodesForExitAndUnswitchedBlocks(
6594da3331dSChandler Carruth           *ExitBB, *SplitExitBB, *ParentBB, *OldPH, /*FullUnswitch*/ true);
6601353f9a4SChandler Carruth     }
661d869b188SChandler Carruth     // Update the case pair to point to the split block.
662d869b188SChandler Carruth     CasePair.second = SplitExitBB;
6631353f9a4SChandler Carruth   }
6641353f9a4SChandler Carruth 
6651353f9a4SChandler Carruth   // Now add the unswitched cases. We do this in reverse order as we built them
6661353f9a4SChandler Carruth   // in reverse order.
6671353f9a4SChandler Carruth   for (auto CasePair : reverse(ExitCases)) {
6681353f9a4SChandler Carruth     ConstantInt *CaseVal = CasePair.first;
6691353f9a4SChandler Carruth     BasicBlock *UnswitchedBB = CasePair.second;
6701353f9a4SChandler Carruth 
6711353f9a4SChandler Carruth     NewSI->addCase(CaseVal, UnswitchedBB);
6721353f9a4SChandler Carruth   }
6731353f9a4SChandler Carruth 
6741353f9a4SChandler Carruth   // If the default was unswitched, re-point it and add explicit cases for
6751353f9a4SChandler Carruth   // entering the loop.
6761353f9a4SChandler Carruth   if (DefaultExitBB) {
6771353f9a4SChandler Carruth     NewSI->setDefaultDest(DefaultExitBB);
6781353f9a4SChandler Carruth 
6791353f9a4SChandler Carruth     // We removed all the exit cases, so we just copy the cases to the
6801353f9a4SChandler Carruth     // unswitched switch.
6811353f9a4SChandler Carruth     for (auto Case : SI.cases())
6821353f9a4SChandler Carruth       NewSI->addCase(Case.getCaseValue(), NewPH);
6831353f9a4SChandler Carruth   }
6841353f9a4SChandler Carruth 
6851353f9a4SChandler Carruth   // If we ended up with a common successor for every path through the switch
6861353f9a4SChandler Carruth   // after unswitching, rewrite it to an unconditional branch to make it easy
6871353f9a4SChandler Carruth   // to recognize. Otherwise we potentially have to recognize the default case
6881353f9a4SChandler Carruth   // pointing at unreachable and other complexity.
6891353f9a4SChandler Carruth   if (CommonSuccBB) {
6901353f9a4SChandler Carruth     BasicBlock *BB = SI.getParent();
6911353f9a4SChandler Carruth     SI.eraseFromParent();
6921353f9a4SChandler Carruth     BranchInst::Create(CommonSuccBB, BB);
6931353f9a4SChandler Carruth   }
6941353f9a4SChandler Carruth 
6952c85a231SChandler Carruth   // Walk the unswitched exit blocks and the unswitched split blocks and update
6962c85a231SChandler Carruth   // the dominator tree based on the CFG edits. While we are walking unordered
6972c85a231SChandler Carruth   // containers here, the API for applyUpdates takes an unordered list of
6982c85a231SChandler Carruth   // updates and requires them to not contain duplicates.
6992c85a231SChandler Carruth   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
7002c85a231SChandler Carruth   for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
7012c85a231SChandler Carruth     DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
7022c85a231SChandler Carruth     DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
7032c85a231SChandler Carruth   }
7042c85a231SChandler Carruth   for (auto SplitUnswitchedPair : SplitExitBBMap) {
7052c85a231SChandler Carruth     auto *UnswitchedBB = SplitUnswitchedPair.second;
7062c85a231SChandler Carruth     DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedBB});
7072c85a231SChandler Carruth     DTUpdates.push_back({DT.Insert, OldPH, UnswitchedBB});
7082c85a231SChandler Carruth   }
7092c85a231SChandler Carruth   DT.applyUpdates(DTUpdates);
7107c35de12SDavid Green   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
711*d8b0c8ceSChandler Carruth 
712*d8b0c8ceSChandler Carruth   // We may have changed the nesting relationship for this loop so hoist it to
713*d8b0c8ceSChandler Carruth   // its correct parent if needed.
714*d8b0c8ceSChandler Carruth   hoistLoopToNewParent(L, *NewPH, DT, LI);
715*d8b0c8ceSChandler Carruth 
7161353f9a4SChandler Carruth   ++NumTrivial;
7171353f9a4SChandler Carruth   ++NumSwitches;
7181353f9a4SChandler Carruth   return true;
7191353f9a4SChandler Carruth }
7201353f9a4SChandler Carruth 
7211353f9a4SChandler Carruth /// This routine scans the loop to find a branch or switch which occurs before
7221353f9a4SChandler Carruth /// any side effects occur. These can potentially be unswitched without
7231353f9a4SChandler Carruth /// duplicating the loop. If a branch or switch is successfully unswitched the
7241353f9a4SChandler Carruth /// scanning continues to see if subsequent branches or switches have become
7251353f9a4SChandler Carruth /// trivial. Once all trivial candidates have been unswitched, this routine
7261353f9a4SChandler Carruth /// returns.
7271353f9a4SChandler Carruth ///
7281353f9a4SChandler Carruth /// The return value indicates whether anything was unswitched (and therefore
7291353f9a4SChandler Carruth /// changed).
7303897ded6SChandler Carruth ///
7313897ded6SChandler Carruth /// If `SE` is not null, it will be updated based on the potential loop SCEVs
7323897ded6SChandler Carruth /// invalidated by this.
7331353f9a4SChandler Carruth static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
7343897ded6SChandler Carruth                                          LoopInfo &LI, ScalarEvolution *SE) {
7351353f9a4SChandler Carruth   bool Changed = false;
7361353f9a4SChandler Carruth 
7371353f9a4SChandler Carruth   // If loop header has only one reachable successor we should keep looking for
7381353f9a4SChandler Carruth   // trivial condition candidates in the successor as well. An alternative is
7391353f9a4SChandler Carruth   // to constant fold conditions and merge successors into loop header (then we
7401353f9a4SChandler Carruth   // only need to check header's terminator). The reason for not doing this in
7411353f9a4SChandler Carruth   // LoopUnswitch pass is that it could potentially break LoopPassManager's
7421353f9a4SChandler Carruth   // invariants. Folding dead branches could either eliminate the current loop
7431353f9a4SChandler Carruth   // or make other loops unreachable. LCSSA form might also not be preserved
7441353f9a4SChandler Carruth   // after deleting branches. The following code keeps traversing loop header's
7451353f9a4SChandler Carruth   // successors until it finds the trivial condition candidate (condition that
7461353f9a4SChandler Carruth   // is not a constant). Since unswitching generates branches with constant
7471353f9a4SChandler Carruth   // conditions, this scenario could be very common in practice.
7481353f9a4SChandler Carruth   BasicBlock *CurrentBB = L.getHeader();
7491353f9a4SChandler Carruth   SmallPtrSet<BasicBlock *, 8> Visited;
7501353f9a4SChandler Carruth   Visited.insert(CurrentBB);
7511353f9a4SChandler Carruth   do {
7521353f9a4SChandler Carruth     // Check if there are any side-effecting instructions (e.g. stores, calls,
7531353f9a4SChandler Carruth     // volatile loads) in the part of the loop that the code *would* execute
7541353f9a4SChandler Carruth     // without unswitching.
7551353f9a4SChandler Carruth     if (llvm::any_of(*CurrentBB,
7561353f9a4SChandler Carruth                      [](Instruction &I) { return I.mayHaveSideEffects(); }))
7571353f9a4SChandler Carruth       return Changed;
7581353f9a4SChandler Carruth 
7591353f9a4SChandler Carruth     TerminatorInst *CurrentTerm = CurrentBB->getTerminator();
7601353f9a4SChandler Carruth 
7611353f9a4SChandler Carruth     if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
7621353f9a4SChandler Carruth       // Don't bother trying to unswitch past a switch with a constant
7631353f9a4SChandler Carruth       // condition. This should be removed prior to running this pass by
7641353f9a4SChandler Carruth       // simplify-cfg.
7651353f9a4SChandler Carruth       if (isa<Constant>(SI->getCondition()))
7661353f9a4SChandler Carruth         return Changed;
7671353f9a4SChandler Carruth 
7683897ded6SChandler Carruth       if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE))
769f209649dSHiroshi Inoue         // Couldn't unswitch this one so we're done.
7701353f9a4SChandler Carruth         return Changed;
7711353f9a4SChandler Carruth 
7721353f9a4SChandler Carruth       // Mark that we managed to unswitch something.
7731353f9a4SChandler Carruth       Changed = true;
7741353f9a4SChandler Carruth 
7751353f9a4SChandler Carruth       // If unswitching turned the terminator into an unconditional branch then
7761353f9a4SChandler Carruth       // we can continue. The unswitching logic specifically works to fold any
7771353f9a4SChandler Carruth       // cases it can into an unconditional branch to make it easier to
7781353f9a4SChandler Carruth       // recognize here.
7791353f9a4SChandler Carruth       auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
7801353f9a4SChandler Carruth       if (!BI || BI->isConditional())
7811353f9a4SChandler Carruth         return Changed;
7821353f9a4SChandler Carruth 
7831353f9a4SChandler Carruth       CurrentBB = BI->getSuccessor(0);
7841353f9a4SChandler Carruth       continue;
7851353f9a4SChandler Carruth     }
7861353f9a4SChandler Carruth 
7871353f9a4SChandler Carruth     auto *BI = dyn_cast<BranchInst>(CurrentTerm);
7881353f9a4SChandler Carruth     if (!BI)
7891353f9a4SChandler Carruth       // We do not understand other terminator instructions.
7901353f9a4SChandler Carruth       return Changed;
7911353f9a4SChandler Carruth 
7921353f9a4SChandler Carruth     // Don't bother trying to unswitch past an unconditional branch or a branch
7931353f9a4SChandler Carruth     // with a constant value. These should be removed by simplify-cfg prior to
7941353f9a4SChandler Carruth     // running this pass.
7951353f9a4SChandler Carruth     if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
7961353f9a4SChandler Carruth       return Changed;
7971353f9a4SChandler Carruth 
7981353f9a4SChandler Carruth     // Found a trivial condition candidate: non-foldable conditional branch. If
7991353f9a4SChandler Carruth     // we fail to unswitch this, we can't do anything else that is trivial.
8003897ded6SChandler Carruth     if (!unswitchTrivialBranch(L, *BI, DT, LI, SE))
8011353f9a4SChandler Carruth       return Changed;
8021353f9a4SChandler Carruth 
8031353f9a4SChandler Carruth     // Mark that we managed to unswitch something.
8041353f9a4SChandler Carruth     Changed = true;
8051353f9a4SChandler Carruth 
8064da3331dSChandler Carruth     // If we only unswitched some of the conditions feeding the branch, we won't
8074da3331dSChandler Carruth     // have collapsed it to a single successor.
8081353f9a4SChandler Carruth     BI = cast<BranchInst>(CurrentBB->getTerminator());
8094da3331dSChandler Carruth     if (BI->isConditional())
8104da3331dSChandler Carruth       return Changed;
8114da3331dSChandler Carruth 
8124da3331dSChandler Carruth     // Follow the newly unconditional branch into its successor.
8131353f9a4SChandler Carruth     CurrentBB = BI->getSuccessor(0);
8141353f9a4SChandler Carruth 
8151353f9a4SChandler Carruth     // When continuing, if we exit the loop or reach a previous visited block,
8161353f9a4SChandler Carruth     // then we can not reach any trivial condition candidates (unfoldable
8171353f9a4SChandler Carruth     // branch instructions or switch instructions) and no unswitch can happen.
8181353f9a4SChandler Carruth   } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
8191353f9a4SChandler Carruth 
8201353f9a4SChandler Carruth   return Changed;
8211353f9a4SChandler Carruth }
8221353f9a4SChandler Carruth 
823693eedb1SChandler Carruth /// Build the cloned blocks for an unswitched copy of the given loop.
824693eedb1SChandler Carruth ///
825693eedb1SChandler Carruth /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
826693eedb1SChandler Carruth /// after the split block (`SplitBB`) that will be used to select between the
827693eedb1SChandler Carruth /// cloned and original loop.
828693eedb1SChandler Carruth ///
829693eedb1SChandler Carruth /// This routine handles cloning all of the necessary loop blocks and exit
830693eedb1SChandler Carruth /// blocks including rewriting their instructions and the relevant PHI nodes.
8311652996fSChandler Carruth /// Any loop blocks or exit blocks which are dominated by a different successor
8321652996fSChandler Carruth /// than the one for this clone of the loop blocks can be trivially skipped. We
8331652996fSChandler Carruth /// use the `DominatingSucc` map to determine whether a block satisfies that
8341652996fSChandler Carruth /// property with a simple map lookup.
8351652996fSChandler Carruth ///
8361652996fSChandler Carruth /// It also correctly creates the unconditional branch in the cloned
837693eedb1SChandler Carruth /// unswitched parent block to only point at the unswitched successor.
838693eedb1SChandler Carruth ///
839693eedb1SChandler Carruth /// This does not handle most of the necessary updates to `LoopInfo`. Only exit
840693eedb1SChandler Carruth /// block splitting is correctly reflected in `LoopInfo`, essentially all of
841693eedb1SChandler Carruth /// the cloned blocks (and their loops) are left without full `LoopInfo`
842693eedb1SChandler Carruth /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
843693eedb1SChandler Carruth /// blocks to them but doesn't create the cloned `DominatorTree` structure and
844693eedb1SChandler Carruth /// instead the caller must recompute an accurate DT. It *does* correctly
845693eedb1SChandler Carruth /// update the `AssumptionCache` provided in `AC`.
846693eedb1SChandler Carruth static BasicBlock *buildClonedLoopBlocks(
847693eedb1SChandler Carruth     Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
848693eedb1SChandler Carruth     ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
849693eedb1SChandler Carruth     BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
8501652996fSChandler Carruth     const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
85169e68f84SChandler Carruth     ValueToValueMapTy &VMap,
85269e68f84SChandler Carruth     SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
85369e68f84SChandler Carruth     DominatorTree &DT, LoopInfo &LI) {
854693eedb1SChandler Carruth   SmallVector<BasicBlock *, 4> NewBlocks;
855693eedb1SChandler Carruth   NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
856693eedb1SChandler Carruth 
857693eedb1SChandler Carruth   // We will need to clone a bunch of blocks, wrap up the clone operation in
858693eedb1SChandler Carruth   // a helper.
859693eedb1SChandler Carruth   auto CloneBlock = [&](BasicBlock *OldBB) {
860693eedb1SChandler Carruth     // Clone the basic block and insert it before the new preheader.
861693eedb1SChandler Carruth     BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
862693eedb1SChandler Carruth     NewBB->moveBefore(LoopPH);
863693eedb1SChandler Carruth 
864693eedb1SChandler Carruth     // Record this block and the mapping.
865693eedb1SChandler Carruth     NewBlocks.push_back(NewBB);
866693eedb1SChandler Carruth     VMap[OldBB] = NewBB;
867693eedb1SChandler Carruth 
868693eedb1SChandler Carruth     return NewBB;
869693eedb1SChandler Carruth   };
870693eedb1SChandler Carruth 
8711652996fSChandler Carruth   // We skip cloning blocks when they have a dominating succ that is not the
8721652996fSChandler Carruth   // succ we are cloning for.
8731652996fSChandler Carruth   auto SkipBlock = [&](BasicBlock *BB) {
8741652996fSChandler Carruth     auto It = DominatingSucc.find(BB);
8751652996fSChandler Carruth     return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
8761652996fSChandler Carruth   };
8771652996fSChandler Carruth 
878693eedb1SChandler Carruth   // First, clone the preheader.
879693eedb1SChandler Carruth   auto *ClonedPH = CloneBlock(LoopPH);
880693eedb1SChandler Carruth 
881693eedb1SChandler Carruth   // Then clone all the loop blocks, skipping the ones that aren't necessary.
882693eedb1SChandler Carruth   for (auto *LoopBB : L.blocks())
8831652996fSChandler Carruth     if (!SkipBlock(LoopBB))
884693eedb1SChandler Carruth       CloneBlock(LoopBB);
885693eedb1SChandler Carruth 
886693eedb1SChandler Carruth   // Split all the loop exit edges so that when we clone the exit blocks, if
887693eedb1SChandler Carruth   // any of the exit blocks are *also* a preheader for some other loop, we
888693eedb1SChandler Carruth   // don't create multiple predecessors entering the loop header.
889693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks) {
8901652996fSChandler Carruth     if (SkipBlock(ExitBB))
891693eedb1SChandler Carruth       continue;
892693eedb1SChandler Carruth 
893693eedb1SChandler Carruth     // When we are going to clone an exit, we don't need to clone all the
894693eedb1SChandler Carruth     // instructions in the exit block and we want to ensure we have an easy
895693eedb1SChandler Carruth     // place to merge the CFG, so split the exit first. This is always safe to
896693eedb1SChandler Carruth     // do because there cannot be any non-loop predecessors of a loop exit in
897693eedb1SChandler Carruth     // loop simplified form.
898693eedb1SChandler Carruth     auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI);
899693eedb1SChandler Carruth 
900693eedb1SChandler Carruth     // Rearrange the names to make it easier to write test cases by having the
901693eedb1SChandler Carruth     // exit block carry the suffix rather than the merge block carrying the
902693eedb1SChandler Carruth     // suffix.
903693eedb1SChandler Carruth     MergeBB->takeName(ExitBB);
904693eedb1SChandler Carruth     ExitBB->setName(Twine(MergeBB->getName()) + ".split");
905693eedb1SChandler Carruth 
906693eedb1SChandler Carruth     // Now clone the original exit block.
907693eedb1SChandler Carruth     auto *ClonedExitBB = CloneBlock(ExitBB);
908693eedb1SChandler Carruth     assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
909693eedb1SChandler Carruth            "Exit block should have been split to have one successor!");
910693eedb1SChandler Carruth     assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
911693eedb1SChandler Carruth            "Cloned exit block has the wrong successor!");
912693eedb1SChandler Carruth 
913693eedb1SChandler Carruth     // Remap any cloned instructions and create a merge phi node for them.
914693eedb1SChandler Carruth     for (auto ZippedInsts : llvm::zip_first(
915693eedb1SChandler Carruth              llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
916693eedb1SChandler Carruth              llvm::make_range(ClonedExitBB->begin(),
917693eedb1SChandler Carruth                               std::prev(ClonedExitBB->end())))) {
918693eedb1SChandler Carruth       Instruction &I = std::get<0>(ZippedInsts);
919693eedb1SChandler Carruth       Instruction &ClonedI = std::get<1>(ZippedInsts);
920693eedb1SChandler Carruth 
921693eedb1SChandler Carruth       // The only instructions in the exit block should be PHI nodes and
922693eedb1SChandler Carruth       // potentially a landing pad.
923693eedb1SChandler Carruth       assert(
924693eedb1SChandler Carruth           (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
925693eedb1SChandler Carruth           "Bad instruction in exit block!");
926693eedb1SChandler Carruth       // We should have a value map between the instruction and its clone.
927693eedb1SChandler Carruth       assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
928693eedb1SChandler Carruth 
929693eedb1SChandler Carruth       auto *MergePN =
930693eedb1SChandler Carruth           PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
931693eedb1SChandler Carruth                           &*MergeBB->getFirstInsertionPt());
932693eedb1SChandler Carruth       I.replaceAllUsesWith(MergePN);
933693eedb1SChandler Carruth       MergePN->addIncoming(&I, ExitBB);
934693eedb1SChandler Carruth       MergePN->addIncoming(&ClonedI, ClonedExitBB);
935693eedb1SChandler Carruth     }
936693eedb1SChandler Carruth   }
937693eedb1SChandler Carruth 
938693eedb1SChandler Carruth   // Rewrite the instructions in the cloned blocks to refer to the instructions
939693eedb1SChandler Carruth   // in the cloned blocks. We have to do this as a second pass so that we have
940693eedb1SChandler Carruth   // everything available. Also, we have inserted new instructions which may
941693eedb1SChandler Carruth   // include assume intrinsics, so we update the assumption cache while
942693eedb1SChandler Carruth   // processing this.
943693eedb1SChandler Carruth   for (auto *ClonedBB : NewBlocks)
944693eedb1SChandler Carruth     for (Instruction &I : *ClonedBB) {
945693eedb1SChandler Carruth       RemapInstruction(&I, VMap,
946693eedb1SChandler Carruth                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
947693eedb1SChandler Carruth       if (auto *II = dyn_cast<IntrinsicInst>(&I))
948693eedb1SChandler Carruth         if (II->getIntrinsicID() == Intrinsic::assume)
949693eedb1SChandler Carruth           AC.registerAssumption(II);
950693eedb1SChandler Carruth     }
951693eedb1SChandler Carruth 
952693eedb1SChandler Carruth   // Remove the cloned parent as a predecessor of the cloned continue successor
953693eedb1SChandler Carruth   // if we did in fact clone it.
954693eedb1SChandler Carruth   auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
955693eedb1SChandler Carruth   if (auto *ClonedContinueSuccBB =
956693eedb1SChandler Carruth           cast_or_null<BasicBlock>(VMap.lookup(ContinueSuccBB)))
957693eedb1SChandler Carruth     ClonedContinueSuccBB->removePredecessor(ClonedParentBB,
958693eedb1SChandler Carruth                                             /*DontDeleteUselessPHIs*/ true);
959b5254241SChandler Carruth   // Replace the cloned branch with an unconditional branch to the cloned
960693eedb1SChandler Carruth   // unswitched successor.
961693eedb1SChandler Carruth   auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
962693eedb1SChandler Carruth   ClonedParentBB->getTerminator()->eraseFromParent();
963693eedb1SChandler Carruth   BranchInst::Create(ClonedSuccBB, ClonedParentBB);
964693eedb1SChandler Carruth 
965693eedb1SChandler Carruth   // Update any PHI nodes in the cloned successors of the skipped blocks to not
966693eedb1SChandler Carruth   // have spurious incoming values.
967693eedb1SChandler Carruth   for (auto *LoopBB : L.blocks())
9681652996fSChandler Carruth     if (SkipBlock(LoopBB))
969693eedb1SChandler Carruth       for (auto *SuccBB : successors(LoopBB))
970693eedb1SChandler Carruth         if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
971693eedb1SChandler Carruth           for (PHINode &PN : ClonedSuccBB->phis())
972693eedb1SChandler Carruth             PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
973693eedb1SChandler Carruth 
97469e68f84SChandler Carruth   // Record the domtree updates for the new blocks.
97544aab925SChandler Carruth   SmallPtrSet<BasicBlock *, 4> SuccSet;
97644aab925SChandler Carruth   for (auto *ClonedBB : NewBlocks) {
97769e68f84SChandler Carruth     for (auto *SuccBB : successors(ClonedBB))
97844aab925SChandler Carruth       if (SuccSet.insert(SuccBB).second)
97969e68f84SChandler Carruth         DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
98044aab925SChandler Carruth     SuccSet.clear();
98144aab925SChandler Carruth   }
98269e68f84SChandler Carruth 
983693eedb1SChandler Carruth   return ClonedPH;
984693eedb1SChandler Carruth }
985693eedb1SChandler Carruth 
986693eedb1SChandler Carruth /// Recursively clone the specified loop and all of its children.
987693eedb1SChandler Carruth ///
988693eedb1SChandler Carruth /// The target parent loop for the clone should be provided, or can be null if
989693eedb1SChandler Carruth /// the clone is a top-level loop. While cloning, all the blocks are mapped
990693eedb1SChandler Carruth /// with the provided value map. The entire original loop must be present in
991693eedb1SChandler Carruth /// the value map. The cloned loop is returned.
992693eedb1SChandler Carruth static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
993693eedb1SChandler Carruth                            const ValueToValueMapTy &VMap, LoopInfo &LI) {
994693eedb1SChandler Carruth   auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
995693eedb1SChandler Carruth     assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
996693eedb1SChandler Carruth     ClonedL.reserveBlocks(OrigL.getNumBlocks());
997693eedb1SChandler Carruth     for (auto *BB : OrigL.blocks()) {
998693eedb1SChandler Carruth       auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
999693eedb1SChandler Carruth       ClonedL.addBlockEntry(ClonedBB);
10000ace148cSChandler Carruth       if (LI.getLoopFor(BB) == &OrigL)
1001693eedb1SChandler Carruth         LI.changeLoopFor(ClonedBB, &ClonedL);
1002693eedb1SChandler Carruth     }
1003693eedb1SChandler Carruth   };
1004693eedb1SChandler Carruth 
1005693eedb1SChandler Carruth   // We specially handle the first loop because it may get cloned into
1006693eedb1SChandler Carruth   // a different parent and because we most commonly are cloning leaf loops.
1007693eedb1SChandler Carruth   Loop *ClonedRootL = LI.AllocateLoop();
1008693eedb1SChandler Carruth   if (RootParentL)
1009693eedb1SChandler Carruth     RootParentL->addChildLoop(ClonedRootL);
1010693eedb1SChandler Carruth   else
1011693eedb1SChandler Carruth     LI.addTopLevelLoop(ClonedRootL);
1012693eedb1SChandler Carruth   AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1013693eedb1SChandler Carruth 
1014693eedb1SChandler Carruth   if (OrigRootL.empty())
1015693eedb1SChandler Carruth     return ClonedRootL;
1016693eedb1SChandler Carruth 
1017693eedb1SChandler Carruth   // If we have a nest, we can quickly clone the entire loop nest using an
1018693eedb1SChandler Carruth   // iterative approach because it is a tree. We keep the cloned parent in the
1019693eedb1SChandler Carruth   // data structure to avoid repeatedly querying through a map to find it.
1020693eedb1SChandler Carruth   SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1021693eedb1SChandler Carruth   // Build up the loops to clone in reverse order as we'll clone them from the
1022693eedb1SChandler Carruth   // back.
1023693eedb1SChandler Carruth   for (Loop *ChildL : llvm::reverse(OrigRootL))
1024693eedb1SChandler Carruth     LoopsToClone.push_back({ClonedRootL, ChildL});
1025693eedb1SChandler Carruth   do {
1026693eedb1SChandler Carruth     Loop *ClonedParentL, *L;
1027693eedb1SChandler Carruth     std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1028693eedb1SChandler Carruth     Loop *ClonedL = LI.AllocateLoop();
1029693eedb1SChandler Carruth     ClonedParentL->addChildLoop(ClonedL);
1030693eedb1SChandler Carruth     AddClonedBlocksToLoop(*L, *ClonedL);
1031693eedb1SChandler Carruth     for (Loop *ChildL : llvm::reverse(*L))
1032693eedb1SChandler Carruth       LoopsToClone.push_back({ClonedL, ChildL});
1033693eedb1SChandler Carruth   } while (!LoopsToClone.empty());
1034693eedb1SChandler Carruth 
1035693eedb1SChandler Carruth   return ClonedRootL;
1036693eedb1SChandler Carruth }
1037693eedb1SChandler Carruth 
1038693eedb1SChandler Carruth /// Build the cloned loops of an original loop from unswitching.
1039693eedb1SChandler Carruth ///
1040693eedb1SChandler Carruth /// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1041693eedb1SChandler Carruth /// operation. We need to re-verify that there even is a loop (as the backedge
1042693eedb1SChandler Carruth /// may not have been cloned), and even if there are remaining backedges the
1043693eedb1SChandler Carruth /// backedge set may be different. However, we know that each child loop is
1044693eedb1SChandler Carruth /// undisturbed, we only need to find where to place each child loop within
1045693eedb1SChandler Carruth /// either any parent loop or within a cloned version of the original loop.
1046693eedb1SChandler Carruth ///
1047693eedb1SChandler Carruth /// Because child loops may end up cloned outside of any cloned version of the
1048693eedb1SChandler Carruth /// original loop, multiple cloned sibling loops may be created. All of them
1049693eedb1SChandler Carruth /// are returned so that the newly introduced loop nest roots can be
1050693eedb1SChandler Carruth /// identified.
10519281503eSChandler Carruth static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1052693eedb1SChandler Carruth                              const ValueToValueMapTy &VMap, LoopInfo &LI,
1053693eedb1SChandler Carruth                              SmallVectorImpl<Loop *> &NonChildClonedLoops) {
1054693eedb1SChandler Carruth   Loop *ClonedL = nullptr;
1055693eedb1SChandler Carruth 
1056693eedb1SChandler Carruth   auto *OrigPH = OrigL.getLoopPreheader();
1057693eedb1SChandler Carruth   auto *OrigHeader = OrigL.getHeader();
1058693eedb1SChandler Carruth 
1059693eedb1SChandler Carruth   auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1060693eedb1SChandler Carruth   auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1061693eedb1SChandler Carruth 
1062693eedb1SChandler Carruth   // We need to know the loops of the cloned exit blocks to even compute the
1063693eedb1SChandler Carruth   // accurate parent loop. If we only clone exits to some parent of the
1064693eedb1SChandler Carruth   // original parent, we want to clone into that outer loop. We also keep track
1065693eedb1SChandler Carruth   // of the loops that our cloned exit blocks participate in.
1066693eedb1SChandler Carruth   Loop *ParentL = nullptr;
1067693eedb1SChandler Carruth   SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1068693eedb1SChandler Carruth   SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1069693eedb1SChandler Carruth   ClonedExitsInLoops.reserve(ExitBlocks.size());
1070693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks)
1071693eedb1SChandler Carruth     if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1072693eedb1SChandler Carruth       if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1073693eedb1SChandler Carruth         ExitLoopMap[ClonedExitBB] = ExitL;
1074693eedb1SChandler Carruth         ClonedExitsInLoops.push_back(ClonedExitBB);
1075693eedb1SChandler Carruth         if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1076693eedb1SChandler Carruth           ParentL = ExitL;
1077693eedb1SChandler Carruth       }
1078693eedb1SChandler Carruth   assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1079693eedb1SChandler Carruth           ParentL->contains(OrigL.getParentLoop())) &&
1080693eedb1SChandler Carruth          "The computed parent loop should always contain (or be) the parent of "
1081693eedb1SChandler Carruth          "the original loop.");
1082693eedb1SChandler Carruth 
1083693eedb1SChandler Carruth   // We build the set of blocks dominated by the cloned header from the set of
1084693eedb1SChandler Carruth   // cloned blocks out of the original loop. While not all of these will
1085693eedb1SChandler Carruth   // necessarily be in the cloned loop, it is enough to establish that they
1086693eedb1SChandler Carruth   // aren't in unreachable cycles, etc.
1087693eedb1SChandler Carruth   SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1088693eedb1SChandler Carruth   for (auto *BB : OrigL.blocks())
1089693eedb1SChandler Carruth     if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1090693eedb1SChandler Carruth       ClonedLoopBlocks.insert(ClonedBB);
1091693eedb1SChandler Carruth 
1092693eedb1SChandler Carruth   // Rebuild the set of blocks that will end up in the cloned loop. We may have
1093693eedb1SChandler Carruth   // skipped cloning some region of this loop which can in turn skip some of
1094693eedb1SChandler Carruth   // the backedges so we have to rebuild the blocks in the loop based on the
1095693eedb1SChandler Carruth   // backedges that remain after cloning.
1096693eedb1SChandler Carruth   SmallVector<BasicBlock *, 16> Worklist;
1097693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1098693eedb1SChandler Carruth   for (auto *Pred : predecessors(ClonedHeader)) {
1099693eedb1SChandler Carruth     // The only possible non-loop header predecessor is the preheader because
1100693eedb1SChandler Carruth     // we know we cloned the loop in simplified form.
1101693eedb1SChandler Carruth     if (Pred == ClonedPH)
1102693eedb1SChandler Carruth       continue;
1103693eedb1SChandler Carruth 
1104693eedb1SChandler Carruth     // Because the loop was in simplified form, the only non-loop predecessor
1105693eedb1SChandler Carruth     // should be the preheader.
1106693eedb1SChandler Carruth     assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1107693eedb1SChandler Carruth                                            "header other than the preheader "
1108693eedb1SChandler Carruth                                            "that is not part of the loop!");
1109693eedb1SChandler Carruth 
1110693eedb1SChandler Carruth     // Insert this block into the loop set and on the first visit (and if it
1111693eedb1SChandler Carruth     // isn't the header we're currently walking) put it into the worklist to
1112693eedb1SChandler Carruth     // recurse through.
1113693eedb1SChandler Carruth     if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1114693eedb1SChandler Carruth       Worklist.push_back(Pred);
1115693eedb1SChandler Carruth   }
1116693eedb1SChandler Carruth 
1117693eedb1SChandler Carruth   // If we had any backedges then there *is* a cloned loop. Put the header into
1118693eedb1SChandler Carruth   // the loop set and then walk the worklist backwards to find all the blocks
1119693eedb1SChandler Carruth   // that remain within the loop after cloning.
1120693eedb1SChandler Carruth   if (!BlocksInClonedLoop.empty()) {
1121693eedb1SChandler Carruth     BlocksInClonedLoop.insert(ClonedHeader);
1122693eedb1SChandler Carruth 
1123693eedb1SChandler Carruth     while (!Worklist.empty()) {
1124693eedb1SChandler Carruth       BasicBlock *BB = Worklist.pop_back_val();
1125693eedb1SChandler Carruth       assert(BlocksInClonedLoop.count(BB) &&
1126693eedb1SChandler Carruth              "Didn't put block into the loop set!");
1127693eedb1SChandler Carruth 
1128693eedb1SChandler Carruth       // Insert any predecessors that are in the possible set into the cloned
1129693eedb1SChandler Carruth       // set, and if the insert is successful, add them to the worklist. Note
1130693eedb1SChandler Carruth       // that we filter on the blocks that are definitely reachable via the
1131693eedb1SChandler Carruth       // backedge to the loop header so we may prune out dead code within the
1132693eedb1SChandler Carruth       // cloned loop.
1133693eedb1SChandler Carruth       for (auto *Pred : predecessors(BB))
1134693eedb1SChandler Carruth         if (ClonedLoopBlocks.count(Pred) &&
1135693eedb1SChandler Carruth             BlocksInClonedLoop.insert(Pred).second)
1136693eedb1SChandler Carruth           Worklist.push_back(Pred);
1137693eedb1SChandler Carruth     }
1138693eedb1SChandler Carruth 
1139693eedb1SChandler Carruth     ClonedL = LI.AllocateLoop();
1140693eedb1SChandler Carruth     if (ParentL) {
1141693eedb1SChandler Carruth       ParentL->addBasicBlockToLoop(ClonedPH, LI);
1142693eedb1SChandler Carruth       ParentL->addChildLoop(ClonedL);
1143693eedb1SChandler Carruth     } else {
1144693eedb1SChandler Carruth       LI.addTopLevelLoop(ClonedL);
1145693eedb1SChandler Carruth     }
11469281503eSChandler Carruth     NonChildClonedLoops.push_back(ClonedL);
1147693eedb1SChandler Carruth 
1148693eedb1SChandler Carruth     ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1149693eedb1SChandler Carruth     // We don't want to just add the cloned loop blocks based on how we
1150693eedb1SChandler Carruth     // discovered them. The original order of blocks was carefully built in
1151693eedb1SChandler Carruth     // a way that doesn't rely on predecessor ordering. Rather than re-invent
1152693eedb1SChandler Carruth     // that logic, we just re-walk the original blocks (and those of the child
1153693eedb1SChandler Carruth     // loops) and filter them as we add them into the cloned loop.
1154693eedb1SChandler Carruth     for (auto *BB : OrigL.blocks()) {
1155693eedb1SChandler Carruth       auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1156693eedb1SChandler Carruth       if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1157693eedb1SChandler Carruth         continue;
1158693eedb1SChandler Carruth 
1159693eedb1SChandler Carruth       // Directly add the blocks that are only in this loop.
1160693eedb1SChandler Carruth       if (LI.getLoopFor(BB) == &OrigL) {
1161693eedb1SChandler Carruth         ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1162693eedb1SChandler Carruth         continue;
1163693eedb1SChandler Carruth       }
1164693eedb1SChandler Carruth 
1165693eedb1SChandler Carruth       // We want to manually add it to this loop and parents.
1166693eedb1SChandler Carruth       // Registering it with LoopInfo will happen when we clone the top
1167693eedb1SChandler Carruth       // loop for this block.
1168693eedb1SChandler Carruth       for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1169693eedb1SChandler Carruth         PL->addBlockEntry(ClonedBB);
1170693eedb1SChandler Carruth     }
1171693eedb1SChandler Carruth 
1172693eedb1SChandler Carruth     // Now add each child loop whose header remains within the cloned loop. All
1173693eedb1SChandler Carruth     // of the blocks within the loop must satisfy the same constraints as the
1174693eedb1SChandler Carruth     // header so once we pass the header checks we can just clone the entire
1175693eedb1SChandler Carruth     // child loop nest.
1176693eedb1SChandler Carruth     for (Loop *ChildL : OrigL) {
1177693eedb1SChandler Carruth       auto *ClonedChildHeader =
1178693eedb1SChandler Carruth           cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1179693eedb1SChandler Carruth       if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1180693eedb1SChandler Carruth         continue;
1181693eedb1SChandler Carruth 
1182693eedb1SChandler Carruth #ifndef NDEBUG
1183693eedb1SChandler Carruth       // We should never have a cloned child loop header but fail to have
1184693eedb1SChandler Carruth       // all of the blocks for that child loop.
1185693eedb1SChandler Carruth       for (auto *ChildLoopBB : ChildL->blocks())
1186693eedb1SChandler Carruth         assert(BlocksInClonedLoop.count(
1187693eedb1SChandler Carruth                    cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1188693eedb1SChandler Carruth                "Child cloned loop has a header within the cloned outer "
1189693eedb1SChandler Carruth                "loop but not all of its blocks!");
1190693eedb1SChandler Carruth #endif
1191693eedb1SChandler Carruth 
1192693eedb1SChandler Carruth       cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1193693eedb1SChandler Carruth     }
1194693eedb1SChandler Carruth   }
1195693eedb1SChandler Carruth 
1196693eedb1SChandler Carruth   // Now that we've handled all the components of the original loop that were
1197693eedb1SChandler Carruth   // cloned into a new loop, we still need to handle anything from the original
1198693eedb1SChandler Carruth   // loop that wasn't in a cloned loop.
1199693eedb1SChandler Carruth 
1200693eedb1SChandler Carruth   // Figure out what blocks are left to place within any loop nest containing
1201693eedb1SChandler Carruth   // the unswitched loop. If we never formed a loop, the cloned PH is one of
1202693eedb1SChandler Carruth   // them.
1203693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1204693eedb1SChandler Carruth   if (BlocksInClonedLoop.empty())
1205693eedb1SChandler Carruth     UnloopedBlockSet.insert(ClonedPH);
1206693eedb1SChandler Carruth   for (auto *ClonedBB : ClonedLoopBlocks)
1207693eedb1SChandler Carruth     if (!BlocksInClonedLoop.count(ClonedBB))
1208693eedb1SChandler Carruth       UnloopedBlockSet.insert(ClonedBB);
1209693eedb1SChandler Carruth 
1210693eedb1SChandler Carruth   // Copy the cloned exits and sort them in ascending loop depth, we'll work
1211693eedb1SChandler Carruth   // backwards across these to process them inside out. The order shouldn't
1212693eedb1SChandler Carruth   // matter as we're just trying to build up the map from inside-out; we use
1213693eedb1SChandler Carruth   // the map in a more stably ordered way below.
1214693eedb1SChandler Carruth   auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
12154da3331dSChandler Carruth   llvm::sort(OrderedClonedExitsInLoops.begin(), OrderedClonedExitsInLoops.end(),
1216693eedb1SChandler Carruth              [&](BasicBlock *LHS, BasicBlock *RHS) {
1217693eedb1SChandler Carruth                return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1218693eedb1SChandler Carruth                       ExitLoopMap.lookup(RHS)->getLoopDepth();
1219693eedb1SChandler Carruth              });
1220693eedb1SChandler Carruth 
1221693eedb1SChandler Carruth   // Populate the existing ExitLoopMap with everything reachable from each
1222693eedb1SChandler Carruth   // exit, starting from the inner most exit.
1223693eedb1SChandler Carruth   while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1224693eedb1SChandler Carruth     assert(Worklist.empty() && "Didn't clear worklist!");
1225693eedb1SChandler Carruth 
1226693eedb1SChandler Carruth     BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1227693eedb1SChandler Carruth     Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1228693eedb1SChandler Carruth 
1229693eedb1SChandler Carruth     // Walk the CFG back until we hit the cloned PH adding everything reachable
1230693eedb1SChandler Carruth     // and in the unlooped set to this exit block's loop.
1231693eedb1SChandler Carruth     Worklist.push_back(ExitBB);
1232693eedb1SChandler Carruth     do {
1233693eedb1SChandler Carruth       BasicBlock *BB = Worklist.pop_back_val();
1234693eedb1SChandler Carruth       // We can stop recursing at the cloned preheader (if we get there).
1235693eedb1SChandler Carruth       if (BB == ClonedPH)
1236693eedb1SChandler Carruth         continue;
1237693eedb1SChandler Carruth 
1238693eedb1SChandler Carruth       for (BasicBlock *PredBB : predecessors(BB)) {
1239693eedb1SChandler Carruth         // If this pred has already been moved to our set or is part of some
1240693eedb1SChandler Carruth         // (inner) loop, no update needed.
1241693eedb1SChandler Carruth         if (!UnloopedBlockSet.erase(PredBB)) {
1242693eedb1SChandler Carruth           assert(
1243693eedb1SChandler Carruth               (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1244693eedb1SChandler Carruth               "Predecessor not mapped to a loop!");
1245693eedb1SChandler Carruth           continue;
1246693eedb1SChandler Carruth         }
1247693eedb1SChandler Carruth 
1248693eedb1SChandler Carruth         // We just insert into the loop set here. We'll add these blocks to the
1249693eedb1SChandler Carruth         // exit loop after we build up the set in an order that doesn't rely on
1250693eedb1SChandler Carruth         // predecessor order (which in turn relies on use list order).
1251693eedb1SChandler Carruth         bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1252693eedb1SChandler Carruth         (void)Inserted;
1253693eedb1SChandler Carruth         assert(Inserted && "Should only visit an unlooped block once!");
1254693eedb1SChandler Carruth 
1255693eedb1SChandler Carruth         // And recurse through to its predecessors.
1256693eedb1SChandler Carruth         Worklist.push_back(PredBB);
1257693eedb1SChandler Carruth       }
1258693eedb1SChandler Carruth     } while (!Worklist.empty());
1259693eedb1SChandler Carruth   }
1260693eedb1SChandler Carruth 
1261693eedb1SChandler Carruth   // Now that the ExitLoopMap gives as  mapping for all the non-looping cloned
1262693eedb1SChandler Carruth   // blocks to their outer loops, walk the cloned blocks and the cloned exits
1263693eedb1SChandler Carruth   // in their original order adding them to the correct loop.
1264693eedb1SChandler Carruth 
1265693eedb1SChandler Carruth   // We need a stable insertion order. We use the order of the original loop
1266693eedb1SChandler Carruth   // order and map into the correct parent loop.
1267693eedb1SChandler Carruth   for (auto *BB : llvm::concat<BasicBlock *const>(
1268693eedb1SChandler Carruth            makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1269693eedb1SChandler Carruth     if (Loop *OuterL = ExitLoopMap.lookup(BB))
1270693eedb1SChandler Carruth       OuterL->addBasicBlockToLoop(BB, LI);
1271693eedb1SChandler Carruth 
1272693eedb1SChandler Carruth #ifndef NDEBUG
1273693eedb1SChandler Carruth   for (auto &BBAndL : ExitLoopMap) {
1274693eedb1SChandler Carruth     auto *BB = BBAndL.first;
1275693eedb1SChandler Carruth     auto *OuterL = BBAndL.second;
1276693eedb1SChandler Carruth     assert(LI.getLoopFor(BB) == OuterL &&
1277693eedb1SChandler Carruth            "Failed to put all blocks into outer loops!");
1278693eedb1SChandler Carruth   }
1279693eedb1SChandler Carruth #endif
1280693eedb1SChandler Carruth 
1281693eedb1SChandler Carruth   // Now that all the blocks are placed into the correct containing loop in the
1282693eedb1SChandler Carruth   // absence of child loops, find all the potentially cloned child loops and
1283693eedb1SChandler Carruth   // clone them into whatever outer loop we placed their header into.
1284693eedb1SChandler Carruth   for (Loop *ChildL : OrigL) {
1285693eedb1SChandler Carruth     auto *ClonedChildHeader =
1286693eedb1SChandler Carruth         cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1287693eedb1SChandler Carruth     if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1288693eedb1SChandler Carruth       continue;
1289693eedb1SChandler Carruth 
1290693eedb1SChandler Carruth #ifndef NDEBUG
1291693eedb1SChandler Carruth     for (auto *ChildLoopBB : ChildL->blocks())
1292693eedb1SChandler Carruth       assert(VMap.count(ChildLoopBB) &&
1293693eedb1SChandler Carruth              "Cloned a child loop header but not all of that loops blocks!");
1294693eedb1SChandler Carruth #endif
1295693eedb1SChandler Carruth 
1296693eedb1SChandler Carruth     NonChildClonedLoops.push_back(cloneLoopNest(
1297693eedb1SChandler Carruth         *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1298693eedb1SChandler Carruth   }
1299693eedb1SChandler Carruth }
1300693eedb1SChandler Carruth 
130169e68f84SChandler Carruth static void
13021652996fSChandler Carruth deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
13031652996fSChandler Carruth                        ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
13041652996fSChandler Carruth                        DominatorTree &DT) {
13051652996fSChandler Carruth   // Find all the dead clones, and remove them from their successors.
13061652996fSChandler Carruth   SmallVector<BasicBlock *, 16> DeadBlocks;
13071652996fSChandler Carruth   for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
13081652996fSChandler Carruth     for (auto &VMap : VMaps)
13091652996fSChandler Carruth       if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
13101652996fSChandler Carruth         if (!DT.isReachableFromEntry(ClonedBB)) {
13111652996fSChandler Carruth           for (BasicBlock *SuccBB : successors(ClonedBB))
13121652996fSChandler Carruth             SuccBB->removePredecessor(ClonedBB);
13131652996fSChandler Carruth           DeadBlocks.push_back(ClonedBB);
13141652996fSChandler Carruth         }
13151652996fSChandler Carruth 
13161652996fSChandler Carruth   // Drop any remaining references to break cycles.
13171652996fSChandler Carruth   for (BasicBlock *BB : DeadBlocks)
13181652996fSChandler Carruth     BB->dropAllReferences();
13191652996fSChandler Carruth   // Erase them from the IR.
13201652996fSChandler Carruth   for (BasicBlock *BB : DeadBlocks)
13211652996fSChandler Carruth     BB->eraseFromParent();
13221652996fSChandler Carruth }
13231652996fSChandler Carruth 
13241652996fSChandler Carruth static void
132569e68f84SChandler Carruth deleteDeadBlocksFromLoop(Loop &L,
1326693eedb1SChandler Carruth                          SmallVectorImpl<BasicBlock *> &ExitBlocks,
1327693eedb1SChandler Carruth                          DominatorTree &DT, LoopInfo &LI) {
13281652996fSChandler Carruth   // Find all the dead blocks, and remove them from their successors.
13291652996fSChandler Carruth   SmallVector<BasicBlock *, 16> DeadBlocks;
13301652996fSChandler Carruth   for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
13311652996fSChandler Carruth     if (!DT.isReachableFromEntry(BB)) {
13321652996fSChandler Carruth       for (BasicBlock *SuccBB : successors(BB))
13331652996fSChandler Carruth         SuccBB->removePredecessor(BB);
13341652996fSChandler Carruth       DeadBlocks.push_back(BB);
13351652996fSChandler Carruth     }
13361652996fSChandler Carruth 
133769e68f84SChandler Carruth   SmallPtrSet<BasicBlock *, 16> DeadBlockSet(DeadBlocks.begin(),
133869e68f84SChandler Carruth                                              DeadBlocks.end());
1339693eedb1SChandler Carruth 
1340693eedb1SChandler Carruth   // Filter out the dead blocks from the exit blocks list so that it can be
1341693eedb1SChandler Carruth   // used in the caller.
1342693eedb1SChandler Carruth   llvm::erase_if(ExitBlocks,
134369e68f84SChandler Carruth                  [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1344693eedb1SChandler Carruth 
1345693eedb1SChandler Carruth   // Walk from this loop up through its parents removing all of the dead blocks.
1346693eedb1SChandler Carruth   for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
1347693eedb1SChandler Carruth     for (auto *BB : DeadBlocks)
1348693eedb1SChandler Carruth       ParentL->getBlocksSet().erase(BB);
1349693eedb1SChandler Carruth     llvm::erase_if(ParentL->getBlocksVector(),
135069e68f84SChandler Carruth                    [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1351693eedb1SChandler Carruth   }
1352693eedb1SChandler Carruth 
1353693eedb1SChandler Carruth   // Now delete the dead child loops. This raw delete will clear them
1354693eedb1SChandler Carruth   // recursively.
1355693eedb1SChandler Carruth   llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
135669e68f84SChandler Carruth     if (!DeadBlockSet.count(ChildL->getHeader()))
1357693eedb1SChandler Carruth       return false;
1358693eedb1SChandler Carruth 
1359693eedb1SChandler Carruth     assert(llvm::all_of(ChildL->blocks(),
1360693eedb1SChandler Carruth                         [&](BasicBlock *ChildBB) {
136169e68f84SChandler Carruth                           return DeadBlockSet.count(ChildBB);
1362693eedb1SChandler Carruth                         }) &&
1363693eedb1SChandler Carruth            "If the child loop header is dead all blocks in the child loop must "
1364693eedb1SChandler Carruth            "be dead as well!");
1365693eedb1SChandler Carruth     LI.destroy(ChildL);
1366693eedb1SChandler Carruth     return true;
1367693eedb1SChandler Carruth   });
1368693eedb1SChandler Carruth 
136969e68f84SChandler Carruth   // Remove the loop mappings for the dead blocks and drop all the references
137069e68f84SChandler Carruth   // from these blocks to others to handle cyclic references as we start
137169e68f84SChandler Carruth   // deleting the blocks themselves.
137269e68f84SChandler Carruth   for (auto *BB : DeadBlocks) {
137369e68f84SChandler Carruth     // Check that the dominator tree has already been updated.
137469e68f84SChandler Carruth     assert(!DT.getNode(BB) && "Should already have cleared domtree!");
1375693eedb1SChandler Carruth     LI.changeLoopFor(BB, nullptr);
1376693eedb1SChandler Carruth     BB->dropAllReferences();
1377693eedb1SChandler Carruth   }
137869e68f84SChandler Carruth 
137969e68f84SChandler Carruth   // Actually delete the blocks now that they've been fully unhooked from the
138069e68f84SChandler Carruth   // IR.
138169e68f84SChandler Carruth   for (auto *BB : DeadBlocks)
138269e68f84SChandler Carruth     BB->eraseFromParent();
1383693eedb1SChandler Carruth }
1384693eedb1SChandler Carruth 
1385693eedb1SChandler Carruth /// Recompute the set of blocks in a loop after unswitching.
1386693eedb1SChandler Carruth ///
1387693eedb1SChandler Carruth /// This walks from the original headers predecessors to rebuild the loop. We
1388693eedb1SChandler Carruth /// take advantage of the fact that new blocks can't have been added, and so we
1389693eedb1SChandler Carruth /// filter by the original loop's blocks. This also handles potentially
1390693eedb1SChandler Carruth /// unreachable code that we don't want to explore but might be found examining
1391693eedb1SChandler Carruth /// the predecessors of the header.
1392693eedb1SChandler Carruth ///
1393693eedb1SChandler Carruth /// If the original loop is no longer a loop, this will return an empty set. If
1394693eedb1SChandler Carruth /// it remains a loop, all the blocks within it will be added to the set
1395693eedb1SChandler Carruth /// (including those blocks in inner loops).
1396693eedb1SChandler Carruth static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1397693eedb1SChandler Carruth                                                                  LoopInfo &LI) {
1398693eedb1SChandler Carruth   SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1399693eedb1SChandler Carruth 
1400693eedb1SChandler Carruth   auto *PH = L.getLoopPreheader();
1401693eedb1SChandler Carruth   auto *Header = L.getHeader();
1402693eedb1SChandler Carruth 
1403693eedb1SChandler Carruth   // A worklist to use while walking backwards from the header.
1404693eedb1SChandler Carruth   SmallVector<BasicBlock *, 16> Worklist;
1405693eedb1SChandler Carruth 
1406693eedb1SChandler Carruth   // First walk the predecessors of the header to find the backedges. This will
1407693eedb1SChandler Carruth   // form the basis of our walk.
1408693eedb1SChandler Carruth   for (auto *Pred : predecessors(Header)) {
1409693eedb1SChandler Carruth     // Skip the preheader.
1410693eedb1SChandler Carruth     if (Pred == PH)
1411693eedb1SChandler Carruth       continue;
1412693eedb1SChandler Carruth 
1413693eedb1SChandler Carruth     // Because the loop was in simplified form, the only non-loop predecessor
1414693eedb1SChandler Carruth     // is the preheader.
1415693eedb1SChandler Carruth     assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1416693eedb1SChandler Carruth                                "than the preheader that is not part of the "
1417693eedb1SChandler Carruth                                "loop!");
1418693eedb1SChandler Carruth 
1419693eedb1SChandler Carruth     // Insert this block into the loop set and on the first visit and, if it
1420693eedb1SChandler Carruth     // isn't the header we're currently walking, put it into the worklist to
1421693eedb1SChandler Carruth     // recurse through.
1422693eedb1SChandler Carruth     if (LoopBlockSet.insert(Pred).second && Pred != Header)
1423693eedb1SChandler Carruth       Worklist.push_back(Pred);
1424693eedb1SChandler Carruth   }
1425693eedb1SChandler Carruth 
1426693eedb1SChandler Carruth   // If no backedges were found, we're done.
1427693eedb1SChandler Carruth   if (LoopBlockSet.empty())
1428693eedb1SChandler Carruth     return LoopBlockSet;
1429693eedb1SChandler Carruth 
1430693eedb1SChandler Carruth   // We found backedges, recurse through them to identify the loop blocks.
1431693eedb1SChandler Carruth   while (!Worklist.empty()) {
1432693eedb1SChandler Carruth     BasicBlock *BB = Worklist.pop_back_val();
1433693eedb1SChandler Carruth     assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1434693eedb1SChandler Carruth 
143543acdb35SChandler Carruth     // No need to walk past the header.
143643acdb35SChandler Carruth     if (BB == Header)
143743acdb35SChandler Carruth       continue;
143843acdb35SChandler Carruth 
1439693eedb1SChandler Carruth     // Because we know the inner loop structure remains valid we can use the
1440693eedb1SChandler Carruth     // loop structure to jump immediately across the entire nested loop.
1441693eedb1SChandler Carruth     // Further, because it is in loop simplified form, we can directly jump
1442693eedb1SChandler Carruth     // to its preheader afterward.
1443693eedb1SChandler Carruth     if (Loop *InnerL = LI.getLoopFor(BB))
1444693eedb1SChandler Carruth       if (InnerL != &L) {
1445693eedb1SChandler Carruth         assert(L.contains(InnerL) &&
1446693eedb1SChandler Carruth                "Should not reach a loop *outside* this loop!");
1447693eedb1SChandler Carruth         // The preheader is the only possible predecessor of the loop so
1448693eedb1SChandler Carruth         // insert it into the set and check whether it was already handled.
1449693eedb1SChandler Carruth         auto *InnerPH = InnerL->getLoopPreheader();
1450693eedb1SChandler Carruth         assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1451693eedb1SChandler Carruth                                       "but not contain the inner loop "
1452693eedb1SChandler Carruth                                       "preheader!");
1453693eedb1SChandler Carruth         if (!LoopBlockSet.insert(InnerPH).second)
1454693eedb1SChandler Carruth           // The only way to reach the preheader is through the loop body
1455693eedb1SChandler Carruth           // itself so if it has been visited the loop is already handled.
1456693eedb1SChandler Carruth           continue;
1457693eedb1SChandler Carruth 
1458693eedb1SChandler Carruth         // Insert all of the blocks (other than those already present) into
1459bf7190a1SChandler Carruth         // the loop set. We expect at least the block that led us to find the
1460bf7190a1SChandler Carruth         // inner loop to be in the block set, but we may also have other loop
1461bf7190a1SChandler Carruth         // blocks if they were already enqueued as predecessors of some other
1462bf7190a1SChandler Carruth         // outer loop block.
1463693eedb1SChandler Carruth         for (auto *InnerBB : InnerL->blocks()) {
1464693eedb1SChandler Carruth           if (InnerBB == BB) {
1465693eedb1SChandler Carruth             assert(LoopBlockSet.count(InnerBB) &&
1466693eedb1SChandler Carruth                    "Block should already be in the set!");
1467693eedb1SChandler Carruth             continue;
1468693eedb1SChandler Carruth           }
1469693eedb1SChandler Carruth 
1470bf7190a1SChandler Carruth           LoopBlockSet.insert(InnerBB);
1471693eedb1SChandler Carruth         }
1472693eedb1SChandler Carruth 
1473693eedb1SChandler Carruth         // Add the preheader to the worklist so we will continue past the
1474693eedb1SChandler Carruth         // loop body.
1475693eedb1SChandler Carruth         Worklist.push_back(InnerPH);
1476693eedb1SChandler Carruth         continue;
1477693eedb1SChandler Carruth       }
1478693eedb1SChandler Carruth 
1479693eedb1SChandler Carruth     // Insert any predecessors that were in the original loop into the new
1480693eedb1SChandler Carruth     // set, and if the insert is successful, add them to the worklist.
1481693eedb1SChandler Carruth     for (auto *Pred : predecessors(BB))
1482693eedb1SChandler Carruth       if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1483693eedb1SChandler Carruth         Worklist.push_back(Pred);
1484693eedb1SChandler Carruth   }
1485693eedb1SChandler Carruth 
148643acdb35SChandler Carruth   assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
148743acdb35SChandler Carruth 
1488693eedb1SChandler Carruth   // We've found all the blocks participating in the loop, return our completed
1489693eedb1SChandler Carruth   // set.
1490693eedb1SChandler Carruth   return LoopBlockSet;
1491693eedb1SChandler Carruth }
1492693eedb1SChandler Carruth 
1493693eedb1SChandler Carruth /// Rebuild a loop after unswitching removes some subset of blocks and edges.
1494693eedb1SChandler Carruth ///
1495693eedb1SChandler Carruth /// The removal may have removed some child loops entirely but cannot have
1496693eedb1SChandler Carruth /// disturbed any remaining child loops. However, they may need to be hoisted
1497693eedb1SChandler Carruth /// to the parent loop (or to be top-level loops). The original loop may be
1498693eedb1SChandler Carruth /// completely removed.
1499693eedb1SChandler Carruth ///
1500693eedb1SChandler Carruth /// The sibling loops resulting from this update are returned. If the original
1501693eedb1SChandler Carruth /// loop remains a valid loop, it will be the first entry in this list with all
1502693eedb1SChandler Carruth /// of the newly sibling loops following it.
1503693eedb1SChandler Carruth ///
1504693eedb1SChandler Carruth /// Returns true if the loop remains a loop after unswitching, and false if it
1505693eedb1SChandler Carruth /// is no longer a loop after unswitching (and should not continue to be
1506693eedb1SChandler Carruth /// referenced).
1507693eedb1SChandler Carruth static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1508693eedb1SChandler Carruth                                      LoopInfo &LI,
1509693eedb1SChandler Carruth                                      SmallVectorImpl<Loop *> &HoistedLoops) {
1510693eedb1SChandler Carruth   auto *PH = L.getLoopPreheader();
1511693eedb1SChandler Carruth 
1512693eedb1SChandler Carruth   // Compute the actual parent loop from the exit blocks. Because we may have
1513693eedb1SChandler Carruth   // pruned some exits the loop may be different from the original parent.
1514693eedb1SChandler Carruth   Loop *ParentL = nullptr;
1515693eedb1SChandler Carruth   SmallVector<Loop *, 4> ExitLoops;
1516693eedb1SChandler Carruth   SmallVector<BasicBlock *, 4> ExitsInLoops;
1517693eedb1SChandler Carruth   ExitsInLoops.reserve(ExitBlocks.size());
1518693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks)
1519693eedb1SChandler Carruth     if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1520693eedb1SChandler Carruth       ExitLoops.push_back(ExitL);
1521693eedb1SChandler Carruth       ExitsInLoops.push_back(ExitBB);
1522693eedb1SChandler Carruth       if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1523693eedb1SChandler Carruth         ParentL = ExitL;
1524693eedb1SChandler Carruth     }
1525693eedb1SChandler Carruth 
1526693eedb1SChandler Carruth   // Recompute the blocks participating in this loop. This may be empty if it
1527693eedb1SChandler Carruth   // is no longer a loop.
1528693eedb1SChandler Carruth   auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1529693eedb1SChandler Carruth 
1530693eedb1SChandler Carruth   // If we still have a loop, we need to re-set the loop's parent as the exit
1531693eedb1SChandler Carruth   // block set changing may have moved it within the loop nest. Note that this
1532693eedb1SChandler Carruth   // can only happen when this loop has a parent as it can only hoist the loop
1533693eedb1SChandler Carruth   // *up* the nest.
1534693eedb1SChandler Carruth   if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1535693eedb1SChandler Carruth     // Remove this loop's (original) blocks from all of the intervening loops.
1536693eedb1SChandler Carruth     for (Loop *IL = L.getParentLoop(); IL != ParentL;
1537693eedb1SChandler Carruth          IL = IL->getParentLoop()) {
1538693eedb1SChandler Carruth       IL->getBlocksSet().erase(PH);
1539693eedb1SChandler Carruth       for (auto *BB : L.blocks())
1540693eedb1SChandler Carruth         IL->getBlocksSet().erase(BB);
1541693eedb1SChandler Carruth       llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1542693eedb1SChandler Carruth         return BB == PH || L.contains(BB);
1543693eedb1SChandler Carruth       });
1544693eedb1SChandler Carruth     }
1545693eedb1SChandler Carruth 
1546693eedb1SChandler Carruth     LI.changeLoopFor(PH, ParentL);
1547693eedb1SChandler Carruth     L.getParentLoop()->removeChildLoop(&L);
1548693eedb1SChandler Carruth     if (ParentL)
1549693eedb1SChandler Carruth       ParentL->addChildLoop(&L);
1550693eedb1SChandler Carruth     else
1551693eedb1SChandler Carruth       LI.addTopLevelLoop(&L);
1552693eedb1SChandler Carruth   }
1553693eedb1SChandler Carruth 
1554693eedb1SChandler Carruth   // Now we update all the blocks which are no longer within the loop.
1555693eedb1SChandler Carruth   auto &Blocks = L.getBlocksVector();
1556693eedb1SChandler Carruth   auto BlocksSplitI =
1557693eedb1SChandler Carruth       LoopBlockSet.empty()
1558693eedb1SChandler Carruth           ? Blocks.begin()
1559693eedb1SChandler Carruth           : std::stable_partition(
1560693eedb1SChandler Carruth                 Blocks.begin(), Blocks.end(),
1561693eedb1SChandler Carruth                 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1562693eedb1SChandler Carruth 
1563693eedb1SChandler Carruth   // Before we erase the list of unlooped blocks, build a set of them.
1564693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1565693eedb1SChandler Carruth   if (LoopBlockSet.empty())
1566693eedb1SChandler Carruth     UnloopedBlocks.insert(PH);
1567693eedb1SChandler Carruth 
1568693eedb1SChandler Carruth   // Now erase these blocks from the loop.
1569693eedb1SChandler Carruth   for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1570693eedb1SChandler Carruth     L.getBlocksSet().erase(BB);
1571693eedb1SChandler Carruth   Blocks.erase(BlocksSplitI, Blocks.end());
1572693eedb1SChandler Carruth 
1573693eedb1SChandler Carruth   // Sort the exits in ascending loop depth, we'll work backwards across these
1574693eedb1SChandler Carruth   // to process them inside out.
1575693eedb1SChandler Carruth   std::stable_sort(ExitsInLoops.begin(), ExitsInLoops.end(),
1576693eedb1SChandler Carruth                    [&](BasicBlock *LHS, BasicBlock *RHS) {
1577693eedb1SChandler Carruth                      return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1578693eedb1SChandler Carruth                    });
1579693eedb1SChandler Carruth 
1580693eedb1SChandler Carruth   // We'll build up a set for each exit loop.
1581693eedb1SChandler Carruth   SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1582693eedb1SChandler Carruth   Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1583693eedb1SChandler Carruth 
1584693eedb1SChandler Carruth   auto RemoveUnloopedBlocksFromLoop =
1585693eedb1SChandler Carruth       [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1586693eedb1SChandler Carruth         for (auto *BB : UnloopedBlocks)
1587693eedb1SChandler Carruth           L.getBlocksSet().erase(BB);
1588693eedb1SChandler Carruth         llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1589693eedb1SChandler Carruth           return UnloopedBlocks.count(BB);
1590693eedb1SChandler Carruth         });
1591693eedb1SChandler Carruth       };
1592693eedb1SChandler Carruth 
1593693eedb1SChandler Carruth   SmallVector<BasicBlock *, 16> Worklist;
1594693eedb1SChandler Carruth   while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1595693eedb1SChandler Carruth     assert(Worklist.empty() && "Didn't clear worklist!");
1596693eedb1SChandler Carruth     assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1597693eedb1SChandler Carruth 
1598693eedb1SChandler Carruth     // Grab the next exit block, in decreasing loop depth order.
1599693eedb1SChandler Carruth     BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1600693eedb1SChandler Carruth     Loop &ExitL = *LI.getLoopFor(ExitBB);
1601693eedb1SChandler Carruth     assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1602693eedb1SChandler Carruth 
1603693eedb1SChandler Carruth     // Erase all of the unlooped blocks from the loops between the previous
1604693eedb1SChandler Carruth     // exit loop and this exit loop. This works because the ExitInLoops list is
1605693eedb1SChandler Carruth     // sorted in increasing order of loop depth and thus we visit loops in
1606693eedb1SChandler Carruth     // decreasing order of loop depth.
1607693eedb1SChandler Carruth     for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1608693eedb1SChandler Carruth       RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1609693eedb1SChandler Carruth 
1610693eedb1SChandler Carruth     // Walk the CFG back until we hit the cloned PH adding everything reachable
1611693eedb1SChandler Carruth     // and in the unlooped set to this exit block's loop.
1612693eedb1SChandler Carruth     Worklist.push_back(ExitBB);
1613693eedb1SChandler Carruth     do {
1614693eedb1SChandler Carruth       BasicBlock *BB = Worklist.pop_back_val();
1615693eedb1SChandler Carruth       // We can stop recursing at the cloned preheader (if we get there).
1616693eedb1SChandler Carruth       if (BB == PH)
1617693eedb1SChandler Carruth         continue;
1618693eedb1SChandler Carruth 
1619693eedb1SChandler Carruth       for (BasicBlock *PredBB : predecessors(BB)) {
1620693eedb1SChandler Carruth         // If this pred has already been moved to our set or is part of some
1621693eedb1SChandler Carruth         // (inner) loop, no update needed.
1622693eedb1SChandler Carruth         if (!UnloopedBlocks.erase(PredBB)) {
1623693eedb1SChandler Carruth           assert((NewExitLoopBlocks.count(PredBB) ||
1624693eedb1SChandler Carruth                   ExitL.contains(LI.getLoopFor(PredBB))) &&
1625693eedb1SChandler Carruth                  "Predecessor not in a nested loop (or already visited)!");
1626693eedb1SChandler Carruth           continue;
1627693eedb1SChandler Carruth         }
1628693eedb1SChandler Carruth 
1629693eedb1SChandler Carruth         // We just insert into the loop set here. We'll add these blocks to the
1630693eedb1SChandler Carruth         // exit loop after we build up the set in a deterministic order rather
1631693eedb1SChandler Carruth         // than the predecessor-influenced visit order.
1632693eedb1SChandler Carruth         bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1633693eedb1SChandler Carruth         (void)Inserted;
1634693eedb1SChandler Carruth         assert(Inserted && "Should only visit an unlooped block once!");
1635693eedb1SChandler Carruth 
1636693eedb1SChandler Carruth         // And recurse through to its predecessors.
1637693eedb1SChandler Carruth         Worklist.push_back(PredBB);
1638693eedb1SChandler Carruth       }
1639693eedb1SChandler Carruth     } while (!Worklist.empty());
1640693eedb1SChandler Carruth 
1641693eedb1SChandler Carruth     // If blocks in this exit loop were directly part of the original loop (as
1642693eedb1SChandler Carruth     // opposed to a child loop) update the map to point to this exit loop. This
1643693eedb1SChandler Carruth     // just updates a map and so the fact that the order is unstable is fine.
1644693eedb1SChandler Carruth     for (auto *BB : NewExitLoopBlocks)
1645693eedb1SChandler Carruth       if (Loop *BBL = LI.getLoopFor(BB))
1646693eedb1SChandler Carruth         if (BBL == &L || !L.contains(BBL))
1647693eedb1SChandler Carruth           LI.changeLoopFor(BB, &ExitL);
1648693eedb1SChandler Carruth 
1649693eedb1SChandler Carruth     // We will remove the remaining unlooped blocks from this loop in the next
1650693eedb1SChandler Carruth     // iteration or below.
1651693eedb1SChandler Carruth     NewExitLoopBlocks.clear();
1652693eedb1SChandler Carruth   }
1653693eedb1SChandler Carruth 
1654693eedb1SChandler Carruth   // Any remaining unlooped blocks are no longer part of any loop unless they
1655693eedb1SChandler Carruth   // are part of some child loop.
1656693eedb1SChandler Carruth   for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1657693eedb1SChandler Carruth     RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1658693eedb1SChandler Carruth   for (auto *BB : UnloopedBlocks)
1659693eedb1SChandler Carruth     if (Loop *BBL = LI.getLoopFor(BB))
1660693eedb1SChandler Carruth       if (BBL == &L || !L.contains(BBL))
1661693eedb1SChandler Carruth         LI.changeLoopFor(BB, nullptr);
1662693eedb1SChandler Carruth 
1663693eedb1SChandler Carruth   // Sink all the child loops whose headers are no longer in the loop set to
1664693eedb1SChandler Carruth   // the parent (or to be top level loops). We reach into the loop and directly
1665693eedb1SChandler Carruth   // update its subloop vector to make this batch update efficient.
1666693eedb1SChandler Carruth   auto &SubLoops = L.getSubLoopsVector();
1667693eedb1SChandler Carruth   auto SubLoopsSplitI =
1668693eedb1SChandler Carruth       LoopBlockSet.empty()
1669693eedb1SChandler Carruth           ? SubLoops.begin()
1670693eedb1SChandler Carruth           : std::stable_partition(
1671693eedb1SChandler Carruth                 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1672693eedb1SChandler Carruth                   return LoopBlockSet.count(SubL->getHeader());
1673693eedb1SChandler Carruth                 });
1674693eedb1SChandler Carruth   for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1675693eedb1SChandler Carruth     HoistedLoops.push_back(HoistedL);
1676693eedb1SChandler Carruth     HoistedL->setParentLoop(nullptr);
1677693eedb1SChandler Carruth 
1678693eedb1SChandler Carruth     // To compute the new parent of this hoisted loop we look at where we
1679693eedb1SChandler Carruth     // placed the preheader above. We can't lookup the header itself because we
1680693eedb1SChandler Carruth     // retained the mapping from the header to the hoisted loop. But the
1681693eedb1SChandler Carruth     // preheader and header should have the exact same new parent computed
1682693eedb1SChandler Carruth     // based on the set of exit blocks from the original loop as the preheader
1683693eedb1SChandler Carruth     // is a predecessor of the header and so reached in the reverse walk. And
1684693eedb1SChandler Carruth     // because the loops were all in simplified form the preheader of the
1685693eedb1SChandler Carruth     // hoisted loop can't be part of some *other* loop.
1686693eedb1SChandler Carruth     if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1687693eedb1SChandler Carruth       NewParentL->addChildLoop(HoistedL);
1688693eedb1SChandler Carruth     else
1689693eedb1SChandler Carruth       LI.addTopLevelLoop(HoistedL);
1690693eedb1SChandler Carruth   }
1691693eedb1SChandler Carruth   SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1692693eedb1SChandler Carruth 
1693693eedb1SChandler Carruth   // Actually delete the loop if nothing remained within it.
1694693eedb1SChandler Carruth   if (Blocks.empty()) {
1695693eedb1SChandler Carruth     assert(SubLoops.empty() &&
1696693eedb1SChandler Carruth            "Failed to remove all subloops from the original loop!");
1697693eedb1SChandler Carruth     if (Loop *ParentL = L.getParentLoop())
1698693eedb1SChandler Carruth       ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1699693eedb1SChandler Carruth     else
1700693eedb1SChandler Carruth       LI.removeLoop(llvm::find(LI, &L));
1701693eedb1SChandler Carruth     LI.destroy(&L);
1702693eedb1SChandler Carruth     return false;
1703693eedb1SChandler Carruth   }
1704693eedb1SChandler Carruth 
1705693eedb1SChandler Carruth   return true;
1706693eedb1SChandler Carruth }
1707693eedb1SChandler Carruth 
1708693eedb1SChandler Carruth /// Helper to visit a dominator subtree, invoking a callable on each node.
1709693eedb1SChandler Carruth ///
1710693eedb1SChandler Carruth /// Returning false at any point will stop walking past that node of the tree.
1711693eedb1SChandler Carruth template <typename CallableT>
1712693eedb1SChandler Carruth void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1713693eedb1SChandler Carruth   SmallVector<DomTreeNode *, 4> DomWorklist;
1714693eedb1SChandler Carruth   DomWorklist.push_back(DT[BB]);
1715693eedb1SChandler Carruth #ifndef NDEBUG
1716693eedb1SChandler Carruth   SmallPtrSet<DomTreeNode *, 4> Visited;
1717693eedb1SChandler Carruth   Visited.insert(DT[BB]);
1718693eedb1SChandler Carruth #endif
1719693eedb1SChandler Carruth   do {
1720693eedb1SChandler Carruth     DomTreeNode *N = DomWorklist.pop_back_val();
1721693eedb1SChandler Carruth 
1722693eedb1SChandler Carruth     // Visit this node.
1723693eedb1SChandler Carruth     if (!Callable(N->getBlock()))
1724693eedb1SChandler Carruth       continue;
1725693eedb1SChandler Carruth 
1726693eedb1SChandler Carruth     // Accumulate the child nodes.
1727693eedb1SChandler Carruth     for (DomTreeNode *ChildN : *N) {
1728693eedb1SChandler Carruth       assert(Visited.insert(ChildN).second &&
1729693eedb1SChandler Carruth              "Cannot visit a node twice when walking a tree!");
1730693eedb1SChandler Carruth       DomWorklist.push_back(ChildN);
1731693eedb1SChandler Carruth     }
1732693eedb1SChandler Carruth   } while (!DomWorklist.empty());
1733693eedb1SChandler Carruth }
1734693eedb1SChandler Carruth 
17351652996fSChandler Carruth static bool unswitchNontrivialInvariants(
17361652996fSChandler Carruth     Loop &L, TerminatorInst &TI, ArrayRef<Value *> Invariants,
17371652996fSChandler Carruth     DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
17383897ded6SChandler Carruth     function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
17393897ded6SChandler Carruth     ScalarEvolution *SE) {
17401652996fSChandler Carruth   auto *ParentBB = TI.getParent();
17411652996fSChandler Carruth   BranchInst *BI = dyn_cast<BranchInst>(&TI);
17421652996fSChandler Carruth   SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
1743d1dab0c3SChandler Carruth 
17441652996fSChandler Carruth   // We can only unswitch switches, conditional branches with an invariant
17451652996fSChandler Carruth   // condition, or combining invariant conditions with an instruction.
17461652996fSChandler Carruth   assert((SI || BI->isConditional()) &&
17471652996fSChandler Carruth          "Can only unswitch switches and conditional branch!");
17481652996fSChandler Carruth   bool FullUnswitch = SI || BI->getCondition() == Invariants[0];
1749d1dab0c3SChandler Carruth   if (FullUnswitch)
1750d1dab0c3SChandler Carruth     assert(Invariants.size() == 1 &&
1751d1dab0c3SChandler Carruth            "Cannot have other invariants with full unswitching!");
1752d1dab0c3SChandler Carruth   else
17531652996fSChandler Carruth     assert(isa<Instruction>(BI->getCondition()) &&
1754d1dab0c3SChandler Carruth            "Partial unswitching requires an instruction as the condition!");
1755d1dab0c3SChandler Carruth 
1756d1dab0c3SChandler Carruth   // Constant and BBs tracking the cloned and continuing successor. When we are
1757d1dab0c3SChandler Carruth   // unswitching the entire condition, this can just be trivially chosen to
1758d1dab0c3SChandler Carruth   // unswitch towards `true`. However, when we are unswitching a set of
1759d1dab0c3SChandler Carruth   // invariants combined with `and` or `or`, the combining operation determines
1760d1dab0c3SChandler Carruth   // the best direction to unswitch: we want to unswitch the direction that will
1761d1dab0c3SChandler Carruth   // collapse the branch.
1762d1dab0c3SChandler Carruth   bool Direction = true;
1763d1dab0c3SChandler Carruth   int ClonedSucc = 0;
1764d1dab0c3SChandler Carruth   if (!FullUnswitch) {
17651652996fSChandler Carruth     if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) {
17661652996fSChandler Carruth       assert(cast<Instruction>(BI->getCondition())->getOpcode() ==
17671652996fSChandler Carruth                  Instruction::And &&
17681652996fSChandler Carruth              "Only `or` and `and` instructions can combine invariants being "
17691652996fSChandler Carruth              "unswitched.");
1770d1dab0c3SChandler Carruth       Direction = false;
1771d1dab0c3SChandler Carruth       ClonedSucc = 1;
1772d1dab0c3SChandler Carruth     }
1773d1dab0c3SChandler Carruth   }
1774693eedb1SChandler Carruth 
17751652996fSChandler Carruth   BasicBlock *RetainedSuccBB =
17761652996fSChandler Carruth       BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
17771652996fSChandler Carruth   SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
17781652996fSChandler Carruth   if (BI)
17791652996fSChandler Carruth     UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
17801652996fSChandler Carruth   else
17811652996fSChandler Carruth     for (auto Case : SI->cases())
17821652996fSChandler Carruth       UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
17831652996fSChandler Carruth 
17841652996fSChandler Carruth   assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
17851652996fSChandler Carruth          "Should not unswitch the same successor we are retaining!");
1786693eedb1SChandler Carruth 
1787693eedb1SChandler Carruth   // The branch should be in this exact loop. Any inner loop's invariant branch
1788693eedb1SChandler Carruth   // should be handled by unswitching that inner loop. The caller of this
1789693eedb1SChandler Carruth   // routine should filter out any candidates that remain (but were skipped for
1790693eedb1SChandler Carruth   // whatever reason).
1791693eedb1SChandler Carruth   assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
1792693eedb1SChandler Carruth 
1793693eedb1SChandler Carruth   SmallVector<BasicBlock *, 4> ExitBlocks;
1794693eedb1SChandler Carruth   L.getUniqueExitBlocks(ExitBlocks);
1795693eedb1SChandler Carruth 
1796693eedb1SChandler Carruth   // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
1797693eedb1SChandler Carruth   // don't know how to split those exit blocks.
1798693eedb1SChandler Carruth   // FIXME: We should teach SplitBlock to handle this and remove this
1799693eedb1SChandler Carruth   // restriction.
1800693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks)
1801693eedb1SChandler Carruth     if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI()))
1802693eedb1SChandler Carruth       return false;
1803693eedb1SChandler Carruth 
1804693eedb1SChandler Carruth   // Compute the parent loop now before we start hacking on things.
1805693eedb1SChandler Carruth   Loop *ParentL = L.getParentLoop();
1806693eedb1SChandler Carruth 
1807693eedb1SChandler Carruth   // Compute the outer-most loop containing one of our exit blocks. This is the
1808693eedb1SChandler Carruth   // furthest up our loopnest which can be mutated, which we will use below to
1809693eedb1SChandler Carruth   // update things.
1810693eedb1SChandler Carruth   Loop *OuterExitL = &L;
1811693eedb1SChandler Carruth   for (auto *ExitBB : ExitBlocks) {
1812693eedb1SChandler Carruth     Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
1813693eedb1SChandler Carruth     if (!NewOuterExitL) {
1814693eedb1SChandler Carruth       // We exited the entire nest with this block, so we're done.
1815693eedb1SChandler Carruth       OuterExitL = nullptr;
1816693eedb1SChandler Carruth       break;
1817693eedb1SChandler Carruth     }
1818693eedb1SChandler Carruth     if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
1819693eedb1SChandler Carruth       OuterExitL = NewOuterExitL;
1820693eedb1SChandler Carruth   }
1821693eedb1SChandler Carruth 
18223897ded6SChandler Carruth   // At this point, we're definitely going to unswitch something so invalidate
18233897ded6SChandler Carruth   // any cached information in ScalarEvolution for the outer most loop
18243897ded6SChandler Carruth   // containing an exit block and all nested loops.
18253897ded6SChandler Carruth   if (SE) {
18263897ded6SChandler Carruth     if (OuterExitL)
18273897ded6SChandler Carruth       SE->forgetLoop(OuterExitL);
18283897ded6SChandler Carruth     else
18293897ded6SChandler Carruth       SE->forgetTopmostLoop(&L);
18303897ded6SChandler Carruth   }
18313897ded6SChandler Carruth 
18321652996fSChandler Carruth   // If the edge from this terminator to a successor dominates that successor,
18331652996fSChandler Carruth   // store a map from each block in its dominator subtree to it. This lets us
18341652996fSChandler Carruth   // tell when cloning for a particular successor if a block is dominated by
18351652996fSChandler Carruth   // some *other* successor with a single data structure. We use this to
18361652996fSChandler Carruth   // significantly reduce cloning.
18371652996fSChandler Carruth   SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
18381652996fSChandler Carruth   for (auto *SuccBB : llvm::concat<BasicBlock *const>(
18391652996fSChandler Carruth            makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
18401652996fSChandler Carruth     if (SuccBB->getUniquePredecessor() ||
18411652996fSChandler Carruth         llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
18421652996fSChandler Carruth           return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
18431652996fSChandler Carruth         }))
18441652996fSChandler Carruth       visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
18451652996fSChandler Carruth         DominatingSucc[BB] = SuccBB;
1846693eedb1SChandler Carruth         return true;
1847693eedb1SChandler Carruth       });
1848693eedb1SChandler Carruth 
1849693eedb1SChandler Carruth   // Split the preheader, so that we know that there is a safe place to insert
1850693eedb1SChandler Carruth   // the conditional branch. We will change the preheader to have a conditional
1851693eedb1SChandler Carruth   // branch on LoopCond. The original preheader will become the split point
1852693eedb1SChandler Carruth   // between the unswitched versions, and we will have a new preheader for the
1853693eedb1SChandler Carruth   // original loop.
1854693eedb1SChandler Carruth   BasicBlock *SplitBB = L.getLoopPreheader();
1855693eedb1SChandler Carruth   BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI);
1856693eedb1SChandler Carruth 
185769e68f84SChandler Carruth   // Keep track of the dominator tree updates needed.
185869e68f84SChandler Carruth   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
185969e68f84SChandler Carruth 
18601652996fSChandler Carruth   // Clone the loop for each unswitched successor.
18611652996fSChandler Carruth   SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
18621652996fSChandler Carruth   VMaps.reserve(UnswitchedSuccBBs.size());
18631652996fSChandler Carruth   SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
18641652996fSChandler Carruth   for (auto *SuccBB : UnswitchedSuccBBs) {
18651652996fSChandler Carruth     VMaps.emplace_back(new ValueToValueMapTy());
18661652996fSChandler Carruth     ClonedPHs[SuccBB] = buildClonedLoopBlocks(
18671652996fSChandler Carruth         L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
18681652996fSChandler Carruth         DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI);
18691652996fSChandler Carruth   }
1870693eedb1SChandler Carruth 
1871d1dab0c3SChandler Carruth   // The stitching of the branched code back together depends on whether we're
1872d1dab0c3SChandler Carruth   // doing full unswitching or not with the exception that we always want to
1873d1dab0c3SChandler Carruth   // nuke the initial terminator placed in the split block.
1874d1dab0c3SChandler Carruth   SplitBB->getTerminator()->eraseFromParent();
1875d1dab0c3SChandler Carruth   if (FullUnswitch) {
18761652996fSChandler Carruth     for (BasicBlock *SuccBB : UnswitchedSuccBBs) {
18771652996fSChandler Carruth       // Remove the parent as a predecessor of the unswitched successor.
18781652996fSChandler Carruth       SuccBB->removePredecessor(ParentBB,
1879d1dab0c3SChandler Carruth                                 /*DontDeleteUselessPHIs*/ true);
18801652996fSChandler Carruth       DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
18811652996fSChandler Carruth     }
1882693eedb1SChandler Carruth 
18831652996fSChandler Carruth     // Now splice the terminator from the original loop and rewrite its
18841652996fSChandler Carruth     // successors.
18851652996fSChandler Carruth     SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
18861652996fSChandler Carruth     if (BI) {
18871652996fSChandler Carruth       assert(UnswitchedSuccBBs.size() == 1 &&
18881652996fSChandler Carruth              "Only one possible unswitched block for a branch!");
18891652996fSChandler Carruth       BasicBlock *ClonedPH = ClonedPHs.begin()->second;
18901652996fSChandler Carruth       BI->setSuccessor(ClonedSucc, ClonedPH);
18911652996fSChandler Carruth       BI->setSuccessor(1 - ClonedSucc, LoopPH);
18921652996fSChandler Carruth       DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
18931652996fSChandler Carruth     } else {
18941652996fSChandler Carruth       assert(SI && "Must either be a branch or switch!");
18951652996fSChandler Carruth 
18961652996fSChandler Carruth       // Walk the cases and directly update their successors.
18971652996fSChandler Carruth       for (auto &Case : SI->cases())
18981652996fSChandler Carruth         Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
18991652996fSChandler Carruth       // We need to use the set to populate domtree updates as even when there
19001652996fSChandler Carruth       // are multiple cases pointing at the same successor we only want to
19011652996fSChandler Carruth       // insert one edge in the domtree.
19021652996fSChandler Carruth       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
19031652996fSChandler Carruth         DTUpdates.push_back(
19041652996fSChandler Carruth             {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
19051652996fSChandler Carruth 
19061652996fSChandler Carruth       SI->setDefaultDest(LoopPH);
19071652996fSChandler Carruth     }
1908693eedb1SChandler Carruth 
1909693eedb1SChandler Carruth     // Create a new unconditional branch to the continuing block (as opposed to
1910693eedb1SChandler Carruth     // the one cloned).
19111652996fSChandler Carruth     BranchInst::Create(RetainedSuccBB, ParentBB);
1912d1dab0c3SChandler Carruth   } else {
19131652996fSChandler Carruth     assert(BI && "Only branches have partial unswitching.");
19141652996fSChandler Carruth     assert(UnswitchedSuccBBs.size() == 1 &&
19151652996fSChandler Carruth            "Only one possible unswitched block for a branch!");
19161652996fSChandler Carruth     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
1917d1dab0c3SChandler Carruth     // When doing a partial unswitch, we have to do a bit more work to build up
1918d1dab0c3SChandler Carruth     // the branch in the split block.
1919d1dab0c3SChandler Carruth     buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
1920d1dab0c3SChandler Carruth                                           *ClonedPH, *LoopPH);
192169e68f84SChandler Carruth     DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
19221652996fSChandler Carruth   }
19231652996fSChandler Carruth 
19241652996fSChandler Carruth   // Apply the updates accumulated above to get an up-to-date dominator tree.
192569e68f84SChandler Carruth   DT.applyUpdates(DTUpdates);
192669e68f84SChandler Carruth 
19271652996fSChandler Carruth   // Now that we have an accurate dominator tree, first delete the dead cloned
19281652996fSChandler Carruth   // blocks so that we can accurately build any cloned loops. It is important to
19291652996fSChandler Carruth   // not delete the blocks from the original loop yet because we still want to
19301652996fSChandler Carruth   // reference the original loop to understand the cloned loop's structure.
19311652996fSChandler Carruth   deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT);
19321652996fSChandler Carruth 
193369e68f84SChandler Carruth   // Build the cloned loop structure itself. This may be substantially
193469e68f84SChandler Carruth   // different from the original structure due to the simplified CFG. This also
193569e68f84SChandler Carruth   // handles inserting all the cloned blocks into the correct loops.
193669e68f84SChandler Carruth   SmallVector<Loop *, 4> NonChildClonedLoops;
19371652996fSChandler Carruth   for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
19381652996fSChandler Carruth     buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
193969e68f84SChandler Carruth 
19401652996fSChandler Carruth   // Now that our cloned loops have been built, we can update the original loop.
19411652996fSChandler Carruth   // First we delete the dead blocks from it and then we rebuild the loop
19421652996fSChandler Carruth   // structure taking these deletions into account.
19431652996fSChandler Carruth   deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI);
1944693eedb1SChandler Carruth   SmallVector<Loop *, 4> HoistedLoops;
1945693eedb1SChandler Carruth   bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
1946693eedb1SChandler Carruth 
194769e68f84SChandler Carruth   // This transformation has a high risk of corrupting the dominator tree, and
194869e68f84SChandler Carruth   // the below steps to rebuild loop structures will result in hard to debug
194969e68f84SChandler Carruth   // errors in that case so verify that the dominator tree is sane first.
195069e68f84SChandler Carruth   // FIXME: Remove this when the bugs stop showing up and rely on existing
195169e68f84SChandler Carruth   // verification steps.
195269e68f84SChandler Carruth   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1953693eedb1SChandler Carruth 
19541652996fSChandler Carruth   if (BI) {
19551652996fSChandler Carruth     // If we unswitched a branch which collapses the condition to a known
19561652996fSChandler Carruth     // constant we want to replace all the uses of the invariants within both
19571652996fSChandler Carruth     // the original and cloned blocks. We do this here so that we can use the
19581652996fSChandler Carruth     // now updated dominator tree to identify which side the users are on.
19591652996fSChandler Carruth     assert(UnswitchedSuccBBs.size() == 1 &&
19601652996fSChandler Carruth            "Only one possible unswitched block for a branch!");
19611652996fSChandler Carruth     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
1962d1dab0c3SChandler Carruth     ConstantInt *UnswitchedReplacement =
19631652996fSChandler Carruth         Direction ? ConstantInt::getTrue(BI->getContext())
19641652996fSChandler Carruth                   : ConstantInt::getFalse(BI->getContext());
1965d1dab0c3SChandler Carruth     ConstantInt *ContinueReplacement =
19661652996fSChandler Carruth         Direction ? ConstantInt::getFalse(BI->getContext())
19671652996fSChandler Carruth                   : ConstantInt::getTrue(BI->getContext());
1968d1dab0c3SChandler Carruth     for (Value *Invariant : Invariants)
1969d1dab0c3SChandler Carruth       for (auto UI = Invariant->use_begin(), UE = Invariant->use_end();
1970d1dab0c3SChandler Carruth            UI != UE;) {
1971d1dab0c3SChandler Carruth         // Grab the use and walk past it so we can clobber it in the use list.
1972d1dab0c3SChandler Carruth         Use *U = &*UI++;
1973d1dab0c3SChandler Carruth         Instruction *UserI = dyn_cast<Instruction>(U->getUser());
1974d1dab0c3SChandler Carruth         if (!UserI)
1975d1dab0c3SChandler Carruth           continue;
1976d1dab0c3SChandler Carruth 
1977d1dab0c3SChandler Carruth         // Replace it with the 'continue' side if in the main loop body, and the
1978d1dab0c3SChandler Carruth         // unswitched if in the cloned blocks.
1979d1dab0c3SChandler Carruth         if (DT.dominates(LoopPH, UserI->getParent()))
1980d1dab0c3SChandler Carruth           U->set(ContinueReplacement);
1981d1dab0c3SChandler Carruth         else if (DT.dominates(ClonedPH, UserI->getParent()))
1982d1dab0c3SChandler Carruth           U->set(UnswitchedReplacement);
1983d1dab0c3SChandler Carruth       }
19841652996fSChandler Carruth   }
1985d1dab0c3SChandler Carruth 
1986693eedb1SChandler Carruth   // We can change which blocks are exit blocks of all the cloned sibling
1987693eedb1SChandler Carruth   // loops, the current loop, and any parent loops which shared exit blocks
1988693eedb1SChandler Carruth   // with the current loop. As a consequence, we need to re-form LCSSA for
1989693eedb1SChandler Carruth   // them. But we shouldn't need to re-form LCSSA for any child loops.
1990693eedb1SChandler Carruth   // FIXME: This could be made more efficient by tracking which exit blocks are
1991693eedb1SChandler Carruth   // new, and focusing on them, but that isn't likely to be necessary.
1992693eedb1SChandler Carruth   //
1993693eedb1SChandler Carruth   // In order to reasonably rebuild LCSSA we need to walk inside-out across the
1994693eedb1SChandler Carruth   // loop nest and update every loop that could have had its exits changed. We
1995693eedb1SChandler Carruth   // also need to cover any intervening loops. We add all of these loops to
1996693eedb1SChandler Carruth   // a list and sort them by loop depth to achieve this without updating
1997693eedb1SChandler Carruth   // unnecessary loops.
19989281503eSChandler Carruth   auto UpdateLoop = [&](Loop &UpdateL) {
1999693eedb1SChandler Carruth #ifndef NDEBUG
200043acdb35SChandler Carruth     UpdateL.verifyLoop();
200143acdb35SChandler Carruth     for (Loop *ChildL : UpdateL) {
200243acdb35SChandler Carruth       ChildL->verifyLoop();
2003693eedb1SChandler Carruth       assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2004693eedb1SChandler Carruth              "Perturbed a child loop's LCSSA form!");
200543acdb35SChandler Carruth     }
2006693eedb1SChandler Carruth #endif
2007693eedb1SChandler Carruth     // First build LCSSA for this loop so that we can preserve it when
2008693eedb1SChandler Carruth     // forming dedicated exits. We don't want to perturb some other loop's
2009693eedb1SChandler Carruth     // LCSSA while doing that CFG edit.
20109281503eSChandler Carruth     formLCSSA(UpdateL, DT, &LI, nullptr);
2011693eedb1SChandler Carruth 
2012693eedb1SChandler Carruth     // For loops reached by this loop's original exit blocks we may
2013693eedb1SChandler Carruth     // introduced new, non-dedicated exits. At least try to re-form dedicated
2014693eedb1SChandler Carruth     // exits for these loops. This may fail if they couldn't have dedicated
2015693eedb1SChandler Carruth     // exits to start with.
20169281503eSChandler Carruth     formDedicatedExitBlocks(&UpdateL, &DT, &LI, /*PreserveLCSSA*/ true);
20179281503eSChandler Carruth   };
20189281503eSChandler Carruth 
20199281503eSChandler Carruth   // For non-child cloned loops and hoisted loops, we just need to update LCSSA
20209281503eSChandler Carruth   // and we can do it in any order as they don't nest relative to each other.
20219281503eSChandler Carruth   //
20229281503eSChandler Carruth   // Also check if any of the loops we have updated have become top-level loops
20239281503eSChandler Carruth   // as that will necessitate widening the outer loop scope.
20249281503eSChandler Carruth   for (Loop *UpdatedL :
20259281503eSChandler Carruth        llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
20269281503eSChandler Carruth     UpdateLoop(*UpdatedL);
20279281503eSChandler Carruth     if (!UpdatedL->getParentLoop())
20289281503eSChandler Carruth       OuterExitL = nullptr;
2029693eedb1SChandler Carruth   }
20309281503eSChandler Carruth   if (IsStillLoop) {
20319281503eSChandler Carruth     UpdateLoop(L);
20329281503eSChandler Carruth     if (!L.getParentLoop())
20339281503eSChandler Carruth       OuterExitL = nullptr;
2034693eedb1SChandler Carruth   }
2035693eedb1SChandler Carruth 
20369281503eSChandler Carruth   // If the original loop had exit blocks, walk up through the outer most loop
20379281503eSChandler Carruth   // of those exit blocks to update LCSSA and form updated dedicated exits.
20389281503eSChandler Carruth   if (OuterExitL != &L)
20399281503eSChandler Carruth     for (Loop *OuterL = ParentL; OuterL != OuterExitL;
20409281503eSChandler Carruth          OuterL = OuterL->getParentLoop())
20419281503eSChandler Carruth       UpdateLoop(*OuterL);
20429281503eSChandler Carruth 
2043693eedb1SChandler Carruth #ifndef NDEBUG
2044693eedb1SChandler Carruth   // Verify the entire loop structure to catch any incorrect updates before we
2045693eedb1SChandler Carruth   // progress in the pass pipeline.
2046693eedb1SChandler Carruth   LI.verify(DT);
2047693eedb1SChandler Carruth #endif
2048693eedb1SChandler Carruth 
2049693eedb1SChandler Carruth   // Now that we've unswitched something, make callbacks to report the changes.
2050693eedb1SChandler Carruth   // For that we need to merge together the updated loops and the cloned loops
2051693eedb1SChandler Carruth   // and check whether the original loop survived.
2052693eedb1SChandler Carruth   SmallVector<Loop *, 4> SibLoops;
2053693eedb1SChandler Carruth   for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2054693eedb1SChandler Carruth     if (UpdatedL->getParentLoop() == ParentL)
2055693eedb1SChandler Carruth       SibLoops.push_back(UpdatedL);
205671fd2704SChandler Carruth   UnswitchCB(IsStillLoop, SibLoops);
2057693eedb1SChandler Carruth 
2058693eedb1SChandler Carruth   ++NumBranches;
2059693eedb1SChandler Carruth   return true;
2060693eedb1SChandler Carruth }
2061693eedb1SChandler Carruth 
2062693eedb1SChandler Carruth /// Recursively compute the cost of a dominator subtree based on the per-block
2063693eedb1SChandler Carruth /// cost map provided.
2064693eedb1SChandler Carruth ///
2065693eedb1SChandler Carruth /// The recursive computation is memozied into the provided DT-indexed cost map
2066693eedb1SChandler Carruth /// to allow querying it for most nodes in the domtree without it becoming
2067693eedb1SChandler Carruth /// quadratic.
2068693eedb1SChandler Carruth static int
2069693eedb1SChandler Carruth computeDomSubtreeCost(DomTreeNode &N,
2070693eedb1SChandler Carruth                       const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
2071693eedb1SChandler Carruth                       SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
2072693eedb1SChandler Carruth   // Don't accumulate cost (or recurse through) blocks not in our block cost
2073693eedb1SChandler Carruth   // map and thus not part of the duplication cost being considered.
2074693eedb1SChandler Carruth   auto BBCostIt = BBCostMap.find(N.getBlock());
2075693eedb1SChandler Carruth   if (BBCostIt == BBCostMap.end())
2076693eedb1SChandler Carruth     return 0;
2077693eedb1SChandler Carruth 
2078693eedb1SChandler Carruth   // Lookup this node to see if we already computed its cost.
2079693eedb1SChandler Carruth   auto DTCostIt = DTCostMap.find(&N);
2080693eedb1SChandler Carruth   if (DTCostIt != DTCostMap.end())
2081693eedb1SChandler Carruth     return DTCostIt->second;
2082693eedb1SChandler Carruth 
2083693eedb1SChandler Carruth   // If not, we have to compute it. We can't use insert above and update
2084693eedb1SChandler Carruth   // because computing the cost may insert more things into the map.
2085693eedb1SChandler Carruth   int Cost = std::accumulate(
2086693eedb1SChandler Carruth       N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
2087693eedb1SChandler Carruth         return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2088693eedb1SChandler Carruth       });
2089693eedb1SChandler Carruth   bool Inserted = DTCostMap.insert({&N, Cost}).second;
2090693eedb1SChandler Carruth   (void)Inserted;
2091693eedb1SChandler Carruth   assert(Inserted && "Should not insert a node while visiting children!");
2092693eedb1SChandler Carruth   return Cost;
2093693eedb1SChandler Carruth }
2094693eedb1SChandler Carruth 
20953897ded6SChandler Carruth static bool
20963897ded6SChandler Carruth unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
20973897ded6SChandler Carruth                       AssumptionCache &AC, TargetTransformInfo &TTI,
20983897ded6SChandler Carruth                       function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
20993897ded6SChandler Carruth                       ScalarEvolution *SE) {
2100d1dab0c3SChandler Carruth   // Collect all invariant conditions within this loop (as opposed to an inner
2101d1dab0c3SChandler Carruth   // loop which would be handled when visiting that inner loop).
2102d1dab0c3SChandler Carruth   SmallVector<std::pair<TerminatorInst *, TinyPtrVector<Value *>>, 4>
2103d1dab0c3SChandler Carruth       UnswitchCandidates;
2104d1dab0c3SChandler Carruth   for (auto *BB : L.blocks()) {
2105d1dab0c3SChandler Carruth     if (LI.getLoopFor(BB) != &L)
2106d1dab0c3SChandler Carruth       continue;
21071353f9a4SChandler Carruth 
21081652996fSChandler Carruth     if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
21091652996fSChandler Carruth       // We can only consider fully loop-invariant switch conditions as we need
21101652996fSChandler Carruth       // to completely eliminate the switch after unswitching.
21111652996fSChandler Carruth       if (!isa<Constant>(SI->getCondition()) &&
21121652996fSChandler Carruth           L.isLoopInvariant(SI->getCondition()))
21131652996fSChandler Carruth         UnswitchCandidates.push_back({SI, {SI->getCondition()}});
21141652996fSChandler Carruth       continue;
21151652996fSChandler Carruth     }
21161652996fSChandler Carruth 
2117d1dab0c3SChandler Carruth     auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
2118d1dab0c3SChandler Carruth     if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2119d1dab0c3SChandler Carruth         BI->getSuccessor(0) == BI->getSuccessor(1))
2120d1dab0c3SChandler Carruth       continue;
21211353f9a4SChandler Carruth 
2122d1dab0c3SChandler Carruth     if (L.isLoopInvariant(BI->getCondition())) {
2123d1dab0c3SChandler Carruth       UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2124d1dab0c3SChandler Carruth       continue;
212571fd2704SChandler Carruth     }
21261353f9a4SChandler Carruth 
2127d1dab0c3SChandler Carruth     Instruction &CondI = *cast<Instruction>(BI->getCondition());
2128d1dab0c3SChandler Carruth     if (CondI.getOpcode() != Instruction::And &&
2129d1dab0c3SChandler Carruth       CondI.getOpcode() != Instruction::Or)
2130d1dab0c3SChandler Carruth       continue;
2131693eedb1SChandler Carruth 
2132d1dab0c3SChandler Carruth     TinyPtrVector<Value *> Invariants =
2133d1dab0c3SChandler Carruth         collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2134d1dab0c3SChandler Carruth     if (Invariants.empty())
2135d1dab0c3SChandler Carruth       continue;
2136d1dab0c3SChandler Carruth 
2137d1dab0c3SChandler Carruth     UnswitchCandidates.push_back({BI, std::move(Invariants)});
2138d1dab0c3SChandler Carruth   }
2139693eedb1SChandler Carruth 
2140693eedb1SChandler Carruth   // If we didn't find any candidates, we're done.
2141693eedb1SChandler Carruth   if (UnswitchCandidates.empty())
214271fd2704SChandler Carruth     return false;
2143693eedb1SChandler Carruth 
214432e62f9cSChandler Carruth   // Check if there are irreducible CFG cycles in this loop. If so, we cannot
214532e62f9cSChandler Carruth   // easily unswitch non-trivial edges out of the loop. Doing so might turn the
214632e62f9cSChandler Carruth   // irreducible control flow into reducible control flow and introduce new
214732e62f9cSChandler Carruth   // loops "out of thin air". If we ever discover important use cases for doing
214832e62f9cSChandler Carruth   // this, we can add support to loop unswitch, but it is a lot of complexity
2149f209649dSHiroshi Inoue   // for what seems little or no real world benefit.
215032e62f9cSChandler Carruth   LoopBlocksRPO RPOT(&L);
215132e62f9cSChandler Carruth   RPOT.perform(&LI);
215232e62f9cSChandler Carruth   if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
215371fd2704SChandler Carruth     return false;
215432e62f9cSChandler Carruth 
2155d34e60caSNicola Zaghen   LLVM_DEBUG(
2156d34e60caSNicola Zaghen       dbgs() << "Considering " << UnswitchCandidates.size()
2157693eedb1SChandler Carruth              << " non-trivial loop invariant conditions for unswitching.\n");
2158693eedb1SChandler Carruth 
2159693eedb1SChandler Carruth   // Given that unswitching these terminators will require duplicating parts of
2160693eedb1SChandler Carruth   // the loop, so we need to be able to model that cost. Compute the ephemeral
2161693eedb1SChandler Carruth   // values and set up a data structure to hold per-BB costs. We cache each
2162693eedb1SChandler Carruth   // block's cost so that we don't recompute this when considering different
2163693eedb1SChandler Carruth   // subsets of the loop for duplication during unswitching.
2164693eedb1SChandler Carruth   SmallPtrSet<const Value *, 4> EphValues;
2165693eedb1SChandler Carruth   CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2166693eedb1SChandler Carruth   SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
2167693eedb1SChandler Carruth 
2168693eedb1SChandler Carruth   // Compute the cost of each block, as well as the total loop cost. Also, bail
2169693eedb1SChandler Carruth   // out if we see instructions which are incompatible with loop unswitching
2170693eedb1SChandler Carruth   // (convergent, noduplicate, or cross-basic-block tokens).
2171693eedb1SChandler Carruth   // FIXME: We might be able to safely handle some of these in non-duplicated
2172693eedb1SChandler Carruth   // regions.
2173693eedb1SChandler Carruth   int LoopCost = 0;
2174693eedb1SChandler Carruth   for (auto *BB : L.blocks()) {
2175693eedb1SChandler Carruth     int Cost = 0;
2176693eedb1SChandler Carruth     for (auto &I : *BB) {
2177693eedb1SChandler Carruth       if (EphValues.count(&I))
2178693eedb1SChandler Carruth         continue;
2179693eedb1SChandler Carruth 
2180693eedb1SChandler Carruth       if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
218171fd2704SChandler Carruth         return false;
2182693eedb1SChandler Carruth       if (auto CS = CallSite(&I))
2183693eedb1SChandler Carruth         if (CS.isConvergent() || CS.cannotDuplicate())
218471fd2704SChandler Carruth           return false;
2185693eedb1SChandler Carruth 
2186693eedb1SChandler Carruth       Cost += TTI.getUserCost(&I);
2187693eedb1SChandler Carruth     }
2188693eedb1SChandler Carruth     assert(Cost >= 0 && "Must not have negative costs!");
2189693eedb1SChandler Carruth     LoopCost += Cost;
2190693eedb1SChandler Carruth     assert(LoopCost >= 0 && "Must not have negative loop costs!");
2191693eedb1SChandler Carruth     BBCostMap[BB] = Cost;
2192693eedb1SChandler Carruth   }
2193d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  Total loop cost: " << LoopCost << "\n");
2194693eedb1SChandler Carruth 
2195693eedb1SChandler Carruth   // Now we find the best candidate by searching for the one with the following
2196693eedb1SChandler Carruth   // properties in order:
2197693eedb1SChandler Carruth   //
2198693eedb1SChandler Carruth   // 1) An unswitching cost below the threshold
2199693eedb1SChandler Carruth   // 2) The smallest number of duplicated unswitch candidates (to avoid
2200693eedb1SChandler Carruth   //    creating redundant subsequent unswitching)
2201693eedb1SChandler Carruth   // 3) The smallest cost after unswitching.
2202693eedb1SChandler Carruth   //
2203693eedb1SChandler Carruth   // We prioritize reducing fanout of unswitch candidates provided the cost
2204693eedb1SChandler Carruth   // remains below the threshold because this has a multiplicative effect.
2205693eedb1SChandler Carruth   //
2206693eedb1SChandler Carruth   // This requires memoizing each dominator subtree to avoid redundant work.
2207693eedb1SChandler Carruth   //
2208693eedb1SChandler Carruth   // FIXME: Need to actually do the number of candidates part above.
2209693eedb1SChandler Carruth   SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
2210693eedb1SChandler Carruth   // Given a terminator which might be unswitched, computes the non-duplicated
2211693eedb1SChandler Carruth   // cost for that terminator.
2212d1dab0c3SChandler Carruth   auto ComputeUnswitchedCost = [&](TerminatorInst &TI, bool FullUnswitch) {
2213d1dab0c3SChandler Carruth     BasicBlock &BB = *TI.getParent();
2214693eedb1SChandler Carruth     SmallPtrSet<BasicBlock *, 4> Visited;
2215693eedb1SChandler Carruth 
2216693eedb1SChandler Carruth     int Cost = LoopCost;
2217693eedb1SChandler Carruth     for (BasicBlock *SuccBB : successors(&BB)) {
2218693eedb1SChandler Carruth       // Don't count successors more than once.
2219693eedb1SChandler Carruth       if (!Visited.insert(SuccBB).second)
2220693eedb1SChandler Carruth         continue;
2221693eedb1SChandler Carruth 
2222d1dab0c3SChandler Carruth       // If this is a partial unswitch candidate, then it must be a conditional
2223d1dab0c3SChandler Carruth       // branch with a condition of either `or` or `and`. In that case, one of
2224d1dab0c3SChandler Carruth       // the successors is necessarily duplicated, so don't even try to remove
2225d1dab0c3SChandler Carruth       // its cost.
2226d1dab0c3SChandler Carruth       if (!FullUnswitch) {
2227d1dab0c3SChandler Carruth         auto &BI = cast<BranchInst>(TI);
2228d1dab0c3SChandler Carruth         if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2229d1dab0c3SChandler Carruth             Instruction::And) {
2230d1dab0c3SChandler Carruth           if (SuccBB == BI.getSuccessor(1))
2231d1dab0c3SChandler Carruth             continue;
2232d1dab0c3SChandler Carruth         } else {
2233d1dab0c3SChandler Carruth           assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2234d1dab0c3SChandler Carruth                      Instruction::Or &&
2235d1dab0c3SChandler Carruth                  "Only `and` and `or` conditions can result in a partial "
2236d1dab0c3SChandler Carruth                  "unswitch!");
2237d1dab0c3SChandler Carruth           if (SuccBB == BI.getSuccessor(0))
2238d1dab0c3SChandler Carruth             continue;
2239d1dab0c3SChandler Carruth         }
2240d1dab0c3SChandler Carruth       }
2241d1dab0c3SChandler Carruth 
2242693eedb1SChandler Carruth       // This successor's domtree will not need to be duplicated after
2243693eedb1SChandler Carruth       // unswitching if the edge to the successor dominates it (and thus the
2244693eedb1SChandler Carruth       // entire tree). This essentially means there is no other path into this
2245693eedb1SChandler Carruth       // subtree and so it will end up live in only one clone of the loop.
2246693eedb1SChandler Carruth       if (SuccBB->getUniquePredecessor() ||
2247693eedb1SChandler Carruth           llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2248693eedb1SChandler Carruth             return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2249693eedb1SChandler Carruth           })) {
2250693eedb1SChandler Carruth         Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2251693eedb1SChandler Carruth         assert(Cost >= 0 &&
2252693eedb1SChandler Carruth                "Non-duplicated cost should never exceed total loop cost!");
2253693eedb1SChandler Carruth       }
2254693eedb1SChandler Carruth     }
2255693eedb1SChandler Carruth 
2256693eedb1SChandler Carruth     // Now scale the cost by the number of unique successors minus one. We
2257693eedb1SChandler Carruth     // subtract one because there is already at least one copy of the entire
2258693eedb1SChandler Carruth     // loop. This is computing the new cost of unswitching a condition.
2259693eedb1SChandler Carruth     assert(Visited.size() > 1 &&
2260693eedb1SChandler Carruth            "Cannot unswitch a condition without multiple distinct successors!");
2261693eedb1SChandler Carruth     return Cost * (Visited.size() - 1);
2262693eedb1SChandler Carruth   };
2263693eedb1SChandler Carruth   TerminatorInst *BestUnswitchTI = nullptr;
2264693eedb1SChandler Carruth   int BestUnswitchCost;
2265d1dab0c3SChandler Carruth   ArrayRef<Value *> BestUnswitchInvariants;
2266d1dab0c3SChandler Carruth   for (auto &TerminatorAndInvariants : UnswitchCandidates) {
2267d1dab0c3SChandler Carruth     TerminatorInst &TI = *TerminatorAndInvariants.first;
2268d1dab0c3SChandler Carruth     ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2269d1dab0c3SChandler Carruth     BranchInst *BI = dyn_cast<BranchInst>(&TI);
22701652996fSChandler Carruth     int CandidateCost = ComputeUnswitchedCost(
22711652996fSChandler Carruth         TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
22721652996fSChandler Carruth                                      Invariants[0] == BI->getCondition()));
2273d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
2274d1dab0c3SChandler Carruth                       << " for unswitch candidate: " << TI << "\n");
2275693eedb1SChandler Carruth     if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
2276d1dab0c3SChandler Carruth       BestUnswitchTI = &TI;
2277693eedb1SChandler Carruth       BestUnswitchCost = CandidateCost;
2278d1dab0c3SChandler Carruth       BestUnswitchInvariants = Invariants;
2279693eedb1SChandler Carruth     }
2280693eedb1SChandler Carruth   }
2281693eedb1SChandler Carruth 
228271fd2704SChandler Carruth   if (BestUnswitchCost >= UnswitchThreshold) {
228371fd2704SChandler Carruth     LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
228471fd2704SChandler Carruth                       << BestUnswitchCost << "\n");
228571fd2704SChandler Carruth     return false;
228671fd2704SChandler Carruth   }
228771fd2704SChandler Carruth 
2288d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  Trying to unswitch non-trivial (cost = "
22891652996fSChandler Carruth                     << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
22901652996fSChandler Carruth                     << "\n");
22911652996fSChandler Carruth   return unswitchNontrivialInvariants(
22923897ded6SChandler Carruth       L, *BestUnswitchTI, BestUnswitchInvariants, DT, LI, AC, UnswitchCB, SE);
22931353f9a4SChandler Carruth }
22941353f9a4SChandler Carruth 
2295d1dab0c3SChandler Carruth /// Unswitch control flow predicated on loop invariant conditions.
2296d1dab0c3SChandler Carruth ///
2297d1dab0c3SChandler Carruth /// This first hoists all branches or switches which are trivial (IE, do not
2298d1dab0c3SChandler Carruth /// require duplicating any part of the loop) out of the loop body. It then
2299d1dab0c3SChandler Carruth /// looks at other loop invariant control flows and tries to unswitch those as
2300d1dab0c3SChandler Carruth /// well by cloning the loop if the result is small enough.
23013897ded6SChandler Carruth ///
23023897ded6SChandler Carruth /// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
23033897ded6SChandler Carruth /// updated based on the unswitch.
23043897ded6SChandler Carruth ///
23053897ded6SChandler Carruth /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
23063897ded6SChandler Carruth /// true, we will attempt to do non-trivial unswitching as well as trivial
23073897ded6SChandler Carruth /// unswitching.
23083897ded6SChandler Carruth ///
23093897ded6SChandler Carruth /// The `UnswitchCB` callback provided will be run after unswitching is
23103897ded6SChandler Carruth /// complete, with the first parameter set to `true` if the provided loop
23113897ded6SChandler Carruth /// remains a loop, and a list of new sibling loops created.
23123897ded6SChandler Carruth ///
23133897ded6SChandler Carruth /// If `SE` is non-null, we will update that analysis based on the unswitching
23143897ded6SChandler Carruth /// done.
23153897ded6SChandler Carruth static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
23163897ded6SChandler Carruth                          AssumptionCache &AC, TargetTransformInfo &TTI,
23173897ded6SChandler Carruth                          bool NonTrivial,
23183897ded6SChandler Carruth                          function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
23193897ded6SChandler Carruth                          ScalarEvolution *SE) {
2320d1dab0c3SChandler Carruth   assert(L.isRecursivelyLCSSAForm(DT, LI) &&
2321d1dab0c3SChandler Carruth          "Loops must be in LCSSA form before unswitching.");
2322d1dab0c3SChandler Carruth   bool Changed = false;
2323d1dab0c3SChandler Carruth 
2324d1dab0c3SChandler Carruth   // Must be in loop simplified form: we need a preheader and dedicated exits.
2325d1dab0c3SChandler Carruth   if (!L.isLoopSimplifyForm())
2326d1dab0c3SChandler Carruth     return false;
2327d1dab0c3SChandler Carruth 
2328d1dab0c3SChandler Carruth   // Try trivial unswitch first before loop over other basic blocks in the loop.
23293897ded6SChandler Carruth   if (unswitchAllTrivialConditions(L, DT, LI, SE)) {
2330d1dab0c3SChandler Carruth     // If we unswitched successfully we will want to clean up the loop before
2331d1dab0c3SChandler Carruth     // processing it further so just mark it as unswitched and return.
2332d1dab0c3SChandler Carruth     UnswitchCB(/*CurrentLoopValid*/ true, {});
2333d1dab0c3SChandler Carruth     return true;
2334d1dab0c3SChandler Carruth   }
2335d1dab0c3SChandler Carruth 
2336d1dab0c3SChandler Carruth   // If we're not doing non-trivial unswitching, we're done. We both accept
2337d1dab0c3SChandler Carruth   // a parameter but also check a local flag that can be used for testing
2338d1dab0c3SChandler Carruth   // a debugging.
2339d1dab0c3SChandler Carruth   if (!NonTrivial && !EnableNonTrivialUnswitch)
2340d1dab0c3SChandler Carruth     return false;
2341d1dab0c3SChandler Carruth 
2342d1dab0c3SChandler Carruth   // For non-trivial unswitching, because it often creates new loops, we rely on
2343d1dab0c3SChandler Carruth   // the pass manager to iterate on the loops rather than trying to immediately
2344d1dab0c3SChandler Carruth   // reach a fixed point. There is no substantial advantage to iterating
2345d1dab0c3SChandler Carruth   // internally, and if any of the new loops are simplified enough to contain
2346d1dab0c3SChandler Carruth   // trivial unswitching we want to prefer those.
2347d1dab0c3SChandler Carruth 
2348d1dab0c3SChandler Carruth   // Try to unswitch the best invariant condition. We prefer this full unswitch to
2349d1dab0c3SChandler Carruth   // a partial unswitch when possible below the threshold.
23503897ded6SChandler Carruth   if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE))
2351d1dab0c3SChandler Carruth     return true;
2352d1dab0c3SChandler Carruth 
2353d1dab0c3SChandler Carruth   // No other opportunities to unswitch.
2354d1dab0c3SChandler Carruth   return Changed;
2355d1dab0c3SChandler Carruth }
2356d1dab0c3SChandler Carruth 
23571353f9a4SChandler Carruth PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
23581353f9a4SChandler Carruth                                               LoopStandardAnalysisResults &AR,
23591353f9a4SChandler Carruth                                               LPMUpdater &U) {
23601353f9a4SChandler Carruth   Function &F = *L.getHeader()->getParent();
23611353f9a4SChandler Carruth   (void)F;
23621353f9a4SChandler Carruth 
2363d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
2364d34e60caSNicola Zaghen                     << "\n");
23651353f9a4SChandler Carruth 
2366693eedb1SChandler Carruth   // Save the current loop name in a variable so that we can report it even
2367693eedb1SChandler Carruth   // after it has been deleted.
2368693eedb1SChandler Carruth   std::string LoopName = L.getName();
2369693eedb1SChandler Carruth 
237071fd2704SChandler Carruth   auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2371693eedb1SChandler Carruth                                         ArrayRef<Loop *> NewLoops) {
2372693eedb1SChandler Carruth     // If we did a non-trivial unswitch, we have added new (cloned) loops.
237371fd2704SChandler Carruth     if (!NewLoops.empty())
2374693eedb1SChandler Carruth       U.addSiblingLoops(NewLoops);
2375693eedb1SChandler Carruth 
2376693eedb1SChandler Carruth     // If the current loop remains valid, we should revisit it to catch any
2377693eedb1SChandler Carruth     // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2378693eedb1SChandler Carruth     if (CurrentLoopValid)
2379693eedb1SChandler Carruth       U.revisitCurrentLoop();
2380693eedb1SChandler Carruth     else
2381693eedb1SChandler Carruth       U.markLoopAsDeleted(L, LoopName);
2382693eedb1SChandler Carruth   };
2383693eedb1SChandler Carruth 
23843897ded6SChandler Carruth   if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB,
23853897ded6SChandler Carruth                     &AR.SE))
23861353f9a4SChandler Carruth     return PreservedAnalyses::all();
23871353f9a4SChandler Carruth 
23881353f9a4SChandler Carruth   // Historically this pass has had issues with the dominator tree so verify it
23891353f9a4SChandler Carruth   // in asserts builds.
23907c35de12SDavid Green   assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
23911353f9a4SChandler Carruth   return getLoopPassPreservedAnalyses();
23921353f9a4SChandler Carruth }
23931353f9a4SChandler Carruth 
23941353f9a4SChandler Carruth namespace {
2395a369a457SEugene Zelenko 
23961353f9a4SChandler Carruth class SimpleLoopUnswitchLegacyPass : public LoopPass {
2397693eedb1SChandler Carruth   bool NonTrivial;
2398693eedb1SChandler Carruth 
23991353f9a4SChandler Carruth public:
24001353f9a4SChandler Carruth   static char ID; // Pass ID, replacement for typeid
2401a369a457SEugene Zelenko 
2402693eedb1SChandler Carruth   explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2403693eedb1SChandler Carruth       : LoopPass(ID), NonTrivial(NonTrivial) {
24041353f9a4SChandler Carruth     initializeSimpleLoopUnswitchLegacyPassPass(
24051353f9a4SChandler Carruth         *PassRegistry::getPassRegistry());
24061353f9a4SChandler Carruth   }
24071353f9a4SChandler Carruth 
24081353f9a4SChandler Carruth   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
24091353f9a4SChandler Carruth 
24101353f9a4SChandler Carruth   void getAnalysisUsage(AnalysisUsage &AU) const override {
24111353f9a4SChandler Carruth     AU.addRequired<AssumptionCacheTracker>();
2412693eedb1SChandler Carruth     AU.addRequired<TargetTransformInfoWrapperPass>();
24131353f9a4SChandler Carruth     getLoopAnalysisUsage(AU);
24141353f9a4SChandler Carruth   }
24151353f9a4SChandler Carruth };
2416a369a457SEugene Zelenko 
2417a369a457SEugene Zelenko } // end anonymous namespace
24181353f9a4SChandler Carruth 
24191353f9a4SChandler Carruth bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
24201353f9a4SChandler Carruth   if (skipLoop(L))
24211353f9a4SChandler Carruth     return false;
24221353f9a4SChandler Carruth 
24231353f9a4SChandler Carruth   Function &F = *L->getHeader()->getParent();
24241353f9a4SChandler Carruth 
2425d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
2426d34e60caSNicola Zaghen                     << "\n");
24271353f9a4SChandler Carruth 
24281353f9a4SChandler Carruth   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
24291353f9a4SChandler Carruth   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
24301353f9a4SChandler Carruth   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2431693eedb1SChandler Carruth   auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
24321353f9a4SChandler Carruth 
24333897ded6SChandler Carruth   auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
24343897ded6SChandler Carruth   auto *SE = SEWP ? &SEWP->getSE() : nullptr;
24353897ded6SChandler Carruth 
243671fd2704SChandler Carruth   auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2437693eedb1SChandler Carruth                                ArrayRef<Loop *> NewLoops) {
2438693eedb1SChandler Carruth     // If we did a non-trivial unswitch, we have added new (cloned) loops.
2439693eedb1SChandler Carruth     for (auto *NewL : NewLoops)
2440693eedb1SChandler Carruth       LPM.addLoop(*NewL);
2441693eedb1SChandler Carruth 
2442693eedb1SChandler Carruth     // If the current loop remains valid, re-add it to the queue. This is
2443693eedb1SChandler Carruth     // a little wasteful as we'll finish processing the current loop as well,
2444693eedb1SChandler Carruth     // but it is the best we can do in the old PM.
2445693eedb1SChandler Carruth     if (CurrentLoopValid)
2446693eedb1SChandler Carruth       LPM.addLoop(*L);
2447693eedb1SChandler Carruth     else
2448693eedb1SChandler Carruth       LPM.markLoopAsDeleted(*L);
2449693eedb1SChandler Carruth   };
2450693eedb1SChandler Carruth 
24513897ded6SChandler Carruth   bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE);
2452693eedb1SChandler Carruth 
2453693eedb1SChandler Carruth   // If anything was unswitched, also clear any cached information about this
2454693eedb1SChandler Carruth   // loop.
2455693eedb1SChandler Carruth   LPM.deleteSimpleAnalysisLoop(L);
24561353f9a4SChandler Carruth 
24571353f9a4SChandler Carruth   // Historically this pass has had issues with the dominator tree so verify it
24581353f9a4SChandler Carruth   // in asserts builds.
24597c35de12SDavid Green   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
24607c35de12SDavid Green 
24611353f9a4SChandler Carruth   return Changed;
24621353f9a4SChandler Carruth }
24631353f9a4SChandler Carruth 
24641353f9a4SChandler Carruth char SimpleLoopUnswitchLegacyPass::ID = 0;
24651353f9a4SChandler Carruth INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
24661353f9a4SChandler Carruth                       "Simple unswitch loops", false, false)
24671353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2468693eedb1SChandler Carruth INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2469693eedb1SChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
24701353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopPass)
24711353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
24721353f9a4SChandler Carruth INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
24731353f9a4SChandler Carruth                     "Simple unswitch loops", false, false)
24741353f9a4SChandler Carruth 
2475693eedb1SChandler Carruth Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
2476693eedb1SChandler Carruth   return new SimpleLoopUnswitchLegacyPass(NonTrivial);
24771353f9a4SChandler Carruth }
2478