xref: /aosp_15_r20/external/llvm/lib/Transforms/Utils/LoopSimplify.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This pass performs several transformations to transform natural loops into a
11*9880d681SAndroid Build Coastguard Worker // simpler form, which makes subsequent analyses and transformations simpler and
12*9880d681SAndroid Build Coastguard Worker // more effective.
13*9880d681SAndroid Build Coastguard Worker //
14*9880d681SAndroid Build Coastguard Worker // Loop pre-header insertion guarantees that there is a single, non-critical
15*9880d681SAndroid Build Coastguard Worker // entry edge from outside of the loop to the loop header.  This simplifies a
16*9880d681SAndroid Build Coastguard Worker // number of analyses and transformations, such as LICM.
17*9880d681SAndroid Build Coastguard Worker //
18*9880d681SAndroid Build Coastguard Worker // Loop exit-block insertion guarantees that all exit blocks from the loop
19*9880d681SAndroid Build Coastguard Worker // (blocks which are outside of the loop that have predecessors inside of the
20*9880d681SAndroid Build Coastguard Worker // loop) only have predecessors from inside of the loop (and are thus dominated
21*9880d681SAndroid Build Coastguard Worker // by the loop header).  This simplifies transformations such as store-sinking
22*9880d681SAndroid Build Coastguard Worker // that are built into LICM.
23*9880d681SAndroid Build Coastguard Worker //
24*9880d681SAndroid Build Coastguard Worker // This pass also guarantees that loops will have exactly one backedge.
25*9880d681SAndroid Build Coastguard Worker //
26*9880d681SAndroid Build Coastguard Worker // Indirectbr instructions introduce several complications. If the loop
27*9880d681SAndroid Build Coastguard Worker // contains or is entered by an indirectbr instruction, it may not be possible
28*9880d681SAndroid Build Coastguard Worker // to transform the loop and make these guarantees. Client code should check
29*9880d681SAndroid Build Coastguard Worker // that these conditions are true before relying on them.
30*9880d681SAndroid Build Coastguard Worker //
31*9880d681SAndroid Build Coastguard Worker // Note that the simplifycfg pass will clean up blocks which are split out but
32*9880d681SAndroid Build Coastguard Worker // end up being unnecessary, so usage of this pass should not pessimize
33*9880d681SAndroid Build Coastguard Worker // generated code.
34*9880d681SAndroid Build Coastguard Worker //
35*9880d681SAndroid Build Coastguard Worker // This pass obviously modifies the CFG, but updates loop information and
36*9880d681SAndroid Build Coastguard Worker // dominator information.
37*9880d681SAndroid Build Coastguard Worker //
38*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
39*9880d681SAndroid Build Coastguard Worker 
40*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/LoopSimplify.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DepthFirstIterator.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SetOperations.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SetVector.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallVector.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AliasAnalysis.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/BasicAliasAnalysis.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AssumptionCache.h"
50*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/DependenceAnalysis.h"
51*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/GlobalsModRef.h"
52*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/InstructionSimplify.h"
53*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopInfo.h"
54*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolution.h"
55*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
56*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CFG.h"
57*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constants.h"
58*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
59*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
60*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Function.h"
61*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
62*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
63*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
64*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
65*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Type.h"
66*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
67*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
68*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/BasicBlockUtils.h"
69*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
70*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/LoopUtils.h"
71*9880d681SAndroid Build Coastguard Worker using namespace llvm;
72*9880d681SAndroid Build Coastguard Worker 
73*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "loop-simplify"
74*9880d681SAndroid Build Coastguard Worker 
75*9880d681SAndroid Build Coastguard Worker STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
76*9880d681SAndroid Build Coastguard Worker STATISTIC(NumNested  , "Number of nested loops split out");
77*9880d681SAndroid Build Coastguard Worker 
78*9880d681SAndroid Build Coastguard Worker // If the block isn't already, move the new block to right after some 'outside
79*9880d681SAndroid Build Coastguard Worker // block' block.  This prevents the preheader from being placed inside the loop
80*9880d681SAndroid Build Coastguard Worker // body, e.g. when the loop hasn't been rotated.
placeSplitBlockCarefully(BasicBlock * NewBB,SmallVectorImpl<BasicBlock * > & SplitPreds,Loop * L)81*9880d681SAndroid Build Coastguard Worker static void placeSplitBlockCarefully(BasicBlock *NewBB,
82*9880d681SAndroid Build Coastguard Worker                                      SmallVectorImpl<BasicBlock *> &SplitPreds,
83*9880d681SAndroid Build Coastguard Worker                                      Loop *L) {
84*9880d681SAndroid Build Coastguard Worker   // Check to see if NewBB is already well placed.
85*9880d681SAndroid Build Coastguard Worker   Function::iterator BBI = --NewBB->getIterator();
86*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
87*9880d681SAndroid Build Coastguard Worker     if (&*BBI == SplitPreds[i])
88*9880d681SAndroid Build Coastguard Worker       return;
89*9880d681SAndroid Build Coastguard Worker   }
90*9880d681SAndroid Build Coastguard Worker 
91*9880d681SAndroid Build Coastguard Worker   // If it isn't already after an outside block, move it after one.  This is
92*9880d681SAndroid Build Coastguard Worker   // always good as it makes the uncond branch from the outside block into a
93*9880d681SAndroid Build Coastguard Worker   // fall-through.
94*9880d681SAndroid Build Coastguard Worker 
95*9880d681SAndroid Build Coastguard Worker   // Figure out *which* outside block to put this after.  Prefer an outside
96*9880d681SAndroid Build Coastguard Worker   // block that neighbors a BB actually in the loop.
97*9880d681SAndroid Build Coastguard Worker   BasicBlock *FoundBB = nullptr;
98*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
99*9880d681SAndroid Build Coastguard Worker     Function::iterator BBI = SplitPreds[i]->getIterator();
100*9880d681SAndroid Build Coastguard Worker     if (++BBI != NewBB->getParent()->end() && L->contains(&*BBI)) {
101*9880d681SAndroid Build Coastguard Worker       FoundBB = SplitPreds[i];
102*9880d681SAndroid Build Coastguard Worker       break;
103*9880d681SAndroid Build Coastguard Worker     }
104*9880d681SAndroid Build Coastguard Worker   }
105*9880d681SAndroid Build Coastguard Worker 
106*9880d681SAndroid Build Coastguard Worker   // If our heuristic for a *good* bb to place this after doesn't find
107*9880d681SAndroid Build Coastguard Worker   // anything, just pick something.  It's likely better than leaving it within
108*9880d681SAndroid Build Coastguard Worker   // the loop.
109*9880d681SAndroid Build Coastguard Worker   if (!FoundBB)
110*9880d681SAndroid Build Coastguard Worker     FoundBB = SplitPreds[0];
111*9880d681SAndroid Build Coastguard Worker   NewBB->moveAfter(FoundBB);
112*9880d681SAndroid Build Coastguard Worker }
113*9880d681SAndroid Build Coastguard Worker 
114*9880d681SAndroid Build Coastguard Worker /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
115*9880d681SAndroid Build Coastguard Worker /// preheader, this method is called to insert one.  This method has two phases:
116*9880d681SAndroid Build Coastguard Worker /// preheader insertion and analysis updating.
117*9880d681SAndroid Build Coastguard Worker ///
InsertPreheaderForLoop(Loop * L,DominatorTree * DT,LoopInfo * LI,bool PreserveLCSSA)118*9880d681SAndroid Build Coastguard Worker BasicBlock *llvm::InsertPreheaderForLoop(Loop *L, DominatorTree *DT,
119*9880d681SAndroid Build Coastguard Worker                                          LoopInfo *LI, bool PreserveLCSSA) {
120*9880d681SAndroid Build Coastguard Worker   BasicBlock *Header = L->getHeader();
121*9880d681SAndroid Build Coastguard Worker 
122*9880d681SAndroid Build Coastguard Worker   // Compute the set of predecessors of the loop that are not in the loop.
123*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock*, 8> OutsideBlocks;
124*9880d681SAndroid Build Coastguard Worker   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
125*9880d681SAndroid Build Coastguard Worker        PI != PE; ++PI) {
126*9880d681SAndroid Build Coastguard Worker     BasicBlock *P = *PI;
127*9880d681SAndroid Build Coastguard Worker     if (!L->contains(P)) {         // Coming in from outside the loop?
128*9880d681SAndroid Build Coastguard Worker       // If the loop is branched to from an indirect branch, we won't
129*9880d681SAndroid Build Coastguard Worker       // be able to fully transform the loop, because it prohibits
130*9880d681SAndroid Build Coastguard Worker       // edge splitting.
131*9880d681SAndroid Build Coastguard Worker       if (isa<IndirectBrInst>(P->getTerminator())) return nullptr;
132*9880d681SAndroid Build Coastguard Worker 
133*9880d681SAndroid Build Coastguard Worker       // Keep track of it.
134*9880d681SAndroid Build Coastguard Worker       OutsideBlocks.push_back(P);
135*9880d681SAndroid Build Coastguard Worker     }
136*9880d681SAndroid Build Coastguard Worker   }
137*9880d681SAndroid Build Coastguard Worker 
138*9880d681SAndroid Build Coastguard Worker   // Split out the loop pre-header.
139*9880d681SAndroid Build Coastguard Worker   BasicBlock *PreheaderBB;
140*9880d681SAndroid Build Coastguard Worker   PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader", DT,
141*9880d681SAndroid Build Coastguard Worker                                        LI, PreserveLCSSA);
142*9880d681SAndroid Build Coastguard Worker   if (!PreheaderBB)
143*9880d681SAndroid Build Coastguard Worker     return nullptr;
144*9880d681SAndroid Build Coastguard Worker 
145*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LoopSimplify: Creating pre-header "
146*9880d681SAndroid Build Coastguard Worker                << PreheaderBB->getName() << "\n");
147*9880d681SAndroid Build Coastguard Worker 
148*9880d681SAndroid Build Coastguard Worker   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
149*9880d681SAndroid Build Coastguard Worker   // code layout too horribly.
150*9880d681SAndroid Build Coastguard Worker   placeSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
151*9880d681SAndroid Build Coastguard Worker 
152*9880d681SAndroid Build Coastguard Worker   return PreheaderBB;
153*9880d681SAndroid Build Coastguard Worker }
154*9880d681SAndroid Build Coastguard Worker 
155*9880d681SAndroid Build Coastguard Worker /// \brief Ensure that the loop preheader dominates all exit blocks.
156*9880d681SAndroid Build Coastguard Worker ///
157*9880d681SAndroid Build Coastguard Worker /// This method is used to split exit blocks that have predecessors outside of
158*9880d681SAndroid Build Coastguard Worker /// the loop.
rewriteLoopExitBlock(Loop * L,BasicBlock * Exit,DominatorTree * DT,LoopInfo * LI,bool PreserveLCSSA)159*9880d681SAndroid Build Coastguard Worker static BasicBlock *rewriteLoopExitBlock(Loop *L, BasicBlock *Exit,
160*9880d681SAndroid Build Coastguard Worker                                         DominatorTree *DT, LoopInfo *LI,
161*9880d681SAndroid Build Coastguard Worker                                         bool PreserveLCSSA) {
162*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock*, 8> LoopBlocks;
163*9880d681SAndroid Build Coastguard Worker   for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I) {
164*9880d681SAndroid Build Coastguard Worker     BasicBlock *P = *I;
165*9880d681SAndroid Build Coastguard Worker     if (L->contains(P)) {
166*9880d681SAndroid Build Coastguard Worker       // Don't do this if the loop is exited via an indirect branch.
167*9880d681SAndroid Build Coastguard Worker       if (isa<IndirectBrInst>(P->getTerminator())) return nullptr;
168*9880d681SAndroid Build Coastguard Worker 
169*9880d681SAndroid Build Coastguard Worker       LoopBlocks.push_back(P);
170*9880d681SAndroid Build Coastguard Worker     }
171*9880d681SAndroid Build Coastguard Worker   }
172*9880d681SAndroid Build Coastguard Worker 
173*9880d681SAndroid Build Coastguard Worker   assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
174*9880d681SAndroid Build Coastguard Worker   BasicBlock *NewExitBB = nullptr;
175*9880d681SAndroid Build Coastguard Worker 
176*9880d681SAndroid Build Coastguard Worker   NewExitBB = SplitBlockPredecessors(Exit, LoopBlocks, ".loopexit", DT, LI,
177*9880d681SAndroid Build Coastguard Worker                                      PreserveLCSSA);
178*9880d681SAndroid Build Coastguard Worker   if (!NewExitBB)
179*9880d681SAndroid Build Coastguard Worker     return nullptr;
180*9880d681SAndroid Build Coastguard Worker 
181*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
182*9880d681SAndroid Build Coastguard Worker                << NewExitBB->getName() << "\n");
183*9880d681SAndroid Build Coastguard Worker   return NewExitBB;
184*9880d681SAndroid Build Coastguard Worker }
185*9880d681SAndroid Build Coastguard Worker 
186*9880d681SAndroid Build Coastguard Worker /// Add the specified block, and all of its predecessors, to the specified set,
187*9880d681SAndroid Build Coastguard Worker /// if it's not already in there.  Stop predecessor traversal when we reach
188*9880d681SAndroid Build Coastguard Worker /// StopBlock.
addBlockAndPredsToSet(BasicBlock * InputBB,BasicBlock * StopBlock,std::set<BasicBlock * > & Blocks)189*9880d681SAndroid Build Coastguard Worker static void addBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
190*9880d681SAndroid Build Coastguard Worker                                   std::set<BasicBlock*> &Blocks) {
191*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock *, 8> Worklist;
192*9880d681SAndroid Build Coastguard Worker   Worklist.push_back(InputBB);
193*9880d681SAndroid Build Coastguard Worker   do {
194*9880d681SAndroid Build Coastguard Worker     BasicBlock *BB = Worklist.pop_back_val();
195*9880d681SAndroid Build Coastguard Worker     if (Blocks.insert(BB).second && BB != StopBlock)
196*9880d681SAndroid Build Coastguard Worker       // If BB is not already processed and it is not a stop block then
197*9880d681SAndroid Build Coastguard Worker       // insert its predecessor in the work list
198*9880d681SAndroid Build Coastguard Worker       for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
199*9880d681SAndroid Build Coastguard Worker         BasicBlock *WBB = *I;
200*9880d681SAndroid Build Coastguard Worker         Worklist.push_back(WBB);
201*9880d681SAndroid Build Coastguard Worker       }
202*9880d681SAndroid Build Coastguard Worker   } while (!Worklist.empty());
203*9880d681SAndroid Build Coastguard Worker }
204*9880d681SAndroid Build Coastguard Worker 
205*9880d681SAndroid Build Coastguard Worker /// \brief The first part of loop-nestification is to find a PHI node that tells
206*9880d681SAndroid Build Coastguard Worker /// us how to partition the loops.
findPHIToPartitionLoops(Loop * L,DominatorTree * DT,AssumptionCache * AC)207*9880d681SAndroid Build Coastguard Worker static PHINode *findPHIToPartitionLoops(Loop *L, DominatorTree *DT,
208*9880d681SAndroid Build Coastguard Worker                                         AssumptionCache *AC) {
209*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
210*9880d681SAndroid Build Coastguard Worker   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
211*9880d681SAndroid Build Coastguard Worker     PHINode *PN = cast<PHINode>(I);
212*9880d681SAndroid Build Coastguard Worker     ++I;
213*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyInstruction(PN, DL, nullptr, DT, AC)) {
214*9880d681SAndroid Build Coastguard Worker       // This is a degenerate PHI already, don't modify it!
215*9880d681SAndroid Build Coastguard Worker       PN->replaceAllUsesWith(V);
216*9880d681SAndroid Build Coastguard Worker       PN->eraseFromParent();
217*9880d681SAndroid Build Coastguard Worker       continue;
218*9880d681SAndroid Build Coastguard Worker     }
219*9880d681SAndroid Build Coastguard Worker 
220*9880d681SAndroid Build Coastguard Worker     // Scan this PHI node looking for a use of the PHI node by itself.
221*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
222*9880d681SAndroid Build Coastguard Worker       if (PN->getIncomingValue(i) == PN &&
223*9880d681SAndroid Build Coastguard Worker           L->contains(PN->getIncomingBlock(i)))
224*9880d681SAndroid Build Coastguard Worker         // We found something tasty to remove.
225*9880d681SAndroid Build Coastguard Worker         return PN;
226*9880d681SAndroid Build Coastguard Worker   }
227*9880d681SAndroid Build Coastguard Worker   return nullptr;
228*9880d681SAndroid Build Coastguard Worker }
229*9880d681SAndroid Build Coastguard Worker 
230*9880d681SAndroid Build Coastguard Worker /// \brief If this loop has multiple backedges, try to pull one of them out into
231*9880d681SAndroid Build Coastguard Worker /// a nested loop.
232*9880d681SAndroid Build Coastguard Worker ///
233*9880d681SAndroid Build Coastguard Worker /// This is important for code that looks like
234*9880d681SAndroid Build Coastguard Worker /// this:
235*9880d681SAndroid Build Coastguard Worker ///
236*9880d681SAndroid Build Coastguard Worker ///  Loop:
237*9880d681SAndroid Build Coastguard Worker ///     ...
238*9880d681SAndroid Build Coastguard Worker ///     br cond, Loop, Next
239*9880d681SAndroid Build Coastguard Worker ///     ...
240*9880d681SAndroid Build Coastguard Worker ///     br cond2, Loop, Out
241*9880d681SAndroid Build Coastguard Worker ///
242*9880d681SAndroid Build Coastguard Worker /// To identify this common case, we look at the PHI nodes in the header of the
243*9880d681SAndroid Build Coastguard Worker /// loop.  PHI nodes with unchanging values on one backedge correspond to values
244*9880d681SAndroid Build Coastguard Worker /// that change in the "outer" loop, but not in the "inner" loop.
245*9880d681SAndroid Build Coastguard Worker ///
246*9880d681SAndroid Build Coastguard Worker /// If we are able to separate out a loop, return the new outer loop that was
247*9880d681SAndroid Build Coastguard Worker /// created.
248*9880d681SAndroid Build Coastguard Worker ///
separateNestedLoop(Loop * L,BasicBlock * Preheader,DominatorTree * DT,LoopInfo * LI,ScalarEvolution * SE,bool PreserveLCSSA,AssumptionCache * AC)249*9880d681SAndroid Build Coastguard Worker static Loop *separateNestedLoop(Loop *L, BasicBlock *Preheader,
250*9880d681SAndroid Build Coastguard Worker                                 DominatorTree *DT, LoopInfo *LI,
251*9880d681SAndroid Build Coastguard Worker                                 ScalarEvolution *SE, bool PreserveLCSSA,
252*9880d681SAndroid Build Coastguard Worker                                 AssumptionCache *AC) {
253*9880d681SAndroid Build Coastguard Worker   // Don't try to separate loops without a preheader.
254*9880d681SAndroid Build Coastguard Worker   if (!Preheader)
255*9880d681SAndroid Build Coastguard Worker     return nullptr;
256*9880d681SAndroid Build Coastguard Worker 
257*9880d681SAndroid Build Coastguard Worker   // The header is not a landing pad; preheader insertion should ensure this.
258*9880d681SAndroid Build Coastguard Worker   BasicBlock *Header = L->getHeader();
259*9880d681SAndroid Build Coastguard Worker   assert(!Header->isEHPad() && "Can't insert backedge to EH pad");
260*9880d681SAndroid Build Coastguard Worker 
261*9880d681SAndroid Build Coastguard Worker   PHINode *PN = findPHIToPartitionLoops(L, DT, AC);
262*9880d681SAndroid Build Coastguard Worker   if (!PN) return nullptr;  // No known way to partition.
263*9880d681SAndroid Build Coastguard Worker 
264*9880d681SAndroid Build Coastguard Worker   // Pull out all predecessors that have varying values in the loop.  This
265*9880d681SAndroid Build Coastguard Worker   // handles the case when a PHI node has multiple instances of itself as
266*9880d681SAndroid Build Coastguard Worker   // arguments.
267*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock*, 8> OuterLoopPreds;
268*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
269*9880d681SAndroid Build Coastguard Worker     if (PN->getIncomingValue(i) != PN ||
270*9880d681SAndroid Build Coastguard Worker         !L->contains(PN->getIncomingBlock(i))) {
271*9880d681SAndroid Build Coastguard Worker       // We can't split indirectbr edges.
272*9880d681SAndroid Build Coastguard Worker       if (isa<IndirectBrInst>(PN->getIncomingBlock(i)->getTerminator()))
273*9880d681SAndroid Build Coastguard Worker         return nullptr;
274*9880d681SAndroid Build Coastguard Worker       OuterLoopPreds.push_back(PN->getIncomingBlock(i));
275*9880d681SAndroid Build Coastguard Worker     }
276*9880d681SAndroid Build Coastguard Worker   }
277*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LoopSimplify: Splitting out a new outer loop\n");
278*9880d681SAndroid Build Coastguard Worker 
279*9880d681SAndroid Build Coastguard Worker   // If ScalarEvolution is around and knows anything about values in
280*9880d681SAndroid Build Coastguard Worker   // this loop, tell it to forget them, because we're about to
281*9880d681SAndroid Build Coastguard Worker   // substantially change it.
282*9880d681SAndroid Build Coastguard Worker   if (SE)
283*9880d681SAndroid Build Coastguard Worker     SE->forgetLoop(L);
284*9880d681SAndroid Build Coastguard Worker 
285*9880d681SAndroid Build Coastguard Worker   BasicBlock *NewBB = SplitBlockPredecessors(Header, OuterLoopPreds, ".outer",
286*9880d681SAndroid Build Coastguard Worker                                              DT, LI, PreserveLCSSA);
287*9880d681SAndroid Build Coastguard Worker 
288*9880d681SAndroid Build Coastguard Worker   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
289*9880d681SAndroid Build Coastguard Worker   // code layout too horribly.
290*9880d681SAndroid Build Coastguard Worker   placeSplitBlockCarefully(NewBB, OuterLoopPreds, L);
291*9880d681SAndroid Build Coastguard Worker 
292*9880d681SAndroid Build Coastguard Worker   // Create the new outer loop.
293*9880d681SAndroid Build Coastguard Worker   Loop *NewOuter = new Loop();
294*9880d681SAndroid Build Coastguard Worker 
295*9880d681SAndroid Build Coastguard Worker   // Change the parent loop to use the outer loop as its child now.
296*9880d681SAndroid Build Coastguard Worker   if (Loop *Parent = L->getParentLoop())
297*9880d681SAndroid Build Coastguard Worker     Parent->replaceChildLoopWith(L, NewOuter);
298*9880d681SAndroid Build Coastguard Worker   else
299*9880d681SAndroid Build Coastguard Worker     LI->changeTopLevelLoop(L, NewOuter);
300*9880d681SAndroid Build Coastguard Worker 
301*9880d681SAndroid Build Coastguard Worker   // L is now a subloop of our outer loop.
302*9880d681SAndroid Build Coastguard Worker   NewOuter->addChildLoop(L);
303*9880d681SAndroid Build Coastguard Worker 
304*9880d681SAndroid Build Coastguard Worker   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
305*9880d681SAndroid Build Coastguard Worker        I != E; ++I)
306*9880d681SAndroid Build Coastguard Worker     NewOuter->addBlockEntry(*I);
307*9880d681SAndroid Build Coastguard Worker 
308*9880d681SAndroid Build Coastguard Worker   // Now reset the header in L, which had been moved by
309*9880d681SAndroid Build Coastguard Worker   // SplitBlockPredecessors for the outer loop.
310*9880d681SAndroid Build Coastguard Worker   L->moveToHeader(Header);
311*9880d681SAndroid Build Coastguard Worker 
312*9880d681SAndroid Build Coastguard Worker   // Determine which blocks should stay in L and which should be moved out to
313*9880d681SAndroid Build Coastguard Worker   // the Outer loop now.
314*9880d681SAndroid Build Coastguard Worker   std::set<BasicBlock*> BlocksInL;
315*9880d681SAndroid Build Coastguard Worker   for (pred_iterator PI=pred_begin(Header), E = pred_end(Header); PI!=E; ++PI) {
316*9880d681SAndroid Build Coastguard Worker     BasicBlock *P = *PI;
317*9880d681SAndroid Build Coastguard Worker     if (DT->dominates(Header, P))
318*9880d681SAndroid Build Coastguard Worker       addBlockAndPredsToSet(P, Header, BlocksInL);
319*9880d681SAndroid Build Coastguard Worker   }
320*9880d681SAndroid Build Coastguard Worker 
321*9880d681SAndroid Build Coastguard Worker   // Scan all of the loop children of L, moving them to OuterLoop if they are
322*9880d681SAndroid Build Coastguard Worker   // not part of the inner loop.
323*9880d681SAndroid Build Coastguard Worker   const std::vector<Loop*> &SubLoops = L->getSubLoops();
324*9880d681SAndroid Build Coastguard Worker   for (size_t I = 0; I != SubLoops.size(); )
325*9880d681SAndroid Build Coastguard Worker     if (BlocksInL.count(SubLoops[I]->getHeader()))
326*9880d681SAndroid Build Coastguard Worker       ++I;   // Loop remains in L
327*9880d681SAndroid Build Coastguard Worker     else
328*9880d681SAndroid Build Coastguard Worker       NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
329*9880d681SAndroid Build Coastguard Worker 
330*9880d681SAndroid Build Coastguard Worker   // Now that we know which blocks are in L and which need to be moved to
331*9880d681SAndroid Build Coastguard Worker   // OuterLoop, move any blocks that need it.
332*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
333*9880d681SAndroid Build Coastguard Worker     BasicBlock *BB = L->getBlocks()[i];
334*9880d681SAndroid Build Coastguard Worker     if (!BlocksInL.count(BB)) {
335*9880d681SAndroid Build Coastguard Worker       // Move this block to the parent, updating the exit blocks sets
336*9880d681SAndroid Build Coastguard Worker       L->removeBlockFromLoop(BB);
337*9880d681SAndroid Build Coastguard Worker       if ((*LI)[BB] == L)
338*9880d681SAndroid Build Coastguard Worker         LI->changeLoopFor(BB, NewOuter);
339*9880d681SAndroid Build Coastguard Worker       --i;
340*9880d681SAndroid Build Coastguard Worker     }
341*9880d681SAndroid Build Coastguard Worker   }
342*9880d681SAndroid Build Coastguard Worker 
343*9880d681SAndroid Build Coastguard Worker   return NewOuter;
344*9880d681SAndroid Build Coastguard Worker }
345*9880d681SAndroid Build Coastguard Worker 
346*9880d681SAndroid Build Coastguard Worker /// \brief This method is called when the specified loop has more than one
347*9880d681SAndroid Build Coastguard Worker /// backedge in it.
348*9880d681SAndroid Build Coastguard Worker ///
349*9880d681SAndroid Build Coastguard Worker /// If this occurs, revector all of these backedges to target a new basic block
350*9880d681SAndroid Build Coastguard Worker /// and have that block branch to the loop header.  This ensures that loops
351*9880d681SAndroid Build Coastguard Worker /// have exactly one backedge.
insertUniqueBackedgeBlock(Loop * L,BasicBlock * Preheader,DominatorTree * DT,LoopInfo * LI)352*9880d681SAndroid Build Coastguard Worker static BasicBlock *insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader,
353*9880d681SAndroid Build Coastguard Worker                                              DominatorTree *DT, LoopInfo *LI) {
354*9880d681SAndroid Build Coastguard Worker   assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
355*9880d681SAndroid Build Coastguard Worker 
356*9880d681SAndroid Build Coastguard Worker   // Get information about the loop
357*9880d681SAndroid Build Coastguard Worker   BasicBlock *Header = L->getHeader();
358*9880d681SAndroid Build Coastguard Worker   Function *F = Header->getParent();
359*9880d681SAndroid Build Coastguard Worker 
360*9880d681SAndroid Build Coastguard Worker   // Unique backedge insertion currently depends on having a preheader.
361*9880d681SAndroid Build Coastguard Worker   if (!Preheader)
362*9880d681SAndroid Build Coastguard Worker     return nullptr;
363*9880d681SAndroid Build Coastguard Worker 
364*9880d681SAndroid Build Coastguard Worker   // The header is not an EH pad; preheader insertion should ensure this.
365*9880d681SAndroid Build Coastguard Worker   assert(!Header->isEHPad() && "Can't insert backedge to EH pad");
366*9880d681SAndroid Build Coastguard Worker 
367*9880d681SAndroid Build Coastguard Worker   // Figure out which basic blocks contain back-edges to the loop header.
368*9880d681SAndroid Build Coastguard Worker   std::vector<BasicBlock*> BackedgeBlocks;
369*9880d681SAndroid Build Coastguard Worker   for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I){
370*9880d681SAndroid Build Coastguard Worker     BasicBlock *P = *I;
371*9880d681SAndroid Build Coastguard Worker 
372*9880d681SAndroid Build Coastguard Worker     // Indirectbr edges cannot be split, so we must fail if we find one.
373*9880d681SAndroid Build Coastguard Worker     if (isa<IndirectBrInst>(P->getTerminator()))
374*9880d681SAndroid Build Coastguard Worker       return nullptr;
375*9880d681SAndroid Build Coastguard Worker 
376*9880d681SAndroid Build Coastguard Worker     if (P != Preheader) BackedgeBlocks.push_back(P);
377*9880d681SAndroid Build Coastguard Worker   }
378*9880d681SAndroid Build Coastguard Worker 
379*9880d681SAndroid Build Coastguard Worker   // Create and insert the new backedge block...
380*9880d681SAndroid Build Coastguard Worker   BasicBlock *BEBlock = BasicBlock::Create(Header->getContext(),
381*9880d681SAndroid Build Coastguard Worker                                            Header->getName() + ".backedge", F);
382*9880d681SAndroid Build Coastguard Worker   BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
383*9880d681SAndroid Build Coastguard Worker   BETerminator->setDebugLoc(Header->getFirstNonPHI()->getDebugLoc());
384*9880d681SAndroid Build Coastguard Worker 
385*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LoopSimplify: Inserting unique backedge block "
386*9880d681SAndroid Build Coastguard Worker                << BEBlock->getName() << "\n");
387*9880d681SAndroid Build Coastguard Worker 
388*9880d681SAndroid Build Coastguard Worker   // Move the new backedge block to right after the last backedge block.
389*9880d681SAndroid Build Coastguard Worker   Function::iterator InsertPos = ++BackedgeBlocks.back()->getIterator();
390*9880d681SAndroid Build Coastguard Worker   F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
391*9880d681SAndroid Build Coastguard Worker 
392*9880d681SAndroid Build Coastguard Worker   // Now that the block has been inserted into the function, create PHI nodes in
393*9880d681SAndroid Build Coastguard Worker   // the backedge block which correspond to any PHI nodes in the header block.
394*9880d681SAndroid Build Coastguard Worker   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
395*9880d681SAndroid Build Coastguard Worker     PHINode *PN = cast<PHINode>(I);
396*9880d681SAndroid Build Coastguard Worker     PHINode *NewPN = PHINode::Create(PN->getType(), BackedgeBlocks.size(),
397*9880d681SAndroid Build Coastguard Worker                                      PN->getName()+".be", BETerminator);
398*9880d681SAndroid Build Coastguard Worker 
399*9880d681SAndroid Build Coastguard Worker     // Loop over the PHI node, moving all entries except the one for the
400*9880d681SAndroid Build Coastguard Worker     // preheader over to the new PHI node.
401*9880d681SAndroid Build Coastguard Worker     unsigned PreheaderIdx = ~0U;
402*9880d681SAndroid Build Coastguard Worker     bool HasUniqueIncomingValue = true;
403*9880d681SAndroid Build Coastguard Worker     Value *UniqueValue = nullptr;
404*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
405*9880d681SAndroid Build Coastguard Worker       BasicBlock *IBB = PN->getIncomingBlock(i);
406*9880d681SAndroid Build Coastguard Worker       Value *IV = PN->getIncomingValue(i);
407*9880d681SAndroid Build Coastguard Worker       if (IBB == Preheader) {
408*9880d681SAndroid Build Coastguard Worker         PreheaderIdx = i;
409*9880d681SAndroid Build Coastguard Worker       } else {
410*9880d681SAndroid Build Coastguard Worker         NewPN->addIncoming(IV, IBB);
411*9880d681SAndroid Build Coastguard Worker         if (HasUniqueIncomingValue) {
412*9880d681SAndroid Build Coastguard Worker           if (!UniqueValue)
413*9880d681SAndroid Build Coastguard Worker             UniqueValue = IV;
414*9880d681SAndroid Build Coastguard Worker           else if (UniqueValue != IV)
415*9880d681SAndroid Build Coastguard Worker             HasUniqueIncomingValue = false;
416*9880d681SAndroid Build Coastguard Worker         }
417*9880d681SAndroid Build Coastguard Worker       }
418*9880d681SAndroid Build Coastguard Worker     }
419*9880d681SAndroid Build Coastguard Worker 
420*9880d681SAndroid Build Coastguard Worker     // Delete all of the incoming values from the old PN except the preheader's
421*9880d681SAndroid Build Coastguard Worker     assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
422*9880d681SAndroid Build Coastguard Worker     if (PreheaderIdx != 0) {
423*9880d681SAndroid Build Coastguard Worker       PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
424*9880d681SAndroid Build Coastguard Worker       PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
425*9880d681SAndroid Build Coastguard Worker     }
426*9880d681SAndroid Build Coastguard Worker     // Nuke all entries except the zero'th.
427*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
428*9880d681SAndroid Build Coastguard Worker       PN->removeIncomingValue(e-i, false);
429*9880d681SAndroid Build Coastguard Worker 
430*9880d681SAndroid Build Coastguard Worker     // Finally, add the newly constructed PHI node as the entry for the BEBlock.
431*9880d681SAndroid Build Coastguard Worker     PN->addIncoming(NewPN, BEBlock);
432*9880d681SAndroid Build Coastguard Worker 
433*9880d681SAndroid Build Coastguard Worker     // As an optimization, if all incoming values in the new PhiNode (which is a
434*9880d681SAndroid Build Coastguard Worker     // subset of the incoming values of the old PHI node) have the same value,
435*9880d681SAndroid Build Coastguard Worker     // eliminate the PHI Node.
436*9880d681SAndroid Build Coastguard Worker     if (HasUniqueIncomingValue) {
437*9880d681SAndroid Build Coastguard Worker       NewPN->replaceAllUsesWith(UniqueValue);
438*9880d681SAndroid Build Coastguard Worker       BEBlock->getInstList().erase(NewPN);
439*9880d681SAndroid Build Coastguard Worker     }
440*9880d681SAndroid Build Coastguard Worker   }
441*9880d681SAndroid Build Coastguard Worker 
442*9880d681SAndroid Build Coastguard Worker   // Now that all of the PHI nodes have been inserted and adjusted, modify the
443*9880d681SAndroid Build Coastguard Worker   // backedge blocks to just to the BEBlock instead of the header.
444*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
445*9880d681SAndroid Build Coastguard Worker     TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
446*9880d681SAndroid Build Coastguard Worker     for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
447*9880d681SAndroid Build Coastguard Worker       if (TI->getSuccessor(Op) == Header)
448*9880d681SAndroid Build Coastguard Worker         TI->setSuccessor(Op, BEBlock);
449*9880d681SAndroid Build Coastguard Worker   }
450*9880d681SAndroid Build Coastguard Worker 
451*9880d681SAndroid Build Coastguard Worker   //===--- Update all analyses which we must preserve now -----------------===//
452*9880d681SAndroid Build Coastguard Worker 
453*9880d681SAndroid Build Coastguard Worker   // Update Loop Information - we know that this block is now in the current
454*9880d681SAndroid Build Coastguard Worker   // loop and all parent loops.
455*9880d681SAndroid Build Coastguard Worker   L->addBasicBlockToLoop(BEBlock, *LI);
456*9880d681SAndroid Build Coastguard Worker 
457*9880d681SAndroid Build Coastguard Worker   // Update dominator information
458*9880d681SAndroid Build Coastguard Worker   DT->splitBlock(BEBlock);
459*9880d681SAndroid Build Coastguard Worker 
460*9880d681SAndroid Build Coastguard Worker   return BEBlock;
461*9880d681SAndroid Build Coastguard Worker }
462*9880d681SAndroid Build Coastguard Worker 
463*9880d681SAndroid Build Coastguard Worker /// \brief Simplify one loop and queue further loops for simplification.
simplifyOneLoop(Loop * L,SmallVectorImpl<Loop * > & Worklist,DominatorTree * DT,LoopInfo * LI,ScalarEvolution * SE,AssumptionCache * AC,bool PreserveLCSSA)464*9880d681SAndroid Build Coastguard Worker static bool simplifyOneLoop(Loop *L, SmallVectorImpl<Loop *> &Worklist,
465*9880d681SAndroid Build Coastguard Worker                             DominatorTree *DT, LoopInfo *LI,
466*9880d681SAndroid Build Coastguard Worker                             ScalarEvolution *SE, AssumptionCache *AC,
467*9880d681SAndroid Build Coastguard Worker                             bool PreserveLCSSA) {
468*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
469*9880d681SAndroid Build Coastguard Worker ReprocessLoop:
470*9880d681SAndroid Build Coastguard Worker 
471*9880d681SAndroid Build Coastguard Worker   // Check to see that no blocks (other than the header) in this loop have
472*9880d681SAndroid Build Coastguard Worker   // predecessors that are not in the loop.  This is not valid for natural
473*9880d681SAndroid Build Coastguard Worker   // loops, but can occur if the blocks are unreachable.  Since they are
474*9880d681SAndroid Build Coastguard Worker   // unreachable we can just shamelessly delete those CFG edges!
475*9880d681SAndroid Build Coastguard Worker   for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
476*9880d681SAndroid Build Coastguard Worker        BB != E; ++BB) {
477*9880d681SAndroid Build Coastguard Worker     if (*BB == L->getHeader()) continue;
478*9880d681SAndroid Build Coastguard Worker 
479*9880d681SAndroid Build Coastguard Worker     SmallPtrSet<BasicBlock*, 4> BadPreds;
480*9880d681SAndroid Build Coastguard Worker     for (pred_iterator PI = pred_begin(*BB),
481*9880d681SAndroid Build Coastguard Worker          PE = pred_end(*BB); PI != PE; ++PI) {
482*9880d681SAndroid Build Coastguard Worker       BasicBlock *P = *PI;
483*9880d681SAndroid Build Coastguard Worker       if (!L->contains(P))
484*9880d681SAndroid Build Coastguard Worker         BadPreds.insert(P);
485*9880d681SAndroid Build Coastguard Worker     }
486*9880d681SAndroid Build Coastguard Worker 
487*9880d681SAndroid Build Coastguard Worker     // Delete each unique out-of-loop (and thus dead) predecessor.
488*9880d681SAndroid Build Coastguard Worker     for (BasicBlock *P : BadPreds) {
489*9880d681SAndroid Build Coastguard Worker 
490*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "LoopSimplify: Deleting edge from dead predecessor "
491*9880d681SAndroid Build Coastguard Worker                    << P->getName() << "\n");
492*9880d681SAndroid Build Coastguard Worker 
493*9880d681SAndroid Build Coastguard Worker       // Zap the dead pred's terminator and replace it with unreachable.
494*9880d681SAndroid Build Coastguard Worker       TerminatorInst *TI = P->getTerminator();
495*9880d681SAndroid Build Coastguard Worker       changeToUnreachable(TI, /*UseLLVMTrap=*/false);
496*9880d681SAndroid Build Coastguard Worker       Changed = true;
497*9880d681SAndroid Build Coastguard Worker     }
498*9880d681SAndroid Build Coastguard Worker   }
499*9880d681SAndroid Build Coastguard Worker 
500*9880d681SAndroid Build Coastguard Worker   // If there are exiting blocks with branches on undef, resolve the undef in
501*9880d681SAndroid Build Coastguard Worker   // the direction which will exit the loop. This will help simplify loop
502*9880d681SAndroid Build Coastguard Worker   // trip count computations.
503*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock*, 8> ExitingBlocks;
504*9880d681SAndroid Build Coastguard Worker   L->getExitingBlocks(ExitingBlocks);
505*9880d681SAndroid Build Coastguard Worker   for (BasicBlock *ExitingBlock : ExitingBlocks)
506*9880d681SAndroid Build Coastguard Worker     if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
507*9880d681SAndroid Build Coastguard Worker       if (BI->isConditional()) {
508*9880d681SAndroid Build Coastguard Worker         if (UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
509*9880d681SAndroid Build Coastguard Worker 
510*9880d681SAndroid Build Coastguard Worker           DEBUG(dbgs() << "LoopSimplify: Resolving \"br i1 undef\" to exit in "
511*9880d681SAndroid Build Coastguard Worker                        << ExitingBlock->getName() << "\n");
512*9880d681SAndroid Build Coastguard Worker 
513*9880d681SAndroid Build Coastguard Worker           BI->setCondition(ConstantInt::get(Cond->getType(),
514*9880d681SAndroid Build Coastguard Worker                                             !L->contains(BI->getSuccessor(0))));
515*9880d681SAndroid Build Coastguard Worker 
516*9880d681SAndroid Build Coastguard Worker           // This may make the loop analyzable, force SCEV recomputation.
517*9880d681SAndroid Build Coastguard Worker           if (SE)
518*9880d681SAndroid Build Coastguard Worker             SE->forgetLoop(L);
519*9880d681SAndroid Build Coastguard Worker 
520*9880d681SAndroid Build Coastguard Worker           Changed = true;
521*9880d681SAndroid Build Coastguard Worker         }
522*9880d681SAndroid Build Coastguard Worker       }
523*9880d681SAndroid Build Coastguard Worker 
524*9880d681SAndroid Build Coastguard Worker   // Does the loop already have a preheader?  If so, don't insert one.
525*9880d681SAndroid Build Coastguard Worker   BasicBlock *Preheader = L->getLoopPreheader();
526*9880d681SAndroid Build Coastguard Worker   if (!Preheader) {
527*9880d681SAndroid Build Coastguard Worker     Preheader = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
528*9880d681SAndroid Build Coastguard Worker     if (Preheader) {
529*9880d681SAndroid Build Coastguard Worker       ++NumInserted;
530*9880d681SAndroid Build Coastguard Worker       Changed = true;
531*9880d681SAndroid Build Coastguard Worker     }
532*9880d681SAndroid Build Coastguard Worker   }
533*9880d681SAndroid Build Coastguard Worker 
534*9880d681SAndroid Build Coastguard Worker   // Next, check to make sure that all exit nodes of the loop only have
535*9880d681SAndroid Build Coastguard Worker   // predecessors that are inside of the loop.  This check guarantees that the
536*9880d681SAndroid Build Coastguard Worker   // loop preheader/header will dominate the exit blocks.  If the exit block has
537*9880d681SAndroid Build Coastguard Worker   // predecessors from outside of the loop, split the edge now.
538*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock*, 8> ExitBlocks;
539*9880d681SAndroid Build Coastguard Worker   L->getExitBlocks(ExitBlocks);
540*9880d681SAndroid Build Coastguard Worker 
541*9880d681SAndroid Build Coastguard Worker   SmallSetVector<BasicBlock *, 8> ExitBlockSet(ExitBlocks.begin(),
542*9880d681SAndroid Build Coastguard Worker                                                ExitBlocks.end());
543*9880d681SAndroid Build Coastguard Worker   for (BasicBlock *ExitBlock : ExitBlockSet) {
544*9880d681SAndroid Build Coastguard Worker     for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
545*9880d681SAndroid Build Coastguard Worker          PI != PE; ++PI)
546*9880d681SAndroid Build Coastguard Worker       // Must be exactly this loop: no subloops, parent loops, or non-loop preds
547*9880d681SAndroid Build Coastguard Worker       // allowed.
548*9880d681SAndroid Build Coastguard Worker       if (!L->contains(*PI)) {
549*9880d681SAndroid Build Coastguard Worker         if (rewriteLoopExitBlock(L, ExitBlock, DT, LI, PreserveLCSSA)) {
550*9880d681SAndroid Build Coastguard Worker           ++NumInserted;
551*9880d681SAndroid Build Coastguard Worker           Changed = true;
552*9880d681SAndroid Build Coastguard Worker         }
553*9880d681SAndroid Build Coastguard Worker         break;
554*9880d681SAndroid Build Coastguard Worker       }
555*9880d681SAndroid Build Coastguard Worker   }
556*9880d681SAndroid Build Coastguard Worker 
557*9880d681SAndroid Build Coastguard Worker   // If the header has more than two predecessors at this point (from the
558*9880d681SAndroid Build Coastguard Worker   // preheader and from multiple backedges), we must adjust the loop.
559*9880d681SAndroid Build Coastguard Worker   BasicBlock *LoopLatch = L->getLoopLatch();
560*9880d681SAndroid Build Coastguard Worker   if (!LoopLatch) {
561*9880d681SAndroid Build Coastguard Worker     // If this is really a nested loop, rip it out into a child loop.  Don't do
562*9880d681SAndroid Build Coastguard Worker     // this for loops with a giant number of backedges, just factor them into a
563*9880d681SAndroid Build Coastguard Worker     // common backedge instead.
564*9880d681SAndroid Build Coastguard Worker     if (L->getNumBackEdges() < 8) {
565*9880d681SAndroid Build Coastguard Worker       if (Loop *OuterL =
566*9880d681SAndroid Build Coastguard Worker               separateNestedLoop(L, Preheader, DT, LI, SE, PreserveLCSSA, AC)) {
567*9880d681SAndroid Build Coastguard Worker         ++NumNested;
568*9880d681SAndroid Build Coastguard Worker         // Enqueue the outer loop as it should be processed next in our
569*9880d681SAndroid Build Coastguard Worker         // depth-first nest walk.
570*9880d681SAndroid Build Coastguard Worker         Worklist.push_back(OuterL);
571*9880d681SAndroid Build Coastguard Worker 
572*9880d681SAndroid Build Coastguard Worker         // This is a big restructuring change, reprocess the whole loop.
573*9880d681SAndroid Build Coastguard Worker         Changed = true;
574*9880d681SAndroid Build Coastguard Worker         // GCC doesn't tail recursion eliminate this.
575*9880d681SAndroid Build Coastguard Worker         // FIXME: It isn't clear we can't rely on LLVM to TRE this.
576*9880d681SAndroid Build Coastguard Worker         goto ReprocessLoop;
577*9880d681SAndroid Build Coastguard Worker       }
578*9880d681SAndroid Build Coastguard Worker     }
579*9880d681SAndroid Build Coastguard Worker 
580*9880d681SAndroid Build Coastguard Worker     // If we either couldn't, or didn't want to, identify nesting of the loops,
581*9880d681SAndroid Build Coastguard Worker     // insert a new block that all backedges target, then make it jump to the
582*9880d681SAndroid Build Coastguard Worker     // loop header.
583*9880d681SAndroid Build Coastguard Worker     LoopLatch = insertUniqueBackedgeBlock(L, Preheader, DT, LI);
584*9880d681SAndroid Build Coastguard Worker     if (LoopLatch) {
585*9880d681SAndroid Build Coastguard Worker       ++NumInserted;
586*9880d681SAndroid Build Coastguard Worker       Changed = true;
587*9880d681SAndroid Build Coastguard Worker     }
588*9880d681SAndroid Build Coastguard Worker   }
589*9880d681SAndroid Build Coastguard Worker 
590*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
591*9880d681SAndroid Build Coastguard Worker 
592*9880d681SAndroid Build Coastguard Worker   // Scan over the PHI nodes in the loop header.  Since they now have only two
593*9880d681SAndroid Build Coastguard Worker   // incoming values (the loop is canonicalized), we may have simplified the PHI
594*9880d681SAndroid Build Coastguard Worker   // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
595*9880d681SAndroid Build Coastguard Worker   PHINode *PN;
596*9880d681SAndroid Build Coastguard Worker   for (BasicBlock::iterator I = L->getHeader()->begin();
597*9880d681SAndroid Build Coastguard Worker        (PN = dyn_cast<PHINode>(I++)); )
598*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyInstruction(PN, DL, nullptr, DT, AC)) {
599*9880d681SAndroid Build Coastguard Worker       if (SE) SE->forgetValue(PN);
600*9880d681SAndroid Build Coastguard Worker       PN->replaceAllUsesWith(V);
601*9880d681SAndroid Build Coastguard Worker       PN->eraseFromParent();
602*9880d681SAndroid Build Coastguard Worker     }
603*9880d681SAndroid Build Coastguard Worker 
604*9880d681SAndroid Build Coastguard Worker   // If this loop has multiple exits and the exits all go to the same
605*9880d681SAndroid Build Coastguard Worker   // block, attempt to merge the exits. This helps several passes, such
606*9880d681SAndroid Build Coastguard Worker   // as LoopRotation, which do not support loops with multiple exits.
607*9880d681SAndroid Build Coastguard Worker   // SimplifyCFG also does this (and this code uses the same utility
608*9880d681SAndroid Build Coastguard Worker   // function), however this code is loop-aware, where SimplifyCFG is
609*9880d681SAndroid Build Coastguard Worker   // not. That gives it the advantage of being able to hoist
610*9880d681SAndroid Build Coastguard Worker   // loop-invariant instructions out of the way to open up more
611*9880d681SAndroid Build Coastguard Worker   // opportunities, and the disadvantage of having the responsibility
612*9880d681SAndroid Build Coastguard Worker   // to preserve dominator information.
613*9880d681SAndroid Build Coastguard Worker   bool UniqueExit = true;
614*9880d681SAndroid Build Coastguard Worker   if (!ExitBlocks.empty())
615*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 1, e = ExitBlocks.size(); i != e; ++i)
616*9880d681SAndroid Build Coastguard Worker       if (ExitBlocks[i] != ExitBlocks[0]) {
617*9880d681SAndroid Build Coastguard Worker         UniqueExit = false;
618*9880d681SAndroid Build Coastguard Worker         break;
619*9880d681SAndroid Build Coastguard Worker       }
620*9880d681SAndroid Build Coastguard Worker   if (UniqueExit) {
621*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
622*9880d681SAndroid Build Coastguard Worker       BasicBlock *ExitingBlock = ExitingBlocks[i];
623*9880d681SAndroid Build Coastguard Worker       if (!ExitingBlock->getSinglePredecessor()) continue;
624*9880d681SAndroid Build Coastguard Worker       BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
625*9880d681SAndroid Build Coastguard Worker       if (!BI || !BI->isConditional()) continue;
626*9880d681SAndroid Build Coastguard Worker       CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
627*9880d681SAndroid Build Coastguard Worker       if (!CI || CI->getParent() != ExitingBlock) continue;
628*9880d681SAndroid Build Coastguard Worker 
629*9880d681SAndroid Build Coastguard Worker       // Attempt to hoist out all instructions except for the
630*9880d681SAndroid Build Coastguard Worker       // comparison and the branch.
631*9880d681SAndroid Build Coastguard Worker       bool AllInvariant = true;
632*9880d681SAndroid Build Coastguard Worker       bool AnyInvariant = false;
633*9880d681SAndroid Build Coastguard Worker       for (BasicBlock::iterator I = ExitingBlock->begin(); &*I != BI; ) {
634*9880d681SAndroid Build Coastguard Worker         Instruction *Inst = &*I++;
635*9880d681SAndroid Build Coastguard Worker         // Skip debug info intrinsics.
636*9880d681SAndroid Build Coastguard Worker         if (isa<DbgInfoIntrinsic>(Inst))
637*9880d681SAndroid Build Coastguard Worker           continue;
638*9880d681SAndroid Build Coastguard Worker         if (Inst == CI)
639*9880d681SAndroid Build Coastguard Worker           continue;
640*9880d681SAndroid Build Coastguard Worker         if (!L->makeLoopInvariant(Inst, AnyInvariant,
641*9880d681SAndroid Build Coastguard Worker                                   Preheader ? Preheader->getTerminator()
642*9880d681SAndroid Build Coastguard Worker                                             : nullptr)) {
643*9880d681SAndroid Build Coastguard Worker           AllInvariant = false;
644*9880d681SAndroid Build Coastguard Worker           break;
645*9880d681SAndroid Build Coastguard Worker         }
646*9880d681SAndroid Build Coastguard Worker       }
647*9880d681SAndroid Build Coastguard Worker       if (AnyInvariant) {
648*9880d681SAndroid Build Coastguard Worker         Changed = true;
649*9880d681SAndroid Build Coastguard Worker         // The loop disposition of all SCEV expressions that depend on any
650*9880d681SAndroid Build Coastguard Worker         // hoisted values have also changed.
651*9880d681SAndroid Build Coastguard Worker         if (SE)
652*9880d681SAndroid Build Coastguard Worker           SE->forgetLoopDispositions(L);
653*9880d681SAndroid Build Coastguard Worker       }
654*9880d681SAndroid Build Coastguard Worker       if (!AllInvariant) continue;
655*9880d681SAndroid Build Coastguard Worker 
656*9880d681SAndroid Build Coastguard Worker       // The block has now been cleared of all instructions except for
657*9880d681SAndroid Build Coastguard Worker       // a comparison and a conditional branch. SimplifyCFG may be able
658*9880d681SAndroid Build Coastguard Worker       // to fold it now.
659*9880d681SAndroid Build Coastguard Worker       if (!FoldBranchToCommonDest(BI))
660*9880d681SAndroid Build Coastguard Worker         continue;
661*9880d681SAndroid Build Coastguard Worker 
662*9880d681SAndroid Build Coastguard Worker       // Success. The block is now dead, so remove it from the loop,
663*9880d681SAndroid Build Coastguard Worker       // update the dominator tree and delete it.
664*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "LoopSimplify: Eliminating exiting block "
665*9880d681SAndroid Build Coastguard Worker                    << ExitingBlock->getName() << "\n");
666*9880d681SAndroid Build Coastguard Worker 
667*9880d681SAndroid Build Coastguard Worker       // Notify ScalarEvolution before deleting this block. Currently assume the
668*9880d681SAndroid Build Coastguard Worker       // parent loop doesn't change (spliting edges doesn't count). If blocks,
669*9880d681SAndroid Build Coastguard Worker       // CFG edges, or other values in the parent loop change, then we need call
670*9880d681SAndroid Build Coastguard Worker       // to forgetLoop() for the parent instead.
671*9880d681SAndroid Build Coastguard Worker       if (SE)
672*9880d681SAndroid Build Coastguard Worker         SE->forgetLoop(L);
673*9880d681SAndroid Build Coastguard Worker 
674*9880d681SAndroid Build Coastguard Worker       assert(pred_begin(ExitingBlock) == pred_end(ExitingBlock));
675*9880d681SAndroid Build Coastguard Worker       Changed = true;
676*9880d681SAndroid Build Coastguard Worker       LI->removeBlock(ExitingBlock);
677*9880d681SAndroid Build Coastguard Worker 
678*9880d681SAndroid Build Coastguard Worker       DomTreeNode *Node = DT->getNode(ExitingBlock);
679*9880d681SAndroid Build Coastguard Worker       const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
680*9880d681SAndroid Build Coastguard Worker         Node->getChildren();
681*9880d681SAndroid Build Coastguard Worker       while (!Children.empty()) {
682*9880d681SAndroid Build Coastguard Worker         DomTreeNode *Child = Children.front();
683*9880d681SAndroid Build Coastguard Worker         DT->changeImmediateDominator(Child, Node->getIDom());
684*9880d681SAndroid Build Coastguard Worker       }
685*9880d681SAndroid Build Coastguard Worker       DT->eraseNode(ExitingBlock);
686*9880d681SAndroid Build Coastguard Worker 
687*9880d681SAndroid Build Coastguard Worker       BI->getSuccessor(0)->removePredecessor(
688*9880d681SAndroid Build Coastguard Worker           ExitingBlock, /* DontDeleteUselessPHIs */ PreserveLCSSA);
689*9880d681SAndroid Build Coastguard Worker       BI->getSuccessor(1)->removePredecessor(
690*9880d681SAndroid Build Coastguard Worker           ExitingBlock, /* DontDeleteUselessPHIs */ PreserveLCSSA);
691*9880d681SAndroid Build Coastguard Worker       ExitingBlock->eraseFromParent();
692*9880d681SAndroid Build Coastguard Worker     }
693*9880d681SAndroid Build Coastguard Worker   }
694*9880d681SAndroid Build Coastguard Worker 
695*9880d681SAndroid Build Coastguard Worker   return Changed;
696*9880d681SAndroid Build Coastguard Worker }
697*9880d681SAndroid Build Coastguard Worker 
simplifyLoop(Loop * L,DominatorTree * DT,LoopInfo * LI,ScalarEvolution * SE,AssumptionCache * AC,bool PreserveLCSSA)698*9880d681SAndroid Build Coastguard Worker bool llvm::simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI,
699*9880d681SAndroid Build Coastguard Worker                         ScalarEvolution *SE, AssumptionCache *AC,
700*9880d681SAndroid Build Coastguard Worker                         bool PreserveLCSSA) {
701*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
702*9880d681SAndroid Build Coastguard Worker 
703*9880d681SAndroid Build Coastguard Worker   // Worklist maintains our depth-first queue of loops in this nest to process.
704*9880d681SAndroid Build Coastguard Worker   SmallVector<Loop *, 4> Worklist;
705*9880d681SAndroid Build Coastguard Worker   Worklist.push_back(L);
706*9880d681SAndroid Build Coastguard Worker 
707*9880d681SAndroid Build Coastguard Worker   // Walk the worklist from front to back, pushing newly found sub loops onto
708*9880d681SAndroid Build Coastguard Worker   // the back. This will let us process loops from back to front in depth-first
709*9880d681SAndroid Build Coastguard Worker   // order. We can use this simple process because loops form a tree.
710*9880d681SAndroid Build Coastguard Worker   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
711*9880d681SAndroid Build Coastguard Worker     Loop *L2 = Worklist[Idx];
712*9880d681SAndroid Build Coastguard Worker     Worklist.append(L2->begin(), L2->end());
713*9880d681SAndroid Build Coastguard Worker   }
714*9880d681SAndroid Build Coastguard Worker 
715*9880d681SAndroid Build Coastguard Worker   while (!Worklist.empty())
716*9880d681SAndroid Build Coastguard Worker     Changed |= simplifyOneLoop(Worklist.pop_back_val(), Worklist, DT, LI, SE,
717*9880d681SAndroid Build Coastguard Worker                                AC, PreserveLCSSA);
718*9880d681SAndroid Build Coastguard Worker 
719*9880d681SAndroid Build Coastguard Worker   return Changed;
720*9880d681SAndroid Build Coastguard Worker }
721*9880d681SAndroid Build Coastguard Worker 
722*9880d681SAndroid Build Coastguard Worker namespace {
723*9880d681SAndroid Build Coastguard Worker   struct LoopSimplify : public FunctionPass {
724*9880d681SAndroid Build Coastguard Worker     static char ID; // Pass identification, replacement for typeid
LoopSimplify__anon1020c6cd0111::LoopSimplify725*9880d681SAndroid Build Coastguard Worker     LoopSimplify() : FunctionPass(ID) {
726*9880d681SAndroid Build Coastguard Worker       initializeLoopSimplifyPass(*PassRegistry::getPassRegistry());
727*9880d681SAndroid Build Coastguard Worker     }
728*9880d681SAndroid Build Coastguard Worker 
729*9880d681SAndroid Build Coastguard Worker     bool runOnFunction(Function &F) override;
730*9880d681SAndroid Build Coastguard Worker 
getAnalysisUsage__anon1020c6cd0111::LoopSimplify731*9880d681SAndroid Build Coastguard Worker     void getAnalysisUsage(AnalysisUsage &AU) const override {
732*9880d681SAndroid Build Coastguard Worker       AU.addRequired<AssumptionCacheTracker>();
733*9880d681SAndroid Build Coastguard Worker 
734*9880d681SAndroid Build Coastguard Worker       // We need loop information to identify the loops...
735*9880d681SAndroid Build Coastguard Worker       AU.addRequired<DominatorTreeWrapperPass>();
736*9880d681SAndroid Build Coastguard Worker       AU.addPreserved<DominatorTreeWrapperPass>();
737*9880d681SAndroid Build Coastguard Worker 
738*9880d681SAndroid Build Coastguard Worker       AU.addRequired<LoopInfoWrapperPass>();
739*9880d681SAndroid Build Coastguard Worker       AU.addPreserved<LoopInfoWrapperPass>();
740*9880d681SAndroid Build Coastguard Worker 
741*9880d681SAndroid Build Coastguard Worker       AU.addPreserved<BasicAAWrapperPass>();
742*9880d681SAndroid Build Coastguard Worker       AU.addPreserved<AAResultsWrapperPass>();
743*9880d681SAndroid Build Coastguard Worker       AU.addPreserved<GlobalsAAWrapperPass>();
744*9880d681SAndroid Build Coastguard Worker       AU.addPreserved<ScalarEvolutionWrapperPass>();
745*9880d681SAndroid Build Coastguard Worker       AU.addPreserved<SCEVAAWrapperPass>();
746*9880d681SAndroid Build Coastguard Worker       AU.addPreservedID(LCSSAID);
747*9880d681SAndroid Build Coastguard Worker       AU.addPreserved<DependenceAnalysisWrapperPass>();
748*9880d681SAndroid Build Coastguard Worker       AU.addPreservedID(BreakCriticalEdgesID);  // No critical edges added.
749*9880d681SAndroid Build Coastguard Worker     }
750*9880d681SAndroid Build Coastguard Worker 
751*9880d681SAndroid Build Coastguard Worker     /// verifyAnalysis() - Verify LoopSimplifyForm's guarantees.
752*9880d681SAndroid Build Coastguard Worker     void verifyAnalysis() const override;
753*9880d681SAndroid Build Coastguard Worker   };
754*9880d681SAndroid Build Coastguard Worker }
755*9880d681SAndroid Build Coastguard Worker 
756*9880d681SAndroid Build Coastguard Worker char LoopSimplify::ID = 0;
757*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(LoopSimplify, "loop-simplify",
758*9880d681SAndroid Build Coastguard Worker                 "Canonicalize natural loops", false, false)
759*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
760*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
761*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
762*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(LoopSimplify, "loop-simplify",
763*9880d681SAndroid Build Coastguard Worker                 "Canonicalize natural loops", false, false)
764*9880d681SAndroid Build Coastguard Worker 
765*9880d681SAndroid Build Coastguard Worker // Publicly exposed interface to pass...
766*9880d681SAndroid Build Coastguard Worker char &llvm::LoopSimplifyID = LoopSimplify::ID;
createLoopSimplifyPass()767*9880d681SAndroid Build Coastguard Worker Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
768*9880d681SAndroid Build Coastguard Worker 
769*9880d681SAndroid Build Coastguard Worker /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
770*9880d681SAndroid Build Coastguard Worker /// it in any convenient order) inserting preheaders...
771*9880d681SAndroid Build Coastguard Worker ///
runOnFunction(Function & F)772*9880d681SAndroid Build Coastguard Worker bool LoopSimplify::runOnFunction(Function &F) {
773*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
774*9880d681SAndroid Build Coastguard Worker   LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
775*9880d681SAndroid Build Coastguard Worker   DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
776*9880d681SAndroid Build Coastguard Worker   auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
777*9880d681SAndroid Build Coastguard Worker   ScalarEvolution *SE = SEWP ? &SEWP->getSE() : nullptr;
778*9880d681SAndroid Build Coastguard Worker   AssumptionCache *AC =
779*9880d681SAndroid Build Coastguard Worker       &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
780*9880d681SAndroid Build Coastguard Worker 
781*9880d681SAndroid Build Coastguard Worker   bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
782*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
783*9880d681SAndroid Build Coastguard Worker   if (PreserveLCSSA) {
784*9880d681SAndroid Build Coastguard Worker     assert(DT && "DT not available.");
785*9880d681SAndroid Build Coastguard Worker     assert(LI && "LI not available.");
786*9880d681SAndroid Build Coastguard Worker     bool InLCSSA =
787*9880d681SAndroid Build Coastguard Worker         all_of(*LI, [&](Loop *L) { return L->isRecursivelyLCSSAForm(*DT); });
788*9880d681SAndroid Build Coastguard Worker     assert(InLCSSA && "Requested to preserve LCSSA, but it's already broken.");
789*9880d681SAndroid Build Coastguard Worker   }
790*9880d681SAndroid Build Coastguard Worker #endif
791*9880d681SAndroid Build Coastguard Worker 
792*9880d681SAndroid Build Coastguard Worker   // Simplify each loop nest in the function.
793*9880d681SAndroid Build Coastguard Worker   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
794*9880d681SAndroid Build Coastguard Worker     Changed |= simplifyLoop(*I, DT, LI, SE, AC, PreserveLCSSA);
795*9880d681SAndroid Build Coastguard Worker 
796*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
797*9880d681SAndroid Build Coastguard Worker   if (PreserveLCSSA) {
798*9880d681SAndroid Build Coastguard Worker     bool InLCSSA =
799*9880d681SAndroid Build Coastguard Worker         all_of(*LI, [&](Loop *L) { return L->isRecursivelyLCSSAForm(*DT); });
800*9880d681SAndroid Build Coastguard Worker     assert(InLCSSA && "LCSSA is broken after loop-simplify.");
801*9880d681SAndroid Build Coastguard Worker   }
802*9880d681SAndroid Build Coastguard Worker #endif
803*9880d681SAndroid Build Coastguard Worker   return Changed;
804*9880d681SAndroid Build Coastguard Worker }
805*9880d681SAndroid Build Coastguard Worker 
run(Function & F,AnalysisManager<Function> & AM)806*9880d681SAndroid Build Coastguard Worker PreservedAnalyses LoopSimplifyPass::run(Function &F,
807*9880d681SAndroid Build Coastguard Worker                                         AnalysisManager<Function> &AM) {
808*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
809*9880d681SAndroid Build Coastguard Worker   LoopInfo *LI = &AM.getResult<LoopAnalysis>(F);
810*9880d681SAndroid Build Coastguard Worker   DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F);
811*9880d681SAndroid Build Coastguard Worker   ScalarEvolution *SE = AM.getCachedResult<ScalarEvolutionAnalysis>(F);
812*9880d681SAndroid Build Coastguard Worker   AssumptionCache *AC = &AM.getResult<AssumptionAnalysis>(F);
813*9880d681SAndroid Build Coastguard Worker 
814*9880d681SAndroid Build Coastguard Worker   // FIXME: This pass should verify that the loops on which it's operating
815*9880d681SAndroid Build Coastguard Worker   // are in canonical SSA form, and that the pass itself preserves this form.
816*9880d681SAndroid Build Coastguard Worker   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
817*9880d681SAndroid Build Coastguard Worker     Changed |= simplifyLoop(*I, DT, LI, SE, AC, true /* PreserveLCSSA */);
818*9880d681SAndroid Build Coastguard Worker 
819*9880d681SAndroid Build Coastguard Worker   if (!Changed)
820*9880d681SAndroid Build Coastguard Worker     return PreservedAnalyses::all();
821*9880d681SAndroid Build Coastguard Worker   PreservedAnalyses PA;
822*9880d681SAndroid Build Coastguard Worker   PA.preserve<DominatorTreeAnalysis>();
823*9880d681SAndroid Build Coastguard Worker   PA.preserve<LoopAnalysis>();
824*9880d681SAndroid Build Coastguard Worker   PA.preserve<BasicAA>();
825*9880d681SAndroid Build Coastguard Worker   PA.preserve<GlobalsAA>();
826*9880d681SAndroid Build Coastguard Worker   PA.preserve<SCEVAA>();
827*9880d681SAndroid Build Coastguard Worker   PA.preserve<ScalarEvolutionAnalysis>();
828*9880d681SAndroid Build Coastguard Worker   PA.preserve<DependenceAnalysis>();
829*9880d681SAndroid Build Coastguard Worker   return PA;
830*9880d681SAndroid Build Coastguard Worker }
831*9880d681SAndroid Build Coastguard Worker 
832*9880d681SAndroid Build Coastguard Worker // FIXME: Restore this code when we re-enable verification in verifyAnalysis
833*9880d681SAndroid Build Coastguard Worker // below.
834*9880d681SAndroid Build Coastguard Worker #if 0
835*9880d681SAndroid Build Coastguard Worker static void verifyLoop(Loop *L) {
836*9880d681SAndroid Build Coastguard Worker   // Verify subloops.
837*9880d681SAndroid Build Coastguard Worker   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
838*9880d681SAndroid Build Coastguard Worker     verifyLoop(*I);
839*9880d681SAndroid Build Coastguard Worker 
840*9880d681SAndroid Build Coastguard Worker   // It used to be possible to just assert L->isLoopSimplifyForm(), however
841*9880d681SAndroid Build Coastguard Worker   // with the introduction of indirectbr, there are now cases where it's
842*9880d681SAndroid Build Coastguard Worker   // not possible to transform a loop as necessary. We can at least check
843*9880d681SAndroid Build Coastguard Worker   // that there is an indirectbr near any time there's trouble.
844*9880d681SAndroid Build Coastguard Worker 
845*9880d681SAndroid Build Coastguard Worker   // Indirectbr can interfere with preheader and unique backedge insertion.
846*9880d681SAndroid Build Coastguard Worker   if (!L->getLoopPreheader() || !L->getLoopLatch()) {
847*9880d681SAndroid Build Coastguard Worker     bool HasIndBrPred = false;
848*9880d681SAndroid Build Coastguard Worker     for (pred_iterator PI = pred_begin(L->getHeader()),
849*9880d681SAndroid Build Coastguard Worker          PE = pred_end(L->getHeader()); PI != PE; ++PI)
850*9880d681SAndroid Build Coastguard Worker       if (isa<IndirectBrInst>((*PI)->getTerminator())) {
851*9880d681SAndroid Build Coastguard Worker         HasIndBrPred = true;
852*9880d681SAndroid Build Coastguard Worker         break;
853*9880d681SAndroid Build Coastguard Worker       }
854*9880d681SAndroid Build Coastguard Worker     assert(HasIndBrPred &&
855*9880d681SAndroid Build Coastguard Worker            "LoopSimplify has no excuse for missing loop header info!");
856*9880d681SAndroid Build Coastguard Worker     (void)HasIndBrPred;
857*9880d681SAndroid Build Coastguard Worker   }
858*9880d681SAndroid Build Coastguard Worker 
859*9880d681SAndroid Build Coastguard Worker   // Indirectbr can interfere with exit block canonicalization.
860*9880d681SAndroid Build Coastguard Worker   if (!L->hasDedicatedExits()) {
861*9880d681SAndroid Build Coastguard Worker     bool HasIndBrExiting = false;
862*9880d681SAndroid Build Coastguard Worker     SmallVector<BasicBlock*, 8> ExitingBlocks;
863*9880d681SAndroid Build Coastguard Worker     L->getExitingBlocks(ExitingBlocks);
864*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
865*9880d681SAndroid Build Coastguard Worker       if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
866*9880d681SAndroid Build Coastguard Worker         HasIndBrExiting = true;
867*9880d681SAndroid Build Coastguard Worker         break;
868*9880d681SAndroid Build Coastguard Worker       }
869*9880d681SAndroid Build Coastguard Worker     }
870*9880d681SAndroid Build Coastguard Worker 
871*9880d681SAndroid Build Coastguard Worker     assert(HasIndBrExiting &&
872*9880d681SAndroid Build Coastguard Worker            "LoopSimplify has no excuse for missing exit block info!");
873*9880d681SAndroid Build Coastguard Worker     (void)HasIndBrExiting;
874*9880d681SAndroid Build Coastguard Worker   }
875*9880d681SAndroid Build Coastguard Worker }
876*9880d681SAndroid Build Coastguard Worker #endif
877*9880d681SAndroid Build Coastguard Worker 
verifyAnalysis() const878*9880d681SAndroid Build Coastguard Worker void LoopSimplify::verifyAnalysis() const {
879*9880d681SAndroid Build Coastguard Worker   // FIXME: This routine is being called mid-way through the loop pass manager
880*9880d681SAndroid Build Coastguard Worker   // as loop passes destroy this analysis. That's actually fine, but we have no
881*9880d681SAndroid Build Coastguard Worker   // way of expressing that here. Once all of the passes that destroy this are
882*9880d681SAndroid Build Coastguard Worker   // hoisted out of the loop pass manager we can add back verification here.
883*9880d681SAndroid Build Coastguard Worker #if 0
884*9880d681SAndroid Build Coastguard Worker   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
885*9880d681SAndroid Build Coastguard Worker     verifyLoop(*I);
886*9880d681SAndroid Build Coastguard Worker #endif
887*9880d681SAndroid Build Coastguard Worker }
888