SimplifyCFG: GEPs with just one non-constant index are also cheap.
[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 is distributed under the University of Illinois Open Source
6 // 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/IntrinsicInst.h"
19 #include "llvm/Type.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ConstantRange.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm>
36 #include <set>
37 #include <map>
38 using namespace llvm;
39
40 static cl::opt<bool>
41 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
42        cl::desc("Duplicate return instructions into unconditional branches"));
43
44 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
45
46 namespace {
47 class SimplifyCFGOpt {
48   const TargetData *const TD;
49
50   Value *isValueEqualityComparison(TerminatorInst *TI);
51   BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
52     std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases);
53   bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
54                                                      BasicBlock *Pred);
55   bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI);
56
57   bool SimplifyReturn(ReturnInst *RI);
58   bool SimplifyUnwind(UnwindInst *UI);
59   bool SimplifyUnreachable(UnreachableInst *UI);
60   bool SimplifySwitch(SwitchInst *SI);
61   bool SimplifyIndirectBr(IndirectBrInst *IBI);
62   bool SimplifyUncondBranch(BranchInst *BI);
63   bool SimplifyCondBranch(BranchInst *BI);
64
65 public:
66   explicit SimplifyCFGOpt(const TargetData *td) : TD(td) {}
67   bool run(BasicBlock *BB);
68 };
69 }
70
71 /// SafeToMergeTerminators - Return true if it is safe to merge these two
72 /// terminator instructions together.
73 ///
74 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
75   if (SI1 == SI2) return false;  // Can't merge with self!
76   
77   // It is not safe to merge these two switch instructions if they have a common
78   // successor, and if that successor has a PHI node, and if *that* PHI node has
79   // conflicting incoming values from the two switch blocks.
80   BasicBlock *SI1BB = SI1->getParent();
81   BasicBlock *SI2BB = SI2->getParent();
82   SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
83   
84   for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
85     if (SI1Succs.count(*I))
86       for (BasicBlock::iterator BBI = (*I)->begin();
87            isa<PHINode>(BBI); ++BBI) {
88         PHINode *PN = cast<PHINode>(BBI);
89         if (PN->getIncomingValueForBlock(SI1BB) !=
90             PN->getIncomingValueForBlock(SI2BB))
91           return false;
92       }
93         
94   return true;
95 }
96
97 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
98 /// now be entries in it from the 'NewPred' block.  The values that will be
99 /// flowing into the PHI nodes will be the same as those coming in from
100 /// ExistPred, an existing predecessor of Succ.
101 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
102                                   BasicBlock *ExistPred) {
103   if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
104   
105   PHINode *PN;
106   for (BasicBlock::iterator I = Succ->begin();
107        (PN = dyn_cast<PHINode>(I)); ++I)
108     PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
109 }
110
111
112 /// GetIfCondition - Given a basic block (BB) with two predecessors (and at
113 /// least one PHI node in it), check to see if the merge at this block is due
114 /// to an "if condition".  If so, return the boolean condition that determines
115 /// which entry into BB will be taken.  Also, return by references the block
116 /// that will be entered from if the condition is true, and the block that will
117 /// be entered if the condition is false.
118 ///
119 /// This does no checking to see if the true/false blocks have large or unsavory
120 /// instructions in them.
121 static Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
122                              BasicBlock *&IfFalse) {
123   PHINode *SomePHI = cast<PHINode>(BB->begin());
124   assert(SomePHI->getNumIncomingValues() == 2 &&
125          "Function can only handle blocks with 2 predecessors!");
126   BasicBlock *Pred1 = SomePHI->getIncomingBlock(0);
127   BasicBlock *Pred2 = SomePHI->getIncomingBlock(1);
128
129   // We can only handle branches.  Other control flow will be lowered to
130   // branches if possible anyway.
131   BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
132   BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
133   if (Pred1Br == 0 || Pred2Br == 0)
134     return 0;
135
136   // Eliminate code duplication by ensuring that Pred1Br is conditional if
137   // either are.
138   if (Pred2Br->isConditional()) {
139     // If both branches are conditional, we don't have an "if statement".  In
140     // reality, we could transform this case, but since the condition will be
141     // required anyway, we stand no chance of eliminating it, so the xform is
142     // probably not profitable.
143     if (Pred1Br->isConditional())
144       return 0;
145
146     std::swap(Pred1, Pred2);
147     std::swap(Pred1Br, Pred2Br);
148   }
149
150   if (Pred1Br->isConditional()) {
151     // The only thing we have to watch out for here is to make sure that Pred2
152     // doesn't have incoming edges from other blocks.  If it does, the condition
153     // doesn't dominate BB.
154     if (Pred2->getSinglePredecessor() == 0)
155       return 0;
156     
157     // If we found a conditional branch predecessor, make sure that it branches
158     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
159     if (Pred1Br->getSuccessor(0) == BB &&
160         Pred1Br->getSuccessor(1) == Pred2) {
161       IfTrue = Pred1;
162       IfFalse = Pred2;
163     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
164                Pred1Br->getSuccessor(1) == BB) {
165       IfTrue = Pred2;
166       IfFalse = Pred1;
167     } else {
168       // We know that one arm of the conditional goes to BB, so the other must
169       // go somewhere unrelated, and this must not be an "if statement".
170       return 0;
171     }
172
173     return Pred1Br->getCondition();
174   }
175
176   // Ok, if we got here, both predecessors end with an unconditional branch to
177   // BB.  Don't panic!  If both blocks only have a single (identical)
178   // predecessor, and THAT is a conditional branch, then we're all ok!
179   BasicBlock *CommonPred = Pred1->getSinglePredecessor();
180   if (CommonPred == 0 || CommonPred != Pred2->getSinglePredecessor())
181     return 0;
182
183   // Otherwise, if this is a conditional branch, then we can use it!
184   BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
185   if (BI == 0) return 0;
186   
187   assert(BI->isConditional() && "Two successors but not conditional?");
188   if (BI->getSuccessor(0) == Pred1) {
189     IfTrue = Pred1;
190     IfFalse = Pred2;
191   } else {
192     IfTrue = Pred2;
193     IfFalse = Pred1;
194   }
195   return BI->getCondition();
196 }
197
198 /// DominatesMergePoint - If we have a merge point of an "if condition" as
199 /// accepted above, return true if the specified value dominates the block.  We
200 /// don't handle the true generality of domination here, just a special case
201 /// which works well enough for us.
202 ///
203 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
204 /// see if V (which must be an instruction) is cheap to compute and is
205 /// non-trapping.  If both are true, the instruction is inserted into the set
206 /// and true is returned.
207 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
208                                 SmallPtrSet<Instruction*, 4> *AggressiveInsts) {
209   Instruction *I = dyn_cast<Instruction>(V);
210   if (!I) {
211     // Non-instructions all dominate instructions, but not all constantexprs
212     // can be executed unconditionally.
213     if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
214       if (C->canTrap())
215         return false;
216     return true;
217   }
218   BasicBlock *PBB = I->getParent();
219
220   // We don't want to allow weird loops that might have the "if condition" in
221   // the bottom of this block.
222   if (PBB == BB) return false;
223
224   // If this instruction is defined in a block that contains an unconditional
225   // branch to BB, then it must be in the 'conditional' part of the "if
226   // statement".  If not, it definitely dominates the region.
227   BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
228   if (BI == 0 || BI->isConditional() || BI->getSuccessor(0) != BB)
229     return true;
230
231   // If we aren't allowing aggressive promotion anymore, then don't consider
232   // instructions in the 'if region'.
233   if (AggressiveInsts == 0) return false;
234   
235   // Okay, it looks like the instruction IS in the "condition".  Check to
236   // see if it's a cheap instruction to unconditionally compute, and if it
237   // only uses stuff defined outside of the condition.  If so, hoist it out.
238   if (!I->isSafeToSpeculativelyExecute())
239     return false;
240
241   switch (I->getOpcode()) {
242   default: return false;  // Cannot hoist this out safely.
243   case Instruction::Load:
244     // We have to check to make sure there are no instructions before the
245     // load in its basic block, as we are going to hoist the load out to its
246     // predecessor.
247     if (PBB->getFirstNonPHIOrDbg() != I)
248       return false;
249     break;
250   case Instruction::GetElementPtr: {
251     // GEPs are cheap if all indices are constant or if there's only one index.
252     GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
253     if (!GEP->hasAllConstantIndices() && GEP->getNumIndices() > 1)
254       return false;
255     break;
256   }
257   case Instruction::Add:
258   case Instruction::Sub:
259   case Instruction::And:
260   case Instruction::Or:
261   case Instruction::Xor:
262   case Instruction::Shl:
263   case Instruction::LShr:
264   case Instruction::AShr:
265   case Instruction::ICmp:
266     break;   // These are all cheap and non-trapping instructions.
267   }
268
269   // Okay, we can only really hoist these out if their operands are not
270   // defined in the conditional region.
271   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
272     if (!DominatesMergePoint(*i, BB, 0))
273       return false;
274   // Okay, it's safe to do this!  Remember this instruction.
275   AggressiveInsts->insert(I);
276   return true;
277 }
278
279 /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
280 /// and PointerNullValue. Return NULL if value is not a constant int.
281 static ConstantInt *GetConstantInt(Value *V, const TargetData *TD) {
282   // Normal constant int.
283   ConstantInt *CI = dyn_cast<ConstantInt>(V);
284   if (CI || !TD || !isa<Constant>(V) || !V->getType()->isPointerTy())
285     return CI;
286
287   // This is some kind of pointer constant. Turn it into a pointer-sized
288   // ConstantInt if possible.
289   const IntegerType *PtrTy = TD->getIntPtrType(V->getContext());
290
291   // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
292   if (isa<ConstantPointerNull>(V))
293     return ConstantInt::get(PtrTy, 0);
294
295   // IntToPtr const int.
296   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
297     if (CE->getOpcode() == Instruction::IntToPtr)
298       if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
299         // The constant is very likely to have the right type already.
300         if (CI->getType() == PtrTy)
301           return CI;
302         else
303           return cast<ConstantInt>
304             (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
305       }
306   return 0;
307 }
308
309 /// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
310 /// collection of icmp eq/ne instructions that compare a value against a
311 /// constant, return the value being compared, and stick the constant into the
312 /// Values vector.
313 static Value *
314 GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
315                        const TargetData *TD, bool isEQ, unsigned &UsedICmps) {
316   Instruction *I = dyn_cast<Instruction>(V);
317   if (I == 0) return 0;
318   
319   // If this is an icmp against a constant, handle this as one of the cases.
320   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
321     if (ConstantInt *C = GetConstantInt(I->getOperand(1), TD)) {
322       if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
323         UsedICmps++;
324         Vals.push_back(C);
325         return I->getOperand(0);
326       }
327       
328       // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
329       // the set.
330       ConstantRange Span =
331         ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
332       
333       // If this is an and/!= check then we want to optimize "x ugt 2" into
334       // x != 0 && x != 1.
335       if (!isEQ)
336         Span = Span.inverse();
337       
338       // If there are a ton of values, we don't want to make a ginormous switch.
339       if (Span.getSetSize().ugt(8) || Span.isEmptySet() ||
340           // We don't handle wrapped sets yet.
341           Span.isWrappedSet())
342         return 0;
343       
344       for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
345         Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
346       UsedICmps++;
347       return I->getOperand(0);
348     }
349     return 0;
350   }
351   
352   // Otherwise, we can only handle an | or &, depending on isEQ.
353   if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
354     return 0;
355   
356   unsigned NumValsBeforeLHS = Vals.size();
357   unsigned UsedICmpsBeforeLHS = UsedICmps;
358   if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, TD,
359                                           isEQ, UsedICmps)) {
360     unsigned NumVals = Vals.size();
361     unsigned UsedICmpsBeforeRHS = UsedICmps;
362     if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
363                                             isEQ, UsedICmps)) {
364       if (LHS == RHS)
365         return LHS;
366       Vals.resize(NumVals);
367       UsedICmps = UsedICmpsBeforeRHS;
368     }
369
370     // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
371     // set it and return success.
372     if (Extra == 0 || Extra == I->getOperand(1)) {
373       Extra = I->getOperand(1);
374       return LHS;
375     }
376     
377     Vals.resize(NumValsBeforeLHS);
378     UsedICmps = UsedICmpsBeforeLHS;
379     return 0;
380   }
381   
382   // If the LHS can't be folded in, but Extra is available and RHS can, try to
383   // use LHS as Extra.
384   if (Extra == 0 || Extra == I->getOperand(0)) {
385     Value *OldExtra = Extra;
386     Extra = I->getOperand(0);
387     if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
388                                             isEQ, UsedICmps))
389       return RHS;
390     assert(Vals.size() == NumValsBeforeLHS);
391     Extra = OldExtra;
392   }
393   
394   return 0;
395 }
396       
397 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
398   Instruction* Cond = 0;
399   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
400     Cond = dyn_cast<Instruction>(SI->getCondition());
401   } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
402     if (BI->isConditional())
403       Cond = dyn_cast<Instruction>(BI->getCondition());
404   } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
405     Cond = dyn_cast<Instruction>(IBI->getAddress());
406   }
407
408   TI->eraseFromParent();
409   if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
410 }
411
412 /// isValueEqualityComparison - Return true if the specified terminator checks
413 /// to see if a value is equal to constant integer value.
414 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
415   Value *CV = 0;
416   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
417     // Do not permit merging of large switch instructions into their
418     // predecessors unless there is only one predecessor.
419     if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
420                                              pred_end(SI->getParent())) <= 128)
421       CV = SI->getCondition();
422   } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
423     if (BI->isConditional() && BI->getCondition()->hasOneUse())
424       if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
425         if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
426              ICI->getPredicate() == ICmpInst::ICMP_NE) &&
427             GetConstantInt(ICI->getOperand(1), TD))
428           CV = ICI->getOperand(0);
429
430   // Unwrap any lossless ptrtoint cast.
431   if (TD && CV && CV->getType() == TD->getIntPtrType(CV->getContext()))
432     if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV))
433       CV = PTII->getOperand(0);
434   return CV;
435 }
436
437 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
438 /// decode all of the 'cases' that it represents and return the 'default' block.
439 BasicBlock *SimplifyCFGOpt::
440 GetValueEqualityComparisonCases(TerminatorInst *TI,
441                                 std::vector<std::pair<ConstantInt*,
442                                                       BasicBlock*> > &Cases) {
443   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
444     Cases.reserve(SI->getNumCases());
445     for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
446       Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
447     return SI->getDefaultDest();
448   }
449
450   BranchInst *BI = cast<BranchInst>(TI);
451   ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
452   Cases.push_back(std::make_pair(GetConstantInt(ICI->getOperand(1), TD),
453                                  BI->getSuccessor(ICI->getPredicate() ==
454                                                   ICmpInst::ICMP_NE)));
455   return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
456 }
457
458
459 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
460 /// in the list that match the specified block.
461 static void EliminateBlockCases(BasicBlock *BB,
462                std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
463   for (unsigned i = 0, e = Cases.size(); i != e; ++i)
464     if (Cases[i].second == BB) {
465       Cases.erase(Cases.begin()+i);
466       --i; --e;
467     }
468 }
469
470 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
471 /// well.
472 static bool
473 ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
474               std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
475   std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
476
477   // Make V1 be smaller than V2.
478   if (V1->size() > V2->size())
479     std::swap(V1, V2);
480
481   if (V1->size() == 0) return false;
482   if (V1->size() == 1) {
483     // Just scan V2.
484     ConstantInt *TheVal = (*V1)[0].first;
485     for (unsigned i = 0, e = V2->size(); i != e; ++i)
486       if (TheVal == (*V2)[i].first)
487         return true;
488   }
489
490   // Otherwise, just sort both lists and compare element by element.
491   array_pod_sort(V1->begin(), V1->end());
492   array_pod_sort(V2->begin(), V2->end());
493   unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
494   while (i1 != e1 && i2 != e2) {
495     if ((*V1)[i1].first == (*V2)[i2].first)
496       return true;
497     if ((*V1)[i1].first < (*V2)[i2].first)
498       ++i1;
499     else
500       ++i2;
501   }
502   return false;
503 }
504
505 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
506 /// terminator instruction and its block is known to only have a single
507 /// predecessor block, check to see if that predecessor is also a value
508 /// comparison with the same value, and if that comparison determines the
509 /// outcome of this comparison.  If so, simplify TI.  This does a very limited
510 /// form of jump threading.
511 bool SimplifyCFGOpt::
512 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
513                                               BasicBlock *Pred) {
514   Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
515   if (!PredVal) return false;  // Not a value comparison in predecessor.
516
517   Value *ThisVal = isValueEqualityComparison(TI);
518   assert(ThisVal && "This isn't a value comparison!!");
519   if (ThisVal != PredVal) return false;  // Different predicates.
520
521   // Find out information about when control will move from Pred to TI's block.
522   std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
523   BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
524                                                         PredCases);
525   EliminateBlockCases(PredDef, PredCases);  // Remove default from cases.
526
527   // Find information about how control leaves this block.
528   std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
529   BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
530   EliminateBlockCases(ThisDef, ThisCases);  // Remove default from cases.
531
532   // If TI's block is the default block from Pred's comparison, potentially
533   // simplify TI based on this knowledge.
534   if (PredDef == TI->getParent()) {
535     // If we are here, we know that the value is none of those cases listed in
536     // PredCases.  If there are any cases in ThisCases that are in PredCases, we
537     // can simplify TI.
538     if (!ValuesOverlap(PredCases, ThisCases))
539       return false;
540     
541     if (isa<BranchInst>(TI)) {
542       // Okay, one of the successors of this condbr is dead.  Convert it to a
543       // uncond br.
544       assert(ThisCases.size() == 1 && "Branch can only have one case!");
545       // Insert the new branch.
546       Instruction *NI = BranchInst::Create(ThisDef, TI);
547       (void) NI;
548
549       // Remove PHI node entries for the dead edge.
550       ThisCases[0].second->removePredecessor(TI->getParent());
551
552       DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
553            << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
554
555       EraseTerminatorInstAndDCECond(TI);
556       return true;
557     }
558       
559     SwitchInst *SI = cast<SwitchInst>(TI);
560     // Okay, TI has cases that are statically dead, prune them away.
561     SmallPtrSet<Constant*, 16> DeadCases;
562     for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
563       DeadCases.insert(PredCases[i].first);
564
565     DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
566                  << "Through successor TI: " << *TI);
567
568     for (unsigned i = SI->getNumCases()-1; i != 0; --i)
569       if (DeadCases.count(SI->getCaseValue(i))) {
570         SI->getSuccessor(i)->removePredecessor(TI->getParent());
571         SI->removeCase(i);
572       }
573
574     DEBUG(dbgs() << "Leaving: " << *TI << "\n");
575     return true;
576   }
577   
578   // Otherwise, TI's block must correspond to some matched value.  Find out
579   // which value (or set of values) this is.
580   ConstantInt *TIV = 0;
581   BasicBlock *TIBB = TI->getParent();
582   for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
583     if (PredCases[i].second == TIBB) {
584       if (TIV != 0)
585         return false;  // Cannot handle multiple values coming to this block.
586       TIV = PredCases[i].first;
587     }
588   assert(TIV && "No edge from pred to succ?");
589
590   // Okay, we found the one constant that our value can be if we get into TI's
591   // BB.  Find out which successor will unconditionally be branched to.
592   BasicBlock *TheRealDest = 0;
593   for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
594     if (ThisCases[i].first == TIV) {
595       TheRealDest = ThisCases[i].second;
596       break;
597     }
598
599   // If not handled by any explicit cases, it is handled by the default case.
600   if (TheRealDest == 0) TheRealDest = ThisDef;
601
602   // Remove PHI node entries for dead edges.
603   BasicBlock *CheckEdge = TheRealDest;
604   for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
605     if (*SI != CheckEdge)
606       (*SI)->removePredecessor(TIBB);
607     else
608       CheckEdge = 0;
609
610   // Insert the new branch.
611   Instruction *NI = BranchInst::Create(TheRealDest, TI);
612   (void) NI;
613
614   DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
615             << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
616
617   EraseTerminatorInstAndDCECond(TI);
618   return true;
619 }
620
621 namespace {
622   /// ConstantIntOrdering - This class implements a stable ordering of constant
623   /// integers that does not depend on their address.  This is important for
624   /// applications that sort ConstantInt's to ensure uniqueness.
625   struct ConstantIntOrdering {
626     bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
627       return LHS->getValue().ult(RHS->getValue());
628     }
629   };
630 }
631
632 static int ConstantIntSortPredicate(const void *P1, const void *P2) {
633   const ConstantInt *LHS = *(const ConstantInt**)P1;
634   const ConstantInt *RHS = *(const ConstantInt**)P2;
635   if (LHS->getValue().ult(RHS->getValue()))
636     return 1;
637   if (LHS->getValue() == RHS->getValue())
638     return 0;
639   return -1;
640 }
641
642 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
643 /// equality comparison instruction (either a switch or a branch on "X == c").
644 /// See if any of the predecessors of the terminator block are value comparisons
645 /// on the same value.  If so, and if safe to do so, fold them together.
646 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
647   BasicBlock *BB = TI->getParent();
648   Value *CV = isValueEqualityComparison(TI);  // CondVal
649   assert(CV && "Not a comparison?");
650   bool Changed = false;
651
652   SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
653   while (!Preds.empty()) {
654     BasicBlock *Pred = Preds.pop_back_val();
655
656     // See if the predecessor is a comparison with the same value.
657     TerminatorInst *PTI = Pred->getTerminator();
658     Value *PCV = isValueEqualityComparison(PTI);  // PredCondVal
659
660     if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
661       // Figure out which 'cases' to copy from SI to PSI.
662       std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
663       BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
664
665       std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
666       BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
667
668       // Based on whether the default edge from PTI goes to BB or not, fill in
669       // PredCases and PredDefault with the new switch cases we would like to
670       // build.
671       SmallVector<BasicBlock*, 8> NewSuccessors;
672
673       if (PredDefault == BB) {
674         // If this is the default destination from PTI, only the edges in TI
675         // that don't occur in PTI, or that branch to BB will be activated.
676         std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
677         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
678           if (PredCases[i].second != BB)
679             PTIHandled.insert(PredCases[i].first);
680           else {
681             // The default destination is BB, we don't need explicit targets.
682             std::swap(PredCases[i], PredCases.back());
683             PredCases.pop_back();
684             --i; --e;
685           }
686
687         // Reconstruct the new switch statement we will be building.
688         if (PredDefault != BBDefault) {
689           PredDefault->removePredecessor(Pred);
690           PredDefault = BBDefault;
691           NewSuccessors.push_back(BBDefault);
692         }
693         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
694           if (!PTIHandled.count(BBCases[i].first) &&
695               BBCases[i].second != BBDefault) {
696             PredCases.push_back(BBCases[i]);
697             NewSuccessors.push_back(BBCases[i].second);
698           }
699
700       } else {
701         // If this is not the default destination from PSI, only the edges
702         // in SI that occur in PSI with a destination of BB will be
703         // activated.
704         std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
705         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
706           if (PredCases[i].second == BB) {
707             PTIHandled.insert(PredCases[i].first);
708             std::swap(PredCases[i], PredCases.back());
709             PredCases.pop_back();
710             --i; --e;
711           }
712
713         // Okay, now we know which constants were sent to BB from the
714         // predecessor.  Figure out where they will all go now.
715         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
716           if (PTIHandled.count(BBCases[i].first)) {
717             // If this is one we are capable of getting...
718             PredCases.push_back(BBCases[i]);
719             NewSuccessors.push_back(BBCases[i].second);
720             PTIHandled.erase(BBCases[i].first);// This constant is taken care of
721           }
722
723         // If there are any constants vectored to BB that TI doesn't handle,
724         // they must go to the default destination of TI.
725         for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I = 
726                                     PTIHandled.begin(),
727                E = PTIHandled.end(); I != E; ++I) {
728           PredCases.push_back(std::make_pair(*I, BBDefault));
729           NewSuccessors.push_back(BBDefault);
730         }
731       }
732
733       // Okay, at this point, we know which new successor Pred will get.  Make
734       // sure we update the number of entries in the PHI nodes for these
735       // successors.
736       for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
737         AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
738
739       // Convert pointer to int before we switch.
740       if (CV->getType()->isPointerTy()) {
741         assert(TD && "Cannot switch on pointer without TargetData");
742         CV = new PtrToIntInst(CV, TD->getIntPtrType(CV->getContext()),
743                               "magicptr", PTI);
744       }
745
746       // Now that the successors are updated, create the new Switch instruction.
747       SwitchInst *NewSI = SwitchInst::Create(CV, PredDefault,
748                                              PredCases.size(), PTI);
749       for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
750         NewSI->addCase(PredCases[i].first, PredCases[i].second);
751
752       EraseTerminatorInstAndDCECond(PTI);
753
754       // Okay, last check.  If BB is still a successor of PSI, then we must
755       // have an infinite loop case.  If so, add an infinitely looping block
756       // to handle the case to preserve the behavior of the code.
757       BasicBlock *InfLoopBlock = 0;
758       for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
759         if (NewSI->getSuccessor(i) == BB) {
760           if (InfLoopBlock == 0) {
761             // Insert it at the end of the function, because it's either code,
762             // or it won't matter if it's hot. :)
763             InfLoopBlock = BasicBlock::Create(BB->getContext(),
764                                               "infloop", BB->getParent());
765             BranchInst::Create(InfLoopBlock, InfLoopBlock);
766           }
767           NewSI->setSuccessor(i, InfLoopBlock);
768         }
769
770       Changed = true;
771     }
772   }
773   return Changed;
774 }
775
776 // isSafeToHoistInvoke - If we would need to insert a select that uses the
777 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
778 // would need to do this), we can't hoist the invoke, as there is nowhere
779 // to put the select in this case.
780 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
781                                 Instruction *I1, Instruction *I2) {
782   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
783     PHINode *PN;
784     for (BasicBlock::iterator BBI = SI->begin();
785          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
786       Value *BB1V = PN->getIncomingValueForBlock(BB1);
787       Value *BB2V = PN->getIncomingValueForBlock(BB2);
788       if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
789         return false;
790       }
791     }
792   }
793   return true;
794 }
795
796 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
797 /// BB2, hoist any common code in the two blocks up into the branch block.  The
798 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
799 static bool HoistThenElseCodeToIf(BranchInst *BI) {
800   // This does very trivial matching, with limited scanning, to find identical
801   // instructions in the two blocks.  In particular, we don't want to get into
802   // O(M*N) situations here where M and N are the sizes of BB1 and BB2.  As
803   // such, we currently just scan for obviously identical instructions in an
804   // identical order.
805   BasicBlock *BB1 = BI->getSuccessor(0);  // The true destination.
806   BasicBlock *BB2 = BI->getSuccessor(1);  // The false destination
807
808   BasicBlock::iterator BB1_Itr = BB1->begin();
809   BasicBlock::iterator BB2_Itr = BB2->begin();
810
811   Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
812   while (isa<DbgInfoIntrinsic>(I1))
813     I1 = BB1_Itr++;
814   while (isa<DbgInfoIntrinsic>(I2))
815     I2 = BB2_Itr++;
816   if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) ||
817       !I1->isIdenticalToWhenDefined(I2) ||
818       (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
819     return false;
820
821   // If we get here, we can hoist at least one instruction.
822   BasicBlock *BIParent = BI->getParent();
823
824   do {
825     // If we are hoisting the terminator instruction, don't move one (making a
826     // broken BB), instead clone it, and remove BI.
827     if (isa<TerminatorInst>(I1))
828       goto HoistTerminator;
829
830     // For a normal instruction, we just move one to right before the branch,
831     // then replace all uses of the other with the first.  Finally, we remove
832     // the now redundant second instruction.
833     BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
834     if (!I2->use_empty())
835       I2->replaceAllUsesWith(I1);
836     I1->intersectOptionalDataWith(I2);
837     I2->eraseFromParent();
838
839     I1 = BB1_Itr++;
840     while (isa<DbgInfoIntrinsic>(I1))
841       I1 = BB1_Itr++;
842     I2 = BB2_Itr++;
843     while (isa<DbgInfoIntrinsic>(I2))
844       I2 = BB2_Itr++;
845   } while (I1->getOpcode() == I2->getOpcode() &&
846            I1->isIdenticalToWhenDefined(I2));
847
848   return true;
849
850 HoistTerminator:
851   // It may not be possible to hoist an invoke.
852   if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
853     return true;
854
855   // Okay, it is safe to hoist the terminator.
856   Instruction *NT = I1->clone();
857   BIParent->getInstList().insert(BI, NT);
858   if (!NT->getType()->isVoidTy()) {
859     I1->replaceAllUsesWith(NT);
860     I2->replaceAllUsesWith(NT);
861     NT->takeName(I1);
862   }
863
864   // Hoisting one of the terminators from our successor is a great thing.
865   // Unfortunately, the successors of the if/else blocks may have PHI nodes in
866   // them.  If they do, all PHI entries for BB1/BB2 must agree for all PHI
867   // nodes, so we insert select instruction to compute the final result.
868   std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
869   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
870     PHINode *PN;
871     for (BasicBlock::iterator BBI = SI->begin();
872          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
873       Value *BB1V = PN->getIncomingValueForBlock(BB1);
874       Value *BB2V = PN->getIncomingValueForBlock(BB2);
875       if (BB1V == BB2V) continue;
876       
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 = SelectInst::Create(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   // Update any PHI nodes in our new successors.
891   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
892     AddPredecessorToBlock(*SI, BIParent, BB1);
893
894   EraseTerminatorInstAndDCECond(BI);
895   return true;
896 }
897
898 /// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
899 /// and an BB2 and the only successor of BB1 is BB2, hoist simple code
900 /// (for now, restricted to a single instruction that's side effect free) from
901 /// the BB1 into the branch block to speculatively execute it.
902 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
903   // Only speculatively execution a single instruction (not counting the
904   // terminator) for now.
905   Instruction *HInst = NULL;
906   Instruction *Term = BB1->getTerminator();
907   for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
908        BBI != BBE; ++BBI) {
909     Instruction *I = BBI;
910     // Skip debug info.
911     if (isa<DbgInfoIntrinsic>(I)) continue;
912     if (I == Term) break;
913
914     if (HInst)
915       return false;
916     HInst = I;
917   }
918   if (!HInst)
919     return false;
920
921   // Be conservative for now. FP select instruction can often be expensive.
922   Value *BrCond = BI->getCondition();
923   if (isa<FCmpInst>(BrCond))
924     return false;
925
926   // If BB1 is actually on the false edge of the conditional branch, remember
927   // to swap the select operands later.
928   bool Invert = false;
929   if (BB1 != BI->getSuccessor(0)) {
930     assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
931     Invert = true;
932   }
933
934   // Turn
935   // BB:
936   //     %t1 = icmp
937   //     br i1 %t1, label %BB1, label %BB2
938   // BB1:
939   //     %t3 = add %t2, c
940   //     br label BB2
941   // BB2:
942   // =>
943   // BB:
944   //     %t1 = icmp
945   //     %t4 = add %t2, c
946   //     %t3 = select i1 %t1, %t2, %t3
947   switch (HInst->getOpcode()) {
948   default: return false;  // Not safe / profitable to hoist.
949   case Instruction::Add:
950   case Instruction::Sub:
951     // Not worth doing for vector ops.
952     if (HInst->getType()->isVectorTy())
953       return false;
954     break;
955   case Instruction::And:
956   case Instruction::Or:
957   case Instruction::Xor:
958   case Instruction::Shl:
959   case Instruction::LShr:
960   case Instruction::AShr:
961     // Don't mess with vector operations.
962     if (HInst->getType()->isVectorTy())
963       return false;
964     break;   // These are all cheap and non-trapping instructions.
965   }
966   
967   // If the instruction is obviously dead, don't try to predicate it.
968   if (HInst->use_empty()) {
969     HInst->eraseFromParent();
970     return true;
971   }
972
973   // Can we speculatively execute the instruction? And what is the value 
974   // if the condition is false? Consider the phi uses, if the incoming value
975   // from the "if" block are all the same V, then V is the value of the
976   // select if the condition is false.
977   BasicBlock *BIParent = BI->getParent();
978   SmallVector<PHINode*, 4> PHIUses;
979   Value *FalseV = NULL;
980   
981   BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
982   for (Value::use_iterator UI = HInst->use_begin(), E = HInst->use_end();
983        UI != E; ++UI) {
984     // Ignore any user that is not a PHI node in BB2.  These can only occur in
985     // unreachable blocks, because they would not be dominated by the instr.
986     PHINode *PN = dyn_cast<PHINode>(*UI);
987     if (!PN || PN->getParent() != BB2)
988       return false;
989     PHIUses.push_back(PN);
990     
991     Value *PHIV = PN->getIncomingValueForBlock(BIParent);
992     if (!FalseV)
993       FalseV = PHIV;
994     else if (FalseV != PHIV)
995       return false;  // Inconsistent value when condition is false.
996   }
997   
998   assert(FalseV && "Must have at least one user, and it must be a PHI");
999
1000   // Do not hoist the instruction if any of its operands are defined but not
1001   // used in this BB. The transformation will prevent the operand from
1002   // being sunk into the use block.
1003   for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end(); 
1004        i != e; ++i) {
1005     Instruction *OpI = dyn_cast<Instruction>(*i);
1006     if (OpI && OpI->getParent() == BIParent &&
1007         !OpI->isUsedInBasicBlock(BIParent))
1008       return false;
1009   }
1010
1011   // If we get here, we can hoist the instruction. Try to place it
1012   // before the icmp instruction preceding the conditional branch.
1013   BasicBlock::iterator InsertPos = BI;
1014   if (InsertPos != BIParent->begin())
1015     --InsertPos;
1016   // Skip debug info between condition and branch.
1017   while (InsertPos != BIParent->begin() && isa<DbgInfoIntrinsic>(InsertPos))
1018     --InsertPos;
1019   if (InsertPos == BrCond && !isa<PHINode>(BrCond)) {
1020     SmallPtrSet<Instruction *, 4> BB1Insns;
1021     for(BasicBlock::iterator BB1I = BB1->begin(), BB1E = BB1->end(); 
1022         BB1I != BB1E; ++BB1I) 
1023       BB1Insns.insert(BB1I);
1024     for(Value::use_iterator UI = BrCond->use_begin(), UE = BrCond->use_end();
1025         UI != UE; ++UI) {
1026       Instruction *Use = cast<Instruction>(*UI);
1027       if (!BB1Insns.count(Use)) continue;
1028       
1029       // If BrCond uses the instruction that place it just before
1030       // branch instruction.
1031       InsertPos = BI;
1032       break;
1033     }
1034   } else
1035     InsertPos = BI;
1036   BIParent->getInstList().splice(InsertPos, BB1->getInstList(), HInst);
1037
1038   // Create a select whose true value is the speculatively executed value and
1039   // false value is the previously determined FalseV.
1040   SelectInst *SI;
1041   if (Invert)
1042     SI = SelectInst::Create(BrCond, FalseV, HInst,
1043                             FalseV->getName() + "." + HInst->getName(), BI);
1044   else
1045     SI = SelectInst::Create(BrCond, HInst, FalseV,
1046                             HInst->getName() + "." + FalseV->getName(), BI);
1047
1048   // Make the PHI node use the select for all incoming values for "then" and
1049   // "if" blocks.
1050   for (unsigned i = 0, e = PHIUses.size(); i != e; ++i) {
1051     PHINode *PN = PHIUses[i];
1052     for (unsigned j = 0, ee = PN->getNumIncomingValues(); j != ee; ++j)
1053       if (PN->getIncomingBlock(j) == BB1 || PN->getIncomingBlock(j) == BIParent)
1054         PN->setIncomingValue(j, SI);
1055   }
1056
1057   ++NumSpeculations;
1058   return true;
1059 }
1060
1061 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1062 /// across this block.
1063 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1064   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1065   unsigned Size = 0;
1066   
1067   for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1068     if (isa<DbgInfoIntrinsic>(BBI))
1069       continue;
1070     if (Size > 10) return false;  // Don't clone large BB's.
1071     ++Size;
1072     
1073     // We can only support instructions that do not define values that are
1074     // live outside of the current basic block.
1075     for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
1076          UI != E; ++UI) {
1077       Instruction *U = cast<Instruction>(*UI);
1078       if (U->getParent() != BB || isa<PHINode>(U)) return false;
1079     }
1080     
1081     // Looks ok, continue checking.
1082   }
1083
1084   return true;
1085 }
1086
1087 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1088 /// that is defined in the same block as the branch and if any PHI entries are
1089 /// constants, thread edges corresponding to that entry to be branches to their
1090 /// ultimate destination.
1091 static bool FoldCondBranchOnPHI(BranchInst *BI, const TargetData *TD) {
1092   BasicBlock *BB = BI->getParent();
1093   PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1094   // NOTE: we currently cannot transform this case if the PHI node is used
1095   // outside of the block.
1096   if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1097     return false;
1098   
1099   // Degenerate case of a single entry PHI.
1100   if (PN->getNumIncomingValues() == 1) {
1101     FoldSingleEntryPHINodes(PN->getParent());
1102     return true;    
1103   }
1104
1105   // Now we know that this block has multiple preds and two succs.
1106   if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1107   
1108   // Okay, this is a simple enough basic block.  See if any phi values are
1109   // constants.
1110   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1111     ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1112     if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue;
1113     
1114     // Okay, we now know that all edges from PredBB should be revectored to
1115     // branch to RealDest.
1116     BasicBlock *PredBB = PN->getIncomingBlock(i);
1117     BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1118     
1119     if (RealDest == BB) continue;  // Skip self loops.
1120     
1121     // The dest block might have PHI nodes, other predecessors and other
1122     // difficult cases.  Instead of being smart about this, just insert a new
1123     // block that jumps to the destination block, effectively splitting
1124     // the edge we are about to create.
1125     BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1126                                             RealDest->getName()+".critedge",
1127                                             RealDest->getParent(), RealDest);
1128     BranchInst::Create(RealDest, EdgeBB);
1129     
1130     // Update PHI nodes.
1131     AddPredecessorToBlock(RealDest, EdgeBB, BB);
1132
1133     // BB may have instructions that are being threaded over.  Clone these
1134     // instructions into EdgeBB.  We know that there will be no uses of the
1135     // cloned instructions outside of EdgeBB.
1136     BasicBlock::iterator InsertPt = EdgeBB->begin();
1137     DenseMap<Value*, Value*> TranslateMap;  // Track translated values.
1138     for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1139       if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1140         TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1141         continue;
1142       }
1143       // Clone the instruction.
1144       Instruction *N = BBI->clone();
1145       if (BBI->hasName()) N->setName(BBI->getName()+".c");
1146       
1147       // Update operands due to translation.
1148       for (User::op_iterator i = N->op_begin(), e = N->op_end();
1149            i != e; ++i) {
1150         DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1151         if (PI != TranslateMap.end())
1152           *i = PI->second;
1153       }
1154       
1155       // Check for trivial simplification.
1156       if (Value *V = SimplifyInstruction(N, TD)) {
1157         TranslateMap[BBI] = V;
1158         delete N;   // Instruction folded away, don't need actual inst
1159       } else {
1160         // Insert the new instruction into its new home.
1161         EdgeBB->getInstList().insert(InsertPt, N);
1162         if (!BBI->use_empty())
1163           TranslateMap[BBI] = N;
1164       }
1165     }
1166
1167     // Loop over all of the edges from PredBB to BB, changing them to branch
1168     // to EdgeBB instead.
1169     TerminatorInst *PredBBTI = PredBB->getTerminator();
1170     for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1171       if (PredBBTI->getSuccessor(i) == BB) {
1172         BB->removePredecessor(PredBB);
1173         PredBBTI->setSuccessor(i, EdgeBB);
1174       }
1175     
1176     // Recurse, simplifying any other constants.
1177     return FoldCondBranchOnPHI(BI, TD) | true;
1178   }
1179
1180   return false;
1181 }
1182
1183 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1184 /// PHI node, see if we can eliminate it.
1185 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetData *TD) {
1186   // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
1187   // statement", which has a very simple dominance structure.  Basically, we
1188   // are trying to find the condition that is being branched on, which
1189   // subsequently causes this merge to happen.  We really want control
1190   // dependence information for this check, but simplifycfg can't keep it up
1191   // to date, and this catches most of the cases we care about anyway.
1192   BasicBlock *BB = PN->getParent();
1193   BasicBlock *IfTrue, *IfFalse;
1194   Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1195   if (!IfCond ||
1196       // Don't bother if the branch will be constant folded trivially.
1197       isa<ConstantInt>(IfCond))
1198     return false;
1199   
1200   // Okay, we found that we can merge this two-entry phi node into a select.
1201   // Doing so would require us to fold *all* two entry phi nodes in this block.
1202   // At some point this becomes non-profitable (particularly if the target
1203   // doesn't support cmov's).  Only do this transformation if there are two or
1204   // fewer PHI nodes in this block.
1205   unsigned NumPhis = 0;
1206   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1207     if (NumPhis > 2)
1208       return false;
1209   
1210   // Loop over the PHI's seeing if we can promote them all to select
1211   // instructions.  While we are at it, keep track of the instructions
1212   // that need to be moved to the dominating block.
1213   SmallPtrSet<Instruction*, 4> AggressiveInsts;
1214   
1215   for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1216     PHINode *PN = cast<PHINode>(II++);
1217     if (Value *V = SimplifyInstruction(PN, TD)) {
1218       PN->replaceAllUsesWith(V);
1219       PN->eraseFromParent();
1220       continue;
1221     }
1222     
1223     if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts) ||
1224         !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts))
1225       return false;
1226   }
1227   
1228   // If we folded the the first phi, PN dangles at this point.  Refresh it.  If
1229   // we ran out of PHIs then we simplified them all.
1230   PN = dyn_cast<PHINode>(BB->begin());
1231   if (PN == 0) return true;
1232   
1233   // Don't fold i1 branches on PHIs which contain binary operators.  These can
1234   // often be turned into switches and other things.
1235   if (PN->getType()->isIntegerTy(1) &&
1236       (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1237        isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1238        isa<BinaryOperator>(IfCond)))
1239     return false;
1240   
1241   // If we all PHI nodes are promotable, check to make sure that all
1242   // instructions in the predecessor blocks can be promoted as well.  If
1243   // not, we won't be able to get rid of the control flow, so it's not
1244   // worth promoting to select instructions.
1245   BasicBlock *DomBlock = 0;
1246   BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1247   BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1248   if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1249     IfBlock1 = 0;
1250   } else {
1251     DomBlock = *pred_begin(IfBlock1);
1252     for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1253       if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1254         // This is not an aggressive instruction that we can promote.
1255         // Because of this, we won't be able to get rid of the control
1256         // flow, so the xform is not worth it.
1257         return false;
1258       }
1259   }
1260     
1261   if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1262     IfBlock2 = 0;
1263   } else {
1264     DomBlock = *pred_begin(IfBlock2);
1265     for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1266       if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1267         // This is not an aggressive instruction that we can promote.
1268         // Because of this, we won't be able to get rid of the control
1269         // flow, so the xform is not worth it.
1270         return false;
1271       }
1272   }
1273   
1274   DEBUG(dbgs() << "FOUND IF CONDITION!  " << *IfCond << "  T: "
1275                << IfTrue->getName() << "  F: " << IfFalse->getName() << "\n");
1276       
1277   // If we can still promote the PHI nodes after this gauntlet of tests,
1278   // do all of the PHI's now.
1279   Instruction *InsertPt = DomBlock->getTerminator();
1280   
1281   // Move all 'aggressive' instructions, which are defined in the
1282   // conditional parts of the if's up to the dominating block.
1283   if (IfBlock1)
1284     DomBlock->getInstList().splice(InsertPt,
1285                                    IfBlock1->getInstList(), IfBlock1->begin(),
1286                                    IfBlock1->getTerminator());
1287   if (IfBlock2)
1288     DomBlock->getInstList().splice(InsertPt,
1289                                    IfBlock2->getInstList(), IfBlock2->begin(),
1290                                    IfBlock2->getTerminator());
1291   
1292   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1293     // Change the PHI node into a select instruction.
1294     Value *TrueVal  = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1295     Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1296     
1297     Value *NV = SelectInst::Create(IfCond, TrueVal, FalseVal, "", InsertPt);
1298     PN->replaceAllUsesWith(NV);
1299     NV->takeName(PN);
1300     PN->eraseFromParent();
1301   }
1302   
1303   // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1304   // has been flattened.  Change DomBlock to jump directly to our new block to
1305   // avoid other simplifycfg's kicking in on the diamond.
1306   TerminatorInst *OldTI = DomBlock->getTerminator();
1307   BranchInst::Create(BB, OldTI);
1308   OldTI->eraseFromParent();
1309   return true;
1310 }
1311
1312 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1313 /// to two returning blocks, try to merge them together into one return,
1314 /// introducing a select if the return values disagree.
1315 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI) {
1316   assert(BI->isConditional() && "Must be a conditional branch");
1317   BasicBlock *TrueSucc = BI->getSuccessor(0);
1318   BasicBlock *FalseSucc = BI->getSuccessor(1);
1319   ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1320   ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1321   
1322   // Check to ensure both blocks are empty (just a return) or optionally empty
1323   // with PHI nodes.  If there are other instructions, merging would cause extra
1324   // computation on one path or the other.
1325   if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1326     return false;
1327   if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1328     return false;
1329
1330   // Okay, we found a branch that is going to two return nodes.  If
1331   // there is no return value for this function, just change the
1332   // branch into a return.
1333   if (FalseRet->getNumOperands() == 0) {
1334     TrueSucc->removePredecessor(BI->getParent());
1335     FalseSucc->removePredecessor(BI->getParent());
1336     ReturnInst::Create(BI->getContext(), 0, BI);
1337     EraseTerminatorInstAndDCECond(BI);
1338     return true;
1339   }
1340     
1341   // Otherwise, figure out what the true and false return values are
1342   // so we can insert a new select instruction.
1343   Value *TrueValue = TrueRet->getReturnValue();
1344   Value *FalseValue = FalseRet->getReturnValue();
1345   
1346   // Unwrap any PHI nodes in the return blocks.
1347   if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1348     if (TVPN->getParent() == TrueSucc)
1349       TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1350   if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1351     if (FVPN->getParent() == FalseSucc)
1352       FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1353   
1354   // In order for this transformation to be safe, we must be able to
1355   // unconditionally execute both operands to the return.  This is
1356   // normally the case, but we could have a potentially-trapping
1357   // constant expression that prevents this transformation from being
1358   // safe.
1359   if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1360     if (TCV->canTrap())
1361       return false;
1362   if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1363     if (FCV->canTrap())
1364       return false;
1365   
1366   // Okay, we collected all the mapped values and checked them for sanity, and
1367   // defined to really do this transformation.  First, update the CFG.
1368   TrueSucc->removePredecessor(BI->getParent());
1369   FalseSucc->removePredecessor(BI->getParent());
1370   
1371   // Insert select instructions where needed.
1372   Value *BrCond = BI->getCondition();
1373   if (TrueValue) {
1374     // Insert a select if the results differ.
1375     if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1376     } else if (isa<UndefValue>(TrueValue)) {
1377       TrueValue = FalseValue;
1378     } else {
1379       TrueValue = SelectInst::Create(BrCond, TrueValue,
1380                                      FalseValue, "retval", BI);
1381     }
1382   }
1383
1384   Value *RI = !TrueValue ?
1385               ReturnInst::Create(BI->getContext(), BI) :
1386               ReturnInst::Create(BI->getContext(), TrueValue, BI);
1387   (void) RI;
1388       
1389   DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1390                << "\n  " << *BI << "NewRet = " << *RI
1391                << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
1392       
1393   EraseTerminatorInstAndDCECond(BI);
1394
1395   return true;
1396 }
1397
1398 /// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
1399 /// and if a predecessor branches to us and one of our successors, fold the
1400 /// setcc into the predecessor and use logical operations to pick the right
1401 /// destination.
1402 bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
1403   BasicBlock *BB = BI->getParent();
1404   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
1405   if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
1406     Cond->getParent() != BB || !Cond->hasOneUse())
1407   return false;
1408   
1409   // Only allow this if the condition is a simple instruction that can be
1410   // executed unconditionally.  It must be in the same block as the branch, and
1411   // must be at the front of the block.
1412   BasicBlock::iterator FrontIt = BB->front();
1413   // Ignore dbg intrinsics.
1414   while (isa<DbgInfoIntrinsic>(FrontIt))
1415     ++FrontIt;
1416     
1417   // Allow a single instruction to be hoisted in addition to the compare
1418   // that feeds the branch.  We later ensure that any values that _it_ uses
1419   // were also live in the predecessor, so that we don't unnecessarily create
1420   // register pressure or inhibit out-of-order execution.
1421   Instruction *BonusInst = 0;
1422   if (&*FrontIt != Cond &&
1423       FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond &&
1424       FrontIt->isSafeToSpeculativelyExecute()) {
1425     BonusInst = &*FrontIt;
1426     ++FrontIt;
1427   }
1428   
1429   // Only a single bonus inst is allowed.
1430   if (&*FrontIt != Cond)
1431     return false;
1432   
1433   // Make sure the instruction after the condition is the cond branch.
1434   BasicBlock::iterator CondIt = Cond; ++CondIt;
1435   // Ingore dbg intrinsics.
1436   while(isa<DbgInfoIntrinsic>(CondIt))
1437     ++CondIt;
1438   if (&*CondIt != BI) {
1439     assert (!isa<DbgInfoIntrinsic>(CondIt) && "Hey do not forget debug info!");
1440     return false;
1441   }
1442
1443   // Cond is known to be a compare or binary operator.  Check to make sure that
1444   // neither operand is a potentially-trapping constant expression.
1445   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
1446     if (CE->canTrap())
1447       return false;
1448   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
1449     if (CE->canTrap())
1450       return false;
1451   
1452   
1453   // Finally, don't infinitely unroll conditional loops.
1454   BasicBlock *TrueDest  = BI->getSuccessor(0);
1455   BasicBlock *FalseDest = BI->getSuccessor(1);
1456   if (TrueDest == BB || FalseDest == BB)
1457     return false;
1458   
1459   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1460     BasicBlock *PredBlock = *PI;
1461     BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
1462     
1463     // Check that we have two conditional branches.  If there is a PHI node in
1464     // the common successor, verify that the same value flows in from both
1465     // blocks.
1466     if (PBI == 0 || PBI->isUnconditional() ||
1467         !SafeToMergeTerminators(BI, PBI))
1468       continue;
1469     
1470     // Ensure that any values used in the bonus instruction are also used
1471     // by the terminator of the predecessor.  This means that those values
1472     // must already have been resolved, so we won't be inhibiting the 
1473     // out-of-order core by speculating them earlier.
1474     if (BonusInst) {
1475       // Collect the values used by the bonus inst
1476       SmallPtrSet<Value*, 4> UsedValues;
1477       for (Instruction::op_iterator OI = BonusInst->op_begin(),
1478            OE = BonusInst->op_end(); OI != OE; ++OI) {
1479         Value* V = *OI;
1480         if (!isa<Constant>(V))
1481           UsedValues.insert(V);
1482       }
1483
1484       SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
1485       Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
1486       
1487       // Walk up to four levels back up the use-def chain of the predecessor's
1488       // terminator to see if all those values were used.  The choice of four
1489       // levels is arbitrary, to provide a compile-time-cost bound.
1490       while (!Worklist.empty()) {
1491         std::pair<Value*, unsigned> Pair = Worklist.back();
1492         Worklist.pop_back();
1493         
1494         if (Pair.second >= 4) continue;
1495         UsedValues.erase(Pair.first);
1496         if (UsedValues.empty()) break;
1497         
1498         if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
1499           for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1500                OI != OE; ++OI)
1501             Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
1502         }       
1503       }
1504       
1505       if (!UsedValues.empty()) return false;
1506     }
1507     
1508     Instruction::BinaryOps Opc;
1509     bool InvertPredCond = false;
1510
1511     if (PBI->getSuccessor(0) == TrueDest)
1512       Opc = Instruction::Or;
1513     else if (PBI->getSuccessor(1) == FalseDest)
1514       Opc = Instruction::And;
1515     else if (PBI->getSuccessor(0) == FalseDest)
1516       Opc = Instruction::And, InvertPredCond = true;
1517     else if (PBI->getSuccessor(1) == TrueDest)
1518       Opc = Instruction::Or, InvertPredCond = true;
1519     else
1520       continue;
1521
1522     DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
1523     
1524     // If we need to invert the condition in the pred block to match, do so now.
1525     if (InvertPredCond) {
1526       Value *NewCond = PBI->getCondition();
1527       
1528       if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
1529         CmpInst *CI = cast<CmpInst>(NewCond);
1530         CI->setPredicate(CI->getInversePredicate());
1531       } else {
1532         NewCond = BinaryOperator::CreateNot(NewCond,
1533                                   PBI->getCondition()->getName()+".not", PBI);
1534       }
1535       
1536       PBI->setCondition(NewCond);
1537       BasicBlock *OldTrue = PBI->getSuccessor(0);
1538       BasicBlock *OldFalse = PBI->getSuccessor(1);
1539       PBI->setSuccessor(0, OldFalse);
1540       PBI->setSuccessor(1, OldTrue);
1541     }
1542     
1543     // If we have a bonus inst, clone it into the predecessor block.
1544     Instruction *NewBonus = 0;
1545     if (BonusInst) {
1546       NewBonus = BonusInst->clone();
1547       PredBlock->getInstList().insert(PBI, NewBonus);
1548       NewBonus->takeName(BonusInst);
1549       BonusInst->setName(BonusInst->getName()+".old");
1550     }
1551     
1552     // Clone Cond into the predecessor basic block, and or/and the
1553     // two conditions together.
1554     Instruction *New = Cond->clone();
1555     if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
1556     PredBlock->getInstList().insert(PBI, New);
1557     New->takeName(Cond);
1558     Cond->setName(New->getName()+".old");
1559     
1560     Value *NewCond = BinaryOperator::Create(Opc, PBI->getCondition(),
1561                                             New, "or.cond", PBI);
1562     PBI->setCondition(NewCond);
1563     if (PBI->getSuccessor(0) == BB) {
1564       AddPredecessorToBlock(TrueDest, PredBlock, BB);
1565       PBI->setSuccessor(0, TrueDest);
1566     }
1567     if (PBI->getSuccessor(1) == BB) {
1568       AddPredecessorToBlock(FalseDest, PredBlock, BB);
1569       PBI->setSuccessor(1, FalseDest);
1570     }
1571     return true;
1572   }
1573   return false;
1574 }
1575
1576 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
1577 /// predecessor of another block, this function tries to simplify it.  We know
1578 /// that PBI and BI are both conditional branches, and BI is in one of the
1579 /// successor blocks of PBI - PBI branches to BI.
1580 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
1581   assert(PBI->isConditional() && BI->isConditional());
1582   BasicBlock *BB = BI->getParent();
1583
1584   // If this block ends with a branch instruction, and if there is a
1585   // predecessor that ends on a branch of the same condition, make 
1586   // this conditional branch redundant.
1587   if (PBI->getCondition() == BI->getCondition() &&
1588       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1589     // Okay, the outcome of this conditional branch is statically
1590     // knowable.  If this block had a single pred, handle specially.
1591     if (BB->getSinglePredecessor()) {
1592       // Turn this into a branch on constant.
1593       bool CondIsTrue = PBI->getSuccessor(0) == BB;
1594       BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()), 
1595                                         CondIsTrue));
1596       return true;  // Nuke the branch on constant.
1597     }
1598     
1599     // Otherwise, if there are multiple predecessors, insert a PHI that merges
1600     // in the constant and simplify the block result.  Subsequent passes of
1601     // simplifycfg will thread the block.
1602     if (BlockIsSimpleEnoughToThreadThrough(BB)) {
1603       PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
1604                                        BI->getCondition()->getName() + ".pr",
1605                                        BB->begin());
1606       // Okay, we're going to insert the PHI node.  Since PBI is not the only
1607       // predecessor, compute the PHI'd conditional value for all of the preds.
1608       // Any predecessor where the condition is not computable we keep symbolic.
1609       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1610         BasicBlock *P = *PI;
1611         if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
1612             PBI != BI && PBI->isConditional() &&
1613             PBI->getCondition() == BI->getCondition() &&
1614             PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1615           bool CondIsTrue = PBI->getSuccessor(0) == BB;
1616           NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()), 
1617                                               CondIsTrue), P);
1618         } else {
1619           NewPN->addIncoming(BI->getCondition(), P);
1620         }
1621       }
1622       
1623       BI->setCondition(NewPN);
1624       return true;
1625     }
1626   }
1627   
1628   // If this is a conditional branch in an empty block, and if any
1629   // predecessors is a conditional branch to one of our destinations,
1630   // fold the conditions into logical ops and one cond br.
1631   BasicBlock::iterator BBI = BB->begin();
1632   // Ignore dbg intrinsics.
1633   while (isa<DbgInfoIntrinsic>(BBI))
1634     ++BBI;
1635   if (&*BBI != BI)
1636     return false;
1637
1638   
1639   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
1640     if (CE->canTrap())
1641       return false;
1642   
1643   int PBIOp, BIOp;
1644   if (PBI->getSuccessor(0) == BI->getSuccessor(0))
1645     PBIOp = BIOp = 0;
1646   else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
1647     PBIOp = 0, BIOp = 1;
1648   else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
1649     PBIOp = 1, BIOp = 0;
1650   else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
1651     PBIOp = BIOp = 1;
1652   else
1653     return false;
1654     
1655   // Check to make sure that the other destination of this branch
1656   // isn't BB itself.  If so, this is an infinite loop that will
1657   // keep getting unwound.
1658   if (PBI->getSuccessor(PBIOp) == BB)
1659     return false;
1660     
1661   // Do not perform this transformation if it would require 
1662   // insertion of a large number of select instructions. For targets
1663   // without predication/cmovs, this is a big pessimization.
1664   BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1665       
1666   unsigned NumPhis = 0;
1667   for (BasicBlock::iterator II = CommonDest->begin();
1668        isa<PHINode>(II); ++II, ++NumPhis)
1669     if (NumPhis > 2) // Disable this xform.
1670       return false;
1671     
1672   // Finally, if everything is ok, fold the branches to logical ops.
1673   BasicBlock *OtherDest  = BI->getSuccessor(BIOp ^ 1);
1674   
1675   DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
1676                << "AND: " << *BI->getParent());
1677   
1678   
1679   // If OtherDest *is* BB, then BB is a basic block with a single conditional
1680   // branch in it, where one edge (OtherDest) goes back to itself but the other
1681   // exits.  We don't *know* that the program avoids the infinite loop
1682   // (even though that seems likely).  If we do this xform naively, we'll end up
1683   // recursively unpeeling the loop.  Since we know that (after the xform is
1684   // done) that the block *is* infinite if reached, we just make it an obviously
1685   // infinite loop with no cond branch.
1686   if (OtherDest == BB) {
1687     // Insert it at the end of the function, because it's either code,
1688     // or it won't matter if it's hot. :)
1689     BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
1690                                                   "infloop", BB->getParent());
1691     BranchInst::Create(InfLoopBlock, InfLoopBlock);
1692     OtherDest = InfLoopBlock;
1693   }  
1694   
1695   DEBUG(dbgs() << *PBI->getParent()->getParent());
1696   
1697   // BI may have other predecessors.  Because of this, we leave
1698   // it alone, but modify PBI.
1699   
1700   // Make sure we get to CommonDest on True&True directions.
1701   Value *PBICond = PBI->getCondition();
1702   if (PBIOp)
1703     PBICond = BinaryOperator::CreateNot(PBICond,
1704                                         PBICond->getName()+".not",
1705                                         PBI);
1706   Value *BICond = BI->getCondition();
1707   if (BIOp)
1708     BICond = BinaryOperator::CreateNot(BICond,
1709                                        BICond->getName()+".not",
1710                                        PBI);
1711   // Merge the conditions.
1712   Value *Cond = BinaryOperator::CreateOr(PBICond, BICond, "brmerge", PBI);
1713   
1714   // Modify PBI to branch on the new condition to the new dests.
1715   PBI->setCondition(Cond);
1716   PBI->setSuccessor(0, CommonDest);
1717   PBI->setSuccessor(1, OtherDest);
1718   
1719   // OtherDest may have phi nodes.  If so, add an entry from PBI's
1720   // block that are identical to the entries for BI's block.
1721   AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
1722   
1723   // We know that the CommonDest already had an edge from PBI to
1724   // it.  If it has PHIs though, the PHIs may have different
1725   // entries for BB and PBI's BB.  If so, insert a select to make
1726   // them agree.
1727   PHINode *PN;
1728   for (BasicBlock::iterator II = CommonDest->begin();
1729        (PN = dyn_cast<PHINode>(II)); ++II) {
1730     Value *BIV = PN->getIncomingValueForBlock(BB);
1731     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1732     Value *PBIV = PN->getIncomingValue(PBBIdx);
1733     if (BIV != PBIV) {
1734       // Insert a select in PBI to pick the right value.
1735       Value *NV = SelectInst::Create(PBICond, PBIV, BIV,
1736                                      PBIV->getName()+".mux", PBI);
1737       PN->setIncomingValue(PBBIdx, NV);
1738     }
1739   }
1740   
1741   DEBUG(dbgs() << "INTO: " << *PBI->getParent());
1742   DEBUG(dbgs() << *PBI->getParent()->getParent());
1743   
1744   // This basic block is probably dead.  We know it has at least
1745   // one fewer predecessor.
1746   return true;
1747 }
1748
1749 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
1750 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
1751 // Takes care of updating the successors and removing the old terminator.
1752 // Also makes sure not to introduce new successors by assuming that edges to
1753 // non-successor TrueBBs and FalseBBs aren't reachable.
1754 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
1755                                        BasicBlock *TrueBB, BasicBlock *FalseBB){
1756   // Remove any superfluous successor edges from the CFG.
1757   // First, figure out which successors to preserve.
1758   // If TrueBB and FalseBB are equal, only try to preserve one copy of that
1759   // successor.
1760   BasicBlock *KeepEdge1 = TrueBB;
1761   BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
1762
1763   // Then remove the rest.
1764   for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
1765     BasicBlock *Succ = OldTerm->getSuccessor(I);
1766     // Make sure only to keep exactly one copy of each edge.
1767     if (Succ == KeepEdge1)
1768       KeepEdge1 = 0;
1769     else if (Succ == KeepEdge2)
1770       KeepEdge2 = 0;
1771     else
1772       Succ->removePredecessor(OldTerm->getParent());
1773   }
1774
1775   // Insert an appropriate new terminator.
1776   if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
1777     if (TrueBB == FalseBB)
1778       // We were only looking for one successor, and it was present.
1779       // Create an unconditional branch to it.
1780       BranchInst::Create(TrueBB, OldTerm);
1781     else
1782       // We found both of the successors we were looking for.
1783       // Create a conditional branch sharing the condition of the select.
1784       BranchInst::Create(TrueBB, FalseBB, Cond, OldTerm);
1785   } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
1786     // Neither of the selected blocks were successors, so this
1787     // terminator must be unreachable.
1788     new UnreachableInst(OldTerm->getContext(), OldTerm);
1789   } else {
1790     // One of the selected values was a successor, but the other wasn't.
1791     // Insert an unconditional branch to the one that was found;
1792     // the edge to the one that wasn't must be unreachable.
1793     if (KeepEdge1 == 0)
1794       // Only TrueBB was found.
1795       BranchInst::Create(TrueBB, OldTerm);
1796     else
1797       // Only FalseBB was found.
1798       BranchInst::Create(FalseBB, OldTerm);
1799   }
1800
1801   EraseTerminatorInstAndDCECond(OldTerm);
1802   return true;
1803 }
1804
1805 // SimplifyIndirectBrOnSelect - Replaces
1806 //   (indirectbr (select cond, blockaddress(@fn, BlockA),
1807 //                             blockaddress(@fn, BlockB)))
1808 // with
1809 //   (br cond, BlockA, BlockB).
1810 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
1811   // Check that both operands of the select are block addresses.
1812   BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
1813   BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
1814   if (!TBA || !FBA)
1815     return false;
1816
1817   // Extract the actual blocks.
1818   BasicBlock *TrueBB = TBA->getBasicBlock();
1819   BasicBlock *FalseBB = FBA->getBasicBlock();
1820
1821   // Perform the actual simplification.
1822   return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB);
1823 }
1824
1825 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
1826 /// instruction (a seteq/setne with a constant) as the only instruction in a
1827 /// block that ends with an uncond branch.  We are looking for a very specific
1828 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified.  In
1829 /// this case, we merge the first two "or's of icmp" into a switch, but then the
1830 /// default value goes to an uncond block with a seteq in it, we get something
1831 /// like:
1832 ///
1833 ///   switch i8 %A, label %DEFAULT [ i8 1, label %end    i8 2, label %end ]
1834 /// DEFAULT:
1835 ///   %tmp = icmp eq i8 %A, 92
1836 ///   br label %end
1837 /// end:
1838 ///   ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
1839 /// 
1840 /// We prefer to split the edge to 'end' so that there is a true/false entry to
1841 /// the PHI, merging the third icmp into the switch.
1842 static bool TryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
1843                                                   const TargetData *TD) {
1844   BasicBlock *BB = ICI->getParent();
1845   // If the block has any PHIs in it or the icmp has multiple uses, it is too
1846   // complex.
1847   if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
1848
1849   Value *V = ICI->getOperand(0);
1850   ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
1851   
1852   // The pattern we're looking for is where our only predecessor is a switch on
1853   // 'V' and this block is the default case for the switch.  In this case we can
1854   // fold the compared value into the switch to simplify things.
1855   BasicBlock *Pred = BB->getSinglePredecessor();
1856   if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator())) return false;
1857   
1858   SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
1859   if (SI->getCondition() != V)
1860     return false;
1861   
1862   // If BB is reachable on a non-default case, then we simply know the value of
1863   // V in this block.  Substitute it and constant fold the icmp instruction
1864   // away.
1865   if (SI->getDefaultDest() != BB) {
1866     ConstantInt *VVal = SI->findCaseDest(BB);
1867     assert(VVal && "Should have a unique destination value");
1868     ICI->setOperand(0, VVal);
1869     
1870     if (Value *V = SimplifyInstruction(ICI, TD)) {
1871       ICI->replaceAllUsesWith(V);
1872       ICI->eraseFromParent();
1873     }
1874     // BB is now empty, so it is likely to simplify away.
1875     return SimplifyCFG(BB) | true;
1876   }
1877   
1878   // Ok, the block is reachable from the default dest.  If the constant we're
1879   // comparing exists in one of the other edges, then we can constant fold ICI
1880   // and zap it.
1881   if (SI->findCaseValue(Cst) != 0) {
1882     Value *V;
1883     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1884       V = ConstantInt::getFalse(BB->getContext());
1885     else
1886       V = ConstantInt::getTrue(BB->getContext());
1887     
1888     ICI->replaceAllUsesWith(V);
1889     ICI->eraseFromParent();
1890     // BB is now empty, so it is likely to simplify away.
1891     return SimplifyCFG(BB) | true;
1892   }
1893   
1894   // The use of the icmp has to be in the 'end' block, by the only PHI node in
1895   // the block.
1896   BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
1897   PHINode *PHIUse = dyn_cast<PHINode>(ICI->use_back());
1898   if (PHIUse == 0 || PHIUse != &SuccBlock->front() ||
1899       isa<PHINode>(++BasicBlock::iterator(PHIUse)))
1900     return false;
1901
1902   // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
1903   // true in the PHI.
1904   Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
1905   Constant *NewCst     = ConstantInt::getFalse(BB->getContext());
1906
1907   if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1908     std::swap(DefaultCst, NewCst);
1909
1910   // Replace ICI (which is used by the PHI for the default value) with true or
1911   // false depending on if it is EQ or NE.
1912   ICI->replaceAllUsesWith(DefaultCst);
1913   ICI->eraseFromParent();
1914
1915   // Okay, the switch goes to this block on a default value.  Add an edge from
1916   // the switch to the merge point on the compared value.
1917   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
1918                                          BB->getParent(), BB);
1919   SI->addCase(Cst, NewBB);
1920   
1921   // NewBB branches to the phi block, add the uncond branch and the phi entry.
1922   BranchInst::Create(SuccBlock, NewBB);
1923   PHIUse->addIncoming(NewCst, NewBB);
1924   return true;
1925 }
1926
1927 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
1928 /// Check to see if it is branching on an or/and chain of icmp instructions, and
1929 /// fold it into a switch instruction if so.
1930 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const TargetData *TD) {
1931   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
1932   if (Cond == 0) return false;
1933   
1934   
1935   // Change br (X == 0 | X == 1), T, F into a switch instruction.
1936   // If this is a bunch of seteq's or'd together, or if it's a bunch of
1937   // 'setne's and'ed together, collect them.
1938   Value *CompVal = 0;
1939   std::vector<ConstantInt*> Values;
1940   bool TrueWhenEqual = true;
1941   Value *ExtraCase = 0;
1942   unsigned UsedICmps = 0;
1943   
1944   if (Cond->getOpcode() == Instruction::Or) {
1945     CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, true,
1946                                      UsedICmps);
1947   } else if (Cond->getOpcode() == Instruction::And) {
1948     CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, false,
1949                                      UsedICmps);
1950     TrueWhenEqual = false;
1951   }
1952   
1953   // If we didn't have a multiply compared value, fail.
1954   if (CompVal == 0) return false;
1955
1956   // Avoid turning single icmps into a switch.
1957   if (UsedICmps <= 1)
1958     return false;
1959
1960   // There might be duplicate constants in the list, which the switch
1961   // instruction can't handle, remove them now.
1962   array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
1963   Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
1964   
1965   // If Extra was used, we require at least two switch values to do the
1966   // transformation.  A switch with one value is just an cond branch.
1967   if (ExtraCase && Values.size() < 2) return false;
1968   
1969   // Figure out which block is which destination.
1970   BasicBlock *DefaultBB = BI->getSuccessor(1);
1971   BasicBlock *EdgeBB    = BI->getSuccessor(0);
1972   if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
1973   
1974   BasicBlock *BB = BI->getParent();
1975   
1976   DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
1977                << " cases into SWITCH.  BB is:\n" << *BB);
1978   
1979   // If there are any extra values that couldn't be folded into the switch
1980   // then we evaluate them with an explicit branch first.  Split the block
1981   // right before the condbr to handle it.
1982   if (ExtraCase) {
1983     BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
1984     // Remove the uncond branch added to the old block.
1985     TerminatorInst *OldTI = BB->getTerminator();
1986     
1987     if (TrueWhenEqual)
1988       BranchInst::Create(EdgeBB, NewBB, ExtraCase, OldTI);
1989     else
1990       BranchInst::Create(NewBB, EdgeBB, ExtraCase, OldTI);
1991       
1992     OldTI->eraseFromParent();
1993     
1994     // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
1995     // for the edge we just added.
1996     AddPredecessorToBlock(EdgeBB, BB, NewBB);
1997     
1998     DEBUG(dbgs() << "  ** 'icmp' chain unhandled condition: " << *ExtraCase
1999           << "\nEXTRABB = " << *BB);
2000     BB = NewBB;
2001   }
2002   
2003   // Convert pointer to int before we switch.
2004   if (CompVal->getType()->isPointerTy()) {
2005     assert(TD && "Cannot switch on pointer without TargetData");
2006     CompVal = new PtrToIntInst(CompVal,
2007                                TD->getIntPtrType(CompVal->getContext()),
2008                                "magicptr", BI);
2009   }
2010   
2011   // Create the new switch instruction now.
2012   SwitchInst *New = SwitchInst::Create(CompVal, DefaultBB, Values.size(), BI);
2013   
2014   // Add all of the 'cases' to the switch instruction.
2015   for (unsigned i = 0, e = Values.size(); i != e; ++i)
2016     New->addCase(Values[i], EdgeBB);
2017   
2018   // We added edges from PI to the EdgeBB.  As such, if there were any
2019   // PHI nodes in EdgeBB, they need entries to be added corresponding to
2020   // the number of edges added.
2021   for (BasicBlock::iterator BBI = EdgeBB->begin();
2022        isa<PHINode>(BBI); ++BBI) {
2023     PHINode *PN = cast<PHINode>(BBI);
2024     Value *InVal = PN->getIncomingValueForBlock(BB);
2025     for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2026       PN->addIncoming(InVal, BB);
2027   }
2028   
2029   // Erase the old branch instruction.
2030   EraseTerminatorInstAndDCECond(BI);
2031   
2032   DEBUG(dbgs() << "  ** 'icmp' chain result is:\n" << *BB << '\n');
2033   return true;
2034 }
2035
2036 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI) {
2037   BasicBlock *BB = RI->getParent();
2038   if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2039   
2040   // Find predecessors that end with branches.
2041   SmallVector<BasicBlock*, 8> UncondBranchPreds;
2042   SmallVector<BranchInst*, 8> CondBranchPreds;
2043   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2044     BasicBlock *P = *PI;
2045     TerminatorInst *PTI = P->getTerminator();
2046     if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2047       if (BI->isUnconditional())
2048         UncondBranchPreds.push_back(P);
2049       else
2050         CondBranchPreds.push_back(BI);
2051     }
2052   }
2053   
2054   // If we found some, do the transformation!
2055   if (!UncondBranchPreds.empty() && DupRet) {
2056     while (!UncondBranchPreds.empty()) {
2057       BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2058       DEBUG(dbgs() << "FOLDING: " << *BB
2059             << "INTO UNCOND BRANCH PRED: " << *Pred);
2060       (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
2061     }
2062     
2063     // If we eliminated all predecessors of the block, delete the block now.
2064     if (pred_begin(BB) == pred_end(BB))
2065       // We know there are no successors, so just nuke the block.
2066       BB->eraseFromParent();
2067     
2068     return true;
2069   }
2070   
2071   // Check out all of the conditional branches going to this return
2072   // instruction.  If any of them just select between returns, change the
2073   // branch itself into a select/return pair.
2074   while (!CondBranchPreds.empty()) {
2075     BranchInst *BI = CondBranchPreds.pop_back_val();
2076     
2077     // Check to see if the non-BB successor is also a return block.
2078     if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2079         isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
2080         SimplifyCondBranchToTwoReturns(BI))
2081       return true;
2082   }
2083   return false;
2084 }
2085
2086 bool SimplifyCFGOpt::SimplifyUnwind(UnwindInst *UI) {
2087   // Check to see if the first instruction in this block is just an unwind.
2088   // If so, replace any invoke instructions which use this as an exception
2089   // destination with call instructions.
2090   BasicBlock *BB = UI->getParent();
2091   if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2092
2093   bool Changed = false;
2094   SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2095   while (!Preds.empty()) {
2096     BasicBlock *Pred = Preds.back();
2097     InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator());
2098     if (II && II->getUnwindDest() == BB) {
2099       // Insert a new branch instruction before the invoke, because this
2100       // is now a fall through.
2101       BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
2102       Pred->getInstList().remove(II);   // Take out of symbol table
2103       
2104       // Insert the call now.
2105       SmallVector<Value*,8> Args(II->op_begin(), II->op_end()-3);
2106       CallInst *CI = CallInst::Create(II->getCalledValue(),
2107                                       Args.begin(), Args.end(),
2108                                       II->getName(), BI);
2109       CI->setCallingConv(II->getCallingConv());
2110       CI->setAttributes(II->getAttributes());
2111       // If the invoke produced a value, the Call now does instead.
2112       II->replaceAllUsesWith(CI);
2113       delete II;
2114       Changed = true;
2115     }
2116     
2117     Preds.pop_back();
2118   }
2119   
2120   // If this block is now dead (and isn't the entry block), remove it.
2121   if (pred_begin(BB) == pred_end(BB) &&
2122       BB != &BB->getParent()->getEntryBlock()) {
2123     // We know there are no successors, so just nuke the block.
2124     BB->eraseFromParent();
2125     return true;
2126   }
2127   
2128   return Changed;  
2129 }
2130
2131 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2132   BasicBlock *BB = UI->getParent();
2133   
2134   bool Changed = false;
2135   
2136   // If there are any instructions immediately before the unreachable that can
2137   // be removed, do so.
2138   while (UI != BB->begin()) {
2139     BasicBlock::iterator BBI = UI;
2140     --BBI;
2141     // Do not delete instructions that can have side effects, like calls
2142     // (which may never return) and volatile loads and stores.
2143     if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
2144     
2145     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
2146       if (SI->isVolatile())
2147         break;
2148     
2149     if (LoadInst *LI = dyn_cast<LoadInst>(BBI))
2150       if (LI->isVolatile())
2151         break;
2152     
2153     // Delete this instruction
2154     BBI->eraseFromParent();
2155     Changed = true;
2156   }
2157   
2158   // If the unreachable instruction is the first in the block, take a gander
2159   // at all of the predecessors of this instruction, and simplify them.
2160   if (&BB->front() != UI) return Changed;
2161   
2162   SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2163   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2164     TerminatorInst *TI = Preds[i]->getTerminator();
2165     
2166     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2167       if (BI->isUnconditional()) {
2168         if (BI->getSuccessor(0) == BB) {
2169           new UnreachableInst(TI->getContext(), TI);
2170           TI->eraseFromParent();
2171           Changed = true;
2172         }
2173       } else {
2174         if (BI->getSuccessor(0) == BB) {
2175           BranchInst::Create(BI->getSuccessor(1), BI);
2176           EraseTerminatorInstAndDCECond(BI);
2177         } else if (BI->getSuccessor(1) == BB) {
2178           BranchInst::Create(BI->getSuccessor(0), BI);
2179           EraseTerminatorInstAndDCECond(BI);
2180           Changed = true;
2181         }
2182       }
2183     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2184       for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2185         if (SI->getSuccessor(i) == BB) {
2186           BB->removePredecessor(SI->getParent());
2187           SI->removeCase(i);
2188           --i; --e;
2189           Changed = true;
2190         }
2191       // If the default value is unreachable, figure out the most popular
2192       // destination and make it the default.
2193       if (SI->getSuccessor(0) == BB) {
2194         std::map<BasicBlock*, unsigned> Popularity;
2195         for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2196           Popularity[SI->getSuccessor(i)]++;
2197         
2198         // Find the most popular block.
2199         unsigned MaxPop = 0;
2200         BasicBlock *MaxBlock = 0;
2201         for (std::map<BasicBlock*, unsigned>::iterator
2202              I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
2203           if (I->second > MaxPop) {
2204             MaxPop = I->second;
2205             MaxBlock = I->first;
2206           }
2207         }
2208         if (MaxBlock) {
2209           // Make this the new default, allowing us to delete any explicit
2210           // edges to it.
2211           SI->setSuccessor(0, MaxBlock);
2212           Changed = true;
2213           
2214           // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
2215           // it.
2216           if (isa<PHINode>(MaxBlock->begin()))
2217             for (unsigned i = 0; i != MaxPop-1; ++i)
2218               MaxBlock->removePredecessor(SI->getParent());
2219           
2220           for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2221             if (SI->getSuccessor(i) == MaxBlock) {
2222               SI->removeCase(i);
2223               --i; --e;
2224             }
2225         }
2226       }
2227     } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
2228       if (II->getUnwindDest() == BB) {
2229         // Convert the invoke to a call instruction.  This would be a good
2230         // place to note that the call does not throw though.
2231         BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
2232         II->removeFromParent();   // Take out of symbol table
2233         
2234         // Insert the call now...
2235         SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
2236         CallInst *CI = CallInst::Create(II->getCalledValue(),
2237                                         Args.begin(), Args.end(),
2238                                         II->getName(), BI);
2239         CI->setCallingConv(II->getCallingConv());
2240         CI->setAttributes(II->getAttributes());
2241         // If the invoke produced a value, the call does now instead.
2242         II->replaceAllUsesWith(CI);
2243         delete II;
2244         Changed = true;
2245       }
2246     }
2247   }
2248   
2249   // If this block is now dead, remove it.
2250   if (pred_begin(BB) == pred_end(BB) &&
2251       BB != &BB->getParent()->getEntryBlock()) {
2252     // We know there are no successors, so just nuke the block.
2253     BB->eraseFromParent();
2254     return true;
2255   }
2256
2257   return Changed;
2258 }
2259
2260 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
2261 /// integer range comparison into a sub, an icmp and a branch.
2262 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI) {
2263   assert(SI->getNumCases() > 2 && "Degenerate switch?");
2264
2265   // Make sure all cases point to the same destination and gather the values.
2266   SmallVector<ConstantInt *, 16> Cases;
2267   Cases.push_back(SI->getCaseValue(1));
2268   for (unsigned I = 2, E = SI->getNumCases(); I != E; ++I) {
2269     if (SI->getSuccessor(I-1) != SI->getSuccessor(I))
2270       return false;
2271     Cases.push_back(SI->getCaseValue(I));
2272   }
2273   assert(Cases.size() == SI->getNumCases()-1 && "Not all cases gathered");
2274
2275   // Sort the case values, then check if they form a range we can transform.
2276   array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
2277   for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
2278     if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
2279       return false;
2280   }
2281
2282   Constant *Offset = ConstantExpr::getNeg(Cases.back());
2283   Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases()-1);
2284
2285   Value *Sub = SI->getCondition();
2286   if (!Offset->isNullValue())
2287     Sub = BinaryOperator::CreateAdd(Sub, Offset, Sub->getName()+".off", SI);
2288   Value *Cmp = new ICmpInst(SI, ICmpInst::ICMP_ULT, Sub, NumCases, "switch");
2289   BranchInst::Create(SI->getSuccessor(1), SI->getDefaultDest(), Cmp, SI);
2290
2291   // Prune obsolete incoming values off the successor's PHI nodes.
2292   for (BasicBlock::iterator BBI = SI->getSuccessor(1)->begin();
2293        isa<PHINode>(BBI); ++BBI) {
2294     for (unsigned I = 0, E = SI->getNumCases()-2; I != E; ++I)
2295       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
2296   }
2297   SI->eraseFromParent();
2298
2299   return true;
2300 }
2301
2302 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI) {
2303   // If this switch is too complex to want to look at, ignore it.
2304   if (!isValueEqualityComparison(SI))
2305     return false;
2306
2307   BasicBlock *BB = SI->getParent();
2308
2309   // If we only have one predecessor, and if it is a branch on this value,
2310   // see if that predecessor totally determines the outcome of this switch.
2311   if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
2312     if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
2313       return SimplifyCFG(BB) | true;
2314   
2315   // If the block only contains the switch, see if we can fold the block
2316   // away into any preds.
2317   BasicBlock::iterator BBI = BB->begin();
2318   // Ignore dbg intrinsics.
2319   while (isa<DbgInfoIntrinsic>(BBI))
2320     ++BBI;
2321   if (SI == &*BBI)
2322     if (FoldValueComparisonIntoPredecessors(SI))
2323       return SimplifyCFG(BB) | true;
2324
2325   // Try to transform the switch into an icmp and a branch.
2326   if (TurnSwitchRangeIntoICmp(SI))
2327     return SimplifyCFG(BB) | true;
2328   
2329   return false;
2330 }
2331
2332 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
2333   BasicBlock *BB = IBI->getParent();
2334   bool Changed = false;
2335   
2336   // Eliminate redundant destinations.
2337   SmallPtrSet<Value *, 8> Succs;
2338   for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
2339     BasicBlock *Dest = IBI->getDestination(i);
2340     if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
2341       Dest->removePredecessor(BB);
2342       IBI->removeDestination(i);
2343       --i; --e;
2344       Changed = true;
2345     }
2346   } 
2347
2348   if (IBI->getNumDestinations() == 0) {
2349     // If the indirectbr has no successors, change it to unreachable.
2350     new UnreachableInst(IBI->getContext(), IBI);
2351     EraseTerminatorInstAndDCECond(IBI);
2352     return true;
2353   }
2354   
2355   if (IBI->getNumDestinations() == 1) {
2356     // If the indirectbr has one successor, change it to a direct branch.
2357     BranchInst::Create(IBI->getDestination(0), IBI);
2358     EraseTerminatorInstAndDCECond(IBI);
2359     return true;
2360   }
2361   
2362   if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
2363     if (SimplifyIndirectBrOnSelect(IBI, SI))
2364       return SimplifyCFG(BB) | true;
2365   }
2366   return Changed;
2367 }
2368
2369 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI) {
2370   BasicBlock *BB = BI->getParent();
2371   
2372   // If the Terminator is the only non-phi instruction, simplify the block.
2373   BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
2374   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
2375       TryToSimplifyUncondBranchFromEmptyBlock(BB))
2376     return true;
2377   
2378   // If the only instruction in the block is a seteq/setne comparison
2379   // against a constant, try to simplify the block.
2380   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
2381     if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
2382       for (++I; isa<DbgInfoIntrinsic>(I); ++I)
2383         ;
2384       if (I->isTerminator() && TryToSimplifyUncondBranchWithICmpInIt(ICI, TD))
2385         return true;
2386     }
2387   
2388   return false;
2389 }
2390
2391
2392 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI) {
2393   BasicBlock *BB = BI->getParent();
2394   
2395   // Conditional branch
2396   if (isValueEqualityComparison(BI)) {
2397     // If we only have one predecessor, and if it is a branch on this value,
2398     // see if that predecessor totally determines the outcome of this
2399     // switch.
2400     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
2401       if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
2402         return SimplifyCFG(BB) | true;
2403     
2404     // This block must be empty, except for the setcond inst, if it exists.
2405     // Ignore dbg intrinsics.
2406     BasicBlock::iterator I = BB->begin();
2407     // Ignore dbg intrinsics.
2408     while (isa<DbgInfoIntrinsic>(I))
2409       ++I;
2410     if (&*I == BI) {
2411       if (FoldValueComparisonIntoPredecessors(BI))
2412         return SimplifyCFG(BB) | true;
2413     } else if (&*I == cast<Instruction>(BI->getCondition())){
2414       ++I;
2415       // Ignore dbg intrinsics.
2416       while (isa<DbgInfoIntrinsic>(I))
2417         ++I;
2418       if (&*I == BI && FoldValueComparisonIntoPredecessors(BI))
2419         return SimplifyCFG(BB) | true;
2420     }
2421   }
2422   
2423   // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
2424   if (SimplifyBranchOnICmpChain(BI, TD))
2425     return true;
2426   
2427   // We have a conditional branch to two blocks that are only reachable
2428   // from BI.  We know that the condbr dominates the two blocks, so see if
2429   // there is any identical code in the "then" and "else" blocks.  If so, we
2430   // can hoist it up to the branching block.
2431   if (BI->getSuccessor(0)->getSinglePredecessor() != 0) {
2432     if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
2433       if (HoistThenElseCodeToIf(BI))
2434         return SimplifyCFG(BB) | true;
2435     } else {
2436       // If Successor #1 has multiple preds, we may be able to conditionally
2437       // execute Successor #0 if it branches to successor #1.
2438       TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
2439       if (Succ0TI->getNumSuccessors() == 1 &&
2440           Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
2441         if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
2442           return SimplifyCFG(BB) | true;
2443     }
2444   } else if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
2445     // If Successor #0 has multiple preds, we may be able to conditionally
2446     // execute Successor #1 if it branches to successor #0.
2447     TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
2448     if (Succ1TI->getNumSuccessors() == 1 &&
2449         Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
2450       if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
2451         return SimplifyCFG(BB) | true;
2452   }
2453   
2454   // If this is a branch on a phi node in the current block, thread control
2455   // through this block if any PHI node entries are constants.
2456   if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
2457     if (PN->getParent() == BI->getParent())
2458       if (FoldCondBranchOnPHI(BI, TD))
2459         return SimplifyCFG(BB) | true;
2460   
2461   // If this basic block is ONLY a setcc and a branch, and if a predecessor
2462   // branches to us and one of our successors, fold the setcc into the
2463   // predecessor and use logical operations to pick the right destination.
2464   if (FoldBranchToCommonDest(BI))
2465     return SimplifyCFG(BB) | true;
2466   
2467   // Scan predecessor blocks for conditional branches.
2468   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2469     if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
2470       if (PBI != BI && PBI->isConditional())
2471         if (SimplifyCondBranchToCondBranch(PBI, BI))
2472           return SimplifyCFG(BB) | true;
2473
2474   return false;
2475 }
2476
2477 bool SimplifyCFGOpt::run(BasicBlock *BB) {
2478   bool Changed = false;
2479
2480   assert(BB && BB->getParent() && "Block not embedded in function!");
2481   assert(BB->getTerminator() && "Degenerate basic block encountered!");
2482
2483   // Remove basic blocks that have no predecessors (except the entry block)...
2484   // or that just have themself as a predecessor.  These are unreachable.
2485   if ((pred_begin(BB) == pred_end(BB) &&
2486        BB != &BB->getParent()->getEntryBlock()) ||
2487       BB->getSinglePredecessor() == BB) {
2488     DEBUG(dbgs() << "Removing BB: \n" << *BB);
2489     DeleteDeadBlock(BB);
2490     return true;
2491   }
2492
2493   // Check to see if we can constant propagate this terminator instruction
2494   // away...
2495   Changed |= ConstantFoldTerminator(BB);
2496
2497   // Check for and eliminate duplicate PHI nodes in this block.
2498   Changed |= EliminateDuplicatePHINodes(BB);
2499
2500   // Merge basic blocks into their predecessor if there is only one distinct
2501   // pred, and if there is only one distinct successor of the predecessor, and
2502   // if there are no PHI nodes.
2503   //
2504   if (MergeBlockIntoPredecessor(BB))
2505     return true;
2506   
2507   // If there is a trivial two-entry PHI node in this basic block, and we can
2508   // eliminate it, do so now.
2509   if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
2510     if (PN->getNumIncomingValues() == 2)
2511       Changed |= FoldTwoEntryPHINode(PN, TD);
2512
2513   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
2514     if (BI->isUnconditional()) {
2515       if (SimplifyUncondBranch(BI)) return true;
2516     } else {
2517       if (SimplifyCondBranch(BI)) return true;
2518     }
2519   } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
2520     if (SimplifyReturn(RI)) return true;
2521   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2522     if (SimplifySwitch(SI)) return true;
2523   } else if (UnreachableInst *UI =
2524                dyn_cast<UnreachableInst>(BB->getTerminator())) {
2525     if (SimplifyUnreachable(UI)) return true;
2526   } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
2527     if (SimplifyUnwind(UI)) return true;
2528   } else if (IndirectBrInst *IBI =
2529                dyn_cast<IndirectBrInst>(BB->getTerminator())) {
2530     if (SimplifyIndirectBr(IBI)) return true;
2531   }
2532
2533   return Changed;
2534 }
2535
2536 /// SimplifyCFG - This function is used to do simplification of a CFG.  For
2537 /// example, it adjusts branches to branches to eliminate the extra hop, it
2538 /// eliminates unreachable basic blocks, and does other "peephole" optimization
2539 /// of the CFG.  It returns true if a modification was made.
2540 ///
2541 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetData *TD) {
2542   return SimplifyCFGOpt(TD).run(BB);
2543 }