Rearrange code a bit
[oota-llvm.git] / lib / Transforms / Utils / SimplifyCFG.cpp
1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
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 // Peephole optimize the CFG.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/Utils/Local.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/Type.h"
18 #include "llvm/Support/CFG.h"
19 #include <algorithm>
20 #include <functional>
21 using namespace llvm;
22
23 // PropagatePredecessorsForPHIs - This gets "Succ" ready to have the
24 // predecessors from "BB".  This is a little tricky because "Succ" has PHI
25 // nodes, which need to have extra slots added to them to hold the merge edges
26 // from BB's predecessors, and BB itself might have had PHI nodes in it.  This
27 // function returns true (failure) if the Succ BB already has a predecessor that
28 // is a predecessor of BB and incoming PHI arguments would not be discernible.
29 //
30 // Assumption: Succ is the single successor for BB.
31 //
32 static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
33   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
34
35   if (!isa<PHINode>(Succ->front()))
36     return false;  // We can make the transformation, no problem.
37
38   // If there is more than one predecessor, and there are PHI nodes in
39   // the successor, then we need to add incoming edges for the PHI nodes
40   //
41   const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
42
43   // Check to see if one of the predecessors of BB is already a predecessor of
44   // Succ.  If so, we cannot do the transformation if there are any PHI nodes
45   // with incompatible values coming in from the two edges!
46   //
47   for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
48     if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
49       // Loop over all of the PHI nodes checking to see if there are
50       // incompatible values coming in.
51       for (BasicBlock::iterator I = Succ->begin();
52            PHINode *PN = dyn_cast<PHINode>(I); ++I) {
53         // Loop up the entries in the PHI node for BB and for *PI if the values
54         // coming in are non-equal, we cannot merge these two blocks (instead we
55         // should insert a conditional move or something, then merge the
56         // blocks).
57         int Idx1 = PN->getBasicBlockIndex(BB);
58         int Idx2 = PN->getBasicBlockIndex(*PI);
59         assert(Idx1 != -1 && Idx2 != -1 &&
60                "Didn't have entries for my predecessors??");
61         if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
62           return true;  // Values are not equal...
63       }
64     }
65
66   // Loop over all of the PHI nodes in the successor BB
67   for (BasicBlock::iterator I = Succ->begin();
68        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
69     Value *OldVal = PN->removeIncomingValue(BB, false);
70     assert(OldVal && "No entry in PHI for Pred BB!");
71
72     // If this incoming value is one of the PHI nodes in BB...
73     if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
74       PHINode *OldValPN = cast<PHINode>(OldVal);
75       for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), 
76              End = BBPreds.end(); PredI != End; ++PredI) {
77         PN->addIncoming(OldValPN->getIncomingValueForBlock(*PredI), *PredI);
78       }
79     } else {
80       for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), 
81              End = BBPreds.end(); PredI != End; ++PredI) {
82         // Add an incoming value for each of the new incoming values...
83         PN->addIncoming(OldVal, *PredI);
84       }
85     }
86   }
87   return false;
88 }
89
90 /// GetIfCondition - Given a basic block (BB) with two predecessors (and
91 /// presumably PHI nodes in it), check to see if the merge at this block is due
92 /// to an "if condition".  If so, return the boolean condition that determines
93 /// which entry into BB will be taken.  Also, return by references the block
94 /// that will be entered from if the condition is true, and the block that will
95 /// be entered if the condition is false.
96 /// 
97 ///
98 static Value *GetIfCondition(BasicBlock *BB,
99                              BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
100   assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
101          "Function can only handle blocks with 2 predecessors!");
102   BasicBlock *Pred1 = *pred_begin(BB);
103   BasicBlock *Pred2 = *++pred_begin(BB);
104
105   // We can only handle branches.  Other control flow will be lowered to
106   // branches if possible anyway.
107   if (!isa<BranchInst>(Pred1->getTerminator()) ||
108       !isa<BranchInst>(Pred2->getTerminator()))
109     return 0;
110   BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
111   BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
112
113   // Eliminate code duplication by ensuring that Pred1Br is conditional if
114   // either are.
115   if (Pred2Br->isConditional()) {
116     // If both branches are conditional, we don't have an "if statement".  In
117     // reality, we could transform this case, but since the condition will be
118     // required anyway, we stand no chance of eliminating it, so the xform is
119     // probably not profitable.
120     if (Pred1Br->isConditional())
121       return 0;
122
123     std::swap(Pred1, Pred2);
124     std::swap(Pred1Br, Pred2Br);
125   }
126
127   if (Pred1Br->isConditional()) {
128     // If we found a conditional branch predecessor, make sure that it branches
129     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
130     if (Pred1Br->getSuccessor(0) == BB &&
131         Pred1Br->getSuccessor(1) == Pred2) {
132       IfTrue = Pred1;
133       IfFalse = Pred2;
134     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
135                Pred1Br->getSuccessor(1) == BB) {
136       IfTrue = Pred2;
137       IfFalse = Pred1;
138     } else {
139       // We know that one arm of the conditional goes to BB, so the other must
140       // go somewhere unrelated, and this must not be an "if statement".
141       return 0;
142     }
143
144     // The only thing we have to watch out for here is to make sure that Pred2
145     // doesn't have incoming edges from other blocks.  If it does, the condition
146     // doesn't dominate BB.
147     if (++pred_begin(Pred2) != pred_end(Pred2))
148       return 0;
149
150     return Pred1Br->getCondition();
151   }
152
153   // Ok, if we got here, both predecessors end with an unconditional branch to
154   // BB.  Don't panic!  If both blocks only have a single (identical)
155   // predecessor, and THAT is a conditional branch, then we're all ok!
156   if (pred_begin(Pred1) == pred_end(Pred1) ||
157       ++pred_begin(Pred1) != pred_end(Pred1) ||
158       pred_begin(Pred2) == pred_end(Pred2) ||
159       ++pred_begin(Pred2) != pred_end(Pred2) ||
160       *pred_begin(Pred1) != *pred_begin(Pred2))
161     return 0;
162
163   // Otherwise, if this is a conditional branch, then we can use it!
164   BasicBlock *CommonPred = *pred_begin(Pred1);
165   if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
166     assert(BI->isConditional() && "Two successors but not conditional?");
167     if (BI->getSuccessor(0) == Pred1) {
168       IfTrue = Pred1;
169       IfFalse = Pred2;
170     } else {
171       IfTrue = Pred2;
172       IfFalse = Pred1;
173     }
174     return BI->getCondition();
175   }
176   return 0;
177 }
178
179
180 // If we have a merge point of an "if condition" as accepted above, return true
181 // if the specified value dominates the block.  We don't handle the true
182 // generality of domination here, just a special case which works well enough
183 // for us.
184 static bool DominatesMergePoint(Value *V, BasicBlock *BB) {
185   if (Instruction *I = dyn_cast<Instruction>(V)) {
186     BasicBlock *PBB = I->getParent();
187     // If this instruction is defined in a block that contains an unconditional
188     // branch to BB, then it must be in the 'conditional' part of the "if
189     // statement".
190     if (isa<BranchInst>(PBB->getTerminator()) && 
191         cast<BranchInst>(PBB->getTerminator())->isUnconditional() && 
192         cast<BranchInst>(PBB->getTerminator())->getSuccessor(0) == BB)
193       return false;
194
195     // We also don't want to allow wierd loops that might have the "if
196     // condition" in the bottom of this block.
197     if (PBB == BB) return false;
198   }
199
200   // Non-instructions all dominate instructions.
201   return true;
202 }
203
204 // GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq
205 // instructions that compare a value against a constant, return the value being
206 // compared, and stick the constant into the Values vector.
207 static Value *GatherConstantSetEQs(Value *V, std::vector<Constant*> &Values) {
208   if (Instruction *Inst = dyn_cast<Instruction>(V))
209     if (Inst->getOpcode() == Instruction::SetEQ) {
210       if (Constant *C = dyn_cast<Constant>(Inst->getOperand(1))) {
211         Values.push_back(C);
212         return Inst->getOperand(0);
213       } else if (Constant *C = dyn_cast<Constant>(Inst->getOperand(0))) {
214         Values.push_back(C);
215         return Inst->getOperand(1);
216       }
217     } else if (Inst->getOpcode() == Instruction::Or) {
218       if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
219         if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
220           if (LHS == RHS)
221             return LHS;
222     }
223   return 0;
224 }
225
226 // GatherConstantSetNEs - Given a potentially 'and'd together collection of
227 // setne instructions that compare a value against a constant, return the value
228 // being compared, and stick the constant into the Values vector.
229 static Value *GatherConstantSetNEs(Value *V, std::vector<Constant*> &Values) {
230   if (Instruction *Inst = dyn_cast<Instruction>(V))
231     if (Inst->getOpcode() == Instruction::SetNE) {
232       if (Constant *C = dyn_cast<Constant>(Inst->getOperand(1))) {
233         Values.push_back(C);
234         return Inst->getOperand(0);
235       } else if (Constant *C = dyn_cast<Constant>(Inst->getOperand(0))) {
236         Values.push_back(C);
237         return Inst->getOperand(1);
238       }
239     } else if (Inst->getOpcode() == Instruction::Cast) {
240       // Cast of X to bool is really a comparison against zero.
241       assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!");
242       Values.push_back(Constant::getNullValue(Inst->getOperand(0)->getType()));
243       return Inst->getOperand(0);
244     } else if (Inst->getOpcode() == Instruction::And) {
245       if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
246         if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
247           if (LHS == RHS)
248             return LHS;
249     }
250   return 0;
251 }
252
253
254
255 /// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
256 /// bunch of comparisons of one value against constants, return the value and
257 /// the constants being compared.
258 static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
259                                    std::vector<Constant*> &Values) {
260   if (Cond->getOpcode() == Instruction::Or) {
261     CompVal = GatherConstantSetEQs(Cond, Values);
262
263     // Return true to indicate that the condition is true if the CompVal is
264     // equal to one of the constants.
265     return true;
266   } else if (Cond->getOpcode() == Instruction::And) {
267     CompVal = GatherConstantSetNEs(Cond, Values);
268         
269     // Return false to indicate that the condition is false if the CompVal is
270     // equal to one of the constants.
271     return false;
272   }
273   return false;
274 }
275
276 /// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
277 /// has no side effects, nuke it.  If it uses any instructions that become dead
278 /// because the instruction is now gone, nuke them too.
279 static void ErasePossiblyDeadInstructionTree(Instruction *I) {
280   if (isInstructionTriviallyDead(I)) {
281     std::vector<Value*> Operands(I->op_begin(), I->op_end());
282     I->getParent()->getInstList().erase(I);
283     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
284       if (Instruction *OpI = dyn_cast<Instruction>(Operands[i]))
285         ErasePossiblyDeadInstructionTree(OpI);
286   }
287 }
288
289 // SimplifyCFG - This function is used to do simplification of a CFG.  For
290 // example, it adjusts branches to branches to eliminate the extra hop, it
291 // eliminates unreachable basic blocks, and does other "peephole" optimization
292 // of the CFG.  It returns true if a modification was made.
293 //
294 // WARNING:  The entry node of a function may not be simplified.
295 //
296 bool llvm::SimplifyCFG(BasicBlock *BB) {
297   bool Changed = false;
298   Function *M = BB->getParent();
299
300   assert(BB && BB->getParent() && "Block not embedded in function!");
301   assert(BB->getTerminator() && "Degenerate basic block encountered!");
302   assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
303
304   // Remove basic blocks that have no predecessors... which are unreachable.
305   if (pred_begin(BB) == pred_end(BB)) {
306     //cerr << "Removing BB: \n" << BB;
307
308     // Loop through all of our successors and make sure they know that one
309     // of their predecessors is going away.
310     for_each(succ_begin(BB), succ_end(BB),
311              std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
312
313     while (!BB->empty()) {
314       Instruction &I = BB->back();
315       // If this instruction is used, replace uses with an arbitrary
316       // constant value.  Because control flow can't get here, we don't care
317       // what we replace the value with.  Note that since this block is 
318       // unreachable, and all values contained within it must dominate their
319       // uses, that all uses will eventually be removed.
320       if (!I.use_empty()) 
321         // Make all users of this instruction reference the constant instead
322         I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
323       
324       // Remove the instruction from the basic block
325       BB->getInstList().pop_back();
326     }
327     M->getBasicBlockList().erase(BB);
328     return true;
329   }
330
331   // Check to see if we can constant propagate this terminator instruction
332   // away...
333   Changed |= ConstantFoldTerminator(BB);
334
335   // Check to see if this block has no non-phi instructions and only a single
336   // successor.  If so, replace references to this basic block with references
337   // to the successor.
338   succ_iterator SI(succ_begin(BB));
339   if (SI != succ_end(BB) && ++SI == succ_end(BB)) {  // One succ?
340
341     BasicBlock::iterator BBI = BB->begin();  // Skip over phi nodes...
342     while (isa<PHINode>(*BBI)) ++BBI;
343
344     if (BBI->isTerminator()) {   // Terminator is the only non-phi instruction!
345       BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
346      
347       if (Succ != BB) {   // Arg, don't hurt infinite loops!
348         // If our successor has PHI nodes, then we need to update them to
349         // include entries for BB's predecessors, not for BB itself.
350         // Be careful though, if this transformation fails (returns true) then
351         // we cannot do this transformation!
352         //
353         if (!PropagatePredecessorsForPHIs(BB, Succ)) {
354           //cerr << "Killing Trivial BB: \n" << BB;
355           std::string OldName = BB->getName();
356
357           std::vector<BasicBlock*>
358             OldSuccPreds(pred_begin(Succ), pred_end(Succ));
359
360           // Move all PHI nodes in BB to Succ if they are alive, otherwise
361           // delete them.
362           while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
363             if (PN->use_empty())
364               BB->getInstList().erase(BB->begin());  // Nuke instruction...
365             else {
366               // The instruction is alive, so this means that Succ must have
367               // *ONLY* had BB as a predecessor, and the PHI node is still valid
368               // now.  Simply move it into Succ, because we know that BB
369               // strictly dominated Succ.
370               BB->getInstList().remove(BB->begin());
371               Succ->getInstList().push_front(PN);
372
373               // We need to add new entries for the PHI node to account for
374               // predecessors of Succ that the PHI node does not take into
375               // account.  At this point, since we know that BB dominated succ,
376               // this means that we should any newly added incoming edges should
377               // use the PHI node as the value for these edges, because they are
378               // loop back edges.
379               
380               for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
381                 if (OldSuccPreds[i] != BB)
382                   PN->addIncoming(PN, OldSuccPreds[i]);
383             }
384
385           // Everything that jumped to BB now goes to Succ...
386           BB->replaceAllUsesWith(Succ);
387
388           // Delete the old basic block...
389           M->getBasicBlockList().erase(BB);
390         
391           if (!OldName.empty() && !Succ->hasName())  // Transfer name if we can
392             Succ->setName(OldName);
393           
394           //cerr << "Function after removal: \n" << M;
395           return true;
396         }
397       }
398     }
399   }
400
401   // If this is a returning block with only PHI nodes in it, fold the return
402   // instruction into any unconditional branch predecessors.
403   if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
404     BasicBlock::iterator BBI = BB->getTerminator();
405     if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
406       // Find predecessors that end with unconditional branches.
407       std::vector<BasicBlock*> UncondBranchPreds;
408       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
409         TerminatorInst *PTI = (*PI)->getTerminator();
410         if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
411           if (BI->isUnconditional())
412             UncondBranchPreds.push_back(*PI);
413       }
414       
415       // If we found some, do the transformation!
416       if (!UncondBranchPreds.empty()) {
417         while (!UncondBranchPreds.empty()) {
418           BasicBlock *Pred = UncondBranchPreds.back();
419           UncondBranchPreds.pop_back();
420           Instruction *UncondBranch = Pred->getTerminator();
421           // Clone the return and add it to the end of the predecessor.
422           Instruction *NewRet = RI->clone();
423           Pred->getInstList().push_back(NewRet);
424
425           // If the return instruction returns a value, and if the value was a
426           // PHI node in "BB", propagate the right value into the return.
427           if (NewRet->getNumOperands() == 1)
428             if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
429               if (PN->getParent() == BB)
430                 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
431           // Update any PHI nodes in the returning block to realize that we no
432           // longer branch to them.
433           BB->removePredecessor(Pred);
434           Pred->getInstList().erase(UncondBranch);
435         }
436
437         // If we eliminated all predecessors of the block, delete the block now.
438         if (pred_begin(BB) == pred_end(BB))
439           // We know there are no successors, so just nuke the block.
440           M->getBasicBlockList().erase(BB);
441
442         
443         return true;
444       }
445     }
446   } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) {
447     // Check to see if the first instruction in this block is just an unwind.
448     // If so, replace any invoke instructions which use this as an exception
449     // destination with call instructions.
450     //
451     std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
452     while (!Preds.empty()) {
453       BasicBlock *Pred = Preds.back();
454       if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
455         if (II->getUnwindDest() == BB) {
456           // Insert a new branch instruction before the invoke, because this
457           // is now a fall through...
458           BranchInst *BI = new BranchInst(II->getNormalDest(), II);
459           Pred->getInstList().remove(II);   // Take out of symbol table
460           
461           // Insert the call now...
462           std::vector<Value*> Args(II->op_begin()+3, II->op_end());
463           CallInst *CI = new CallInst(II->getCalledValue(), Args,
464                                       II->getName(), BI);
465           // If the invoke produced a value, the Call now does instead
466           II->replaceAllUsesWith(CI);
467           delete II;
468           Changed = true;
469         }
470       
471       Preds.pop_back();
472     }
473   }
474
475   // Merge basic blocks into their predecessor if there is only one distinct
476   // pred, and if there is only one distinct successor of the predecessor, and
477   // if there are no PHI nodes.
478   //
479   pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
480   BasicBlock *OnlyPred = *PI++;
481   for (; PI != PE; ++PI)  // Search all predecessors, see if they are all same
482     if (*PI != OnlyPred) {
483       OnlyPred = 0;       // There are multiple different predecessors...
484       break;
485     }
486   
487   BasicBlock *OnlySucc = 0;
488   if (OnlyPred && OnlyPred != BB &&    // Don't break self loops
489       OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
490     // Check to see if there is only one distinct successor...
491     succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
492     OnlySucc = BB;
493     for (; SI != SE; ++SI)
494       if (*SI != OnlySucc) {
495         OnlySucc = 0;     // There are multiple distinct successors!
496         break;
497       }
498   }
499
500   if (OnlySucc) {
501     //cerr << "Merging: " << BB << "into: " << OnlyPred;
502     TerminatorInst *Term = OnlyPred->getTerminator();
503
504     // Resolve any PHI nodes at the start of the block.  They are all
505     // guaranteed to have exactly one entry if they exist, unless there are
506     // multiple duplicate (but guaranteed to be equal) entries for the
507     // incoming edges.  This occurs when there are multiple edges from
508     // OnlyPred to OnlySucc.
509     //
510     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
511       PN->replaceAllUsesWith(PN->getIncomingValue(0));
512       BB->getInstList().pop_front();  // Delete the phi node...
513     }
514
515     // Delete the unconditional branch from the predecessor...
516     OnlyPred->getInstList().pop_back();
517       
518     // Move all definitions in the successor to the predecessor...
519     OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
520                                      
521     // Make all PHI nodes that referred to BB now refer to Pred as their
522     // source...
523     BB->replaceAllUsesWith(OnlyPred);
524
525     std::string OldName = BB->getName();
526
527     // Erase basic block from the function... 
528     M->getBasicBlockList().erase(BB);
529
530     // Inherit predecessors name if it exists...
531     if (!OldName.empty() && !OnlyPred->hasName())
532       OnlyPred->setName(OldName);
533       
534     return true;
535   }
536
537   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
538     if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
539       // Change br (X == 0 | X == 1), T, F into a switch instruction.
540       if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
541         Instruction *Cond = cast<Instruction>(BI->getCondition());
542         // If this is a bunch of seteq's or'd together, or if it's a bunch of
543         // 'setne's and'ed together, collect them.
544         Value *CompVal = 0;
545         std::vector<Constant*> Values;
546         bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
547         if (CompVal && CompVal->getType()->isInteger()) {
548           // There might be duplicate constants in the list, which the switch
549           // instruction can't handle, remove them now.
550           std::sort(Values.begin(), Values.end());
551           Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
552           
553           // Figure out which block is which destination.
554           BasicBlock *DefaultBB = BI->getSuccessor(1);
555           BasicBlock *EdgeBB    = BI->getSuccessor(0);
556           if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
557           
558           // Create the new switch instruction now.
559           SwitchInst *New = new SwitchInst(CompVal, DefaultBB, BI);
560           
561           // Add all of the 'cases' to the switch instruction.
562           for (unsigned i = 0, e = Values.size(); i != e; ++i)
563             New->addCase(Values[i], EdgeBB);
564           
565           // We added edges from PI to the EdgeBB.  As such, if there were any
566           // PHI nodes in EdgeBB, they need entries to be added corresponding to
567           // the number of edges added.
568           for (BasicBlock::iterator BBI = EdgeBB->begin();
569                PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
570             Value *InVal = PN->getIncomingValueForBlock(*PI);
571             for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
572               PN->addIncoming(InVal, *PI);
573           }
574
575           // Erase the old branch instruction.
576           (*PI)->getInstList().erase(BI);
577
578           // Erase the potentially condition tree that was used to computed the
579           // branch condition.
580           ErasePossiblyDeadInstructionTree(Cond);
581           return true;
582         }
583       }
584
585   // If there is a trivial two-entry PHI node in this basic block, and we can
586   // eliminate it, do so now.
587   if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
588     if (PN->getNumIncomingValues() == 2) {
589       // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
590       // statement", which has a very simple dominance structure.  Basically, we
591       // are trying to find the condition that is being branched on, which
592       // subsequently causes this merge to happen.  We really want control
593       // dependence information for this check, but simplifycfg can't keep it up
594       // to date, and this catches most of the cases we care about anyway.
595       //
596       BasicBlock *IfTrue, *IfFalse;
597       if (Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse)) {
598         //std::cerr << "FOUND IF CONDITION!  " << *IfCond << "  T: "
599         //       << IfTrue->getName() << "  F: " << IfFalse->getName() << "\n";
600
601         // Figure out where to insert instructions as necessary.
602         BasicBlock::iterator AfterPHIIt = BB->begin();
603         while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt;
604
605         BasicBlock::iterator I = BB->begin();
606         while (PHINode *PN = dyn_cast<PHINode>(I)) {
607           ++I;
608
609           // If we can eliminate this PHI by directly computing it based on the
610           // condition, do so now.  We can't eliminate PHI nodes where the
611           // incoming values are defined in the conditional parts of the branch,
612           // so check for this.
613           //
614           if (DominatesMergePoint(PN->getIncomingValue(0), BB) &&
615               DominatesMergePoint(PN->getIncomingValue(1), BB)) {
616             Value *TrueVal =
617               PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
618             Value *FalseVal =
619               PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
620
621             // FIXME: when we have a 'select' statement, we can be completely
622             // generic and clean here and let the instcombine pass clean up
623             // after us, by folding the select instructions away when possible.
624             //
625             if (TrueVal == FalseVal) {
626               // Degenerate case...
627               PN->replaceAllUsesWith(TrueVal);
628               BB->getInstList().erase(PN);
629               Changed = true;
630             } else if (isa<ConstantBool>(TrueVal) &&
631                        isa<ConstantBool>(FalseVal)) {
632               if (TrueVal == ConstantBool::True) {
633                 // The PHI node produces the same thing as the condition.
634                 PN->replaceAllUsesWith(IfCond);
635               } else {
636                 // The PHI node produces the inverse of the condition.  Insert a
637                 // "NOT" instruction, which is really a XOR.
638                 Value *InverseCond =
639                   BinaryOperator::createNot(IfCond, IfCond->getName()+".inv",
640                                             AfterPHIIt);
641                 PN->replaceAllUsesWith(InverseCond);
642               }
643               BB->getInstList().erase(PN);
644               Changed = true;
645             } else if (isa<ConstantInt>(TrueVal) && isa<ConstantInt>(FalseVal)){
646               // If this is a PHI of two constant integers, we insert a cast of
647               // the boolean to the integer type in question, giving us 0 or 1.
648               // Then we multiply this by the difference of the two constants,
649               // giving us 0 if false, and the difference if true.  We add this
650               // result to the base constant, giving us our final value.  We
651               // rely on the instruction combiner to eliminate many special
652               // cases, like turning multiplies into shifts when possible.
653               std::string Name = PN->getName(); PN->setName("");
654               Value *TheCast = new CastInst(IfCond, TrueVal->getType(),
655                                             Name, AfterPHIIt);
656               Constant *TheDiff = ConstantExpr::get(Instruction::Sub,
657                                                     cast<Constant>(TrueVal),
658                                                     cast<Constant>(FalseVal));
659               Value *V = TheCast;
660               if (TheDiff != ConstantInt::get(TrueVal->getType(), 1))
661                 V = BinaryOperator::create(Instruction::Mul, TheCast,
662                                            TheDiff, TheCast->getName()+".scale",
663                                            AfterPHIIt);
664               if (!cast<Constant>(FalseVal)->isNullValue())
665                 V = BinaryOperator::create(Instruction::Add, V, FalseVal,
666                                            V->getName()+".offs", AfterPHIIt);
667               PN->replaceAllUsesWith(V);
668               BB->getInstList().erase(PN);
669               Changed = true;
670             } else if (isa<ConstantInt>(FalseVal) &&
671                        cast<Constant>(FalseVal)->isNullValue()) {
672               // If the false condition is an integral zero value, we can
673               // compute the PHI by multiplying the condition by the other
674               // value.
675               std::string Name = PN->getName(); PN->setName("");
676               Value *TheCast = new CastInst(IfCond, TrueVal->getType(),
677                                             Name+".c", AfterPHIIt);
678               Value *V = BinaryOperator::create(Instruction::Mul, TrueVal,
679                                                 TheCast, Name, AfterPHIIt);
680               PN->replaceAllUsesWith(V);
681               BB->getInstList().erase(PN);
682               Changed = true;
683             } else if (isa<ConstantInt>(TrueVal) &&
684                        cast<Constant>(TrueVal)->isNullValue()) {
685               // If the true condition is an integral zero value, we can compute
686               // the PHI by multiplying the inverse condition by the other
687               // value.
688               std::string Name = PN->getName(); PN->setName("");
689               Value *NotCond = BinaryOperator::createNot(IfCond, Name+".inv",
690                                                          AfterPHIIt);
691               Value *TheCast = new CastInst(NotCond, TrueVal->getType(),
692                                             Name+".inv", AfterPHIIt);
693               Value *V = BinaryOperator::create(Instruction::Mul, FalseVal,
694                                                 TheCast, Name, AfterPHIIt);
695               PN->replaceAllUsesWith(V);
696               BB->getInstList().erase(PN);
697               Changed = true;
698             }
699           }
700         }
701       }
702     }
703   
704   return Changed;
705 }