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