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