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