Fix SimplifyCFG/2005-12-03-IncorrectPHIFold.ll
[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 #define DEBUG_TYPE "simplifycfg"
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Type.h"
19 #include "llvm/Support/CFG.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
22 #include <algorithm>
23 #include <functional>
24 #include <set>
25 #include <map>
26 using namespace llvm;
27
28 /// SafeToMergeTerminators - Return true if it is safe to merge these two
29 /// terminator instructions together.
30 ///
31 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
32   if (SI1 == SI2) return false;  // Can't merge with self!
33   
34   // It is not safe to merge these two switch instructions if they have a common
35   // successor, and if that successor has a PHI node, and if *that* PHI node has
36   // conflicting incoming values from the two switch blocks.
37   BasicBlock *SI1BB = SI1->getParent();
38   BasicBlock *SI2BB = SI2->getParent();
39   std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
40   
41   for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
42     if (SI1Succs.count(*I))
43       for (BasicBlock::iterator BBI = (*I)->begin();
44            isa<PHINode>(BBI); ++BBI) {
45         PHINode *PN = cast<PHINode>(BBI);
46         if (PN->getIncomingValueForBlock(SI1BB) !=
47             PN->getIncomingValueForBlock(SI2BB))
48           return false;
49       }
50         
51   return true;
52 }
53
54 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
55 /// now be entries in it from the 'NewPred' block.  The values that will be
56 /// flowing into the PHI nodes will be the same as those coming in from
57 /// ExistPred, an existing predecessor of Succ.
58 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
59                                   BasicBlock *ExistPred) {
60   assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
61          succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
62   if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
63   
64   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
65     PHINode *PN = cast<PHINode>(I);
66     Value *V = PN->getIncomingValueForBlock(ExistPred);
67     PN->addIncoming(V, NewPred);
68   }
69 }
70
71 // CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
72 // almost-empty BB ending in an unconditional branch to Succ, into succ.
73 //
74 // Assumption: Succ is the single successor for BB.
75 //
76 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
77   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
78
79   // Check to see if one of the predecessors of BB is already a predecessor of
80   // Succ.  If so, we cannot do the transformation if there are any PHI nodes
81   // with incompatible values coming in from the two edges!
82   //
83   if (isa<PHINode>(Succ->front())) {
84     std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
85     for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
86          PI != PE; ++PI)
87       if (std::find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
88         // Loop over all of the PHI nodes checking to see if there are
89         // incompatible values coming in.
90         for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
91           PHINode *PN = cast<PHINode>(I);
92           // Loop up the entries in the PHI node for BB and for *PI if the
93           // values coming in are non-equal, we cannot merge these two blocks
94           // (instead we should insert a conditional move or something, then
95           // merge the blocks).
96           if (PN->getIncomingValueForBlock(BB) !=
97               PN->getIncomingValueForBlock(*PI))
98             return false;  // Values are not equal...
99         }
100       }
101   }
102     
103   // Finally, if BB has PHI nodes that are used by things other than the PHIs in
104   // Succ and Succ has predecessors that are not Succ and not Pred, we cannot
105   // fold these blocks, as we don't know whether BB dominates Succ or not to
106   // update the PHI nodes correctly.
107   if (!isa<PHINode>(BB->begin()) || Succ->getSinglePredecessor()) return true;
108
109   // If the predecessors of Succ are only BB and Succ itself, we can handle this.
110   bool IsSafe = true;
111   for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
112     if (*PI != Succ && *PI != BB) {
113       IsSafe = false;
114       break;
115     }
116   if (IsSafe) return true;
117   
118   // If the PHI nodes in BB are only used by instructions in Succ, we are ok if
119   // BB and Succ have no common predecessors.
120   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I) && IsSafe; ++I) {
121     PHINode *PN = cast<PHINode>(I);
122     for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E;
123          ++UI)
124       if (cast<Instruction>(*UI)->getParent() != Succ)
125         return false;
126   }
127   
128   // Scan the predecessor sets of BB and Succ, making sure there are no common
129   // predecessors.  Common predecessors would cause us to build a phi node with
130   // differing incoming values, which is not legal.
131   std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
132   for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
133     if (BBPreds.count(*PI))
134       return false;
135     
136   return true;
137 }
138
139 /// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
140 /// branch to Succ, and contains no instructions other than PHI nodes and the
141 /// branch.  If possible, eliminate BB.
142 static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
143                                                     BasicBlock *Succ) {
144   // If our successor has PHI nodes, then we need to update them to include
145   // entries for BB's predecessors, not for BB itself.  Be careful though,
146   // if this transformation fails (returns true) then we cannot do this
147   // transformation!
148   //
149   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
150   
151   DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB);
152   
153   if (isa<PHINode>(Succ->begin())) {
154     // If there is more than one pred of succ, and there are PHI nodes in
155     // the successor, then we need to add incoming edges for the PHI nodes
156     //
157     const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
158     
159     // Loop over all of the PHI nodes in the successor of BB.
160     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
161       PHINode *PN = cast<PHINode>(I);
162       Value *OldVal = PN->removeIncomingValue(BB, false);
163       assert(OldVal && "No entry in PHI for Pred BB!");
164       
165       // If this incoming value is one of the PHI nodes in BB, the new entries
166       // in the PHI node are the entries from the old PHI.
167       if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
168         PHINode *OldValPN = cast<PHINode>(OldVal);
169         for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
170           PN->addIncoming(OldValPN->getIncomingValue(i),
171                           OldValPN->getIncomingBlock(i));
172       } else {
173         for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
174              End = BBPreds.end(); PredI != End; ++PredI) {
175           // Add an incoming value for each of the new incoming values...
176           PN->addIncoming(OldVal, *PredI);
177         }
178       }
179     }
180   }
181   
182   if (isa<PHINode>(&BB->front())) {
183     std::vector<BasicBlock*>
184     OldSuccPreds(pred_begin(Succ), pred_end(Succ));
185     
186     // Move all PHI nodes in BB to Succ if they are alive, otherwise
187     // delete them.
188     while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
189       if (PN->use_empty()) {
190         // Just remove the dead phi.  This happens if Succ's PHIs were the only
191         // users of the PHI nodes.
192         PN->eraseFromParent();
193       } else {
194         // The instruction is alive, so this means that Succ must have
195         // *ONLY* had BB as a predecessor, and the PHI node is still valid
196         // now.  Simply move it into Succ, because we know that BB
197         // strictly dominated Succ.
198         Succ->getInstList().splice(Succ->begin(),
199                                    BB->getInstList(), BB->begin());
200         
201         // We need to add new entries for the PHI node to account for
202         // predecessors of Succ that the PHI node does not take into
203         // account.  At this point, since we know that BB dominated succ,
204         // this means that we should any newly added incoming edges should
205         // use the PHI node as the value for these edges, because they are
206         // loop back edges.
207         for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
208           if (OldSuccPreds[i] != BB)
209             PN->addIncoming(PN, OldSuccPreds[i]);
210       }
211   }
212     
213   // Everything that jumped to BB now goes to Succ.
214   std::string OldName = BB->getName();
215   BB->replaceAllUsesWith(Succ);
216   BB->eraseFromParent();              // Delete the old basic block.
217   
218   if (!OldName.empty() && !Succ->hasName())  // Transfer name if we can
219     Succ->setName(OldName);
220   return true;
221 }
222
223 /// GetIfCondition - Given a basic block (BB) with two predecessors (and
224 /// presumably PHI nodes in it), check to see if the merge at this block is due
225 /// to an "if condition".  If so, return the boolean condition that determines
226 /// which entry into BB will be taken.  Also, return by references the block
227 /// that will be entered from if the condition is true, and the block that will
228 /// be entered if the condition is false.
229 ///
230 ///
231 static Value *GetIfCondition(BasicBlock *BB,
232                              BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
233   assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
234          "Function can only handle blocks with 2 predecessors!");
235   BasicBlock *Pred1 = *pred_begin(BB);
236   BasicBlock *Pred2 = *++pred_begin(BB);
237
238   // We can only handle branches.  Other control flow will be lowered to
239   // branches if possible anyway.
240   if (!isa<BranchInst>(Pred1->getTerminator()) ||
241       !isa<BranchInst>(Pred2->getTerminator()))
242     return 0;
243   BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
244   BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
245
246   // Eliminate code duplication by ensuring that Pred1Br is conditional if
247   // either are.
248   if (Pred2Br->isConditional()) {
249     // If both branches are conditional, we don't have an "if statement".  In
250     // reality, we could transform this case, but since the condition will be
251     // required anyway, we stand no chance of eliminating it, so the xform is
252     // probably not profitable.
253     if (Pred1Br->isConditional())
254       return 0;
255
256     std::swap(Pred1, Pred2);
257     std::swap(Pred1Br, Pred2Br);
258   }
259
260   if (Pred1Br->isConditional()) {
261     // If we found a conditional branch predecessor, make sure that it branches
262     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
263     if (Pred1Br->getSuccessor(0) == BB &&
264         Pred1Br->getSuccessor(1) == Pred2) {
265       IfTrue = Pred1;
266       IfFalse = Pred2;
267     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
268                Pred1Br->getSuccessor(1) == BB) {
269       IfTrue = Pred2;
270       IfFalse = Pred1;
271     } else {
272       // We know that one arm of the conditional goes to BB, so the other must
273       // go somewhere unrelated, and this must not be an "if statement".
274       return 0;
275     }
276
277     // The only thing we have to watch out for here is to make sure that Pred2
278     // doesn't have incoming edges from other blocks.  If it does, the condition
279     // doesn't dominate BB.
280     if (++pred_begin(Pred2) != pred_end(Pred2))
281       return 0;
282
283     return Pred1Br->getCondition();
284   }
285
286   // Ok, if we got here, both predecessors end with an unconditional branch to
287   // BB.  Don't panic!  If both blocks only have a single (identical)
288   // predecessor, and THAT is a conditional branch, then we're all ok!
289   if (pred_begin(Pred1) == pred_end(Pred1) ||
290       ++pred_begin(Pred1) != pred_end(Pred1) ||
291       pred_begin(Pred2) == pred_end(Pred2) ||
292       ++pred_begin(Pred2) != pred_end(Pred2) ||
293       *pred_begin(Pred1) != *pred_begin(Pred2))
294     return 0;
295
296   // Otherwise, if this is a conditional branch, then we can use it!
297   BasicBlock *CommonPred = *pred_begin(Pred1);
298   if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
299     assert(BI->isConditional() && "Two successors but not conditional?");
300     if (BI->getSuccessor(0) == Pred1) {
301       IfTrue = Pred1;
302       IfFalse = Pred2;
303     } else {
304       IfTrue = Pred2;
305       IfFalse = Pred1;
306     }
307     return BI->getCondition();
308   }
309   return 0;
310 }
311
312
313 // If we have a merge point of an "if condition" as accepted above, return true
314 // if the specified value dominates the block.  We don't handle the true
315 // generality of domination here, just a special case which works well enough
316 // for us.
317 //
318 // If AggressiveInsts is non-null, and if V does not dominate BB, we check to
319 // see if V (which must be an instruction) is cheap to compute and is
320 // non-trapping.  If both are true, the instruction is inserted into the set and
321 // true is returned.
322 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
323                                 std::set<Instruction*> *AggressiveInsts) {
324   Instruction *I = dyn_cast<Instruction>(V);
325   if (!I) return true;    // Non-instructions all dominate instructions.
326   BasicBlock *PBB = I->getParent();
327
328   // We don't want to allow weird loops that might have the "if condition" in
329   // the bottom of this block.
330   if (PBB == BB) return false;
331
332   // If this instruction is defined in a block that contains an unconditional
333   // branch to BB, then it must be in the 'conditional' part of the "if
334   // statement".
335   if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
336     if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
337       if (!AggressiveInsts) return false;
338       // Okay, it looks like the instruction IS in the "condition".  Check to
339       // see if its a cheap instruction to unconditionally compute, and if it
340       // only uses stuff defined outside of the condition.  If so, hoist it out.
341       switch (I->getOpcode()) {
342       default: return false;  // Cannot hoist this out safely.
343       case Instruction::Load:
344         // We can hoist loads that are non-volatile and obviously cannot trap.
345         if (cast<LoadInst>(I)->isVolatile())
346           return false;
347         if (!isa<AllocaInst>(I->getOperand(0)) &&
348             !isa<Constant>(I->getOperand(0)))
349           return false;
350
351         // Finally, we have to check to make sure there are no instructions
352         // before the load in its basic block, as we are going to hoist the loop
353         // out to its predecessor.
354         if (PBB->begin() != BasicBlock::iterator(I))
355           return false;
356         break;
357       case Instruction::Add:
358       case Instruction::Sub:
359       case Instruction::And:
360       case Instruction::Or:
361       case Instruction::Xor:
362       case Instruction::Shl:
363       case Instruction::Shr:
364       case Instruction::SetEQ:
365       case Instruction::SetNE:
366       case Instruction::SetLT:
367       case Instruction::SetGT:
368       case Instruction::SetLE:
369       case Instruction::SetGE:
370         break;   // These are all cheap and non-trapping instructions.
371       }
372
373       // Okay, we can only really hoist these out if their operands are not
374       // defined in the conditional region.
375       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
376         if (!DominatesMergePoint(I->getOperand(i), BB, 0))
377           return false;
378       // Okay, it's safe to do this!  Remember this instruction.
379       AggressiveInsts->insert(I);
380     }
381
382   return true;
383 }
384
385 // GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq
386 // instructions that compare a value against a constant, return the value being
387 // compared, and stick the constant into the Values vector.
388 static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
389   if (Instruction *Inst = dyn_cast<Instruction>(V))
390     if (Inst->getOpcode() == Instruction::SetEQ) {
391       if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
392         Values.push_back(C);
393         return Inst->getOperand(0);
394       } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
395         Values.push_back(C);
396         return Inst->getOperand(1);
397       }
398     } else if (Inst->getOpcode() == Instruction::Or) {
399       if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
400         if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
401           if (LHS == RHS)
402             return LHS;
403     }
404   return 0;
405 }
406
407 // GatherConstantSetNEs - Given a potentially 'and'd together collection of
408 // setne instructions that compare a value against a constant, return the value
409 // being compared, and stick the constant into the Values vector.
410 static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
411   if (Instruction *Inst = dyn_cast<Instruction>(V))
412     if (Inst->getOpcode() == Instruction::SetNE) {
413       if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
414         Values.push_back(C);
415         return Inst->getOperand(0);
416       } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
417         Values.push_back(C);
418         return Inst->getOperand(1);
419       }
420     } else if (Inst->getOpcode() == Instruction::Cast) {
421       // Cast of X to bool is really a comparison against zero.
422       assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!");
423       Values.push_back(ConstantInt::get(Inst->getOperand(0)->getType(), 0));
424       return Inst->getOperand(0);
425     } else if (Inst->getOpcode() == Instruction::And) {
426       if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
427         if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
428           if (LHS == RHS)
429             return LHS;
430     }
431   return 0;
432 }
433
434
435
436 /// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
437 /// bunch of comparisons of one value against constants, return the value and
438 /// the constants being compared.
439 static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
440                                    std::vector<ConstantInt*> &Values) {
441   if (Cond->getOpcode() == Instruction::Or) {
442     CompVal = GatherConstantSetEQs(Cond, Values);
443
444     // Return true to indicate that the condition is true if the CompVal is
445     // equal to one of the constants.
446     return true;
447   } else if (Cond->getOpcode() == Instruction::And) {
448     CompVal = GatherConstantSetNEs(Cond, Values);
449
450     // Return false to indicate that the condition is false if the CompVal is
451     // equal to one of the constants.
452     return false;
453   }
454   return false;
455 }
456
457 /// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
458 /// has no side effects, nuke it.  If it uses any instructions that become dead
459 /// because the instruction is now gone, nuke them too.
460 static void ErasePossiblyDeadInstructionTree(Instruction *I) {
461   if (isInstructionTriviallyDead(I)) {
462     std::vector<Value*> Operands(I->op_begin(), I->op_end());
463     I->getParent()->getInstList().erase(I);
464     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
465       if (Instruction *OpI = dyn_cast<Instruction>(Operands[i]))
466         ErasePossiblyDeadInstructionTree(OpI);
467   }
468 }
469
470 // isValueEqualityComparison - Return true if the specified terminator checks to
471 // see if a value is equal to constant integer value.
472 static Value *isValueEqualityComparison(TerminatorInst *TI) {
473   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
474     // Do not permit merging of large switch instructions into their
475     // predecessors unless there is only one predecessor.
476     if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
477                                                pred_end(SI->getParent())) > 128)
478       return 0;
479
480     return SI->getCondition();
481   }
482   if (BranchInst *BI = dyn_cast<BranchInst>(TI))
483     if (BI->isConditional() && BI->getCondition()->hasOneUse())
484       if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
485         if ((SCI->getOpcode() == Instruction::SetEQ ||
486              SCI->getOpcode() == Instruction::SetNE) &&
487             isa<ConstantInt>(SCI->getOperand(1)))
488           return SCI->getOperand(0);
489   return 0;
490 }
491
492 // Given a value comparison instruction, decode all of the 'cases' that it
493 // represents and return the 'default' block.
494 static BasicBlock *
495 GetValueEqualityComparisonCases(TerminatorInst *TI,
496                                 std::vector<std::pair<ConstantInt*,
497                                                       BasicBlock*> > &Cases) {
498   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
499     Cases.reserve(SI->getNumCases());
500     for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
501       Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
502     return SI->getDefaultDest();
503   }
504
505   BranchInst *BI = cast<BranchInst>(TI);
506   SetCondInst *SCI = cast<SetCondInst>(BI->getCondition());
507   Cases.push_back(std::make_pair(cast<ConstantInt>(SCI->getOperand(1)),
508                                  BI->getSuccessor(SCI->getOpcode() ==
509                                                         Instruction::SetNE)));
510   return BI->getSuccessor(SCI->getOpcode() == Instruction::SetEQ);
511 }
512
513
514 // EliminateBlockCases - Given an vector of bb/value pairs, remove any entries
515 // in the list that match the specified block.
516 static void EliminateBlockCases(BasicBlock *BB,
517                std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
518   for (unsigned i = 0, e = Cases.size(); i != e; ++i)
519     if (Cases[i].second == BB) {
520       Cases.erase(Cases.begin()+i);
521       --i; --e;
522     }
523 }
524
525 // ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
526 // well.
527 static bool
528 ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
529               std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
530   std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
531
532   // Make V1 be smaller than V2.
533   if (V1->size() > V2->size())
534     std::swap(V1, V2);
535
536   if (V1->size() == 0) return false;
537   if (V1->size() == 1) {
538     // Just scan V2.
539     ConstantInt *TheVal = (*V1)[0].first;
540     for (unsigned i = 0, e = V2->size(); i != e; ++i)
541       if (TheVal == (*V2)[i].first)
542         return true;
543   }
544
545   // Otherwise, just sort both lists and compare element by element.
546   std::sort(V1->begin(), V1->end());
547   std::sort(V2->begin(), V2->end());
548   unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
549   while (i1 != e1 && i2 != e2) {
550     if ((*V1)[i1].first == (*V2)[i2].first)
551       return true;
552     if ((*V1)[i1].first < (*V2)[i2].first)
553       ++i1;
554     else
555       ++i2;
556   }
557   return false;
558 }
559
560 // SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
561 // terminator instruction and its block is known to only have a single
562 // predecessor block, check to see if that predecessor is also a value
563 // comparison with the same value, and if that comparison determines the outcome
564 // of this comparison.  If so, simplify TI.  This does a very limited form of
565 // jump threading.
566 static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
567                                                           BasicBlock *Pred) {
568   Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
569   if (!PredVal) return false;  // Not a value comparison in predecessor.
570
571   Value *ThisVal = isValueEqualityComparison(TI);
572   assert(ThisVal && "This isn't a value comparison!!");
573   if (ThisVal != PredVal) return false;  // Different predicates.
574
575   // Find out information about when control will move from Pred to TI's block.
576   std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
577   BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
578                                                         PredCases);
579   EliminateBlockCases(PredDef, PredCases);  // Remove default from cases.
580
581   // Find information about how control leaves this block.
582   std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
583   BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
584   EliminateBlockCases(ThisDef, ThisCases);  // Remove default from cases.
585
586   // If TI's block is the default block from Pred's comparison, potentially
587   // simplify TI based on this knowledge.
588   if (PredDef == TI->getParent()) {
589     // If we are here, we know that the value is none of those cases listed in
590     // PredCases.  If there are any cases in ThisCases that are in PredCases, we
591     // can simplify TI.
592     if (ValuesOverlap(PredCases, ThisCases)) {
593       if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) {
594         // Okay, one of the successors of this condbr is dead.  Convert it to a
595         // uncond br.
596         assert(ThisCases.size() == 1 && "Branch can only have one case!");
597         Value *Cond = BTI->getCondition();
598         // Insert the new branch.
599         Instruction *NI = new BranchInst(ThisDef, TI);
600
601         // Remove PHI node entries for the dead edge.
602         ThisCases[0].second->removePredecessor(TI->getParent());
603
604         DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
605               << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
606
607         TI->eraseFromParent();   // Nuke the old one.
608         // If condition is now dead, nuke it.
609         if (Instruction *CondI = dyn_cast<Instruction>(Cond))
610           ErasePossiblyDeadInstructionTree(CondI);
611         return true;
612
613       } else {
614         SwitchInst *SI = cast<SwitchInst>(TI);
615         // Okay, TI has cases that are statically dead, prune them away.
616         std::set<Constant*> DeadCases;
617         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
618           DeadCases.insert(PredCases[i].first);
619
620         DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
621                   << "Through successor TI: " << *TI);
622
623         for (unsigned i = SI->getNumCases()-1; i != 0; --i)
624           if (DeadCases.count(SI->getCaseValue(i))) {
625             SI->getSuccessor(i)->removePredecessor(TI->getParent());
626             SI->removeCase(i);
627           }
628
629         DEBUG(std::cerr << "Leaving: " << *TI << "\n");
630         return true;
631       }
632     }
633
634   } else {
635     // Otherwise, TI's block must correspond to some matched value.  Find out
636     // which value (or set of values) this is.
637     ConstantInt *TIV = 0;
638     BasicBlock *TIBB = TI->getParent();
639     for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
640       if (PredCases[i].second == TIBB)
641         if (TIV == 0)
642           TIV = PredCases[i].first;
643         else
644           return false;  // Cannot handle multiple values coming to this block.
645     assert(TIV && "No edge from pred to succ?");
646
647     // Okay, we found the one constant that our value can be if we get into TI's
648     // BB.  Find out which successor will unconditionally be branched to.
649     BasicBlock *TheRealDest = 0;
650     for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
651       if (ThisCases[i].first == TIV) {
652         TheRealDest = ThisCases[i].second;
653         break;
654       }
655
656     // If not handled by any explicit cases, it is handled by the default case.
657     if (TheRealDest == 0) TheRealDest = ThisDef;
658
659     // Remove PHI node entries for dead edges.
660     BasicBlock *CheckEdge = TheRealDest;
661     for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
662       if (*SI != CheckEdge)
663         (*SI)->removePredecessor(TIBB);
664       else
665         CheckEdge = 0;
666
667     // Insert the new branch.
668     Instruction *NI = new BranchInst(TheRealDest, TI);
669
670     DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
671           << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
672     Instruction *Cond = 0;
673     if (BranchInst *BI = dyn_cast<BranchInst>(TI))
674       Cond = dyn_cast<Instruction>(BI->getCondition());
675     TI->eraseFromParent();   // Nuke the old one.
676
677     if (Cond) ErasePossiblyDeadInstructionTree(Cond);
678     return true;
679   }
680   return false;
681 }
682
683 // FoldValueComparisonIntoPredecessors - The specified terminator is a value
684 // equality comparison instruction (either a switch or a branch on "X == c").
685 // See if any of the predecessors of the terminator block are value comparisons
686 // on the same value.  If so, and if safe to do so, fold them together.
687 static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
688   BasicBlock *BB = TI->getParent();
689   Value *CV = isValueEqualityComparison(TI);  // CondVal
690   assert(CV && "Not a comparison?");
691   bool Changed = false;
692
693   std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
694   while (!Preds.empty()) {
695     BasicBlock *Pred = Preds.back();
696     Preds.pop_back();
697
698     // See if the predecessor is a comparison with the same value.
699     TerminatorInst *PTI = Pred->getTerminator();
700     Value *PCV = isValueEqualityComparison(PTI);  // PredCondVal
701
702     if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
703       // Figure out which 'cases' to copy from SI to PSI.
704       std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
705       BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
706
707       std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
708       BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
709
710       // Based on whether the default edge from PTI goes to BB or not, fill in
711       // PredCases and PredDefault with the new switch cases we would like to
712       // build.
713       std::vector<BasicBlock*> NewSuccessors;
714
715       if (PredDefault == BB) {
716         // If this is the default destination from PTI, only the edges in TI
717         // that don't occur in PTI, or that branch to BB will be activated.
718         std::set<ConstantInt*> PTIHandled;
719         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
720           if (PredCases[i].second != BB)
721             PTIHandled.insert(PredCases[i].first);
722           else {
723             // The default destination is BB, we don't need explicit targets.
724             std::swap(PredCases[i], PredCases.back());
725             PredCases.pop_back();
726             --i; --e;
727           }
728
729         // Reconstruct the new switch statement we will be building.
730         if (PredDefault != BBDefault) {
731           PredDefault->removePredecessor(Pred);
732           PredDefault = BBDefault;
733           NewSuccessors.push_back(BBDefault);
734         }
735         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
736           if (!PTIHandled.count(BBCases[i].first) &&
737               BBCases[i].second != BBDefault) {
738             PredCases.push_back(BBCases[i]);
739             NewSuccessors.push_back(BBCases[i].second);
740           }
741
742       } else {
743         // If this is not the default destination from PSI, only the edges
744         // in SI that occur in PSI with a destination of BB will be
745         // activated.
746         std::set<ConstantInt*> PTIHandled;
747         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
748           if (PredCases[i].second == BB) {
749             PTIHandled.insert(PredCases[i].first);
750             std::swap(PredCases[i], PredCases.back());
751             PredCases.pop_back();
752             --i; --e;
753           }
754
755         // Okay, now we know which constants were sent to BB from the
756         // predecessor.  Figure out where they will all go now.
757         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
758           if (PTIHandled.count(BBCases[i].first)) {
759             // If this is one we are capable of getting...
760             PredCases.push_back(BBCases[i]);
761             NewSuccessors.push_back(BBCases[i].second);
762             PTIHandled.erase(BBCases[i].first);// This constant is taken care of
763           }
764
765         // If there are any constants vectored to BB that TI doesn't handle,
766         // they must go to the default destination of TI.
767         for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
768                E = PTIHandled.end(); I != E; ++I) {
769           PredCases.push_back(std::make_pair(*I, BBDefault));
770           NewSuccessors.push_back(BBDefault);
771         }
772       }
773
774       // Okay, at this point, we know which new successor Pred will get.  Make
775       // sure we update the number of entries in the PHI nodes for these
776       // successors.
777       for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
778         AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
779
780       // Now that the successors are updated, create the new Switch instruction.
781       SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI);
782       for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
783         NewSI->addCase(PredCases[i].first, PredCases[i].second);
784
785       Instruction *DeadCond = 0;
786       if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
787         // If PTI is a branch, remember the condition.
788         DeadCond = dyn_cast<Instruction>(BI->getCondition());
789       Pred->getInstList().erase(PTI);
790
791       // If the condition is dead now, remove the instruction tree.
792       if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond);
793
794       // Okay, last check.  If BB is still a successor of PSI, then we must
795       // have an infinite loop case.  If so, add an infinitely looping block
796       // to handle the case to preserve the behavior of the code.
797       BasicBlock *InfLoopBlock = 0;
798       for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
799         if (NewSI->getSuccessor(i) == BB) {
800           if (InfLoopBlock == 0) {
801             // Insert it at the end of the loop, because it's either code,
802             // or it won't matter if it's hot. :)
803             InfLoopBlock = new BasicBlock("infloop", BB->getParent());
804             new BranchInst(InfLoopBlock, InfLoopBlock);
805           }
806           NewSI->setSuccessor(i, InfLoopBlock);
807         }
808
809       Changed = true;
810     }
811   }
812   return Changed;
813 }
814
815 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
816 /// BB2, hoist any common code in the two blocks up into the branch block.  The
817 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
818 static bool HoistThenElseCodeToIf(BranchInst *BI) {
819   // This does very trivial matching, with limited scanning, to find identical
820   // instructions in the two blocks.  In particular, we don't want to get into
821   // O(M*N) situations here where M and N are the sizes of BB1 and BB2.  As
822   // such, we currently just scan for obviously identical instructions in an
823   // identical order.
824   BasicBlock *BB1 = BI->getSuccessor(0);  // The true destination.
825   BasicBlock *BB2 = BI->getSuccessor(1);  // The false destination
826
827   Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
828   if (I1->getOpcode() != I2->getOpcode() || !I1->isIdenticalTo(I2) ||
829       isa<PHINode>(I1))
830     return false;
831
832   // If we get here, we can hoist at least one instruction.
833   BasicBlock *BIParent = BI->getParent();
834
835   do {
836     // If we are hoisting the terminator instruction, don't move one (making a
837     // broken BB), instead clone it, and remove BI.
838     if (isa<TerminatorInst>(I1))
839       goto HoistTerminator;
840
841     // For a normal instruction, we just move one to right before the branch,
842     // then replace all uses of the other with the first.  Finally, we remove
843     // the now redundant second instruction.
844     BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
845     if (!I2->use_empty())
846       I2->replaceAllUsesWith(I1);
847     BB2->getInstList().erase(I2);
848
849     I1 = BB1->begin();
850     I2 = BB2->begin();
851   } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
852
853   return true;
854
855 HoistTerminator:
856   // Okay, it is safe to hoist the terminator.
857   Instruction *NT = I1->clone();
858   BIParent->getInstList().insert(BI, NT);
859   if (NT->getType() != Type::VoidTy) {
860     I1->replaceAllUsesWith(NT);
861     I2->replaceAllUsesWith(NT);
862     NT->setName(I1->getName());
863   }
864
865   // Hoisting one of the terminators from our successor is a great thing.
866   // Unfortunately, the successors of the if/else blocks may have PHI nodes in
867   // them.  If they do, all PHI entries for BB1/BB2 must agree for all PHI
868   // nodes, so we insert select instruction to compute the final result.
869   std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
870   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
871     PHINode *PN;
872     for (BasicBlock::iterator BBI = SI->begin();
873          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
874       Value *BB1V = PN->getIncomingValueForBlock(BB1);
875       Value *BB2V = PN->getIncomingValueForBlock(BB2);
876       if (BB1V != BB2V) {
877         // These values do not agree.  Insert a select instruction before NT
878         // that determines the right value.
879         SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
880         if (SI == 0)
881           SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
882                               BB1V->getName()+"."+BB2V->getName(), NT);
883         // Make the PHI node use the select for all incoming values for BB1/BB2
884         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
885           if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
886             PN->setIncomingValue(i, SI);
887       }
888     }
889   }
890
891   // Update any PHI nodes in our new successors.
892   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
893     AddPredecessorToBlock(*SI, BIParent, BB1);
894
895   BI->eraseFromParent();
896   return true;
897 }
898
899 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
900 /// across this block.
901 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
902   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
903   Value *Cond = BI->getCondition();
904   
905   unsigned Size = 0;
906   
907   // If this basic block contains anything other than a PHI (which controls the
908   // branch) and branch itself, bail out.  FIXME: improve this in the future.
909   for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI, ++Size) {
910     if (Size > 10) return false;  // Don't clone large BB's.
911     
912     // We can only support instructions that are do not define values that are
913     // live outside of the current basic block.
914     for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
915          UI != E; ++UI) {
916       Instruction *U = cast<Instruction>(*UI);
917       if (U->getParent() != BB || isa<PHINode>(U)) return false;
918     }
919     
920     // Looks ok, continue checking.
921   }
922
923   return true;
924 }
925
926 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
927 /// that is defined in the same block as the branch and if any PHI entries are
928 /// constants, thread edges corresponding to that entry to be branches to their
929 /// ultimate destination.
930 static bool FoldCondBranchOnPHI(BranchInst *BI) {
931   BasicBlock *BB = BI->getParent();
932   PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
933   // NOTE: we currently cannot transform this case if the PHI node is used
934   // outside of the block.
935   if (!PN || PN->getParent() != BB || !PN->hasOneUse())
936     return false;
937   
938   // Degenerate case of a single entry PHI.
939   if (PN->getNumIncomingValues() == 1) {
940     if (PN->getIncomingValue(0) != PN)
941       PN->replaceAllUsesWith(PN->getIncomingValue(0));
942     else
943       PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
944     PN->eraseFromParent();
945     return true;    
946   }
947
948   // Now we know that this block has multiple preds and two succs.
949   if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
950   
951   // Okay, this is a simple enough basic block.  See if any phi values are
952   // constants.
953   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
954     if (ConstantBool *CB = dyn_cast<ConstantBool>(PN->getIncomingValue(i))) {
955       // Okay, we now know that all edges from PredBB should be revectored to
956       // branch to RealDest.
957       BasicBlock *PredBB = PN->getIncomingBlock(i);
958       BasicBlock *RealDest = BI->getSuccessor(!CB->getValue());
959       
960       if (RealDest == BB) continue;  // Skip self loops.
961       
962       // The dest block might have PHI nodes, other predecessors and other
963       // difficult cases.  Instead of being smart about this, just insert a new
964       // block that jumps to the destination block, effectively splitting
965       // the edge we are about to create.
966       BasicBlock *EdgeBB = new BasicBlock(RealDest->getName()+".critedge",
967                                           RealDest->getParent(), RealDest);
968       new BranchInst(RealDest, EdgeBB);
969       PHINode *PN;
970       for (BasicBlock::iterator BBI = RealDest->begin();
971            (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
972         Value *V = PN->getIncomingValueForBlock(BB);
973         PN->addIncoming(V, EdgeBB);
974       }
975
976       // BB may have instructions that are being threaded over.  Clone these
977       // instructions into EdgeBB.  We know that there will be no uses of the
978       // cloned instructions outside of EdgeBB.
979       BasicBlock::iterator InsertPt = EdgeBB->begin();
980       std::map<Value*, Value*> TranslateMap;  // Track translated values.
981       for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
982         if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
983           TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
984         } else {
985           // Clone the instruction.
986           Instruction *N = BBI->clone();
987           if (BBI->hasName()) N->setName(BBI->getName()+".c");
988           
989           // Update operands due to translation.
990           for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
991             std::map<Value*, Value*>::iterator PI =
992               TranslateMap.find(N->getOperand(i));
993             if (PI != TranslateMap.end())
994               N->setOperand(i, PI->second);
995           }
996           
997           // Check for trivial simplification.
998           if (Constant *C = ConstantFoldInstruction(N)) {
999             TranslateMap[BBI] = C;
1000             delete N;   // Constant folded away, don't need actual inst
1001           } else {
1002             // Insert the new instruction into its new home.
1003             EdgeBB->getInstList().insert(InsertPt, N);
1004             if (!BBI->use_empty())
1005               TranslateMap[BBI] = N;
1006           }
1007         }
1008       }
1009
1010       // Loop over all of the edges from PredBB to BB, changing them to branch
1011       // to EdgeBB instead.
1012       TerminatorInst *PredBBTI = PredBB->getTerminator();
1013       for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1014         if (PredBBTI->getSuccessor(i) == BB) {
1015           BB->removePredecessor(PredBB);
1016           PredBBTI->setSuccessor(i, EdgeBB);
1017         }
1018       
1019       // Recurse, simplifying any other constants.
1020       return FoldCondBranchOnPHI(BI) | true;
1021     }
1022
1023   return false;
1024 }
1025
1026 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1027 /// PHI node, see if we can eliminate it.
1028 static bool FoldTwoEntryPHINode(PHINode *PN) {
1029   // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
1030   // statement", which has a very simple dominance structure.  Basically, we
1031   // are trying to find the condition that is being branched on, which
1032   // subsequently causes this merge to happen.  We really want control
1033   // dependence information for this check, but simplifycfg can't keep it up
1034   // to date, and this catches most of the cases we care about anyway.
1035   //
1036   BasicBlock *BB = PN->getParent();
1037   BasicBlock *IfTrue, *IfFalse;
1038   Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1039   if (!IfCond) return false;
1040   
1041   DEBUG(std::cerr << "FOUND IF CONDITION!  " << *IfCond << "  T: "
1042         << IfTrue->getName() << "  F: " << IfFalse->getName() << "\n");
1043   
1044   // Loop over the PHI's seeing if we can promote them all to select
1045   // instructions.  While we are at it, keep track of the instructions
1046   // that need to be moved to the dominating block.
1047   std::set<Instruction*> AggressiveInsts;
1048   
1049   BasicBlock::iterator AfterPHIIt = BB->begin();
1050   while (isa<PHINode>(AfterPHIIt)) {
1051     PHINode *PN = cast<PHINode>(AfterPHIIt++);
1052     if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1053       if (PN->getIncomingValue(0) != PN)
1054         PN->replaceAllUsesWith(PN->getIncomingValue(0));
1055       else
1056         PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1057     } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1058                                     &AggressiveInsts) ||
1059                !DominatesMergePoint(PN->getIncomingValue(1), BB,
1060                                     &AggressiveInsts)) {
1061       return false;
1062     }
1063   }
1064   
1065   // If we all PHI nodes are promotable, check to make sure that all
1066   // instructions in the predecessor blocks can be promoted as well.  If
1067   // not, we won't be able to get rid of the control flow, so it's not
1068   // worth promoting to select instructions.
1069   BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1070   PN = cast<PHINode>(BB->begin());
1071   BasicBlock *Pred = PN->getIncomingBlock(0);
1072   if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1073     IfBlock1 = Pred;
1074     DomBlock = *pred_begin(Pred);
1075     for (BasicBlock::iterator I = Pred->begin();
1076          !isa<TerminatorInst>(I); ++I)
1077       if (!AggressiveInsts.count(I)) {
1078         // This is not an aggressive instruction that we can promote.
1079         // Because of this, we won't be able to get rid of the control
1080         // flow, so the xform is not worth it.
1081         return false;
1082       }
1083   }
1084     
1085   Pred = PN->getIncomingBlock(1);
1086   if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1087     IfBlock2 = Pred;
1088     DomBlock = *pred_begin(Pred);
1089     for (BasicBlock::iterator I = Pred->begin();
1090          !isa<TerminatorInst>(I); ++I)
1091       if (!AggressiveInsts.count(I)) {
1092         // This is not an aggressive instruction that we can promote.
1093         // Because of this, we won't be able to get rid of the control
1094         // flow, so the xform is not worth it.
1095         return false;
1096       }
1097   }
1098       
1099   // If we can still promote the PHI nodes after this gauntlet of tests,
1100   // do all of the PHI's now.
1101
1102   // Move all 'aggressive' instructions, which are defined in the
1103   // conditional parts of the if's up to the dominating block.
1104   if (IfBlock1) {
1105     DomBlock->getInstList().splice(DomBlock->getTerminator(),
1106                                    IfBlock1->getInstList(),
1107                                    IfBlock1->begin(),
1108                                    IfBlock1->getTerminator());
1109   }
1110   if (IfBlock2) {
1111     DomBlock->getInstList().splice(DomBlock->getTerminator(),
1112                                    IfBlock2->getInstList(),
1113                                    IfBlock2->begin(),
1114                                    IfBlock2->getTerminator());
1115   }
1116   
1117   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1118     // Change the PHI node into a select instruction.
1119     Value *TrueVal =
1120       PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1121     Value *FalseVal =
1122       PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1123     
1124     std::string Name = PN->getName(); PN->setName("");
1125     PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal,
1126                                           Name, AfterPHIIt));
1127     BB->getInstList().erase(PN);
1128   }
1129   return true;
1130 }
1131
1132 namespace {
1133   /// ConstantIntOrdering - This class implements a stable ordering of constant
1134   /// integers that does not depend on their address.  This is important for
1135   /// applications that sort ConstantInt's to ensure uniqueness.
1136   struct ConstantIntOrdering {
1137     bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1138       return LHS->getRawValue() < RHS->getRawValue();
1139     }
1140   };
1141 }
1142
1143 // SimplifyCFG - This function is used to do simplification of a CFG.  For
1144 // example, it adjusts branches to branches to eliminate the extra hop, it
1145 // eliminates unreachable basic blocks, and does other "peephole" optimization
1146 // of the CFG.  It returns true if a modification was made.
1147 //
1148 // WARNING:  The entry node of a function may not be simplified.
1149 //
1150 bool llvm::SimplifyCFG(BasicBlock *BB) {
1151   bool Changed = false;
1152   Function *M = BB->getParent();
1153
1154   assert(BB && BB->getParent() && "Block not embedded in function!");
1155   assert(BB->getTerminator() && "Degenerate basic block encountered!");
1156   assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
1157
1158   // Remove basic blocks that have no predecessors... which are unreachable.
1159   if (pred_begin(BB) == pred_end(BB) ||
1160       *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
1161     DEBUG(std::cerr << "Removing BB: \n" << *BB);
1162
1163     // Loop through all of our successors and make sure they know that one
1164     // of their predecessors is going away.
1165     for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1166       SI->removePredecessor(BB);
1167
1168     while (!BB->empty()) {
1169       Instruction &I = BB->back();
1170       // If this instruction is used, replace uses with an arbitrary
1171       // value.  Because control flow can't get here, we don't care
1172       // what we replace the value with.  Note that since this block is
1173       // unreachable, and all values contained within it must dominate their
1174       // uses, that all uses will eventually be removed.
1175       if (!I.use_empty())
1176         // Make all users of this instruction use undef instead
1177         I.replaceAllUsesWith(UndefValue::get(I.getType()));
1178
1179       // Remove the instruction from the basic block
1180       BB->getInstList().pop_back();
1181     }
1182     M->getBasicBlockList().erase(BB);
1183     return true;
1184   }
1185
1186   // Check to see if we can constant propagate this terminator instruction
1187   // away...
1188   Changed |= ConstantFoldTerminator(BB);
1189
1190   // If this is a returning block with only PHI nodes in it, fold the return
1191   // instruction into any unconditional branch predecessors.
1192   //
1193   // If any predecessor is a conditional branch that just selects among
1194   // different return values, fold the replace the branch/return with a select
1195   // and return.
1196   if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
1197     BasicBlock::iterator BBI = BB->getTerminator();
1198     if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
1199       // Find predecessors that end with branches.
1200       std::vector<BasicBlock*> UncondBranchPreds;
1201       std::vector<BranchInst*> CondBranchPreds;
1202       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1203         TerminatorInst *PTI = (*PI)->getTerminator();
1204         if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
1205           if (BI->isUnconditional())
1206             UncondBranchPreds.push_back(*PI);
1207           else
1208             CondBranchPreds.push_back(BI);
1209       }
1210
1211       // If we found some, do the transformation!
1212       if (!UncondBranchPreds.empty()) {
1213         while (!UncondBranchPreds.empty()) {
1214           BasicBlock *Pred = UncondBranchPreds.back();
1215           DEBUG(std::cerr << "FOLDING: " << *BB
1216                           << "INTO UNCOND BRANCH PRED: " << *Pred);
1217           UncondBranchPreds.pop_back();
1218           Instruction *UncondBranch = Pred->getTerminator();
1219           // Clone the return and add it to the end of the predecessor.
1220           Instruction *NewRet = RI->clone();
1221           Pred->getInstList().push_back(NewRet);
1222
1223           // If the return instruction returns a value, and if the value was a
1224           // PHI node in "BB", propagate the right value into the return.
1225           if (NewRet->getNumOperands() == 1)
1226             if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
1227               if (PN->getParent() == BB)
1228                 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
1229           // Update any PHI nodes in the returning block to realize that we no
1230           // longer branch to them.
1231           BB->removePredecessor(Pred);
1232           Pred->getInstList().erase(UncondBranch);
1233         }
1234
1235         // If we eliminated all predecessors of the block, delete the block now.
1236         if (pred_begin(BB) == pred_end(BB))
1237           // We know there are no successors, so just nuke the block.
1238           M->getBasicBlockList().erase(BB);
1239
1240         return true;
1241       }
1242
1243       // Check out all of the conditional branches going to this return
1244       // instruction.  If any of them just select between returns, change the
1245       // branch itself into a select/return pair.
1246       while (!CondBranchPreds.empty()) {
1247         BranchInst *BI = CondBranchPreds.back();
1248         CondBranchPreds.pop_back();
1249         BasicBlock *TrueSucc = BI->getSuccessor(0);
1250         BasicBlock *FalseSucc = BI->getSuccessor(1);
1251         BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
1252
1253         // Check to see if the non-BB successor is also a return block.
1254         if (isa<ReturnInst>(OtherSucc->getTerminator())) {
1255           // Check to see if there are only PHI instructions in this block.
1256           BasicBlock::iterator OSI = OtherSucc->getTerminator();
1257           if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
1258             // Okay, we found a branch that is going to two return nodes.  If
1259             // there is no return value for this function, just change the
1260             // branch into a return.
1261             if (RI->getNumOperands() == 0) {
1262               TrueSucc->removePredecessor(BI->getParent());
1263               FalseSucc->removePredecessor(BI->getParent());
1264               new ReturnInst(0, BI);
1265               BI->getParent()->getInstList().erase(BI);
1266               return true;
1267             }
1268
1269             // Otherwise, figure out what the true and false return values are
1270             // so we can insert a new select instruction.
1271             Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
1272             Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
1273
1274             // Unwrap any PHI nodes in the return blocks.
1275             if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
1276               if (TVPN->getParent() == TrueSucc)
1277                 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1278             if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
1279               if (FVPN->getParent() == FalseSucc)
1280                 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1281
1282             TrueSucc->removePredecessor(BI->getParent());
1283             FalseSucc->removePredecessor(BI->getParent());
1284
1285             // Insert a new select instruction.
1286             Value *NewRetVal;
1287             Value *BrCond = BI->getCondition();
1288             if (TrueValue != FalseValue)
1289               NewRetVal = new SelectInst(BrCond, TrueValue,
1290                                          FalseValue, "retval", BI);
1291             else
1292               NewRetVal = TrueValue;
1293             
1294             DEBUG(std::cerr << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1295                   << "\n  " << *BI << "Select = " << *NewRetVal
1296                   << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
1297
1298             new ReturnInst(NewRetVal, BI);
1299             BI->eraseFromParent();
1300             if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
1301               if (isInstructionTriviallyDead(BrCondI))
1302                 BrCondI->eraseFromParent();
1303             return true;
1304           }
1305         }
1306       }
1307     }
1308   } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) {
1309     // Check to see if the first instruction in this block is just an unwind.
1310     // If so, replace any invoke instructions which use this as an exception
1311     // destination with call instructions, and any unconditional branch
1312     // predecessor with an unwind.
1313     //
1314     std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1315     while (!Preds.empty()) {
1316       BasicBlock *Pred = Preds.back();
1317       if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
1318         if (BI->isUnconditional()) {
1319           Pred->getInstList().pop_back();  // nuke uncond branch
1320           new UnwindInst(Pred);            // Use unwind.
1321           Changed = true;
1322         }
1323       } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
1324         if (II->getUnwindDest() == BB) {
1325           // Insert a new branch instruction before the invoke, because this
1326           // is now a fall through...
1327           BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1328           Pred->getInstList().remove(II);   // Take out of symbol table
1329
1330           // Insert the call now...
1331           std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1332           CallInst *CI = new CallInst(II->getCalledValue(), Args,
1333                                       II->getName(), BI);
1334           CI->setCallingConv(II->getCallingConv());
1335           // If the invoke produced a value, the Call now does instead
1336           II->replaceAllUsesWith(CI);
1337           delete II;
1338           Changed = true;
1339         }
1340
1341       Preds.pop_back();
1342     }
1343
1344     // If this block is now dead, remove it.
1345     if (pred_begin(BB) == pred_end(BB)) {
1346       // We know there are no successors, so just nuke the block.
1347       M->getBasicBlockList().erase(BB);
1348       return true;
1349     }
1350
1351   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1352     if (isValueEqualityComparison(SI)) {
1353       // If we only have one predecessor, and if it is a branch on this value,
1354       // see if that predecessor totally determines the outcome of this switch.
1355       if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1356         if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1357           return SimplifyCFG(BB) || 1;
1358
1359       // If the block only contains the switch, see if we can fold the block
1360       // away into any preds.
1361       if (SI == &BB->front())
1362         if (FoldValueComparisonIntoPredecessors(SI))
1363           return SimplifyCFG(BB) || 1;
1364     }
1365   } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
1366     if (BI->isUnconditional()) {
1367       BasicBlock::iterator BBI = BB->begin();  // Skip over phi nodes...
1368       while (isa<PHINode>(*BBI)) ++BBI;
1369
1370       BasicBlock *Succ = BI->getSuccessor(0);
1371       if (BBI->isTerminator() &&  // Terminator is the only non-phi instruction!
1372           Succ != BB)             // Don't hurt infinite loops!
1373         if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
1374           return 1;
1375       
1376     } else {  // Conditional branch
1377       if (Value *CompVal = isValueEqualityComparison(BI)) {
1378         // If we only have one predecessor, and if it is a branch on this value,
1379         // see if that predecessor totally determines the outcome of this
1380         // switch.
1381         if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1382           if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1383             return SimplifyCFG(BB) || 1;
1384
1385         // This block must be empty, except for the setcond inst, if it exists.
1386         BasicBlock::iterator I = BB->begin();
1387         if (&*I == BI ||
1388             (&*I == cast<Instruction>(BI->getCondition()) &&
1389              &*++I == BI))
1390           if (FoldValueComparisonIntoPredecessors(BI))
1391             return SimplifyCFG(BB) | true;
1392       }
1393       
1394       // If this is a branch on a phi node in the current block, thread control
1395       // through this block if any PHI node entries are constants.
1396       if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
1397         if (PN->getParent() == BI->getParent())
1398           if (FoldCondBranchOnPHI(BI))
1399             return SimplifyCFG(BB) | true;
1400
1401       // If this basic block is ONLY a setcc and a branch, and if a predecessor
1402       // branches to us and one of our successors, fold the setcc into the
1403       // predecessor and use logical operations to pick the right destination.
1404       BasicBlock *TrueDest  = BI->getSuccessor(0);
1405       BasicBlock *FalseDest = BI->getSuccessor(1);
1406       if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(BI->getCondition()))
1407         if (Cond->getParent() == BB && &BB->front() == Cond &&
1408             Cond->getNext() == BI && Cond->hasOneUse() &&
1409             TrueDest != BB && FalseDest != BB)
1410           for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
1411             if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1412               if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
1413                 BasicBlock *PredBlock = *PI;
1414                 if (PBI->getSuccessor(0) == FalseDest ||
1415                     PBI->getSuccessor(1) == TrueDest) {
1416                   // Invert the predecessors condition test (xor it with true),
1417                   // which allows us to write this code once.
1418                   Value *NewCond =
1419                     BinaryOperator::createNot(PBI->getCondition(),
1420                                     PBI->getCondition()->getName()+".not", PBI);
1421                   PBI->setCondition(NewCond);
1422                   BasicBlock *OldTrue = PBI->getSuccessor(0);
1423                   BasicBlock *OldFalse = PBI->getSuccessor(1);
1424                   PBI->setSuccessor(0, OldFalse);
1425                   PBI->setSuccessor(1, OldTrue);
1426                 }
1427
1428                 if (PBI->getSuccessor(0) == TrueDest ||
1429                     PBI->getSuccessor(1) == FalseDest) {
1430                   // Clone Cond into the predecessor basic block, and or/and the
1431                   // two conditions together.
1432                   Instruction *New = Cond->clone();
1433                   New->setName(Cond->getName());
1434                   Cond->setName(Cond->getName()+".old");
1435                   PredBlock->getInstList().insert(PBI, New);
1436                   Instruction::BinaryOps Opcode =
1437                     PBI->getSuccessor(0) == TrueDest ?
1438                     Instruction::Or : Instruction::And;
1439                   Value *NewCond =
1440                     BinaryOperator::create(Opcode, PBI->getCondition(),
1441                                            New, "bothcond", PBI);
1442                   PBI->setCondition(NewCond);
1443                   if (PBI->getSuccessor(0) == BB) {
1444                     AddPredecessorToBlock(TrueDest, PredBlock, BB);
1445                     PBI->setSuccessor(0, TrueDest);
1446                   }
1447                   if (PBI->getSuccessor(1) == BB) {
1448                     AddPredecessorToBlock(FalseDest, PredBlock, BB);
1449                     PBI->setSuccessor(1, FalseDest);
1450                   }
1451                   return SimplifyCFG(BB) | 1;
1452                 }
1453               }
1454
1455       // Scan predessor blocks for conditional branchs.
1456       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1457         if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1458           if (PBI != BI && PBI->isConditional()) {
1459               
1460             // If this block ends with a branch instruction, and if there is a
1461             // predecessor that ends on a branch of the same condition, make this 
1462             // conditional branch redundant.
1463             if (PBI->getCondition() == BI->getCondition() &&
1464                 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1465               // Okay, the outcome of this conditional branch is statically
1466               // knowable.  If this block had a single pred, handle specially.
1467               if (BB->getSinglePredecessor()) {
1468                 // Turn this into a branch on constant.
1469                 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1470                 BI->setCondition(ConstantBool::get(CondIsTrue));
1471                 return SimplifyCFG(BB);  // Nuke the branch on constant.
1472               }
1473               
1474               // Otherwise, if there are multiple predecessors, insert a PHI that
1475               // merges in the constant and simplify the block result.
1476               if (BlockIsSimpleEnoughToThreadThrough(BB)) {
1477                 PHINode *NewPN = new PHINode(Type::BoolTy,
1478                                              BI->getCondition()->getName()+".pr",
1479                                              BB->begin());
1480                 for (PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1481                   if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
1482                       PBI != BI && PBI->isConditional() &&
1483                       PBI->getCondition() == BI->getCondition() &&
1484                       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1485                     bool CondIsTrue = PBI->getSuccessor(0) == BB;
1486                     NewPN->addIncoming(ConstantBool::get(CondIsTrue), *PI);
1487                   } else {
1488                     NewPN->addIncoming(BI->getCondition(), *PI);
1489                   }
1490                 
1491                 BI->setCondition(NewPN);
1492                 // This will thread the branch.
1493                 return SimplifyCFG(BB) | true;
1494               }
1495             }
1496             
1497             // If this is a conditional branch in an empty block, and if any
1498             // predecessors is a conditional branch to one of our destinations,
1499             // fold the conditions into logical ops and one cond br.
1500             if (&BB->front() == BI) {
1501               int PBIOp, BIOp;
1502               if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
1503                 PBIOp = BIOp = 0;
1504               } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
1505                 PBIOp = 0; BIOp = 1;
1506               } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
1507                 PBIOp = 1; BIOp = 0;
1508               } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
1509                 PBIOp = BIOp = 1;
1510               } else {
1511                 PBIOp = BIOp = -1;
1512               }
1513               
1514               // Finally, if everything is ok, fold the branches to logical ops.
1515               if (PBIOp != -1) {
1516                 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1517                 BasicBlock *OtherDest  = BI->getSuccessor(BIOp ^ 1);
1518
1519                 DEBUG(std::cerr << "FOLDING BRs:" << *PBI->getParent()
1520                                 << "AND: " << *BI->getParent());
1521                                 
1522                 // BI may have other predecessors.  Because of this, we leave
1523                 // it alone, but modify PBI.
1524                 
1525                 // Make sure we get to CommonDest on True&True directions.
1526                 Value *PBICond = PBI->getCondition();
1527                 if (PBIOp)
1528                   PBICond = BinaryOperator::createNot(PBICond,
1529                                                       PBICond->getName()+".not",
1530                                                       PBI);
1531                 Value *BICond = BI->getCondition();
1532                 if (BIOp)
1533                   BICond = BinaryOperator::createNot(BICond,
1534                                                      BICond->getName()+".not",
1535                                                      PBI);
1536                 // Merge the conditions.
1537                 Value *Cond =
1538                   BinaryOperator::createOr(PBICond, BICond, "brmerge", PBI);
1539                 
1540                 // Modify PBI to branch on the new condition to the new dests.
1541                 PBI->setCondition(Cond);
1542                 PBI->setSuccessor(0, CommonDest);
1543                 PBI->setSuccessor(1, OtherDest);
1544
1545                 // OtherDest may have phi nodes.  If so, add an entry from PBI's
1546                 // block that are identical to the entries for BI's block.
1547                 PHINode *PN;
1548                 for (BasicBlock::iterator II = OtherDest->begin();
1549                      (PN = dyn_cast<PHINode>(II)); ++II) {
1550                   Value *V = PN->getIncomingValueForBlock(BB);
1551                   PN->addIncoming(V, PBI->getParent());
1552                 }
1553                 
1554                 // We know that the CommonDest already had an edge from PBI to
1555                 // it.  If it has PHIs though, the PHIs may have different
1556                 // entries for BB and PBI's BB.  If so, insert a select to make
1557                 // them agree.
1558                 for (BasicBlock::iterator II = CommonDest->begin();
1559                      (PN = dyn_cast<PHINode>(II)); ++II) {
1560                   Value * BIV = PN->getIncomingValueForBlock(BB);
1561                   unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1562                   Value *PBIV = PN->getIncomingValue(PBBIdx);
1563                   if (BIV != PBIV) {
1564                     // Insert a select in PBI to pick the right value.
1565                     Value *NV = new SelectInst(PBICond, PBIV, BIV,
1566                                                PBIV->getName()+".mux", PBI);
1567                     PN->setIncomingValue(PBBIdx, NV);
1568                   }
1569                 }
1570
1571                 DEBUG(std::cerr << "INTO: " << *PBI->getParent());
1572
1573                 // This basic block is probably dead.  We know it has at least
1574                 // one fewer predecessor.
1575                 return SimplifyCFG(BB) | true;
1576               }
1577             }
1578           }
1579     }
1580   } else if (isa<UnreachableInst>(BB->getTerminator())) {
1581     // If there are any instructions immediately before the unreachable that can
1582     // be removed, do so.
1583     Instruction *Unreachable = BB->getTerminator();
1584     while (Unreachable != BB->begin()) {
1585       BasicBlock::iterator BBI = Unreachable;
1586       --BBI;
1587       if (isa<CallInst>(BBI)) break;
1588       // Delete this instruction
1589       BB->getInstList().erase(BBI);
1590       Changed = true;
1591     }
1592
1593     // If the unreachable instruction is the first in the block, take a gander
1594     // at all of the predecessors of this instruction, and simplify them.
1595     if (&BB->front() == Unreachable) {
1596       std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1597       for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1598         TerminatorInst *TI = Preds[i]->getTerminator();
1599
1600         if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1601           if (BI->isUnconditional()) {
1602             if (BI->getSuccessor(0) == BB) {
1603               new UnreachableInst(TI);
1604               TI->eraseFromParent();
1605               Changed = true;
1606             }
1607           } else {
1608             if (BI->getSuccessor(0) == BB) {
1609               new BranchInst(BI->getSuccessor(1), BI);
1610               BI->eraseFromParent();
1611             } else if (BI->getSuccessor(1) == BB) {
1612               new BranchInst(BI->getSuccessor(0), BI);
1613               BI->eraseFromParent();
1614               Changed = true;
1615             }
1616           }
1617         } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1618           for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1619             if (SI->getSuccessor(i) == BB) {
1620               BB->removePredecessor(SI->getParent());
1621               SI->removeCase(i);
1622               --i; --e;
1623               Changed = true;
1624             }
1625           // If the default value is unreachable, figure out the most popular
1626           // destination and make it the default.
1627           if (SI->getSuccessor(0) == BB) {
1628             std::map<BasicBlock*, unsigned> Popularity;
1629             for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1630               Popularity[SI->getSuccessor(i)]++;
1631
1632             // Find the most popular block.
1633             unsigned MaxPop = 0;
1634             BasicBlock *MaxBlock = 0;
1635             for (std::map<BasicBlock*, unsigned>::iterator
1636                    I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
1637               if (I->second > MaxPop) {
1638                 MaxPop = I->second;
1639                 MaxBlock = I->first;
1640               }
1641             }
1642             if (MaxBlock) {
1643               // Make this the new default, allowing us to delete any explicit
1644               // edges to it.
1645               SI->setSuccessor(0, MaxBlock);
1646               Changed = true;
1647
1648               // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
1649               // it.
1650               if (isa<PHINode>(MaxBlock->begin()))
1651                 for (unsigned i = 0; i != MaxPop-1; ++i)
1652                   MaxBlock->removePredecessor(SI->getParent());
1653
1654               for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1655                 if (SI->getSuccessor(i) == MaxBlock) {
1656                   SI->removeCase(i);
1657                   --i; --e;
1658                 }
1659             }
1660           }
1661         } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
1662           if (II->getUnwindDest() == BB) {
1663             // Convert the invoke to a call instruction.  This would be a good
1664             // place to note that the call does not throw though.
1665             BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1666             II->removeFromParent();   // Take out of symbol table
1667
1668             // Insert the call now...
1669             std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1670             CallInst *CI = new CallInst(II->getCalledValue(), Args,
1671                                         II->getName(), BI);
1672             CI->setCallingConv(II->getCallingConv());
1673             // If the invoke produced a value, the Call does now instead.
1674             II->replaceAllUsesWith(CI);
1675             delete II;
1676             Changed = true;
1677           }
1678         }
1679       }
1680
1681       // If this block is now dead, remove it.
1682       if (pred_begin(BB) == pred_end(BB)) {
1683         // We know there are no successors, so just nuke the block.
1684         M->getBasicBlockList().erase(BB);
1685         return true;
1686       }
1687     }
1688   }
1689
1690   // Merge basic blocks into their predecessor if there is only one distinct
1691   // pred, and if there is only one distinct successor of the predecessor, and
1692   // if there are no PHI nodes.
1693   //
1694   pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
1695   BasicBlock *OnlyPred = *PI++;
1696   for (; PI != PE; ++PI)  // Search all predecessors, see if they are all same
1697     if (*PI != OnlyPred) {
1698       OnlyPred = 0;       // There are multiple different predecessors...
1699       break;
1700     }
1701
1702   BasicBlock *OnlySucc = 0;
1703   if (OnlyPred && OnlyPred != BB &&    // Don't break self loops
1704       OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
1705     // Check to see if there is only one distinct successor...
1706     succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
1707     OnlySucc = BB;
1708     for (; SI != SE; ++SI)
1709       if (*SI != OnlySucc) {
1710         OnlySucc = 0;     // There are multiple distinct successors!
1711         break;
1712       }
1713   }
1714
1715   if (OnlySucc) {
1716     DEBUG(std::cerr << "Merging: " << *BB << "into: " << *OnlyPred);
1717     TerminatorInst *Term = OnlyPred->getTerminator();
1718
1719     // Resolve any PHI nodes at the start of the block.  They are all
1720     // guaranteed to have exactly one entry if they exist, unless there are
1721     // multiple duplicate (but guaranteed to be equal) entries for the
1722     // incoming edges.  This occurs when there are multiple edges from
1723     // OnlyPred to OnlySucc.
1724     //
1725     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1726       PN->replaceAllUsesWith(PN->getIncomingValue(0));
1727       BB->getInstList().pop_front();  // Delete the phi node...
1728     }
1729
1730     // Delete the unconditional branch from the predecessor...
1731     OnlyPred->getInstList().pop_back();
1732
1733     // Move all definitions in the successor to the predecessor...
1734     OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
1735
1736     // Make all PHI nodes that referred to BB now refer to Pred as their
1737     // source...
1738     BB->replaceAllUsesWith(OnlyPred);
1739
1740     std::string OldName = BB->getName();
1741
1742     // Erase basic block from the function...
1743     M->getBasicBlockList().erase(BB);
1744
1745     // Inherit predecessors name if it exists...
1746     if (!OldName.empty() && !OnlyPred->hasName())
1747       OnlyPred->setName(OldName);
1748
1749     return true;
1750   }
1751
1752   // Otherwise, if this block only has a single predecessor, and if that block
1753   // is a conditional branch, see if we can hoist any code from this block up
1754   // into our predecessor.
1755   if (OnlyPred)
1756     if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1757       if (BI->isConditional()) {
1758         // Get the other block.
1759         BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
1760         PI = pred_begin(OtherBB);
1761         ++PI;
1762         if (PI == pred_end(OtherBB)) {
1763           // We have a conditional branch to two blocks that are only reachable
1764           // from the condbr.  We know that the condbr dominates the two blocks,
1765           // so see if there is any identical code in the "then" and "else"
1766           // blocks.  If so, we can hoist it up to the branching block.
1767           Changed |= HoistThenElseCodeToIf(BI);
1768         }
1769       }
1770
1771   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1772     if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1773       // Change br (X == 0 | X == 1), T, F into a switch instruction.
1774       if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
1775         Instruction *Cond = cast<Instruction>(BI->getCondition());
1776         // If this is a bunch of seteq's or'd together, or if it's a bunch of
1777         // 'setne's and'ed together, collect them.
1778         Value *CompVal = 0;
1779         std::vector<ConstantInt*> Values;
1780         bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
1781         if (CompVal && CompVal->getType()->isInteger()) {
1782           // There might be duplicate constants in the list, which the switch
1783           // instruction can't handle, remove them now.
1784           std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
1785           Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
1786
1787           // Figure out which block is which destination.
1788           BasicBlock *DefaultBB = BI->getSuccessor(1);
1789           BasicBlock *EdgeBB    = BI->getSuccessor(0);
1790           if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
1791
1792           // Create the new switch instruction now.
1793           SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI);
1794
1795           // Add all of the 'cases' to the switch instruction.
1796           for (unsigned i = 0, e = Values.size(); i != e; ++i)
1797             New->addCase(Values[i], EdgeBB);
1798
1799           // We added edges from PI to the EdgeBB.  As such, if there were any
1800           // PHI nodes in EdgeBB, they need entries to be added corresponding to
1801           // the number of edges added.
1802           for (BasicBlock::iterator BBI = EdgeBB->begin();
1803                isa<PHINode>(BBI); ++BBI) {
1804             PHINode *PN = cast<PHINode>(BBI);
1805             Value *InVal = PN->getIncomingValueForBlock(*PI);
1806             for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1807               PN->addIncoming(InVal, *PI);
1808           }
1809
1810           // Erase the old branch instruction.
1811           (*PI)->getInstList().erase(BI);
1812
1813           // Erase the potentially condition tree that was used to computed the
1814           // branch condition.
1815           ErasePossiblyDeadInstructionTree(Cond);
1816           return true;
1817         }
1818       }
1819
1820   // If there is a trivial two-entry PHI node in this basic block, and we can
1821   // eliminate it, do so now.
1822   if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1823     if (PN->getNumIncomingValues() == 2)
1824       Changed |= FoldTwoEntryPHINode(PN); 
1825
1826   return Changed;
1827 }