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