Fix PR1333
[oota-llvm.git] / lib / Transforms / Scalar / LoopUnswitch.cpp
1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass transforms loops that contain branches on loop-invariant conditions
11 // to have multiple loops.  For example, it turns the left into the right code:
12 //
13 //  for (...)                  if (lic)
14 //    A                          for (...)
15 //    if (lic)                     A; B; C
16 //      B                      else
17 //    C                          for (...)
18 //                                 A; C
19 //
20 // This can increase the size of the code exponentially (doubling it every time
21 // a loop is unswitched) so we only unswitch if the resultant code will be
22 // smaller than a threshold.
23 //
24 // This pass expects LICM to be run before it to hoist invariant conditions out
25 // of the loop, to make the unswitching opportunity obvious.
26 //
27 //===----------------------------------------------------------------------===//
28
29 #define DEBUG_TYPE "loop-unswitch"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Constants.h"
32 #include "llvm/DerivedTypes.h"
33 #include "llvm/Function.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/Analysis/ConstantFolding.h"
36 #include "llvm/Analysis/LoopInfo.h"
37 #include "llvm/Analysis/LoopPass.h"
38 #include "llvm/Transforms/Utils/Cloning.h"
39 #include "llvm/Transforms/Utils/Local.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/PostOrderIterator.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
47 #include <algorithm>
48 #include <set>
49 using namespace llvm;
50
51 STATISTIC(NumBranches, "Number of branches unswitched");
52 STATISTIC(NumSwitches, "Number of switches unswitched");
53 STATISTIC(NumSelects , "Number of selects unswitched");
54 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
55 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
56
57 namespace {
58   cl::opt<unsigned>
59   Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
60             cl::init(10), cl::Hidden);
61   
62   class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
63     LoopInfo *LI;  // Loop information
64     LPPassManager *LPM;
65
66     // LoopProcessWorklist - Used to check if second loop needs processing
67     // after RewriteLoopBodyWithConditionConstant rewrites first loop.
68     std::vector<Loop*> LoopProcessWorklist;
69     SmallPtrSet<Value *,8> UnswitchedVals;
70
71   public:
72     static char ID; // Pass ID, replacement for typeid
73     LoopUnswitch() : LoopPass((intptr_t)&ID) {}
74
75     bool runOnLoop(Loop *L, LPPassManager &LPM);
76
77     /// This transformation requires natural loop information & requires that
78     /// loop preheaders be inserted into the CFG...
79     ///
80     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
81       AU.addRequiredID(LoopSimplifyID);
82       AU.addPreservedID(LoopSimplifyID);
83       AU.addRequired<LoopInfo>();
84       AU.addPreserved<LoopInfo>();
85       AU.addRequiredID(LCSSAID);
86       AU.addPreservedID(LCSSAID);
87     }
88
89   private:
90     /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
91     /// remove it.
92     void RemoveLoopFromWorklist(Loop *L) {
93       std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
94                                                  LoopProcessWorklist.end(), L);
95       if (I != LoopProcessWorklist.end())
96         LoopProcessWorklist.erase(I);
97     }
98       
99     bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
100     unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
101     void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
102                                   BasicBlock *ExitBlock);
103     void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
104     BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
105     BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
106
107     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
108                                               Constant *Val, bool isEqual);
109     
110     void SimplifyCode(std::vector<Instruction*> &Worklist);
111     void RemoveBlockIfDead(BasicBlock *BB,
112                            std::vector<Instruction*> &Worklist);
113     void RemoveLoopFromHierarchy(Loop *L);
114   };
115   char LoopUnswitch::ID = 0;
116   RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
117 }
118
119 LoopPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
120
121 /// FindLIVLoopCondition - Cond is a condition that occurs in L.  If it is
122 /// invariant in the loop, or has an invariant piece, return the invariant.
123 /// Otherwise, return null.
124 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
125   // Constants should be folded, not unswitched on!
126   if (isa<Constant>(Cond)) return false;
127   
128   // TODO: Handle: br (VARIANT|INVARIANT).
129   // TODO: Hoist simple expressions out of loops.
130   if (L->isLoopInvariant(Cond)) return Cond;
131   
132   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
133     if (BO->getOpcode() == Instruction::And ||
134         BO->getOpcode() == Instruction::Or) {
135       // If either the left or right side is invariant, we can unswitch on this,
136       // which will cause the branch to go away in one loop and the condition to
137       // simplify in the other one.
138       if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
139         return LHS;
140       if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
141         return RHS;
142     }
143       
144       return 0;
145 }
146
147 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
148   assert(L->isLCSSAForm());
149   LI = &getAnalysis<LoopInfo>();
150   LPM = &LPM_Ref;
151   bool Changed = false;
152   
153   // Loop over all of the basic blocks in the loop.  If we find an interior
154   // block that is branching on a loop-invariant condition, we can unswitch this
155   // loop.
156   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
157        I != E; ++I) {
158     TerminatorInst *TI = (*I)->getTerminator();
159     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
160       // If this isn't branching on an invariant condition, we can't unswitch
161       // it.
162       if (BI->isConditional()) {
163         // See if this, or some part of it, is loop invariant.  If so, we can
164         // unswitch on it if we desire.
165         Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
166         if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
167                                              L)) {
168           ++NumBranches;
169           return true;
170         }
171       }      
172     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
173       Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
174       if (LoopCond && SI->getNumCases() > 1) {
175         // Find a value to unswitch on:
176         // FIXME: this should chose the most expensive case!
177         Constant *UnswitchVal = SI->getCaseValue(1);
178         // Do not process same value again and again.
179         if (!UnswitchedVals.insert(UnswitchVal))
180           continue;
181
182         if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
183           ++NumSwitches;
184           return true;
185         }
186       }
187     }
188     
189     // Scan the instructions to check for unswitchable values.
190     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end(); 
191          BBI != E; ++BBI)
192       if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
193         Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
194         if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
195                                              L)) {
196           ++NumSelects;
197           return true;
198         }
199       }
200   }
201   
202   assert(L->isLCSSAForm());
203   
204   return Changed;
205 }
206
207 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
208 ///   1. Exit the loop with no side effects.
209 ///   2. Branch to the latch block with no side-effects.
210 ///
211 /// If these conditions are true, we return true and set ExitBB to the block we
212 /// exit through.
213 ///
214 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
215                                          BasicBlock *&ExitBB,
216                                          std::set<BasicBlock*> &Visited) {
217   if (!Visited.insert(BB).second) {
218     // Already visited and Ok, end of recursion.
219     return true;
220   } else if (!L->contains(BB)) {
221     // Otherwise, this is a loop exit, this is fine so long as this is the
222     // first exit.
223     if (ExitBB != 0) return false;
224     ExitBB = BB;
225     return true;
226   }
227   
228   // Otherwise, this is an unvisited intra-loop node.  Check all successors.
229   for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
230     // Check to see if the successor is a trivial loop exit.
231     if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
232       return false;
233   }
234
235   // Okay, everything after this looks good, check to make sure that this block
236   // doesn't include any side effects.
237   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
238     if (I->mayWriteToMemory())
239       return false;
240   
241   return true;
242 }
243
244 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
245 /// leads to an exit from the specified loop, and has no side-effects in the 
246 /// process.  If so, return the block that is exited to, otherwise return null.
247 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
248   std::set<BasicBlock*> Visited;
249   Visited.insert(L->getHeader());  // Branches to header are ok.
250   BasicBlock *ExitBB = 0;
251   if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
252     return ExitBB;
253   return 0;
254 }
255
256 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
257 /// trivial: that is, that the condition controls whether or not the loop does
258 /// anything at all.  If this is a trivial condition, unswitching produces no
259 /// code duplications (equivalently, it produces a simpler loop and a new empty
260 /// loop, which gets deleted).
261 ///
262 /// If this is a trivial condition, return true, otherwise return false.  When
263 /// returning true, this sets Cond and Val to the condition that controls the
264 /// trivial condition: when Cond dynamically equals Val, the loop is known to
265 /// exit.  Finally, this sets LoopExit to the BB that the loop exits to when
266 /// Cond == Val.
267 ///
268 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
269                                        BasicBlock **LoopExit = 0) {
270   BasicBlock *Header = L->getHeader();
271   TerminatorInst *HeaderTerm = Header->getTerminator();
272   
273   BasicBlock *LoopExitBB = 0;
274   if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
275     // If the header block doesn't end with a conditional branch on Cond, we
276     // can't handle it.
277     if (!BI->isConditional() || BI->getCondition() != Cond)
278       return false;
279   
280     // Check to see if a successor of the branch is guaranteed to go to the
281     // latch block or exit through a one exit block without having any 
282     // side-effects.  If so, determine the value of Cond that causes it to do
283     // this.
284     if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
285       if (Val) *Val = ConstantInt::getTrue();
286     } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
287       if (Val) *Val = ConstantInt::getFalse();
288     }
289   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
290     // If this isn't a switch on Cond, we can't handle it.
291     if (SI->getCondition() != Cond) return false;
292     
293     // Check to see if a successor of the switch is guaranteed to go to the
294     // latch block or exit through a one exit block without having any 
295     // side-effects.  If so, determine the value of Cond that causes it to do
296     // this.  Note that we can't trivially unswitch on the default case.
297     for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
298       if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
299         // Okay, we found a trivial case, remember the value that is trivial.
300         if (Val) *Val = SI->getCaseValue(i);
301         break;
302       }
303   }
304
305   // If we didn't find a single unique LoopExit block, or if the loop exit block
306   // contains phi nodes, this isn't trivial.
307   if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
308     return false;   // Can't handle this.
309   
310   if (LoopExit) *LoopExit = LoopExitBB;
311   
312   // We already know that nothing uses any scalar values defined inside of this
313   // loop.  As such, we just have to check to see if this loop will execute any
314   // side-effecting instructions (e.g. stores, calls, volatile loads) in the
315   // part of the loop that the code *would* execute.  We already checked the
316   // tail, check the header now.
317   for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
318     if (I->mayWriteToMemory())
319       return false;
320   return true;
321 }
322
323 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
324 /// we choose to unswitch the specified loop on the specified value.
325 ///
326 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
327   // If the condition is trivial, always unswitch.  There is no code growth for
328   // this case.
329   if (IsTrivialUnswitchCondition(L, LIC))
330     return 0;
331   
332   // FIXME: This is really overly conservative.  However, more liberal 
333   // estimations have thus far resulted in excessive unswitching, which is bad
334   // both in compile time and in code size.  This should be replaced once
335   // someone figures out how a good estimation.
336   return L->getBlocks().size();
337   
338   unsigned Cost = 0;
339   // FIXME: this is brain dead.  It should take into consideration code
340   // shrinkage.
341   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
342        I != E; ++I) {
343     BasicBlock *BB = *I;
344     // Do not include empty blocks in the cost calculation.  This happen due to
345     // loop canonicalization and will be removed.
346     if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
347       continue;
348     
349     // Count basic blocks.
350     ++Cost;
351   }
352
353   return Cost;
354 }
355
356 /// UnswitchIfProfitable - We have found that we can unswitch L when
357 /// LoopCond == Val to simplify the loop.  If we decide that this is profitable,
358 /// unswitch the loop, reprocess the pieces, then return true.
359 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
360   // Check to see if it would be profitable to unswitch this loop.
361   unsigned Cost = getLoopUnswitchCost(L, LoopCond);
362   if (Cost > Threshold) {
363     // FIXME: this should estimate growth by the amount of code shared by the
364     // resultant unswitched loops.
365     //
366     DOUT << "NOT unswitching loop %"
367          << L->getHeader()->getName() << ", cost too high: "
368          << L->getBlocks().size() << "\n";
369     return false;
370   }
371   
372   // If this is a trivial condition to unswitch (which results in no code
373   // duplication), do it now.
374   Constant *CondVal;
375   BasicBlock *ExitBlock;
376   if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
377     UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
378   } else {
379     UnswitchNontrivialCondition(LoopCond, Val, L);
380   }
381  
382   return true;
383 }
384
385 /// SplitBlock - Split the specified block at the specified instruction - every
386 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
387 /// to a new block.  The two blocks are joined by an unconditional branch and
388 /// the loop info is updated.
389 ///
390 BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
391   BasicBlock::iterator SplitIt = SplitPt;
392   while (isa<PHINode>(SplitIt))
393     ++SplitIt;
394   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
395
396   // The new block lives in whichever loop the old one did.
397   if (Loop *L = LI->getLoopFor(Old))
398     L->addBasicBlockToLoop(New, *LI);
399
400   return New;
401 }
402
403
404 BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
405   TerminatorInst *LatchTerm = BB->getTerminator();
406   unsigned SuccNum = 0;
407   for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
408     assert(i != e && "Didn't find edge?");
409     if (LatchTerm->getSuccessor(i) == Succ) {
410       SuccNum = i;
411       break;
412     }
413   }
414   
415   // If this is a critical edge, let SplitCriticalEdge do it.
416   Loop *OrigDestBBL = LI->getLoopFor(BB->getTerminator()->getSuccessor(SuccNum));
417   if (SplitCriticalEdge(BB->getTerminator(), SuccNum)) {
418     BasicBlock *NewBB = LatchTerm->getSuccessor(SuccNum);
419
420     Loop *BBL = LI->getLoopFor(BB);
421     if (!BBL || !OrigDestBBL)
422       return NewBB;
423
424     // If edge is inside a loop then NewBB is part of same loop.
425     if (BBL == OrigDestBBL)
426       BBL->addBasicBlockToLoop(NewBB, *LI);
427     // If edge is entering loop then NewBB is part of outer loop.
428     else if (BBL->contains(OrigDestBBL->getHeader()))
429       BBL->addBasicBlockToLoop(NewBB, *LI);
430     // If edge is from an inner loop to outer loop then NewBB is part
431     // of outer loop.
432     else if (OrigDestBBL->contains(BBL->getHeader()))
433       OrigDestBBL->addBasicBlockToLoop(NewBB, *LI);
434     // Else edge is connecting two loops and NewBB is part of their parent loop
435     else if (Loop *PL = OrigDestBBL->getParentLoop())
436       PL->addBasicBlockToLoop(NewBB, *LI);
437
438     return NewBB;
439   }
440
441   // If the edge isn't critical, then BB has a single successor or Succ has a
442   // single pred.  Split the block.
443   BasicBlock::iterator SplitPoint;
444   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
445     // If the successor only has a single pred, split the top of the successor
446     // block.
447     assert(SP == BB && "CFG broken");
448     return SplitBlock(Succ, Succ->begin());
449   } else {
450     // Otherwise, if BB has a single successor, split it at the bottom of the
451     // block.
452     assert(BB->getTerminator()->getNumSuccessors() == 1 &&
453            "Should have a single succ!"); 
454     return SplitBlock(BB, BB->getTerminator());
455   }
456 }
457   
458
459
460 // RemapInstruction - Convert the instruction operands from referencing the
461 // current values into those specified by ValueMap.
462 //
463 static inline void RemapInstruction(Instruction *I,
464                                     DenseMap<const Value *, Value*> &ValueMap) {
465   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
466     Value *Op = I->getOperand(op);
467     DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
468     if (It != ValueMap.end()) Op = It->second;
469     I->setOperand(op, Op);
470   }
471 }
472
473 /// CloneLoop - Recursively clone the specified loop and all of its children,
474 /// mapping the blocks with the specified map.
475 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
476                        LoopInfo *LI, LPPassManager *LPM) {
477   Loop *New = new Loop();
478
479   LPM->insertLoop(New, PL);
480
481   // Add all of the blocks in L to the new loop.
482   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
483        I != E; ++I)
484     if (LI->getLoopFor(*I) == L)
485       New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
486
487   // Add all of the subloops to the new loop.
488   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
489     CloneLoop(*I, New, VM, LI, LPM);
490
491   return New;
492 }
493
494 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
495 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest.  Insert the
496 /// code immediately before InsertPt.
497 static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
498                                            BasicBlock *TrueDest,
499                                            BasicBlock *FalseDest,
500                                            Instruction *InsertPt) {
501   // Insert a conditional branch on LIC to the two preheaders.  The original
502   // code is the true version and the new code is the false version.
503   Value *BranchVal = LIC;
504   if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
505     BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
506   else if (Val != ConstantInt::getTrue())
507     // We want to enter the new loop when the condition is true.
508     std::swap(TrueDest, FalseDest);
509
510   // Insert the new branch.
511   new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
512 }
513
514
515 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
516 /// condition in it (a cond branch from its header block to its latch block,
517 /// where the path through the loop that doesn't execute its body has no 
518 /// side-effects), unswitch it.  This doesn't involve any code duplication, just
519 /// moving the conditional branch outside of the loop and updating loop info.
520 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, 
521                                             Constant *Val, 
522                                             BasicBlock *ExitBlock) {
523   DOUT << "loop-unswitch: Trivial-Unswitch loop %"
524        << L->getHeader()->getName() << " [" << L->getBlocks().size()
525        << " blocks] in Function " << L->getHeader()->getParent()->getName()
526        << " on cond: " << *Val << " == " << *Cond << "\n";
527   
528   // First step, split the preheader, so that we know that there is a safe place
529   // to insert the conditional branch.  We will change 'OrigPH' to have a
530   // conditional branch on Cond.
531   BasicBlock *OrigPH = L->getLoopPreheader();
532   BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
533
534   // Now that we have a place to insert the conditional branch, create a place
535   // to branch to: this is the exit block out of the loop that we should
536   // short-circuit to.
537   
538   // Split this block now, so that the loop maintains its exit block, and so
539   // that the jump from the preheader can execute the contents of the exit block
540   // without actually branching to it (the exit block should be dominated by the
541   // loop header, not the preheader).
542   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
543   BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
544     
545   // Okay, now we have a position to branch from and a position to branch to, 
546   // insert the new conditional branch.
547   EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, 
548                                  OrigPH->getTerminator());
549   OrigPH->getTerminator()->eraseFromParent();
550
551   // We need to reprocess this loop, it could be unswitched again.
552   LPM->redoLoop(L);
553   
554   // Now that we know that the loop is never entered when this condition is a
555   // particular value, rewrite the loop with this info.  We know that this will
556   // at least eliminate the old branch.
557   RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
558   ++NumTrivial;
559 }
560
561
562 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
563 /// equal Val.  Split it into loop versions and test the condition outside of
564 /// either loop.  Return the loops created as Out1/Out2.
565 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val, 
566                                                Loop *L) {
567   Function *F = L->getHeader()->getParent();
568   DOUT << "loop-unswitch: Unswitching loop %"
569        << L->getHeader()->getName() << " [" << L->getBlocks().size()
570        << " blocks] in Function " << F->getName()
571        << " when '" << *Val << "' == " << *LIC << "\n";
572
573   // LoopBlocks contains all of the basic blocks of the loop, including the
574   // preheader of the loop, the body of the loop, and the exit blocks of the 
575   // loop, in that order.
576   std::vector<BasicBlock*> LoopBlocks;
577
578   // First step, split the preheader and exit blocks, and add these blocks to
579   // the LoopBlocks list.
580   BasicBlock *OrigPreheader = L->getLoopPreheader();
581   LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
582
583   // We want the loop to come after the preheader, but before the exit blocks.
584   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
585
586   std::vector<BasicBlock*> ExitBlocks;
587   L->getUniqueExitBlocks(ExitBlocks);
588
589   // Split all of the edges from inside the loop to their exit blocks.  Update
590   // the appropriate Phi nodes as we do so.
591   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
592     BasicBlock *ExitBlock = ExitBlocks[i];
593     std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
594
595     for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
596       BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
597       BasicBlock* StartBlock = Preds[j];
598       BasicBlock* EndBlock;
599       if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
600         EndBlock = MiddleBlock;
601         MiddleBlock = EndBlock->getSinglePredecessor();;
602       } else {
603         EndBlock = ExitBlock;
604       }
605       
606       std::set<PHINode*> InsertedPHIs;
607       PHINode* OldLCSSA = 0;
608       for (BasicBlock::iterator I = EndBlock->begin();
609            (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
610         Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
611         PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
612                                         OldLCSSA->getName() + ".us-lcssa",
613                                         MiddleBlock->getTerminator());
614         NewLCSSA->addIncoming(OldValue, StartBlock);
615         OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
616                                    NewLCSSA);
617         InsertedPHIs.insert(NewLCSSA);
618       }
619
620       BasicBlock::iterator InsertPt = EndBlock->begin();
621       while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
622       for (BasicBlock::iterator I = MiddleBlock->begin();
623          (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
624          ++I) {
625         PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
626                                         OldLCSSA->getName() + ".us-lcssa",
627                                         InsertPt);
628         OldLCSSA->replaceAllUsesWith(NewLCSSA);
629         NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
630       }
631     }    
632   }
633   
634   // The exit blocks may have been changed due to edge splitting, recompute.
635   ExitBlocks.clear();
636   L->getUniqueExitBlocks(ExitBlocks);
637
638   // Add exit blocks to the loop blocks.
639   LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
640
641   // Next step, clone all of the basic blocks that make up the loop (including
642   // the loop preheader and exit blocks), keeping track of the mapping between
643   // the instructions and blocks.
644   std::vector<BasicBlock*> NewBlocks;
645   NewBlocks.reserve(LoopBlocks.size());
646   DenseMap<const Value*, Value*> ValueMap;
647   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
648     BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
649     NewBlocks.push_back(New);
650     ValueMap[LoopBlocks[i]] = New;  // Keep the BB mapping.
651   }
652
653   // Splice the newly inserted blocks into the function right before the
654   // original preheader.
655   F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
656                                 NewBlocks[0], F->end());
657
658   // Now we create the new Loop object for the versioned loop.
659   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
660   Loop *ParentLoop = L->getParentLoop();
661   if (ParentLoop) {
662     // Make sure to add the cloned preheader and exit blocks to the parent loop
663     // as well.
664     ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
665   }
666   
667   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
668     BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
669     // The new exit block should be in the same loop as the old one.
670     if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
671       ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
672     
673     assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
674            "Exit block should have been split to have one successor!");
675     BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
676     
677     // If the successor of the exit block had PHI nodes, add an entry for
678     // NewExit.
679     PHINode *PN;
680     for (BasicBlock::iterator I = ExitSucc->begin();
681          (PN = dyn_cast<PHINode>(I)); ++I) {
682       Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
683       DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
684       if (It != ValueMap.end()) V = It->second;
685       PN->addIncoming(V, NewExit);
686     }
687   }
688
689   // Rewrite the code to refer to itself.
690   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
691     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
692            E = NewBlocks[i]->end(); I != E; ++I)
693       RemapInstruction(I, ValueMap);
694   
695   // Rewrite the original preheader to select between versions of the loop.
696   BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
697   assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
698          "Preheader splitting did not work correctly!");
699
700   // Emit the new branch that selects between the two versions of this loop.
701   EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
702   OldBR->eraseFromParent();
703   
704   LoopProcessWorklist.push_back(NewLoop);
705   LPM->redoLoop(L);
706
707   // Now we rewrite the original code to know that the condition is true and the
708   // new code to know that the condition is false.
709   RewriteLoopBodyWithConditionConstant(L      , LIC, Val, false);
710   
711   // It's possible that simplifying one loop could cause the other to be
712   // deleted.  If so, don't simplify it.
713   if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
714     RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
715 }
716
717 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
718 /// specified.
719 static void RemoveFromWorklist(Instruction *I, 
720                                std::vector<Instruction*> &Worklist) {
721   std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
722                                                      Worklist.end(), I);
723   while (WI != Worklist.end()) {
724     unsigned Offset = WI-Worklist.begin();
725     Worklist.erase(WI);
726     WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
727   }
728 }
729
730 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
731 /// program, replacing all uses with V and update the worklist.
732 static void ReplaceUsesOfWith(Instruction *I, Value *V, 
733                               std::vector<Instruction*> &Worklist) {
734   DOUT << "Replace with '" << *V << "': " << *I;
735
736   // Add uses to the worklist, which may be dead now.
737   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
738     if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
739       Worklist.push_back(Use);
740
741   // Add users to the worklist which may be simplified now.
742   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
743        UI != E; ++UI)
744     Worklist.push_back(cast<Instruction>(*UI));
745   I->replaceAllUsesWith(V);
746   I->eraseFromParent();
747   RemoveFromWorklist(I, Worklist);
748   ++NumSimplify;
749 }
750
751 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
752 /// information, and remove any dead successors it has.
753 ///
754 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
755                                      std::vector<Instruction*> &Worklist) {
756   if (pred_begin(BB) != pred_end(BB)) {
757     // This block isn't dead, since an edge to BB was just removed, see if there
758     // are any easy simplifications we can do now.
759     if (BasicBlock *Pred = BB->getSinglePredecessor()) {
760       // If it has one pred, fold phi nodes in BB.
761       while (isa<PHINode>(BB->begin()))
762         ReplaceUsesOfWith(BB->begin(), 
763                           cast<PHINode>(BB->begin())->getIncomingValue(0), 
764                           Worklist);
765       
766       // If this is the header of a loop and the only pred is the latch, we now
767       // have an unreachable loop.
768       if (Loop *L = LI->getLoopFor(BB))
769         if (L->getHeader() == BB && L->contains(Pred)) {
770           // Remove the branch from the latch to the header block, this makes
771           // the header dead, which will make the latch dead (because the header
772           // dominates the latch).
773           Pred->getTerminator()->eraseFromParent();
774           new UnreachableInst(Pred);
775           
776           // The loop is now broken, remove it from LI.
777           RemoveLoopFromHierarchy(L);
778           
779           // Reprocess the header, which now IS dead.
780           RemoveBlockIfDead(BB, Worklist);
781           return;
782         }
783       
784       // If pred ends in a uncond branch, add uncond branch to worklist so that
785       // the two blocks will get merged.
786       if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
787         if (BI->isUnconditional())
788           Worklist.push_back(BI);
789     }
790     return;
791   }
792
793   DOUT << "Nuking dead block: " << *BB;
794   
795   // Remove the instructions in the basic block from the worklist.
796   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
797     RemoveFromWorklist(I, Worklist);
798     
799     // Anything that uses the instructions in this basic block should have their
800     // uses replaced with undefs.
801     if (!I->use_empty())
802       I->replaceAllUsesWith(UndefValue::get(I->getType()));
803   }
804   
805   // If this is the edge to the header block for a loop, remove the loop and
806   // promote all subloops.
807   if (Loop *BBLoop = LI->getLoopFor(BB)) {
808     if (BBLoop->getLoopLatch() == BB)
809       RemoveLoopFromHierarchy(BBLoop);
810   }
811
812   // Remove the block from the loop info, which removes it from any loops it
813   // was in.
814   LI->removeBlock(BB);
815   
816   
817   // Remove phi node entries in successors for this block.
818   TerminatorInst *TI = BB->getTerminator();
819   std::vector<BasicBlock*> Succs;
820   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
821     Succs.push_back(TI->getSuccessor(i));
822     TI->getSuccessor(i)->removePredecessor(BB);
823   }
824   
825   // Unique the successors, remove anything with multiple uses.
826   std::sort(Succs.begin(), Succs.end());
827   Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
828   
829   // Remove the basic block, including all of the instructions contained in it.
830   BB->eraseFromParent();
831   
832   // Remove successor blocks here that are not dead, so that we know we only
833   // have dead blocks in this list.  Nondead blocks have a way of becoming dead,
834   // then getting removed before we revisit them, which is badness.
835   //
836   for (unsigned i = 0; i != Succs.size(); ++i)
837     if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
838       // One exception is loop headers.  If this block was the preheader for a
839       // loop, then we DO want to visit the loop so the loop gets deleted.
840       // We know that if the successor is a loop header, that this loop had to
841       // be the preheader: the case where this was the latch block was handled
842       // above and headers can only have two predecessors.
843       if (!LI->isLoopHeader(Succs[i])) {
844         Succs.erase(Succs.begin()+i);
845         --i;
846       }
847     }
848   
849   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
850     RemoveBlockIfDead(Succs[i], Worklist);
851 }
852
853 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
854 /// become unwrapped, either because the backedge was deleted, or because the
855 /// edge into the header was removed.  If the edge into the header from the
856 /// latch block was removed, the loop is unwrapped but subloops are still alive,
857 /// so they just reparent loops.  If the loops are actually dead, they will be
858 /// removed later.
859 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
860   LPM->deleteLoopFromQueue(L);
861   RemoveLoopFromWorklist(L);
862 }
863
864
865
866 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
867 // the value specified by Val in the specified loop, or we know it does NOT have
868 // that value.  Rewrite any uses of LIC or of properties correlated to it.
869 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
870                                                         Constant *Val,
871                                                         bool IsEqual) {
872   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
873   
874   // FIXME: Support correlated properties, like:
875   //  for (...)
876   //    if (li1 < li2)
877   //      ...
878   //    if (li1 > li2)
879   //      ...
880   
881   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
882   // selects, switches.
883   std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
884   std::vector<Instruction*> Worklist;
885
886   // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
887   // in the loop with the appropriate one directly.
888   if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
889     Value *Replacement;
890     if (IsEqual)
891       Replacement = Val;
892     else
893       Replacement = ConstantInt::get(Type::Int1Ty, 
894                                      !cast<ConstantInt>(Val)->getZExtValue());
895     
896     for (unsigned i = 0, e = Users.size(); i != e; ++i)
897       if (Instruction *U = cast<Instruction>(Users[i])) {
898         if (!L->contains(U->getParent()))
899           continue;
900         U->replaceUsesOfWith(LIC, Replacement);
901         Worklist.push_back(U);
902       }
903   } else {
904     // Otherwise, we don't know the precise value of LIC, but we do know that it
905     // is certainly NOT "Val".  As such, simplify any uses in the loop that we
906     // can.  This case occurs when we unswitch switch statements.
907     for (unsigned i = 0, e = Users.size(); i != e; ++i)
908       if (Instruction *U = cast<Instruction>(Users[i])) {
909         if (!L->contains(U->getParent()))
910           continue;
911
912         Worklist.push_back(U);
913
914         // If we know that LIC is not Val, use this info to simplify code.
915         if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
916           for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
917             if (SI->getCaseValue(i) == Val) {
918               // Found a dead case value.  Don't remove PHI nodes in the 
919               // successor if they become single-entry, those PHI nodes may
920               // be in the Users list.
921               
922               // FIXME: This is a hack.  We need to keep the successor around
923               // and hooked up so as to preserve the loop structure, because
924               // trying to update it is complicated.  So instead we preserve the
925               // loop structure and put the block on an dead code path.
926               
927               BasicBlock* Old = SI->getParent();
928               BasicBlock* Split = SplitBlock(Old, SI);
929               
930               Instruction* OldTerm = Old->getTerminator();
931               new BranchInst(Split, SI->getSuccessor(i),
932                              ConstantInt::getTrue(), OldTerm);
933               
934               Old->getTerminator()->eraseFromParent();
935               
936               
937               PHINode *PN;
938               for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
939                    (PN = dyn_cast<PHINode>(II)); ++II) {
940                 Value *InVal = PN->removeIncomingValue(Split, false);
941                 PN->addIncoming(InVal, Old);
942               }
943
944               SI->removeCase(i);
945               break;
946             }
947           }
948         }
949         
950         // TODO: We could do other simplifications, for example, turning 
951         // LIC == Val -> false.
952       }
953   }
954   
955   SimplifyCode(Worklist);
956 }
957
958 /// SimplifyCode - Okay, now that we have simplified some instructions in the 
959 /// loop, walk over it and constant prop, dce, and fold control flow where
960 /// possible.  Note that this is effectively a very simple loop-structure-aware
961 /// optimizer.  During processing of this loop, L could very well be deleted, so
962 /// it must not be used.
963 ///
964 /// FIXME: When the loop optimizer is more mature, separate this out to a new
965 /// pass.
966 ///
967 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
968   while (!Worklist.empty()) {
969     Instruction *I = Worklist.back();
970     Worklist.pop_back();
971     
972     // Simple constant folding.
973     if (Constant *C = ConstantFoldInstruction(I)) {
974       ReplaceUsesOfWith(I, C, Worklist);
975       continue;
976     }
977     
978     // Simple DCE.
979     if (isInstructionTriviallyDead(I)) {
980       DOUT << "Remove dead instruction '" << *I;
981       
982       // Add uses to the worklist, which may be dead now.
983       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
984         if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
985           Worklist.push_back(Use);
986       I->eraseFromParent();
987       RemoveFromWorklist(I, Worklist);
988       ++NumSimplify;
989       continue;
990     }
991     
992     // Special case hacks that appear commonly in unswitched code.
993     switch (I->getOpcode()) {
994     case Instruction::Select:
995       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
996         ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
997         continue;
998       }
999       break;
1000     case Instruction::And:
1001       if (isa<ConstantInt>(I->getOperand(0)) && 
1002           I->getOperand(0)->getType() == Type::Int1Ty)   // constant -> RHS
1003         cast<BinaryOperator>(I)->swapOperands();
1004       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1))) 
1005         if (CB->getType() == Type::Int1Ty) {
1006           if (CB->isOne())      // X & 1 -> X
1007             ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1008           else                  // X & 0 -> 0
1009             ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1010           continue;
1011         }
1012       break;
1013     case Instruction::Or:
1014       if (isa<ConstantInt>(I->getOperand(0)) &&
1015           I->getOperand(0)->getType() == Type::Int1Ty)   // constant -> RHS
1016         cast<BinaryOperator>(I)->swapOperands();
1017       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1018         if (CB->getType() == Type::Int1Ty) {
1019           if (CB->isOne())   // X | 1 -> 1
1020             ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1021           else                  // X | 0 -> X
1022             ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1023           continue;
1024         }
1025       break;
1026     case Instruction::Br: {
1027       BranchInst *BI = cast<BranchInst>(I);
1028       if (BI->isUnconditional()) {
1029         // If BI's parent is the only pred of the successor, fold the two blocks
1030         // together.
1031         BasicBlock *Pred = BI->getParent();
1032         BasicBlock *Succ = BI->getSuccessor(0);
1033         BasicBlock *SinglePred = Succ->getSinglePredecessor();
1034         if (!SinglePred) continue;  // Nothing to do.
1035         assert(SinglePred == Pred && "CFG broken");
1036
1037         DOUT << "Merging blocks: " << Pred->getName() << " <- " 
1038              << Succ->getName() << "\n";
1039         
1040         // Resolve any single entry PHI nodes in Succ.
1041         while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1042           ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1043         
1044         // Move all of the successor contents from Succ to Pred.
1045         Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1046                                    Succ->end());
1047         BI->eraseFromParent();
1048         RemoveFromWorklist(BI, Worklist);
1049         
1050         // If Succ has any successors with PHI nodes, update them to have
1051         // entries coming from Pred instead of Succ.
1052         Succ->replaceAllUsesWith(Pred);
1053         
1054         // Remove Succ from the loop tree.
1055         LI->removeBlock(Succ);
1056         Succ->eraseFromParent();
1057         ++NumSimplify;
1058       } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1059         // Conditional branch.  Turn it into an unconditional branch, then
1060         // remove dead blocks.
1061         break;  // FIXME: Enable.
1062
1063         DOUT << "Folded branch: " << *BI;
1064         BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1065         BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1066         DeadSucc->removePredecessor(BI->getParent(), true);
1067         Worklist.push_back(new BranchInst(LiveSucc, BI));
1068         BI->eraseFromParent();
1069         RemoveFromWorklist(BI, Worklist);
1070         ++NumSimplify;
1071
1072         RemoveBlockIfDead(DeadSucc, Worklist);
1073       }
1074       break;
1075     }
1076     }
1077   }
1078 }