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