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