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