LLVM API Documentation

SimplifyCFG.cpp

Go to the documentation of this file.
00001 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Peephole optimize the CFG.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "simplifycfg"
00015 #include "llvm/Transforms/Utils/Local.h"
00016 #include "llvm/Constants.h"
00017 #include "llvm/Instructions.h"
00018 #include "llvm/Type.h"
00019 #include "llvm/Support/CFG.h"
00020 #include "llvm/Support/Debug.h"
00021 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00022 #include <algorithm>
00023 #include <functional>
00024 #include <set>
00025 #include <map>
00026 #include <iostream>
00027 using namespace llvm;
00028 
00029 /// SafeToMergeTerminators - Return true if it is safe to merge these two
00030 /// terminator instructions together.
00031 ///
00032 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
00033   if (SI1 == SI2) return false;  // Can't merge with self!
00034   
00035   // It is not safe to merge these two switch instructions if they have a common
00036   // successor, and if that successor has a PHI node, and if *that* PHI node has
00037   // conflicting incoming values from the two switch blocks.
00038   BasicBlock *SI1BB = SI1->getParent();
00039   BasicBlock *SI2BB = SI2->getParent();
00040   std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
00041   
00042   for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
00043     if (SI1Succs.count(*I))
00044       for (BasicBlock::iterator BBI = (*I)->begin();
00045            isa<PHINode>(BBI); ++BBI) {
00046         PHINode *PN = cast<PHINode>(BBI);
00047         if (PN->getIncomingValueForBlock(SI1BB) !=
00048             PN->getIncomingValueForBlock(SI2BB))
00049           return false;
00050       }
00051         
00052   return true;
00053 }
00054 
00055 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
00056 /// now be entries in it from the 'NewPred' block.  The values that will be
00057 /// flowing into the PHI nodes will be the same as those coming in from
00058 /// ExistPred, an existing predecessor of Succ.
00059 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
00060                                   BasicBlock *ExistPred) {
00061   assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
00062          succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
00063   if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
00064   
00065   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00066     PHINode *PN = cast<PHINode>(I);
00067     Value *V = PN->getIncomingValueForBlock(ExistPred);
00068     PN->addIncoming(V, NewPred);
00069   }
00070 }
00071 
00072 // CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
00073 // almost-empty BB ending in an unconditional branch to Succ, into succ.
00074 //
00075 // Assumption: Succ is the single successor for BB.
00076 //
00077 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
00078   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
00079 
00080   // Check to see if one of the predecessors of BB is already a predecessor of
00081   // Succ.  If so, we cannot do the transformation if there are any PHI nodes
00082   // with incompatible values coming in from the two edges!
00083   //
00084   if (isa<PHINode>(Succ->front())) {
00085     std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
00086     for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
00087          PI != PE; ++PI)
00088       if (std::find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
00089         // Loop over all of the PHI nodes checking to see if there are
00090         // incompatible values coming in.
00091         for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00092           PHINode *PN = cast<PHINode>(I);
00093           // Loop up the entries in the PHI node for BB and for *PI if the
00094           // values coming in are non-equal, we cannot merge these two blocks
00095           // (instead we should insert a conditional move or something, then
00096           // merge the blocks).
00097           if (PN->getIncomingValueForBlock(BB) !=
00098               PN->getIncomingValueForBlock(*PI))
00099             return false;  // Values are not equal...
00100         }
00101       }
00102   }
00103     
00104   // Finally, if BB has PHI nodes that are used by things other than the PHIs in
00105   // Succ and Succ has predecessors that are not Succ and not Pred, we cannot
00106   // fold these blocks, as we don't know whether BB dominates Succ or not to
00107   // update the PHI nodes correctly.
00108   if (!isa<PHINode>(BB->begin()) || Succ->getSinglePredecessor()) return true;
00109 
00110   // If the predecessors of Succ are only BB and Succ itself, we can handle this.
00111   bool IsSafe = true;
00112   for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
00113     if (*PI != Succ && *PI != BB) {
00114       IsSafe = false;
00115       break;
00116     }
00117   if (IsSafe) return true;
00118   
00119   // If the PHI nodes in BB are only used by instructions in Succ, we are ok if
00120   // BB and Succ have no common predecessors.
00121   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I) && IsSafe; ++I) {
00122     PHINode *PN = cast<PHINode>(I);
00123     for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E;
00124          ++UI)
00125       if (cast<Instruction>(*UI)->getParent() != Succ)
00126         return false;
00127   }
00128   
00129   // Scan the predecessor sets of BB and Succ, making sure there are no common
00130   // predecessors.  Common predecessors would cause us to build a phi node with
00131   // differing incoming values, which is not legal.
00132   std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
00133   for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
00134     if (BBPreds.count(*PI))
00135       return false;
00136     
00137   return true;
00138 }
00139 
00140 /// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
00141 /// branch to Succ, and contains no instructions other than PHI nodes and the
00142 /// branch.  If possible, eliminate BB.
00143 static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
00144                                                     BasicBlock *Succ) {
00145   // If our successor has PHI nodes, then we need to update them to include
00146   // entries for BB's predecessors, not for BB itself.  Be careful though,
00147   // if this transformation fails (returns true) then we cannot do this
00148   // transformation!
00149   //
00150   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
00151   
00152   DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB);
00153   
00154   if (isa<PHINode>(Succ->begin())) {
00155     // If there is more than one pred of succ, and there are PHI nodes in
00156     // the successor, then we need to add incoming edges for the PHI nodes
00157     //
00158     const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
00159     
00160     // Loop over all of the PHI nodes in the successor of BB.
00161     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00162       PHINode *PN = cast<PHINode>(I);
00163       Value *OldVal = PN->removeIncomingValue(BB, false);
00164       assert(OldVal && "No entry in PHI for Pred BB!");
00165       
00166       // If this incoming value is one of the PHI nodes in BB, the new entries
00167       // in the PHI node are the entries from the old PHI.
00168       if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
00169         PHINode *OldValPN = cast<PHINode>(OldVal);
00170         for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
00171           PN->addIncoming(OldValPN->getIncomingValue(i),
00172                           OldValPN->getIncomingBlock(i));
00173       } else {
00174         for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
00175              End = BBPreds.end(); PredI != End; ++PredI) {
00176           // Add an incoming value for each of the new incoming values...
00177           PN->addIncoming(OldVal, *PredI);
00178         }
00179       }
00180     }
00181   }
00182   
00183   if (isa<PHINode>(&BB->front())) {
00184     std::vector<BasicBlock*>
00185     OldSuccPreds(pred_begin(Succ), pred_end(Succ));
00186     
00187     // Move all PHI nodes in BB to Succ if they are alive, otherwise
00188     // delete them.
00189     while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
00190       if (PN->use_empty()) {
00191         // Just remove the dead phi.  This happens if Succ's PHIs were the only
00192         // users of the PHI nodes.
00193         PN->eraseFromParent();
00194       } else {
00195         // The instruction is alive, so this means that Succ must have
00196         // *ONLY* had BB as a predecessor, and the PHI node is still valid
00197         // now.  Simply move it into Succ, because we know that BB
00198         // strictly dominated Succ.
00199         Succ->getInstList().splice(Succ->begin(),
00200                                    BB->getInstList(), BB->begin());
00201         
00202         // We need to add new entries for the PHI node to account for
00203         // predecessors of Succ that the PHI node does not take into
00204         // account.  At this point, since we know that BB dominated succ,
00205         // this means that we should any newly added incoming edges should
00206         // use the PHI node as the value for these edges, because they are
00207         // loop back edges.
00208         for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
00209           if (OldSuccPreds[i] != BB)
00210             PN->addIncoming(PN, OldSuccPreds[i]);
00211       }
00212   }
00213     
00214   // Everything that jumped to BB now goes to Succ.
00215   std::string OldName = BB->getName();
00216   BB->replaceAllUsesWith(Succ);
00217   BB->eraseFromParent();              // Delete the old basic block.
00218   
00219   if (!OldName.empty() && !Succ->hasName())  // Transfer name if we can
00220     Succ->setName(OldName);
00221   return true;
00222 }
00223 
00224 /// GetIfCondition - Given a basic block (BB) with two predecessors (and
00225 /// presumably PHI nodes in it), check to see if the merge at this block is due
00226 /// to an "if condition".  If so, return the boolean condition that determines
00227 /// which entry into BB will be taken.  Also, return by references the block
00228 /// that will be entered from if the condition is true, and the block that will
00229 /// be entered if the condition is false.
00230 ///
00231 ///
00232 static Value *GetIfCondition(BasicBlock *BB,
00233                              BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
00234   assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
00235          "Function can only handle blocks with 2 predecessors!");
00236   BasicBlock *Pred1 = *pred_begin(BB);
00237   BasicBlock *Pred2 = *++pred_begin(BB);
00238 
00239   // We can only handle branches.  Other control flow will be lowered to
00240   // branches if possible anyway.
00241   if (!isa<BranchInst>(Pred1->getTerminator()) ||
00242       !isa<BranchInst>(Pred2->getTerminator()))
00243     return 0;
00244   BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
00245   BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
00246 
00247   // Eliminate code duplication by ensuring that Pred1Br is conditional if
00248   // either are.
00249   if (Pred2Br->isConditional()) {
00250     // If both branches are conditional, we don't have an "if statement".  In
00251     // reality, we could transform this case, but since the condition will be
00252     // required anyway, we stand no chance of eliminating it, so the xform is
00253     // probably not profitable.
00254     if (Pred1Br->isConditional())
00255       return 0;
00256 
00257     std::swap(Pred1, Pred2);
00258     std::swap(Pred1Br, Pred2Br);
00259   }
00260 
00261   if (Pred1Br->isConditional()) {
00262     // If we found a conditional branch predecessor, make sure that it branches
00263     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
00264     if (Pred1Br->getSuccessor(0) == BB &&
00265         Pred1Br->getSuccessor(1) == Pred2) {
00266       IfTrue = Pred1;
00267       IfFalse = Pred2;
00268     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
00269                Pred1Br->getSuccessor(1) == BB) {
00270       IfTrue = Pred2;
00271       IfFalse = Pred1;
00272     } else {
00273       // We know that one arm of the conditional goes to BB, so the other must
00274       // go somewhere unrelated, and this must not be an "if statement".
00275       return 0;
00276     }
00277 
00278     // The only thing we have to watch out for here is to make sure that Pred2
00279     // doesn't have incoming edges from other blocks.  If it does, the condition
00280     // doesn't dominate BB.
00281     if (++pred_begin(Pred2) != pred_end(Pred2))
00282       return 0;
00283 
00284     return Pred1Br->getCondition();
00285   }
00286 
00287   // Ok, if we got here, both predecessors end with an unconditional branch to
00288   // BB.  Don't panic!  If both blocks only have a single (identical)
00289   // predecessor, and THAT is a conditional branch, then we're all ok!
00290   if (pred_begin(Pred1) == pred_end(Pred1) ||
00291       ++pred_begin(Pred1) != pred_end(Pred1) ||
00292       pred_begin(Pred2) == pred_end(Pred2) ||
00293       ++pred_begin(Pred2) != pred_end(Pred2) ||
00294       *pred_begin(Pred1) != *pred_begin(Pred2))
00295     return 0;
00296 
00297   // Otherwise, if this is a conditional branch, then we can use it!
00298   BasicBlock *CommonPred = *pred_begin(Pred1);
00299   if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
00300     assert(BI->isConditional() && "Two successors but not conditional?");
00301     if (BI->getSuccessor(0) == Pred1) {
00302       IfTrue = Pred1;
00303       IfFalse = Pred2;
00304     } else {
00305       IfTrue = Pred2;
00306       IfFalse = Pred1;
00307     }
00308     return BI->getCondition();
00309   }
00310   return 0;
00311 }
00312 
00313 
00314 // If we have a merge point of an "if condition" as accepted above, return true
00315 // if the specified value dominates the block.  We don't handle the true
00316 // generality of domination here, just a special case which works well enough
00317 // for us.
00318 //
00319 // If AggressiveInsts is non-null, and if V does not dominate BB, we check to
00320 // see if V (which must be an instruction) is cheap to compute and is
00321 // non-trapping.  If both are true, the instruction is inserted into the set and
00322 // true is returned.
00323 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
00324                                 std::set<Instruction*> *AggressiveInsts) {
00325   Instruction *I = dyn_cast<Instruction>(V);
00326   if (!I) return true;    // Non-instructions all dominate instructions.
00327   BasicBlock *PBB = I->getParent();
00328 
00329   // We don't want to allow weird loops that might have the "if condition" in
00330   // the bottom of this block.
00331   if (PBB == BB) return false;
00332 
00333   // If this instruction is defined in a block that contains an unconditional
00334   // branch to BB, then it must be in the 'conditional' part of the "if
00335   // statement".
00336   if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
00337     if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
00338       if (!AggressiveInsts) return false;
00339       // Okay, it looks like the instruction IS in the "condition".  Check to
00340       // see if its a cheap instruction to unconditionally compute, and if it
00341       // only uses stuff defined outside of the condition.  If so, hoist it out.
00342       switch (I->getOpcode()) {
00343       default: return false;  // Cannot hoist this out safely.
00344       case Instruction::Load:
00345         // We can hoist loads that are non-volatile and obviously cannot trap.
00346         if (cast<LoadInst>(I)->isVolatile())
00347           return false;
00348         if (!isa<AllocaInst>(I->getOperand(0)) &&
00349             !isa<Constant>(I->getOperand(0)))
00350           return false;
00351 
00352         // Finally, we have to check to make sure there are no instructions
00353         // before the load in its basic block, as we are going to hoist the loop
00354         // out to its predecessor.
00355         if (PBB->begin() != BasicBlock::iterator(I))
00356           return false;
00357         break;
00358       case Instruction::Add:
00359       case Instruction::Sub:
00360       case Instruction::And:
00361       case Instruction::Or:
00362       case Instruction::Xor:
00363       case Instruction::Shl:
00364       case Instruction::Shr:
00365       case Instruction::SetEQ:
00366       case Instruction::SetNE:
00367       case Instruction::SetLT:
00368       case Instruction::SetGT:
00369       case Instruction::SetLE:
00370       case Instruction::SetGE:
00371         break;   // These are all cheap and non-trapping instructions.
00372       }
00373 
00374       // Okay, we can only really hoist these out if their operands are not
00375       // defined in the conditional region.
00376       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00377         if (!DominatesMergePoint(I->getOperand(i), BB, 0))
00378           return false;
00379       // Okay, it's safe to do this!  Remember this instruction.
00380       AggressiveInsts->insert(I);
00381     }
00382 
00383   return true;
00384 }
00385 
00386 // GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq
00387 // instructions that compare a value against a constant, return the value being
00388 // compared, and stick the constant into the Values vector.
00389 static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
00390   if (Instruction *Inst = dyn_cast<Instruction>(V))
00391     if (Inst->getOpcode() == Instruction::SetEQ) {
00392       if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
00393         Values.push_back(C);
00394         return Inst->getOperand(0);
00395       } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
00396         Values.push_back(C);
00397         return Inst->getOperand(1);
00398       }
00399     } else if (Inst->getOpcode() == Instruction::Or) {
00400       if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
00401         if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
00402           if (LHS == RHS)
00403             return LHS;
00404     }
00405   return 0;
00406 }
00407 
00408 // GatherConstantSetNEs - Given a potentially 'and'd together collection of
00409 // setne instructions that compare a value against a constant, return the value
00410 // being compared, and stick the constant into the Values vector.
00411 static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
00412   if (Instruction *Inst = dyn_cast<Instruction>(V))
00413     if (Inst->getOpcode() == Instruction::SetNE) {
00414       if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
00415         Values.push_back(C);
00416         return Inst->getOperand(0);
00417       } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
00418         Values.push_back(C);
00419         return Inst->getOperand(1);
00420       }
00421     } else if (Inst->getOpcode() == Instruction::Cast) {
00422       // Cast of X to bool is really a comparison against zero.
00423       assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!");
00424       Values.push_back(ConstantInt::get(Inst->getOperand(0)->getType(), 0));
00425       return Inst->getOperand(0);
00426     } else if (Inst->getOpcode() == Instruction::And) {
00427       if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
00428         if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
00429           if (LHS == RHS)
00430             return LHS;
00431     }
00432   return 0;
00433 }
00434 
00435 
00436 
00437 /// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
00438 /// bunch of comparisons of one value against constants, return the value and
00439 /// the constants being compared.
00440 static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
00441                                    std::vector<ConstantInt*> &Values) {
00442   if (Cond->getOpcode() == Instruction::Or) {
00443     CompVal = GatherConstantSetEQs(Cond, Values);
00444 
00445     // Return true to indicate that the condition is true if the CompVal is
00446     // equal to one of the constants.
00447     return true;
00448   } else if (Cond->getOpcode() == Instruction::And) {
00449     CompVal = GatherConstantSetNEs(Cond, Values);
00450 
00451     // Return false to indicate that the condition is false if the CompVal is
00452     // equal to one of the constants.
00453     return false;
00454   }
00455   return false;
00456 }
00457 
00458 /// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
00459 /// has no side effects, nuke it.  If it uses any instructions that become dead
00460 /// because the instruction is now gone, nuke them too.
00461 static void ErasePossiblyDeadInstructionTree(Instruction *I) {
00462   if (isInstructionTriviallyDead(I)) {
00463     std::vector<Value*> Operands(I->op_begin(), I->op_end());
00464     I->getParent()->getInstList().erase(I);
00465     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
00466       if (Instruction *OpI = dyn_cast<Instruction>(Operands[i]))
00467         ErasePossiblyDeadInstructionTree(OpI);
00468   }
00469 }
00470 
00471 // isValueEqualityComparison - Return true if the specified terminator checks to
00472 // see if a value is equal to constant integer value.
00473 static Value *isValueEqualityComparison(TerminatorInst *TI) {
00474   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00475     // Do not permit merging of large switch instructions into their
00476     // predecessors unless there is only one predecessor.
00477     if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
00478                                                pred_end(SI->getParent())) > 128)
00479       return 0;
00480 
00481     return SI->getCondition();
00482   }
00483   if (BranchInst *BI = dyn_cast<BranchInst>(TI))
00484     if (BI->isConditional() && BI->getCondition()->hasOneUse())
00485       if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
00486         if ((SCI->getOpcode() == Instruction::SetEQ ||
00487              SCI->getOpcode() == Instruction::SetNE) &&
00488             isa<ConstantInt>(SCI->getOperand(1)))
00489           return SCI->getOperand(0);
00490   return 0;
00491 }
00492 
00493 // Given a value comparison instruction, decode all of the 'cases' that it
00494 // represents and return the 'default' block.
00495 static BasicBlock *
00496 GetValueEqualityComparisonCases(TerminatorInst *TI,
00497                                 std::vector<std::pair<ConstantInt*,
00498                                                       BasicBlock*> > &Cases) {
00499   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00500     Cases.reserve(SI->getNumCases());
00501     for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
00502       Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
00503     return SI->getDefaultDest();
00504   }
00505 
00506   BranchInst *BI = cast<BranchInst>(TI);
00507   SetCondInst *SCI = cast<SetCondInst>(BI->getCondition());
00508   Cases.push_back(std::make_pair(cast<ConstantInt>(SCI->getOperand(1)),
00509                                  BI->getSuccessor(SCI->getOpcode() ==
00510                                                         Instruction::SetNE)));
00511   return BI->getSuccessor(SCI->getOpcode() == Instruction::SetEQ);
00512 }
00513 
00514 
00515 // EliminateBlockCases - Given an vector of bb/value pairs, remove any entries
00516 // in the list that match the specified block.
00517 static void EliminateBlockCases(BasicBlock *BB,
00518                std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
00519   for (unsigned i = 0, e = Cases.size(); i != e; ++i)
00520     if (Cases[i].second == BB) {
00521       Cases.erase(Cases.begin()+i);
00522       --i; --e;
00523     }
00524 }
00525 
00526 // ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
00527 // well.
00528 static bool
00529 ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
00530               std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
00531   std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
00532 
00533   // Make V1 be smaller than V2.
00534   if (V1->size() > V2->size())
00535     std::swap(V1, V2);
00536 
00537   if (V1->size() == 0) return false;
00538   if (V1->size() == 1) {
00539     // Just scan V2.
00540     ConstantInt *TheVal = (*V1)[0].first;
00541     for (unsigned i = 0, e = V2->size(); i != e; ++i)
00542       if (TheVal == (*V2)[i].first)
00543         return true;
00544   }
00545 
00546   // Otherwise, just sort both lists and compare element by element.
00547   std::sort(V1->begin(), V1->end());
00548   std::sort(V2->begin(), V2->end());
00549   unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
00550   while (i1 != e1 && i2 != e2) {
00551     if ((*V1)[i1].first == (*V2)[i2].first)
00552       return true;
00553     if ((*V1)[i1].first < (*V2)[i2].first)
00554       ++i1;
00555     else
00556       ++i2;
00557   }
00558   return false;
00559 }
00560 
00561 // SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
00562 // terminator instruction and its block is known to only have a single
00563 // predecessor block, check to see if that predecessor is also a value
00564 // comparison with the same value, and if that comparison determines the outcome
00565 // of this comparison.  If so, simplify TI.  This does a very limited form of
00566 // jump threading.
00567 static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
00568                                                           BasicBlock *Pred) {
00569   Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
00570   if (!PredVal) return false;  // Not a value comparison in predecessor.
00571 
00572   Value *ThisVal = isValueEqualityComparison(TI);
00573   assert(ThisVal && "This isn't a value comparison!!");
00574   if (ThisVal != PredVal) return false;  // Different predicates.
00575 
00576   // Find out information about when control will move from Pred to TI's block.
00577   std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
00578   BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
00579                                                         PredCases);
00580   EliminateBlockCases(PredDef, PredCases);  // Remove default from cases.
00581 
00582   // Find information about how control leaves this block.
00583   std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
00584   BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
00585   EliminateBlockCases(ThisDef, ThisCases);  // Remove default from cases.
00586 
00587   // If TI's block is the default block from Pred's comparison, potentially
00588   // simplify TI based on this knowledge.
00589   if (PredDef == TI->getParent()) {
00590     // If we are here, we know that the value is none of those cases listed in
00591     // PredCases.  If there are any cases in ThisCases that are in PredCases, we
00592     // can simplify TI.
00593     if (ValuesOverlap(PredCases, ThisCases)) {
00594       if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) {
00595         // Okay, one of the successors of this condbr is dead.  Convert it to a
00596         // uncond br.
00597         assert(ThisCases.size() == 1 && "Branch can only have one case!");
00598         Value *Cond = BTI->getCondition();
00599         // Insert the new branch.
00600         Instruction *NI = new BranchInst(ThisDef, TI);
00601 
00602         // Remove PHI node entries for the dead edge.
00603         ThisCases[0].second->removePredecessor(TI->getParent());
00604 
00605         DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
00606               << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
00607 
00608         TI->eraseFromParent();   // Nuke the old one.
00609         // If condition is now dead, nuke it.
00610         if (Instruction *CondI = dyn_cast<Instruction>(Cond))
00611           ErasePossiblyDeadInstructionTree(CondI);
00612         return true;
00613 
00614       } else {
00615         SwitchInst *SI = cast<SwitchInst>(TI);
00616         // Okay, TI has cases that are statically dead, prune them away.
00617         std::set<Constant*> DeadCases;
00618         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00619           DeadCases.insert(PredCases[i].first);
00620 
00621         DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
00622                   << "Through successor TI: " << *TI);
00623 
00624         for (unsigned i = SI->getNumCases()-1; i != 0; --i)
00625           if (DeadCases.count(SI->getCaseValue(i))) {
00626             SI->getSuccessor(i)->removePredecessor(TI->getParent());
00627             SI->removeCase(i);
00628           }
00629 
00630         DEBUG(std::cerr << "Leaving: " << *TI << "\n");
00631         return true;
00632       }
00633     }
00634 
00635   } else {
00636     // Otherwise, TI's block must correspond to some matched value.  Find out
00637     // which value (or set of values) this is.
00638     ConstantInt *TIV = 0;
00639     BasicBlock *TIBB = TI->getParent();
00640     for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00641       if (PredCases[i].second == TIBB)
00642         if (TIV == 0)
00643           TIV = PredCases[i].first;
00644         else
00645           return false;  // Cannot handle multiple values coming to this block.
00646     assert(TIV && "No edge from pred to succ?");
00647 
00648     // Okay, we found the one constant that our value can be if we get into TI's
00649     // BB.  Find out which successor will unconditionally be branched to.
00650     BasicBlock *TheRealDest = 0;
00651     for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
00652       if (ThisCases[i].first == TIV) {
00653         TheRealDest = ThisCases[i].second;
00654         break;
00655       }
00656 
00657     // If not handled by any explicit cases, it is handled by the default case.
00658     if (TheRealDest == 0) TheRealDest = ThisDef;
00659 
00660     // Remove PHI node entries for dead edges.
00661     BasicBlock *CheckEdge = TheRealDest;
00662     for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
00663       if (*SI != CheckEdge)
00664         (*SI)->removePredecessor(TIBB);
00665       else
00666         CheckEdge = 0;
00667 
00668     // Insert the new branch.
00669     Instruction *NI = new BranchInst(TheRealDest, TI);
00670 
00671     DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
00672           << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
00673     Instruction *Cond = 0;
00674     if (BranchInst *BI = dyn_cast<BranchInst>(TI))
00675       Cond = dyn_cast<Instruction>(BI->getCondition());
00676     TI->eraseFromParent();   // Nuke the old one.
00677 
00678     if (Cond) ErasePossiblyDeadInstructionTree(Cond);
00679     return true;
00680   }
00681   return false;
00682 }
00683 
00684 // FoldValueComparisonIntoPredecessors - The specified terminator is a value
00685 // equality comparison instruction (either a switch or a branch on "X == c").
00686 // See if any of the predecessors of the terminator block are value comparisons
00687 // on the same value.  If so, and if safe to do so, fold them together.
00688 static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
00689   BasicBlock *BB = TI->getParent();
00690   Value *CV = isValueEqualityComparison(TI);  // CondVal
00691   assert(CV && "Not a comparison?");
00692   bool Changed = false;
00693 
00694   std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
00695   while (!Preds.empty()) {
00696     BasicBlock *Pred = Preds.back();
00697     Preds.pop_back();
00698 
00699     // See if the predecessor is a comparison with the same value.
00700     TerminatorInst *PTI = Pred->getTerminator();
00701     Value *PCV = isValueEqualityComparison(PTI);  // PredCondVal
00702 
00703     if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
00704       // Figure out which 'cases' to copy from SI to PSI.
00705       std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
00706       BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
00707 
00708       std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
00709       BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
00710 
00711       // Based on whether the default edge from PTI goes to BB or not, fill in
00712       // PredCases and PredDefault with the new switch cases we would like to
00713       // build.
00714       std::vector<BasicBlock*> NewSuccessors;
00715 
00716       if (PredDefault == BB) {
00717         // If this is the default destination from PTI, only the edges in TI
00718         // that don't occur in PTI, or that branch to BB will be activated.
00719         std::set<ConstantInt*> PTIHandled;
00720         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00721           if (PredCases[i].second != BB)
00722             PTIHandled.insert(PredCases[i].first);
00723           else {
00724             // The default destination is BB, we don't need explicit targets.
00725             std::swap(PredCases[i], PredCases.back());
00726             PredCases.pop_back();
00727             --i; --e;
00728           }
00729 
00730         // Reconstruct the new switch statement we will be building.
00731         if (PredDefault != BBDefault) {
00732           PredDefault->removePredecessor(Pred);
00733           PredDefault = BBDefault;
00734           NewSuccessors.push_back(BBDefault);
00735         }
00736         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
00737           if (!PTIHandled.count(BBCases[i].first) &&
00738               BBCases[i].second != BBDefault) {
00739             PredCases.push_back(BBCases[i]);
00740             NewSuccessors.push_back(BBCases[i].second);
00741           }
00742 
00743       } else {
00744         // If this is not the default destination from PSI, only the edges
00745         // in SI that occur in PSI with a destination of BB will be
00746         // activated.
00747         std::set<ConstantInt*> PTIHandled;
00748         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00749           if (PredCases[i].second == BB) {
00750             PTIHandled.insert(PredCases[i].first);
00751             std::swap(PredCases[i], PredCases.back());
00752             PredCases.pop_back();
00753             --i; --e;
00754           }
00755 
00756         // Okay, now we know which constants were sent to BB from the
00757         // predecessor.  Figure out where they will all go now.
00758         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
00759           if (PTIHandled.count(BBCases[i].first)) {
00760             // If this is one we are capable of getting...
00761             PredCases.push_back(BBCases[i]);
00762             NewSuccessors.push_back(BBCases[i].second);
00763             PTIHandled.erase(BBCases[i].first);// This constant is taken care of
00764           }
00765 
00766         // If there are any constants vectored to BB that TI doesn't handle,
00767         // they must go to the default destination of TI.
00768         for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
00769                E = PTIHandled.end(); I != E; ++I) {
00770           PredCases.push_back(std::make_pair(*I, BBDefault));
00771           NewSuccessors.push_back(BBDefault);
00772         }
00773       }
00774 
00775       // Okay, at this point, we know which new successor Pred will get.  Make
00776       // sure we update the number of entries in the PHI nodes for these
00777       // successors.
00778       for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
00779         AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
00780 
00781       // Now that the successors are updated, create the new Switch instruction.
00782       SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI);
00783       for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00784         NewSI->addCase(PredCases[i].first, PredCases[i].second);
00785 
00786       Instruction *DeadCond = 0;
00787       if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
00788         // If PTI is a branch, remember the condition.
00789         DeadCond = dyn_cast<Instruction>(BI->getCondition());
00790       Pred->getInstList().erase(PTI);
00791 
00792       // If the condition is dead now, remove the instruction tree.
00793       if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond);
00794 
00795       // Okay, last check.  If BB is still a successor of PSI, then we must
00796       // have an infinite loop case.  If so, add an infinitely looping block
00797       // to handle the case to preserve the behavior of the code.
00798       BasicBlock *InfLoopBlock = 0;
00799       for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
00800         if (NewSI->getSuccessor(i) == BB) {
00801           if (InfLoopBlock == 0) {
00802             // Insert it at the end of the loop, because it's either code,
00803             // or it won't matter if it's hot. :)
00804             InfLoopBlock = new BasicBlock("infloop", BB->getParent());
00805             new BranchInst(InfLoopBlock, InfLoopBlock);
00806           }
00807           NewSI->setSuccessor(i, InfLoopBlock);
00808         }
00809 
00810       Changed = true;
00811     }
00812   }
00813   return Changed;
00814 }
00815 
00816 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
00817 /// BB2, hoist any common code in the two blocks up into the branch block.  The
00818 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
00819 static bool HoistThenElseCodeToIf(BranchInst *BI) {
00820   // This does very trivial matching, with limited scanning, to find identical
00821   // instructions in the two blocks.  In particular, we don't want to get into
00822   // O(M*N) situations here where M and N are the sizes of BB1 and BB2.  As
00823   // such, we currently just scan for obviously identical instructions in an
00824   // identical order.
00825   BasicBlock *BB1 = BI->getSuccessor(0);  // The true destination.
00826   BasicBlock *BB2 = BI->getSuccessor(1);  // The false destination
00827 
00828   Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
00829   if (I1->getOpcode() != I2->getOpcode() || !I1->isIdenticalTo(I2) ||
00830       isa<PHINode>(I1))
00831     return false;
00832 
00833   // If we get here, we can hoist at least one instruction.
00834   BasicBlock *BIParent = BI->getParent();
00835 
00836   do {
00837     // If we are hoisting the terminator instruction, don't move one (making a
00838     // broken BB), instead clone it, and remove BI.
00839     if (isa<TerminatorInst>(I1))
00840       goto HoistTerminator;
00841 
00842     // For a normal instruction, we just move one to right before the branch,
00843     // then replace all uses of the other with the first.  Finally, we remove
00844     // the now redundant second instruction.
00845     BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
00846     if (!I2->use_empty())
00847       I2->replaceAllUsesWith(I1);
00848     BB2->getInstList().erase(I2);
00849 
00850     I1 = BB1->begin();
00851     I2 = BB2->begin();
00852   } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
00853 
00854   return true;
00855 
00856 HoistTerminator:
00857   // Okay, it is safe to hoist the terminator.
00858   Instruction *NT = I1->clone();
00859   BIParent->getInstList().insert(BI, NT);
00860   if (NT->getType() != Type::VoidTy) {
00861     I1->replaceAllUsesWith(NT);
00862     I2->replaceAllUsesWith(NT);
00863     NT->setName(I1->getName());
00864   }
00865 
00866   // Hoisting one of the terminators from our successor is a great thing.
00867   // Unfortunately, the successors of the if/else blocks may have PHI nodes in
00868   // them.  If they do, all PHI entries for BB1/BB2 must agree for all PHI
00869   // nodes, so we insert select instruction to compute the final result.
00870   std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
00871   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
00872     PHINode *PN;
00873     for (BasicBlock::iterator BBI = SI->begin();
00874          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
00875       Value *BB1V = PN->getIncomingValueForBlock(BB1);
00876       Value *BB2V = PN->getIncomingValueForBlock(BB2);
00877       if (BB1V != BB2V) {
00878         // These values do not agree.  Insert a select instruction before NT
00879         // that determines the right value.
00880         SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
00881         if (SI == 0)
00882           SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
00883                               BB1V->getName()+"."+BB2V->getName(), NT);
00884         // Make the PHI node use the select for all incoming values for BB1/BB2
00885         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00886           if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
00887             PN->setIncomingValue(i, SI);
00888       }
00889     }
00890   }
00891 
00892   // Update any PHI nodes in our new successors.
00893   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
00894     AddPredecessorToBlock(*SI, BIParent, BB1);
00895 
00896   BI->eraseFromParent();
00897   return true;
00898 }
00899 
00900 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
00901 /// across this block.
00902 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
00903   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
00904   Value *Cond = BI->getCondition();
00905   
00906   unsigned Size = 0;
00907   
00908   // If this basic block contains anything other than a PHI (which controls the
00909   // branch) and branch itself, bail out.  FIXME: improve this in the future.
00910   for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI, ++Size) {
00911     if (Size > 10) return false;  // Don't clone large BB's.
00912     
00913     // We can only support instructions that are do not define values that are
00914     // live outside of the current basic block.
00915     for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
00916          UI != E; ++UI) {
00917       Instruction *U = cast<Instruction>(*UI);
00918       if (U->getParent() != BB || isa<PHINode>(U)) return false;
00919     }
00920     
00921     // Looks ok, continue checking.
00922   }
00923 
00924   return true;
00925 }
00926 
00927 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
00928 /// that is defined in the same block as the branch and if any PHI entries are
00929 /// constants, thread edges corresponding to that entry to be branches to their
00930 /// ultimate destination.
00931 static bool FoldCondBranchOnPHI(BranchInst *BI) {
00932   BasicBlock *BB = BI->getParent();
00933   PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
00934   // NOTE: we currently cannot transform this case if the PHI node is used
00935   // outside of the block.
00936   if (!PN || PN->getParent() != BB || !PN->hasOneUse())
00937     return false;
00938   
00939   // Degenerate case of a single entry PHI.
00940   if (PN->getNumIncomingValues() == 1) {
00941     if (PN->getIncomingValue(0) != PN)
00942       PN->replaceAllUsesWith(PN->getIncomingValue(0));
00943     else
00944       PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
00945     PN->eraseFromParent();
00946     return true;    
00947   }
00948 
00949   // Now we know that this block has multiple preds and two succs.
00950   if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
00951   
00952   // Okay, this is a simple enough basic block.  See if any phi values are
00953   // constants.
00954   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00955     if (ConstantBool *CB = dyn_cast<ConstantBool>(PN->getIncomingValue(i))) {
00956       // Okay, we now know that all edges from PredBB should be revectored to
00957       // branch to RealDest.
00958       BasicBlock *PredBB = PN->getIncomingBlock(i);
00959       BasicBlock *RealDest = BI->getSuccessor(!CB->getValue());
00960       
00961       if (RealDest == BB) continue;  // Skip self loops.
00962       
00963       // The dest block might have PHI nodes, other predecessors and other
00964       // difficult cases.  Instead of being smart about this, just insert a new
00965       // block that jumps to the destination block, effectively splitting
00966       // the edge we are about to create.
00967       BasicBlock *EdgeBB = new BasicBlock(RealDest->getName()+".critedge",
00968                                           RealDest->getParent(), RealDest);
00969       new BranchInst(RealDest, EdgeBB);
00970       PHINode *PN;
00971       for (BasicBlock::iterator BBI = RealDest->begin();
00972            (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
00973         Value *V = PN->getIncomingValueForBlock(BB);
00974         PN->addIncoming(V, EdgeBB);
00975       }
00976 
00977       // BB may have instructions that are being threaded over.  Clone these
00978       // instructions into EdgeBB.  We know that there will be no uses of the
00979       // cloned instructions outside of EdgeBB.
00980       BasicBlock::iterator InsertPt = EdgeBB->begin();
00981       std::map<Value*, Value*> TranslateMap;  // Track translated values.
00982       for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
00983         if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
00984           TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
00985         } else {
00986           // Clone the instruction.
00987           Instruction *N = BBI->clone();
00988           if (BBI->hasName()) N->setName(BBI->getName()+".c");
00989           
00990           // Update operands due to translation.
00991           for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00992             std::map<Value*, Value*>::iterator PI =
00993               TranslateMap.find(N->getOperand(i));
00994             if (PI != TranslateMap.end())
00995               N->setOperand(i, PI->second);
00996           }
00997           
00998           // Check for trivial simplification.
00999           if (Constant *C = ConstantFoldInstruction(N)) {
01000             TranslateMap[BBI] = C;
01001             delete N;   // Constant folded away, don't need actual inst
01002           } else {
01003             // Insert the new instruction into its new home.
01004             EdgeBB->getInstList().insert(InsertPt, N);
01005             if (!BBI->use_empty())
01006               TranslateMap[BBI] = N;
01007           }
01008         }
01009       }
01010 
01011       // Loop over all of the edges from PredBB to BB, changing them to branch
01012       // to EdgeBB instead.
01013       TerminatorInst *PredBBTI = PredBB->getTerminator();
01014       for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
01015         if (PredBBTI->getSuccessor(i) == BB) {
01016           BB->removePredecessor(PredBB);
01017           PredBBTI->setSuccessor(i, EdgeBB);
01018         }
01019       
01020       // Recurse, simplifying any other constants.
01021       return FoldCondBranchOnPHI(BI) | true;
01022     }
01023 
01024   return false;
01025 }
01026 
01027 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
01028 /// PHI node, see if we can eliminate it.
01029 static bool FoldTwoEntryPHINode(PHINode *PN) {
01030   // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
01031   // statement", which has a very simple dominance structure.  Basically, we
01032   // are trying to find the condition that is being branched on, which
01033   // subsequently causes this merge to happen.  We really want control
01034   // dependence information for this check, but simplifycfg can't keep it up
01035   // to date, and this catches most of the cases we care about anyway.
01036   //
01037   BasicBlock *BB = PN->getParent();
01038   BasicBlock *IfTrue, *IfFalse;
01039   Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
01040   if (!IfCond) return false;
01041   
01042   DEBUG(std::cerr << "FOUND IF CONDITION!  " << *IfCond << "  T: "
01043         << IfTrue->getName() << "  F: " << IfFalse->getName() << "\n");
01044   
01045   // Loop over the PHI's seeing if we can promote them all to select
01046   // instructions.  While we are at it, keep track of the instructions
01047   // that need to be moved to the dominating block.
01048   std::set<Instruction*> AggressiveInsts;
01049   
01050   BasicBlock::iterator AfterPHIIt = BB->begin();
01051   while (isa<PHINode>(AfterPHIIt)) {
01052     PHINode *PN = cast<PHINode>(AfterPHIIt++);
01053     if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
01054       if (PN->getIncomingValue(0) != PN)
01055         PN->replaceAllUsesWith(PN->getIncomingValue(0));
01056       else
01057         PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
01058     } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
01059                                     &AggressiveInsts) ||
01060                !DominatesMergePoint(PN->getIncomingValue(1), BB,
01061                                     &AggressiveInsts)) {
01062       return false;
01063     }
01064   }
01065   
01066   // If we all PHI nodes are promotable, check to make sure that all
01067   // instructions in the predecessor blocks can be promoted as well.  If
01068   // not, we won't be able to get rid of the control flow, so it's not
01069   // worth promoting to select instructions.
01070   BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
01071   PN = cast<PHINode>(BB->begin());
01072   BasicBlock *Pred = PN->getIncomingBlock(0);
01073   if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
01074     IfBlock1 = Pred;
01075     DomBlock = *pred_begin(Pred);
01076     for (BasicBlock::iterator I = Pred->begin();
01077          !isa<TerminatorInst>(I); ++I)
01078       if (!AggressiveInsts.count(I)) {
01079         // This is not an aggressive instruction that we can promote.
01080         // Because of this, we won't be able to get rid of the control
01081         // flow, so the xform is not worth it.
01082         return false;
01083       }
01084   }
01085     
01086   Pred = PN->getIncomingBlock(1);
01087   if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
01088     IfBlock2 = Pred;
01089     DomBlock = *pred_begin(Pred);
01090     for (BasicBlock::iterator I = Pred->begin();
01091          !isa<TerminatorInst>(I); ++I)
01092       if (!AggressiveInsts.count(I)) {
01093         // This is not an aggressive instruction that we can promote.
01094         // Because of this, we won't be able to get rid of the control
01095         // flow, so the xform is not worth it.
01096         return false;
01097       }
01098   }
01099       
01100   // If we can still promote the PHI nodes after this gauntlet of tests,
01101   // do all of the PHI's now.
01102 
01103   // Move all 'aggressive' instructions, which are defined in the
01104   // conditional parts of the if's up to the dominating block.
01105   if (IfBlock1) {
01106     DomBlock->getInstList().splice(DomBlock->getTerminator(),
01107                                    IfBlock1->getInstList(),
01108                                    IfBlock1->begin(),
01109                                    IfBlock1->getTerminator());
01110   }
01111   if (IfBlock2) {
01112     DomBlock->getInstList().splice(DomBlock->getTerminator(),
01113                                    IfBlock2->getInstList(),
01114                                    IfBlock2->begin(),
01115                                    IfBlock2->getTerminator());
01116   }
01117   
01118   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
01119     // Change the PHI node into a select instruction.
01120     Value *TrueVal =
01121       PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
01122     Value *FalseVal =
01123       PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
01124     
01125     std::string Name = PN->getName(); PN->setName("");
01126     PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal,
01127                                           Name, AfterPHIIt));
01128     BB->getInstList().erase(PN);
01129   }
01130   return true;
01131 }
01132 
01133 namespace {
01134   /// ConstantIntOrdering - This class implements a stable ordering of constant
01135   /// integers that does not depend on their address.  This is important for
01136   /// applications that sort ConstantInt's to ensure uniqueness.
01137   struct ConstantIntOrdering {
01138     bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
01139       return LHS->getRawValue() < RHS->getRawValue();
01140     }
01141   };
01142 }
01143 
01144 // SimplifyCFG - This function is used to do simplification of a CFG.  For
01145 // example, it adjusts branches to branches to eliminate the extra hop, it
01146 // eliminates unreachable basic blocks, and does other "peephole" optimization
01147 // of the CFG.  It returns true if a modification was made.
01148 //
01149 // WARNING:  The entry node of a function may not be simplified.
01150 //
01151 bool llvm::SimplifyCFG(BasicBlock *BB) {
01152   bool Changed = false;
01153   Function *M = BB->getParent();
01154 
01155   assert(BB && BB->getParent() && "Block not embedded in function!");
01156   assert(BB->getTerminator() && "Degenerate basic block encountered!");
01157   assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
01158 
01159   // Remove basic blocks that have no predecessors... which are unreachable.
01160   if (pred_begin(BB) == pred_end(BB) ||
01161       *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
01162     DEBUG(std::cerr << "Removing BB: \n" << *BB);
01163 
01164     // Loop through all of our successors and make sure they know that one
01165     // of their predecessors is going away.
01166     for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
01167       SI->removePredecessor(BB);
01168 
01169     while (!BB->empty()) {
01170       Instruction &I = BB->back();
01171       // If this instruction is used, replace uses with an arbitrary
01172       // value.  Because control flow can't get here, we don't care
01173       // what we replace the value with.  Note that since this block is
01174       // unreachable, and all values contained within it must dominate their
01175       // uses, that all uses will eventually be removed.
01176       if (!I.use_empty())
01177         // Make all users of this instruction use undef instead
01178         I.replaceAllUsesWith(UndefValue::get(I.getType()));
01179 
01180       // Remove the instruction from the basic block
01181       BB->getInstList().pop_back();
01182     }
01183     M->getBasicBlockList().erase(BB);
01184     return true;
01185   }
01186 
01187   // Check to see if we can constant propagate this terminator instruction
01188   // away...
01189   Changed |= ConstantFoldTerminator(BB);
01190 
01191   // If this is a returning block with only PHI nodes in it, fold the return
01192   // instruction into any unconditional branch predecessors.
01193   //
01194   // If any predecessor is a conditional branch that just selects among
01195   // different return values, fold the replace the branch/return with a select
01196   // and return.
01197   if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
01198     BasicBlock::iterator BBI = BB->getTerminator();
01199     if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
01200       // Find predecessors that end with branches.
01201       std::vector<BasicBlock*> UncondBranchPreds;
01202       std::vector<BranchInst*> CondBranchPreds;
01203       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
01204         TerminatorInst *PTI = (*PI)->getTerminator();
01205         if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
01206           if (BI->isUnconditional())
01207             UncondBranchPreds.push_back(*PI);
01208           else
01209             CondBranchPreds.push_back(BI);
01210       }
01211 
01212       // If we found some, do the transformation!
01213       if (!UncondBranchPreds.empty()) {
01214         while (!UncondBranchPreds.empty()) {
01215           BasicBlock *Pred = UncondBranchPreds.back();
01216           DEBUG(std::cerr << "FOLDING: " << *BB
01217                           << "INTO UNCOND BRANCH PRED: " << *Pred);
01218           UncondBranchPreds.pop_back();
01219           Instruction *UncondBranch = Pred->getTerminator();
01220           // Clone the return and add it to the end of the predecessor.
01221           Instruction *NewRet = RI->clone();
01222           Pred->getInstList().push_back(NewRet);
01223 
01224           // If the return instruction returns a value, and if the value was a
01225           // PHI node in "BB", propagate the right value into the return.
01226           if (NewRet->getNumOperands() == 1)
01227             if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
01228               if (PN->getParent() == BB)
01229                 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
01230           // Update any PHI nodes in the returning block to realize that we no
01231           // longer branch to them.
01232           BB->removePredecessor(Pred);
01233           Pred->getInstList().erase(UncondBranch);
01234         }
01235 
01236         // If we eliminated all predecessors of the block, delete the block now.
01237         if (pred_begin(BB) == pred_end(BB))
01238           // We know there are no successors, so just nuke the block.
01239           M->getBasicBlockList().erase(BB);
01240 
01241         return true;
01242       }
01243 
01244       // Check out all of the conditional branches going to this return
01245       // instruction.  If any of them just select between returns, change the
01246       // branch itself into a select/return pair.
01247       while (!CondBranchPreds.empty()) {
01248         BranchInst *BI = CondBranchPreds.back();
01249         CondBranchPreds.pop_back();
01250         BasicBlock *TrueSucc = BI->getSuccessor(0);
01251         BasicBlock *FalseSucc = BI->getSuccessor(1);
01252         BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
01253 
01254         // Check to see if the non-BB successor is also a return block.
01255         if (isa<ReturnInst>(OtherSucc->getTerminator())) {
01256           // Check to see if there are only PHI instructions in this block.
01257           BasicBlock::iterator OSI = OtherSucc->getTerminator();
01258           if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
01259             // Okay, we found a branch that is going to two return nodes.  If
01260             // there is no return value for this function, just change the
01261             // branch into a return.
01262             if (RI->getNumOperands() == 0) {
01263               TrueSucc->removePredecessor(BI->getParent());
01264               FalseSucc->removePredecessor(BI->getParent());
01265               new ReturnInst(0, BI);
01266               BI->getParent()->getInstList().erase(BI);
01267               return true;
01268             }
01269 
01270             // Otherwise, figure out what the true and false return values are
01271             // so we can insert a new select instruction.
01272             Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
01273             Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
01274 
01275             // Unwrap any PHI nodes in the return blocks.
01276             if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
01277               if (TVPN->getParent() == TrueSucc)
01278                 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
01279             if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
01280               if (FVPN->getParent() == FalseSucc)
01281                 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
01282 
01283             TrueSucc->removePredecessor(BI->getParent());
01284             FalseSucc->removePredecessor(BI->getParent());
01285 
01286             // Insert a new select instruction.
01287             Value *NewRetVal;
01288             Value *BrCond = BI->getCondition();
01289             if (TrueValue != FalseValue)
01290               NewRetVal = new SelectInst(BrCond, TrueValue,
01291                                          FalseValue, "retval", BI);
01292             else
01293               NewRetVal = TrueValue;
01294             
01295             DEBUG(std::cerr << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
01296                   << "\n  " << *BI << "Select = " << *NewRetVal
01297                   << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
01298 
01299             new ReturnInst(NewRetVal, BI);
01300             BI->eraseFromParent();
01301             if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
01302               if (isInstructionTriviallyDead(BrCondI))
01303                 BrCondI->eraseFromParent();
01304             return true;
01305           }
01306         }
01307       }
01308     }
01309   } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) {
01310     // Check to see if the first instruction in this block is just an unwind.
01311     // If so, replace any invoke instructions which use this as an exception
01312     // destination with call instructions, and any unconditional branch
01313     // predecessor with an unwind.
01314     //
01315     std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
01316     while (!Preds.empty()) {
01317       BasicBlock *Pred = Preds.back();
01318       if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
01319         if (BI->isUnconditional()) {
01320           Pred->getInstList().pop_back();  // nuke uncond branch
01321           new UnwindInst(Pred);            // Use unwind.
01322           Changed = true;
01323         }
01324       } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
01325         if (II->getUnwindDest() == BB) {
01326           // Insert a new branch instruction before the invoke, because this
01327           // is now a fall through...
01328           BranchInst *BI = new BranchInst(II->getNormalDest(), II);
01329           Pred->getInstList().remove(II);   // Take out of symbol table
01330 
01331           // Insert the call now...
01332           std::vector<Value*> Args(II->op_begin()+3, II->op_end());
01333           CallInst *CI = new CallInst(II->getCalledValue(), Args,
01334                                       II->getName(), BI);
01335           CI->setCallingConv(II->getCallingConv());
01336           // If the invoke produced a value, the Call now does instead
01337           II->replaceAllUsesWith(CI);
01338           delete II;
01339           Changed = true;
01340         }
01341 
01342       Preds.pop_back();
01343     }
01344 
01345     // If this block is now dead, remove it.
01346     if (pred_begin(BB) == pred_end(BB)) {
01347       // We know there are no successors, so just nuke the block.
01348       M->getBasicBlockList().erase(BB);
01349       return true;
01350     }
01351 
01352   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
01353     if (isValueEqualityComparison(SI)) {
01354       // If we only have one predecessor, and if it is a branch on this value,
01355       // see if that predecessor totally determines the outcome of this switch.
01356       if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
01357         if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
01358           return SimplifyCFG(BB) || 1;
01359 
01360       // If the block only contains the switch, see if we can fold the block
01361       // away into any preds.
01362       if (SI == &BB->front())
01363         if (FoldValueComparisonIntoPredecessors(SI))
01364           return SimplifyCFG(BB) || 1;
01365     }
01366   } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
01367     if (BI->isUnconditional()) {
01368       BasicBlock::iterator BBI = BB->begin();  // Skip over phi nodes...
01369       while (isa<PHINode>(*BBI)) ++BBI;
01370 
01371       BasicBlock *Succ = BI->getSuccessor(0);
01372       if (BBI->isTerminator() &&  // Terminator is the only non-phi instruction!
01373           Succ != BB)             // Don't hurt infinite loops!
01374         if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
01375           return 1;
01376       
01377     } else {  // Conditional branch
01378       if (Value *CompVal = isValueEqualityComparison(BI)) {
01379         // If we only have one predecessor, and if it is a branch on this value,
01380         // see if that predecessor totally determines the outcome of this
01381         // switch.
01382         if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
01383           if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
01384             return SimplifyCFG(BB) || 1;
01385 
01386         // This block must be empty, except for the setcond inst, if it exists.
01387         BasicBlock::iterator I = BB->begin();
01388         if (&*I == BI ||
01389             (&*I == cast<Instruction>(BI->getCondition()) &&
01390              &*++I == BI))
01391           if (FoldValueComparisonIntoPredecessors(BI))
01392             return SimplifyCFG(BB) | true;
01393       }
01394       
01395       // If this is a branch on a phi node in the current block, thread control
01396       // through this block if any PHI node entries are constants.
01397       if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
01398         if (PN->getParent() == BI->getParent())
01399           if (FoldCondBranchOnPHI(BI))
01400             return SimplifyCFG(BB) | true;
01401 
01402       // If this basic block is ONLY a setcc and a branch, and if a predecessor
01403       // branches to us and one of our successors, fold the setcc into the
01404       // predecessor and use logical operations to pick the right destination.
01405       BasicBlock *TrueDest  = BI->getSuccessor(0);
01406       BasicBlock *FalseDest = BI->getSuccessor(1);
01407       if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(BI->getCondition()))
01408         if (Cond->getParent() == BB && &BB->front() == Cond &&
01409             Cond->getNext() == BI && Cond->hasOneUse() &&
01410             TrueDest != BB && FalseDest != BB)
01411           for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
01412             if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
01413               if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
01414                 BasicBlock *PredBlock = *PI;
01415                 if (PBI->getSuccessor(0) == FalseDest ||
01416                     PBI->getSuccessor(1) == TrueDest) {
01417                   // Invert the predecessors condition test (xor it with true),
01418                   // which allows us to write this code once.
01419                   Value *NewCond =
01420                     BinaryOperator::createNot(PBI->getCondition(),
01421                                     PBI->getCondition()->getName()+".not", PBI);
01422                   PBI->setCondition(NewCond);
01423                   BasicBlock *OldTrue = PBI->getSuccessor(0);
01424                   BasicBlock *OldFalse = PBI->getSuccessor(1);
01425                   PBI->setSuccessor(0, OldFalse);
01426                   PBI->setSuccessor(1, OldTrue);
01427                 }
01428 
01429                 if ((PBI->getSuccessor(0) == TrueDest && FalseDest != BB) ||
01430                     (PBI->getSuccessor(1) == FalseDest && TrueDest != BB)) {
01431                   // Clone Cond into the predecessor basic block, and or/and the
01432                   // two conditions together.
01433                   Instruction *New = Cond->clone();
01434                   New->setName(Cond->getName());
01435                   Cond->setName(Cond->getName()+".old");
01436                   PredBlock->getInstList().insert(PBI, New);
01437                   Instruction::BinaryOps Opcode =
01438                     PBI->getSuccessor(0) == TrueDest ?
01439                     Instruction::Or : Instruction::And;
01440                   Value *NewCond =
01441                     BinaryOperator::create(Opcode, PBI->getCondition(),
01442                                            New, "bothcond", PBI);
01443                   PBI->setCondition(NewCond);
01444                   if (PBI->getSuccessor(0) == BB) {
01445                     AddPredecessorToBlock(TrueDest, PredBlock, BB);
01446                     PBI->setSuccessor(0, TrueDest);
01447                   }
01448                   if (PBI->getSuccessor(1) == BB) {
01449                     AddPredecessorToBlock(FalseDest, PredBlock, BB);
01450                     PBI->setSuccessor(1, FalseDest);
01451                   }
01452                   return SimplifyCFG(BB) | 1;
01453                 }
01454               }
01455 
01456       // Scan predessor blocks for conditional branchs.
01457       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
01458         if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
01459           if (PBI != BI && PBI->isConditional()) {
01460               
01461             // If this block ends with a branch instruction, and if there is a
01462             // predecessor that ends on a branch of the same condition, make this 
01463             // conditional branch redundant.
01464             if (PBI->getCondition() == BI->getCondition() &&
01465                 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
01466               // Okay, the outcome of this conditional branch is statically
01467               // knowable.  If this block had a single pred, handle specially.
01468               if (BB->getSinglePredecessor()) {
01469                 // Turn this into a branch on constant.
01470                 bool CondIsTrue = PBI->getSuccessor(0) == BB;
01471                 BI->setCondition(ConstantBool::get(CondIsTrue));
01472                 return SimplifyCFG(BB);  // Nuke the branch on constant.
01473               }
01474               
01475               // Otherwise, if there are multiple predecessors, insert a PHI that
01476               // merges in the constant and simplify the block result.
01477               if (BlockIsSimpleEnoughToThreadThrough(BB)) {
01478                 PHINode *NewPN = new PHINode(Type::BoolTy,
01479                                              BI->getCondition()->getName()+".pr",
01480                                              BB->begin());
01481                 for (PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
01482                   if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
01483                       PBI != BI && PBI->isConditional() &&
01484                       PBI->getCondition() == BI->getCondition() &&
01485                       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
01486                     bool CondIsTrue = PBI->getSuccessor(0) == BB;
01487                     NewPN->addIncoming(ConstantBool::get(CondIsTrue), *PI);
01488                   } else {
01489                     NewPN->addIncoming(BI->getCondition(), *PI);
01490                   }
01491                 
01492                 BI->setCondition(NewPN);
01493                 // This will thread the branch.
01494                 return SimplifyCFG(BB) | true;
01495               }
01496             }
01497             
01498             // If this is a conditional branch in an empty block, and if any
01499             // predecessors is a conditional branch to one of our destinations,
01500             // fold the conditions into logical ops and one cond br.
01501             if (&BB->front() == BI) {
01502               int PBIOp, BIOp;
01503               if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
01504                 PBIOp = BIOp = 0;
01505               } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
01506                 PBIOp = 0; BIOp = 1;
01507               } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
01508                 PBIOp = 1; BIOp = 0;
01509               } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
01510                 PBIOp = BIOp = 1;
01511               } else {
01512                 PBIOp = BIOp = -1;
01513               }
01514               
01515               // Check to make sure that the other destination of this branch
01516               // isn't BB itself.  If so, this is an infinite loop that will
01517               // keep getting unwound.
01518               if (PBIOp != -1 && PBI->getSuccessor(PBIOp) == BB)
01519                 PBIOp = BIOp = -1;
01520               
01521               // Finally, if everything is ok, fold the branches to logical ops.
01522               if (PBIOp != -1) {
01523                 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
01524                 BasicBlock *OtherDest  = BI->getSuccessor(BIOp ^ 1);
01525 
01526                 DEBUG(std::cerr << "FOLDING BRs:" << *PBI->getParent()
01527                                 << "AND: " << *BI->getParent());
01528                                 
01529                 // BI may have other predecessors.  Because of this, we leave
01530                 // it alone, but modify PBI.
01531                 
01532                 // Make sure we get to CommonDest on True&True directions.
01533                 Value *PBICond = PBI->getCondition();
01534                 if (PBIOp)
01535                   PBICond = BinaryOperator::createNot(PBICond,
01536                                                       PBICond->getName()+".not",
01537                                                       PBI);
01538                 Value *BICond = BI->getCondition();
01539                 if (BIOp)
01540                   BICond = BinaryOperator::createNot(BICond,
01541                                                      BICond->getName()+".not",
01542                                                      PBI);
01543                 // Merge the conditions.
01544                 Value *Cond =
01545                   BinaryOperator::createOr(PBICond, BICond, "brmerge", PBI);
01546                 
01547                 // Modify PBI to branch on the new condition to the new dests.
01548                 PBI->setCondition(Cond);
01549                 PBI->setSuccessor(0, CommonDest);
01550                 PBI->setSuccessor(1, OtherDest);
01551 
01552                 // OtherDest may have phi nodes.  If so, add an entry from PBI's
01553                 // block that are identical to the entries for BI's block.
01554                 PHINode *PN;
01555                 for (BasicBlock::iterator II = OtherDest->begin();
01556                      (PN = dyn_cast<PHINode>(II)); ++II) {
01557                   Value *V = PN->getIncomingValueForBlock(BB);
01558                   PN->addIncoming(V, PBI->getParent());
01559                 }
01560                 
01561                 // We know that the CommonDest already had an edge from PBI to
01562                 // it.  If it has PHIs though, the PHIs may have different
01563                 // entries for BB and PBI's BB.  If so, insert a select to make
01564                 // them agree.
01565                 for (BasicBlock::iterator II = CommonDest->begin();
01566                      (PN = dyn_cast<PHINode>(II)); ++II) {
01567                   Value * BIV = PN->getIncomingValueForBlock(BB);
01568                   unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
01569                   Value *PBIV = PN->getIncomingValue(PBBIdx);
01570                   if (BIV != PBIV) {
01571                     // Insert a select in PBI to pick the right value.
01572                     Value *NV = new SelectInst(PBICond, PBIV, BIV,
01573                                                PBIV->getName()+".mux", PBI);
01574                     PN->setIncomingValue(PBBIdx, NV);
01575                   }
01576                 }
01577 
01578                 DEBUG(std::cerr << "INTO: " << *PBI->getParent());
01579 
01580                 // This basic block is probably dead.  We know it has at least
01581                 // one fewer predecessor.
01582                 return SimplifyCFG(BB) | true;
01583               }
01584             }
01585           }
01586     }
01587   } else if (isa<UnreachableInst>(BB->getTerminator())) {
01588     // If there are any instructions immediately before the unreachable that can
01589     // be removed, do so.
01590     Instruction *Unreachable = BB->getTerminator();
01591     while (Unreachable != BB->begin()) {
01592       BasicBlock::iterator BBI = Unreachable;
01593       --BBI;
01594       if (isa<CallInst>(BBI)) break;
01595       // Delete this instruction
01596       BB->getInstList().erase(BBI);
01597       Changed = true;
01598     }
01599 
01600     // If the unreachable instruction is the first in the block, take a gander
01601     // at all of the predecessors of this instruction, and simplify them.
01602     if (&BB->front() == Unreachable) {
01603       std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
01604       for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
01605         TerminatorInst *TI = Preds[i]->getTerminator();
01606 
01607         if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
01608           if (BI->isUnconditional()) {
01609             if (BI->getSuccessor(0) == BB) {
01610               new UnreachableInst(TI);
01611               TI->eraseFromParent();
01612               Changed = true;
01613             }
01614           } else {
01615             if (BI->getSuccessor(0) == BB) {
01616               new BranchInst(BI->getSuccessor(1), BI);
01617               BI->eraseFromParent();
01618             } else if (BI->getSuccessor(1) == BB) {
01619               new BranchInst(BI->getSuccessor(0), BI);
01620               BI->eraseFromParent();
01621               Changed = true;
01622             }
01623           }
01624         } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
01625           for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
01626             if (SI->getSuccessor(i) == BB) {
01627               BB->removePredecessor(SI->getParent());
01628               SI->removeCase(i);
01629               --i; --e;
01630               Changed = true;
01631             }
01632           // If the default value is unreachable, figure out the most popular
01633           // destination and make it the default.
01634           if (SI->getSuccessor(0) == BB) {
01635             std::map<BasicBlock*, unsigned> Popularity;
01636             for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
01637               Popularity[SI->getSuccessor(i)]++;
01638 
01639             // Find the most popular block.
01640             unsigned MaxPop = 0;
01641             BasicBlock *MaxBlock = 0;
01642             for (std::map<BasicBlock*, unsigned>::iterator
01643                    I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
01644               if (I->second > MaxPop) {
01645                 MaxPop = I->second;
01646                 MaxBlock = I->first;
01647               }
01648             }
01649             if (MaxBlock) {
01650               // Make this the new default, allowing us to delete any explicit
01651               // edges to it.
01652               SI->setSuccessor(0, MaxBlock);
01653               Changed = true;
01654 
01655               // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
01656               // it.
01657               if (isa<PHINode>(MaxBlock->begin()))
01658                 for (unsigned i = 0; i != MaxPop-1; ++i)
01659                   MaxBlock->removePredecessor(SI->getParent());
01660 
01661               for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
01662                 if (SI->getSuccessor(i) == MaxBlock) {
01663                   SI->removeCase(i);
01664                   --i; --e;
01665                 }
01666             }
01667           }
01668         } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
01669           if (II->getUnwindDest() == BB) {
01670             // Convert the invoke to a call instruction.  This would be a good
01671             // place to note that the call does not throw though.
01672             BranchInst *BI = new BranchInst(II->getNormalDest(), II);
01673             II->removeFromParent();   // Take out of symbol table
01674 
01675             // Insert the call now...
01676             std::vector<Value*> Args(II->op_begin()+3, II->op_end());
01677             CallInst *CI = new CallInst(II->getCalledValue(), Args,
01678                                         II->getName(), BI);
01679             CI->setCallingConv(II->getCallingConv());
01680             // If the invoke produced a value, the Call does now instead.
01681             II->replaceAllUsesWith(CI);
01682             delete II;
01683             Changed = true;
01684           }
01685         }
01686       }
01687 
01688       // If this block is now dead, remove it.
01689       if (pred_begin(BB) == pred_end(BB)) {
01690         // We know there are no successors, so just nuke the block.
01691         M->getBasicBlockList().erase(BB);
01692         return true;
01693       }
01694     }
01695   }
01696 
01697   // Merge basic blocks into their predecessor if there is only one distinct
01698   // pred, and if there is only one distinct successor of the predecessor, and
01699   // if there are no PHI nodes.
01700   //
01701   pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
01702   BasicBlock *OnlyPred = *PI++;
01703   for (; PI != PE; ++PI)  // Search all predecessors, see if they are all same
01704     if (*PI != OnlyPred) {
01705       OnlyPred = 0;       // There are multiple different predecessors...
01706       break;
01707     }
01708 
01709   BasicBlock *OnlySucc = 0;
01710   if (OnlyPred && OnlyPred != BB &&    // Don't break self loops
01711       OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
01712     // Check to see if there is only one distinct successor...
01713     succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
01714     OnlySucc = BB;
01715     for (; SI != SE; ++SI)
01716       if (*SI != OnlySucc) {
01717         OnlySucc = 0;     // There are multiple distinct successors!
01718         break;
01719       }
01720   }
01721 
01722   if (OnlySucc) {
01723     DEBUG(std::cerr << "Merging: " << *BB << "into: " << *OnlyPred);
01724     TerminatorInst *Term = OnlyPred->getTerminator();
01725 
01726     // Resolve any PHI nodes at the start of the block.  They are all
01727     // guaranteed to have exactly one entry if they exist, unless there are
01728     // multiple duplicate (but guaranteed to be equal) entries for the
01729     // incoming edges.  This occurs when there are multiple edges from
01730     // OnlyPred to OnlySucc.
01731     //
01732     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
01733       PN->replaceAllUsesWith(PN->getIncomingValue(0));
01734       BB->getInstList().pop_front();  // Delete the phi node...
01735     }
01736 
01737     // Delete the unconditional branch from the predecessor...
01738     OnlyPred->getInstList().pop_back();
01739 
01740     // Move all definitions in the successor to the predecessor...
01741     OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
01742 
01743     // Make all PHI nodes that referred to BB now refer to Pred as their
01744     // source...
01745     BB->replaceAllUsesWith(OnlyPred);
01746 
01747     std::string OldName = BB->getName();
01748 
01749     // Erase basic block from the function...
01750     M->getBasicBlockList().erase(BB);
01751 
01752     // Inherit predecessors name if it exists...
01753     if (!OldName.empty() && !OnlyPred->hasName())
01754       OnlyPred->setName(OldName);
01755 
01756     return true;
01757   }
01758 
01759   // Otherwise, if this block only has a single predecessor, and if that block
01760   // is a conditional branch, see if we can hoist any code from this block up
01761   // into our predecessor.
01762   if (OnlyPred)
01763     if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
01764       if (BI->isConditional()) {
01765         // Get the other block.
01766         BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
01767         PI = pred_begin(OtherBB);
01768         ++PI;
01769         if (PI == pred_end(OtherBB)) {
01770           // We have a conditional branch to two blocks that are only reachable
01771           // from the condbr.  We know that the condbr dominates the two blocks,
01772           // so see if there is any identical code in the "then" and "else"
01773           // blocks.  If so, we can hoist it up to the branching block.
01774           Changed |= HoistThenElseCodeToIf(BI);
01775         }
01776       }
01777 
01778   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
01779     if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
01780       // Change br (X == 0 | X == 1), T, F into a switch instruction.
01781       if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
01782         Instruction *Cond = cast<Instruction>(BI->getCondition());
01783         // If this is a bunch of seteq's or'd together, or if it's a bunch of
01784         // 'setne's and'ed together, collect them.
01785         Value *CompVal = 0;
01786         std::vector<ConstantInt*> Values;
01787         bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
01788         if (CompVal && CompVal->getType()->isInteger()) {
01789           // There might be duplicate constants in the list, which the switch
01790           // instruction can't handle, remove them now.
01791           std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
01792           Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
01793 
01794           // Figure out which block is which destination.
01795           BasicBlock *DefaultBB = BI->getSuccessor(1);
01796           BasicBlock *EdgeBB    = BI->getSuccessor(0);
01797           if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
01798 
01799           // Create the new switch instruction now.
01800           SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI);
01801 
01802           // Add all of the 'cases' to the switch instruction.
01803           for (unsigned i = 0, e = Values.size(); i != e; ++i)
01804             New->addCase(Values[i], EdgeBB);
01805 
01806           // We added edges from PI to the EdgeBB.  As such, if there were any
01807           // PHI nodes in EdgeBB, they need entries to be added corresponding to
01808           // the number of edges added.
01809           for (BasicBlock::iterator BBI = EdgeBB->begin();
01810                isa<PHINode>(BBI); ++BBI) {
01811             PHINode *PN = cast<PHINode>(BBI);
01812             Value *InVal = PN->getIncomingValueForBlock(*PI);
01813             for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
01814               PN->addIncoming(InVal, *PI);
01815           }
01816 
01817           // Erase the old branch instruction.
01818           (*PI)->getInstList().erase(BI);
01819 
01820           // Erase the potentially condition tree that was used to computed the
01821           // branch condition.
01822           ErasePossiblyDeadInstructionTree(Cond);
01823           return true;
01824         }
01825       }
01826 
01827   // If there is a trivial two-entry PHI node in this basic block, and we can
01828   // eliminate it, do so now.
01829   if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
01830     if (PN->getNumIncomingValues() == 2)
01831       Changed |= FoldTwoEntryPHINode(PN); 
01832 
01833   return Changed;
01834 }