LLVM API Documentation

JumpThreading.cpp
Go to the documentation of this file.
00001 //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Jump Threading pass.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "jump-threading"
00015 #include "llvm/Transforms/Scalar.h"
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/ADT/DenseSet.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/SmallPtrSet.h"
00020 #include "llvm/ADT/SmallSet.h"
00021 #include "llvm/ADT/Statistic.h"
00022 #include "llvm/Analysis/ConstantFolding.h"
00023 #include "llvm/Analysis/InstructionSimplify.h"
00024 #include "llvm/Analysis/LazyValueInfo.h"
00025 #include "llvm/Analysis/Loads.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/IR/IntrinsicInst.h"
00028 #include "llvm/IR/LLVMContext.h"
00029 #include "llvm/Pass.h"
00030 #include "llvm/Support/CommandLine.h"
00031 #include "llvm/Support/Debug.h"
00032 #include "llvm/Support/ValueHandle.h"
00033 #include "llvm/Support/raw_ostream.h"
00034 #include "llvm/Target/TargetLibraryInfo.h"
00035 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00036 #include "llvm/Transforms/Utils/Local.h"
00037 #include "llvm/Transforms/Utils/SSAUpdater.h"
00038 using namespace llvm;
00039 
00040 STATISTIC(NumThreads, "Number of jumps threaded");
00041 STATISTIC(NumFolds,   "Number of terminators folded");
00042 STATISTIC(NumDupes,   "Number of branch blocks duplicated to eliminate phi");
00043 
00044 static cl::opt<unsigned>
00045 Threshold("jump-threading-threshold",
00046           cl::desc("Max block size to duplicate for jump threading"),
00047           cl::init(6), cl::Hidden);
00048 
00049 namespace {
00050   // These are at global scope so static functions can use them too.
00051   typedef SmallVectorImpl<std::pair<Constant*, BasicBlock*> > PredValueInfo;
00052   typedef SmallVector<std::pair<Constant*, BasicBlock*>, 8> PredValueInfoTy;
00053 
00054   // This is used to keep track of what kind of constant we're currently hoping
00055   // to find.
00056   enum ConstantPreference {
00057     WantInteger,
00058     WantBlockAddress
00059   };
00060 
00061   /// This pass performs 'jump threading', which looks at blocks that have
00062   /// multiple predecessors and multiple successors.  If one or more of the
00063   /// predecessors of the block can be proven to always jump to one of the
00064   /// successors, we forward the edge from the predecessor to the successor by
00065   /// duplicating the contents of this block.
00066   ///
00067   /// An example of when this can occur is code like this:
00068   ///
00069   ///   if () { ...
00070   ///     X = 4;
00071   ///   }
00072   ///   if (X < 3) {
00073   ///
00074   /// In this case, the unconditional branch at the end of the first if can be
00075   /// revectored to the false side of the second if.
00076   ///
00077   class JumpThreading : public FunctionPass {
00078     DataLayout *TD;
00079     TargetLibraryInfo *TLI;
00080     LazyValueInfo *LVI;
00081 #ifdef NDEBUG
00082     SmallPtrSet<BasicBlock*, 16> LoopHeaders;
00083 #else
00084     SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
00085 #endif
00086     DenseSet<std::pair<Value*, BasicBlock*> > RecursionSet;
00087 
00088     // RAII helper for updating the recursion stack.
00089     struct RecursionSetRemover {
00090       DenseSet<std::pair<Value*, BasicBlock*> > &TheSet;
00091       std::pair<Value*, BasicBlock*> ThePair;
00092 
00093       RecursionSetRemover(DenseSet<std::pair<Value*, BasicBlock*> > &S,
00094                           std::pair<Value*, BasicBlock*> P)
00095         : TheSet(S), ThePair(P) { }
00096 
00097       ~RecursionSetRemover() {
00098         TheSet.erase(ThePair);
00099       }
00100     };
00101   public:
00102     static char ID; // Pass identification
00103     JumpThreading() : FunctionPass(ID) {
00104       initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
00105     }
00106 
00107     bool runOnFunction(Function &F);
00108 
00109     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00110       AU.addRequired<LazyValueInfo>();
00111       AU.addPreserved<LazyValueInfo>();
00112       AU.addRequired<TargetLibraryInfo>();
00113     }
00114 
00115     void FindLoopHeaders(Function &F);
00116     bool ProcessBlock(BasicBlock *BB);
00117     bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs,
00118                     BasicBlock *SuccBB);
00119     bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
00120                                   const SmallVectorImpl<BasicBlock *> &PredBBs);
00121 
00122     bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
00123                                          PredValueInfo &Result,
00124                                          ConstantPreference Preference);
00125     bool ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
00126                                 ConstantPreference Preference);
00127 
00128     bool ProcessBranchOnPHI(PHINode *PN);
00129     bool ProcessBranchOnXOR(BinaryOperator *BO);
00130 
00131     bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
00132   };
00133 }
00134 
00135 char JumpThreading::ID = 0;
00136 INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
00137                 "Jump Threading", false, false)
00138 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
00139 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
00140 INITIALIZE_PASS_END(JumpThreading, "jump-threading",
00141                 "Jump Threading", false, false)
00142 
00143 // Public interface to the Jump Threading pass
00144 FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
00145 
00146 /// runOnFunction - Top level algorithm.
00147 ///
00148 bool JumpThreading::runOnFunction(Function &F) {
00149   DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
00150   TD = getAnalysisIfAvailable<DataLayout>();
00151   TLI = &getAnalysis<TargetLibraryInfo>();
00152   LVI = &getAnalysis<LazyValueInfo>();
00153 
00154   FindLoopHeaders(F);
00155 
00156   bool Changed, EverChanged = false;
00157   do {
00158     Changed = false;
00159     for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
00160       BasicBlock *BB = I;
00161       // Thread all of the branches we can over this block.
00162       while (ProcessBlock(BB))
00163         Changed = true;
00164 
00165       ++I;
00166 
00167       // If the block is trivially dead, zap it.  This eliminates the successor
00168       // edges which simplifies the CFG.
00169       if (pred_begin(BB) == pred_end(BB) &&
00170           BB != &BB->getParent()->getEntryBlock()) {
00171         DEBUG(dbgs() << "  JT: Deleting dead block '" << BB->getName()
00172               << "' with terminator: " << *BB->getTerminator() << '\n');
00173         LoopHeaders.erase(BB);
00174         LVI->eraseBlock(BB);
00175         DeleteDeadBlock(BB);
00176         Changed = true;
00177         continue;
00178       }
00179 
00180       BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
00181 
00182       // Can't thread an unconditional jump, but if the block is "almost
00183       // empty", we can replace uses of it with uses of the successor and make
00184       // this dead.
00185       if (BI && BI->isUnconditional() &&
00186           BB != &BB->getParent()->getEntryBlock() &&
00187           // If the terminator is the only non-phi instruction, try to nuke it.
00188           BB->getFirstNonPHIOrDbg()->isTerminator()) {
00189         // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
00190         // block, we have to make sure it isn't in the LoopHeaders set.  We
00191         // reinsert afterward if needed.
00192         bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
00193         BasicBlock *Succ = BI->getSuccessor(0);
00194 
00195         // FIXME: It is always conservatively correct to drop the info
00196         // for a block even if it doesn't get erased.  This isn't totally
00197         // awesome, but it allows us to use AssertingVH to prevent nasty
00198         // dangling pointer issues within LazyValueInfo.
00199         LVI->eraseBlock(BB);
00200         if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) {
00201           Changed = true;
00202           // If we deleted BB and BB was the header of a loop, then the
00203           // successor is now the header of the loop.
00204           BB = Succ;
00205         }
00206 
00207         if (ErasedFromLoopHeaders)
00208           LoopHeaders.insert(BB);
00209       }
00210     }
00211     EverChanged |= Changed;
00212   } while (Changed);
00213 
00214   LoopHeaders.clear();
00215   return EverChanged;
00216 }
00217 
00218 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
00219 /// thread across it. Stop scanning the block when passing the threshold.
00220 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB,
00221                                              unsigned Threshold) {
00222   /// Ignore PHI nodes, these will be flattened when duplication happens.
00223   BasicBlock::const_iterator I = BB->getFirstNonPHI();
00224 
00225   // FIXME: THREADING will delete values that are just used to compute the
00226   // branch, so they shouldn't count against the duplication cost.
00227 
00228   // Sum up the cost of each instruction until we get to the terminator.  Don't
00229   // include the terminator because the copy won't include it.
00230   unsigned Size = 0;
00231   for (; !isa<TerminatorInst>(I); ++I) {
00232 
00233     // Stop scanning the block if we've reached the threshold.
00234     if (Size > Threshold)
00235       return Size;
00236 
00237     // Debugger intrinsics don't incur code size.
00238     if (isa<DbgInfoIntrinsic>(I)) continue;
00239 
00240     // If this is a pointer->pointer bitcast, it is free.
00241     if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
00242       continue;
00243 
00244     // All other instructions count for at least one unit.
00245     ++Size;
00246 
00247     // Calls are more expensive.  If they are non-intrinsic calls, we model them
00248     // as having cost of 4.  If they are a non-vector intrinsic, we model them
00249     // as having cost of 2 total, and if they are a vector intrinsic, we model
00250     // them as having cost 1.
00251     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
00252       if (CI->hasFnAttr(Attribute::NoDuplicate))
00253         // Blocks with NoDuplicate are modelled as having infinite cost, so they
00254         // are never duplicated.
00255         return ~0U;
00256       else if (!isa<IntrinsicInst>(CI))
00257         Size += 3;
00258       else if (!CI->getType()->isVectorTy())
00259         Size += 1;
00260     }
00261   }
00262 
00263   // Threading through a switch statement is particularly profitable.  If this
00264   // block ends in a switch, decrease its cost to make it more likely to happen.
00265   if (isa<SwitchInst>(I))
00266     Size = Size > 6 ? Size-6 : 0;
00267 
00268   // The same holds for indirect branches, but slightly more so.
00269   if (isa<IndirectBrInst>(I))
00270     Size = Size > 8 ? Size-8 : 0;
00271 
00272   return Size;
00273 }
00274 
00275 /// FindLoopHeaders - We do not want jump threading to turn proper loop
00276 /// structures into irreducible loops.  Doing this breaks up the loop nesting
00277 /// hierarchy and pessimizes later transformations.  To prevent this from
00278 /// happening, we first have to find the loop headers.  Here we approximate this
00279 /// by finding targets of backedges in the CFG.
00280 ///
00281 /// Note that there definitely are cases when we want to allow threading of
00282 /// edges across a loop header.  For example, threading a jump from outside the
00283 /// loop (the preheader) to an exit block of the loop is definitely profitable.
00284 /// It is also almost always profitable to thread backedges from within the loop
00285 /// to exit blocks, and is often profitable to thread backedges to other blocks
00286 /// within the loop (forming a nested loop).  This simple analysis is not rich
00287 /// enough to track all of these properties and keep it up-to-date as the CFG
00288 /// mutates, so we don't allow any of these transformations.
00289 ///
00290 void JumpThreading::FindLoopHeaders(Function &F) {
00291   SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
00292   FindFunctionBackedges(F, Edges);
00293 
00294   for (unsigned i = 0, e = Edges.size(); i != e; ++i)
00295     LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
00296 }
00297 
00298 /// getKnownConstant - Helper method to determine if we can thread over a
00299 /// terminator with the given value as its condition, and if so what value to
00300 /// use for that. What kind of value this is depends on whether we want an
00301 /// integer or a block address, but an undef is always accepted.
00302 /// Returns null if Val is null or not an appropriate constant.
00303 static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
00304   if (!Val)
00305     return 0;
00306 
00307   // Undef is "known" enough.
00308   if (UndefValue *U = dyn_cast<UndefValue>(Val))
00309     return U;
00310 
00311   if (Preference == WantBlockAddress)
00312     return dyn_cast<BlockAddress>(Val->stripPointerCasts());
00313 
00314   return dyn_cast<ConstantInt>(Val);
00315 }
00316 
00317 /// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
00318 /// if we can infer that the value is a known ConstantInt/BlockAddress or undef
00319 /// in any of our predecessors.  If so, return the known list of value and pred
00320 /// BB in the result vector.
00321 ///
00322 /// This returns true if there were any known values.
00323 ///
00324 bool JumpThreading::
00325 ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB, PredValueInfo &Result,
00326                                 ConstantPreference Preference) {
00327   // This method walks up use-def chains recursively.  Because of this, we could
00328   // get into an infinite loop going around loops in the use-def chain.  To
00329   // prevent this, keep track of what (value, block) pairs we've already visited
00330   // and terminate the search if we loop back to them
00331   if (!RecursionSet.insert(std::make_pair(V, BB)).second)
00332     return false;
00333 
00334   // An RAII help to remove this pair from the recursion set once the recursion
00335   // stack pops back out again.
00336   RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
00337 
00338   // If V is a constant, then it is known in all predecessors.
00339   if (Constant *KC = getKnownConstant(V, Preference)) {
00340     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
00341       Result.push_back(std::make_pair(KC, *PI));
00342 
00343     return true;
00344   }
00345 
00346   // If V is a non-instruction value, or an instruction in a different block,
00347   // then it can't be derived from a PHI.
00348   Instruction *I = dyn_cast<Instruction>(V);
00349   if (I == 0 || I->getParent() != BB) {
00350 
00351     // Okay, if this is a live-in value, see if it has a known value at the end
00352     // of any of our predecessors.
00353     //
00354     // FIXME: This should be an edge property, not a block end property.
00355     /// TODO: Per PR2563, we could infer value range information about a
00356     /// predecessor based on its terminator.
00357     //
00358     // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
00359     // "I" is a non-local compare-with-a-constant instruction.  This would be
00360     // able to handle value inequalities better, for example if the compare is
00361     // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
00362     // Perhaps getConstantOnEdge should be smart enough to do this?
00363 
00364     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
00365       BasicBlock *P = *PI;
00366       // If the value is known by LazyValueInfo to be a constant in a
00367       // predecessor, use that information to try to thread this block.
00368       Constant *PredCst = LVI->getConstantOnEdge(V, P, BB);
00369       if (Constant *KC = getKnownConstant(PredCst, Preference))
00370         Result.push_back(std::make_pair(KC, P));
00371     }
00372 
00373     return !Result.empty();
00374   }
00375 
00376   /// If I is a PHI node, then we know the incoming values for any constants.
00377   if (PHINode *PN = dyn_cast<PHINode>(I)) {
00378     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00379       Value *InVal = PN->getIncomingValue(i);
00380       if (Constant *KC = getKnownConstant(InVal, Preference)) {
00381         Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
00382       } else {
00383         Constant *CI = LVI->getConstantOnEdge(InVal,
00384                                               PN->getIncomingBlock(i), BB);
00385         if (Constant *KC = getKnownConstant(CI, Preference))
00386           Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
00387       }
00388     }
00389 
00390     return !Result.empty();
00391   }
00392 
00393   PredValueInfoTy LHSVals, RHSVals;
00394 
00395   // Handle some boolean conditions.
00396   if (I->getType()->getPrimitiveSizeInBits() == 1) {
00397     assert(Preference == WantInteger && "One-bit non-integer type?");
00398     // X | true -> true
00399     // X & false -> false
00400     if (I->getOpcode() == Instruction::Or ||
00401         I->getOpcode() == Instruction::And) {
00402       ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
00403                                       WantInteger);
00404       ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals,
00405                                       WantInteger);
00406 
00407       if (LHSVals.empty() && RHSVals.empty())
00408         return false;
00409 
00410       ConstantInt *InterestingVal;
00411       if (I->getOpcode() == Instruction::Or)
00412         InterestingVal = ConstantInt::getTrue(I->getContext());
00413       else
00414         InterestingVal = ConstantInt::getFalse(I->getContext());
00415 
00416       SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
00417 
00418       // Scan for the sentinel.  If we find an undef, force it to the
00419       // interesting value: x|undef -> true and x&undef -> false.
00420       for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
00421         if (LHSVals[i].first == InterestingVal ||
00422             isa<UndefValue>(LHSVals[i].first)) {
00423           Result.push_back(LHSVals[i]);
00424           Result.back().first = InterestingVal;
00425           LHSKnownBBs.insert(LHSVals[i].second);
00426         }
00427       for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
00428         if (RHSVals[i].first == InterestingVal ||
00429             isa<UndefValue>(RHSVals[i].first)) {
00430           // If we already inferred a value for this block on the LHS, don't
00431           // re-add it.
00432           if (!LHSKnownBBs.count(RHSVals[i].second)) {
00433             Result.push_back(RHSVals[i]);
00434             Result.back().first = InterestingVal;
00435           }
00436         }
00437 
00438       return !Result.empty();
00439     }
00440 
00441     // Handle the NOT form of XOR.
00442     if (I->getOpcode() == Instruction::Xor &&
00443         isa<ConstantInt>(I->getOperand(1)) &&
00444         cast<ConstantInt>(I->getOperand(1))->isOne()) {
00445       ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result,
00446                                       WantInteger);
00447       if (Result.empty())
00448         return false;
00449 
00450       // Invert the known values.
00451       for (unsigned i = 0, e = Result.size(); i != e; ++i)
00452         Result[i].first = ConstantExpr::getNot(Result[i].first);
00453 
00454       return true;
00455     }
00456 
00457   // Try to simplify some other binary operator values.
00458   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
00459     assert(Preference != WantBlockAddress
00460             && "A binary operator creating a block address?");
00461     if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
00462       PredValueInfoTy LHSVals;
00463       ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals,
00464                                       WantInteger);
00465 
00466       // Try to use constant folding to simplify the binary operator.
00467       for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
00468         Constant *V = LHSVals[i].first;
00469         Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
00470 
00471         if (Constant *KC = getKnownConstant(Folded, WantInteger))
00472           Result.push_back(std::make_pair(KC, LHSVals[i].second));
00473       }
00474     }
00475 
00476     return !Result.empty();
00477   }
00478 
00479   // Handle compare with phi operand, where the PHI is defined in this block.
00480   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
00481     assert(Preference == WantInteger && "Compares only produce integers");
00482     PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
00483     if (PN && PN->getParent() == BB) {
00484       // We can do this simplification if any comparisons fold to true or false.
00485       // See if any do.
00486       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00487         BasicBlock *PredBB = PN->getIncomingBlock(i);
00488         Value *LHS = PN->getIncomingValue(i);
00489         Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
00490 
00491         Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, TD);
00492         if (Res == 0) {
00493           if (!isa<Constant>(RHS))
00494             continue;
00495 
00496           LazyValueInfo::Tristate
00497             ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS,
00498                                            cast<Constant>(RHS), PredBB, BB);
00499           if (ResT == LazyValueInfo::Unknown)
00500             continue;
00501           Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
00502         }
00503 
00504         if (Constant *KC = getKnownConstant(Res, WantInteger))
00505           Result.push_back(std::make_pair(KC, PredBB));
00506       }
00507 
00508       return !Result.empty();
00509     }
00510 
00511 
00512     // If comparing a live-in value against a constant, see if we know the
00513     // live-in value on any predecessors.
00514     if (isa<Constant>(Cmp->getOperand(1)) && Cmp->getType()->isIntegerTy()) {
00515       if (!isa<Instruction>(Cmp->getOperand(0)) ||
00516           cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) {
00517         Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
00518 
00519         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB);PI != E; ++PI){
00520           BasicBlock *P = *PI;
00521           // If the value is known by LazyValueInfo to be a constant in a
00522           // predecessor, use that information to try to thread this block.
00523           LazyValueInfo::Tristate Res =
00524             LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
00525                                     RHSCst, P, BB);
00526           if (Res == LazyValueInfo::Unknown)
00527             continue;
00528 
00529           Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
00530           Result.push_back(std::make_pair(ResC, P));
00531         }
00532 
00533         return !Result.empty();
00534       }
00535 
00536       // Try to find a constant value for the LHS of a comparison,
00537       // and evaluate it statically if we can.
00538       if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) {
00539         PredValueInfoTy LHSVals;
00540         ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
00541                                         WantInteger);
00542 
00543         for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
00544           Constant *V = LHSVals[i].first;
00545           Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(),
00546                                                       V, CmpConst);
00547           if (Constant *KC = getKnownConstant(Folded, WantInteger))
00548             Result.push_back(std::make_pair(KC, LHSVals[i].second));
00549         }
00550 
00551         return !Result.empty();
00552       }
00553     }
00554   }
00555 
00556   if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
00557     // Handle select instructions where at least one operand is a known constant
00558     // and we can figure out the condition value for any predecessor block.
00559     Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
00560     Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
00561     PredValueInfoTy Conds;
00562     if ((TrueVal || FalseVal) &&
00563         ComputeValueKnownInPredecessors(SI->getCondition(), BB, Conds,
00564                                         WantInteger)) {
00565       for (unsigned i = 0, e = Conds.size(); i != e; ++i) {
00566         Constant *Cond = Conds[i].first;
00567 
00568         // Figure out what value to use for the condition.
00569         bool KnownCond;
00570         if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
00571           // A known boolean.
00572           KnownCond = CI->isOne();
00573         } else {
00574           assert(isa<UndefValue>(Cond) && "Unexpected condition value");
00575           // Either operand will do, so be sure to pick the one that's a known
00576           // constant.
00577           // FIXME: Do this more cleverly if both values are known constants?
00578           KnownCond = (TrueVal != 0);
00579         }
00580 
00581         // See if the select has a known constant value for this predecessor.
00582         if (Constant *Val = KnownCond ? TrueVal : FalseVal)
00583           Result.push_back(std::make_pair(Val, Conds[i].second));
00584       }
00585 
00586       return !Result.empty();
00587     }
00588   }
00589 
00590   // If all else fails, see if LVI can figure out a constant value for us.
00591   Constant *CI = LVI->getConstant(V, BB);
00592   if (Constant *KC = getKnownConstant(CI, Preference)) {
00593     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
00594       Result.push_back(std::make_pair(KC, *PI));
00595   }
00596 
00597   return !Result.empty();
00598 }
00599 
00600 
00601 
00602 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
00603 /// in an undefined jump, decide which block is best to revector to.
00604 ///
00605 /// Since we can pick an arbitrary destination, we pick the successor with the
00606 /// fewest predecessors.  This should reduce the in-degree of the others.
00607 ///
00608 static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
00609   TerminatorInst *BBTerm = BB->getTerminator();
00610   unsigned MinSucc = 0;
00611   BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
00612   // Compute the successor with the minimum number of predecessors.
00613   unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
00614   for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
00615     TestBB = BBTerm->getSuccessor(i);
00616     unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
00617     if (NumPreds < MinNumPreds) {
00618       MinSucc = i;
00619       MinNumPreds = NumPreds;
00620     }
00621   }
00622 
00623   return MinSucc;
00624 }
00625 
00626 static bool hasAddressTakenAndUsed(BasicBlock *BB) {
00627   if (!BB->hasAddressTaken()) return false;
00628 
00629   // If the block has its address taken, it may be a tree of dead constants
00630   // hanging off of it.  These shouldn't keep the block alive.
00631   BlockAddress *BA = BlockAddress::get(BB);
00632   BA->removeDeadConstantUsers();
00633   return !BA->use_empty();
00634 }
00635 
00636 /// ProcessBlock - If there are any predecessors whose control can be threaded
00637 /// through to a successor, transform them now.
00638 bool JumpThreading::ProcessBlock(BasicBlock *BB) {
00639   // If the block is trivially dead, just return and let the caller nuke it.
00640   // This simplifies other transformations.
00641   if (pred_begin(BB) == pred_end(BB) &&
00642       BB != &BB->getParent()->getEntryBlock())
00643     return false;
00644 
00645   // If this block has a single predecessor, and if that pred has a single
00646   // successor, merge the blocks.  This encourages recursive jump threading
00647   // because now the condition in this block can be threaded through
00648   // predecessors of our predecessor block.
00649   if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
00650     if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
00651         SinglePred != BB && !hasAddressTakenAndUsed(BB)) {
00652       // If SinglePred was a loop header, BB becomes one.
00653       if (LoopHeaders.erase(SinglePred))
00654         LoopHeaders.insert(BB);
00655 
00656       // Remember if SinglePred was the entry block of the function.  If so, we
00657       // will need to move BB back to the entry position.
00658       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
00659       LVI->eraseBlock(SinglePred);
00660       MergeBasicBlockIntoOnlyPred(BB);
00661 
00662       if (isEntry && BB != &BB->getParent()->getEntryBlock())
00663         BB->moveBefore(&BB->getParent()->getEntryBlock());
00664       return true;
00665     }
00666   }
00667 
00668   // What kind of constant we're looking for.
00669   ConstantPreference Preference = WantInteger;
00670 
00671   // Look to see if the terminator is a conditional branch, switch or indirect
00672   // branch, if not we can't thread it.
00673   Value *Condition;
00674   Instruction *Terminator = BB->getTerminator();
00675   if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
00676     // Can't thread an unconditional jump.
00677     if (BI->isUnconditional()) return false;
00678     Condition = BI->getCondition();
00679   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
00680     Condition = SI->getCondition();
00681   } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
00682     // Can't thread indirect branch with no successors.
00683     if (IB->getNumSuccessors() == 0) return false;
00684     Condition = IB->getAddress()->stripPointerCasts();
00685     Preference = WantBlockAddress;
00686   } else {
00687     return false; // Must be an invoke.
00688   }
00689 
00690   // Run constant folding to see if we can reduce the condition to a simple
00691   // constant.
00692   if (Instruction *I = dyn_cast<Instruction>(Condition)) {
00693     Value *SimpleVal = ConstantFoldInstruction(I, TD, TLI);
00694     if (SimpleVal) {
00695       I->replaceAllUsesWith(SimpleVal);
00696       I->eraseFromParent();
00697       Condition = SimpleVal;
00698     }
00699   }
00700 
00701   // If the terminator is branching on an undef, we can pick any of the
00702   // successors to branch to.  Let GetBestDestForJumpOnUndef decide.
00703   if (isa<UndefValue>(Condition)) {
00704     unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
00705 
00706     // Fold the branch/switch.
00707     TerminatorInst *BBTerm = BB->getTerminator();
00708     for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
00709       if (i == BestSucc) continue;
00710       BBTerm->getSuccessor(i)->removePredecessor(BB, true);
00711     }
00712 
00713     DEBUG(dbgs() << "  In block '" << BB->getName()
00714           << "' folding undef terminator: " << *BBTerm << '\n');
00715     BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
00716     BBTerm->eraseFromParent();
00717     return true;
00718   }
00719 
00720   // If the terminator of this block is branching on a constant, simplify the
00721   // terminator to an unconditional branch.  This can occur due to threading in
00722   // other blocks.
00723   if (getKnownConstant(Condition, Preference)) {
00724     DEBUG(dbgs() << "  In block '" << BB->getName()
00725           << "' folding terminator: " << *BB->getTerminator() << '\n');
00726     ++NumFolds;
00727     ConstantFoldTerminator(BB, true);
00728     return true;
00729   }
00730 
00731   Instruction *CondInst = dyn_cast<Instruction>(Condition);
00732 
00733   // All the rest of our checks depend on the condition being an instruction.
00734   if (CondInst == 0) {
00735     // FIXME: Unify this with code below.
00736     if (ProcessThreadableEdges(Condition, BB, Preference))
00737       return true;
00738     return false;
00739   }
00740 
00741 
00742   if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
00743     // For a comparison where the LHS is outside this block, it's possible
00744     // that we've branched on it before.  Used LVI to see if we can simplify
00745     // the branch based on that.
00746     BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
00747     Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
00748     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
00749     if (CondBr && CondConst && CondBr->isConditional() && PI != PE &&
00750         (!isa<Instruction>(CondCmp->getOperand(0)) ||
00751          cast<Instruction>(CondCmp->getOperand(0))->getParent() != BB)) {
00752       // For predecessor edge, determine if the comparison is true or false
00753       // on that edge.  If they're all true or all false, we can simplify the
00754       // branch.
00755       // FIXME: We could handle mixed true/false by duplicating code.
00756       LazyValueInfo::Tristate Baseline =
00757         LVI->getPredicateOnEdge(CondCmp->getPredicate(), CondCmp->getOperand(0),
00758                                 CondConst, *PI, BB);
00759       if (Baseline != LazyValueInfo::Unknown) {
00760         // Check that all remaining incoming values match the first one.
00761         while (++PI != PE) {
00762           LazyValueInfo::Tristate Ret =
00763             LVI->getPredicateOnEdge(CondCmp->getPredicate(),
00764                                     CondCmp->getOperand(0), CondConst, *PI, BB);
00765           if (Ret != Baseline) break;
00766         }
00767 
00768         // If we terminated early, then one of the values didn't match.
00769         if (PI == PE) {
00770           unsigned ToRemove = Baseline == LazyValueInfo::True ? 1 : 0;
00771           unsigned ToKeep = Baseline == LazyValueInfo::True ? 0 : 1;
00772           CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true);
00773           BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
00774           CondBr->eraseFromParent();
00775           return true;
00776         }
00777       }
00778     }
00779   }
00780 
00781   // Check for some cases that are worth simplifying.  Right now we want to look
00782   // for loads that are used by a switch or by the condition for the branch.  If
00783   // we see one, check to see if it's partially redundant.  If so, insert a PHI
00784   // which can then be used to thread the values.
00785   //
00786   Value *SimplifyValue = CondInst;
00787   if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
00788     if (isa<Constant>(CondCmp->getOperand(1)))
00789       SimplifyValue = CondCmp->getOperand(0);
00790 
00791   // TODO: There are other places where load PRE would be profitable, such as
00792   // more complex comparisons.
00793   if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
00794     if (SimplifyPartiallyRedundantLoad(LI))
00795       return true;
00796 
00797 
00798   // Handle a variety of cases where we are branching on something derived from
00799   // a PHI node in the current block.  If we can prove that any predecessors
00800   // compute a predictable value based on a PHI node, thread those predecessors.
00801   //
00802   if (ProcessThreadableEdges(CondInst, BB, Preference))
00803     return true;
00804 
00805   // If this is an otherwise-unfoldable branch on a phi node in the current
00806   // block, see if we can simplify.
00807   if (PHINode *PN = dyn_cast<PHINode>(CondInst))
00808     if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
00809       return ProcessBranchOnPHI(PN);
00810 
00811 
00812   // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
00813   if (CondInst->getOpcode() == Instruction::Xor &&
00814       CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
00815     return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
00816 
00817 
00818   // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
00819   // "(X == 4)", thread through this block.
00820 
00821   return false;
00822 }
00823 
00824 
00825 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
00826 /// load instruction, eliminate it by replacing it with a PHI node.  This is an
00827 /// important optimization that encourages jump threading, and needs to be run
00828 /// interlaced with other jump threading tasks.
00829 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
00830   // Don't hack volatile/atomic loads.
00831   if (!LI->isSimple()) return false;
00832 
00833   // If the load is defined in a block with exactly one predecessor, it can't be
00834   // partially redundant.
00835   BasicBlock *LoadBB = LI->getParent();
00836   if (LoadBB->getSinglePredecessor())
00837     return false;
00838 
00839   Value *LoadedPtr = LI->getOperand(0);
00840 
00841   // If the loaded operand is defined in the LoadBB, it can't be available.
00842   // TODO: Could do simple PHI translation, that would be fun :)
00843   if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
00844     if (PtrOp->getParent() == LoadBB)
00845       return false;
00846 
00847   // Scan a few instructions up from the load, to see if it is obviously live at
00848   // the entry to its block.
00849   BasicBlock::iterator BBIt = LI;
00850 
00851   if (Value *AvailableVal =
00852         FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
00853     // If the value if the load is locally available within the block, just use
00854     // it.  This frequently occurs for reg2mem'd allocas.
00855     //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
00856 
00857     // If the returned value is the load itself, replace with an undef. This can
00858     // only happen in dead loops.
00859     if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
00860     LI->replaceAllUsesWith(AvailableVal);
00861     LI->eraseFromParent();
00862     return true;
00863   }
00864 
00865   // Otherwise, if we scanned the whole block and got to the top of the block,
00866   // we know the block is locally transparent to the load.  If not, something
00867   // might clobber its value.
00868   if (BBIt != LoadBB->begin())
00869     return false;
00870 
00871   // If all of the loads and stores that feed the value have the same TBAA tag,
00872   // then we can propagate it onto any newly inserted loads.
00873   MDNode *TBAATag = LI->getMetadata(LLVMContext::MD_tbaa);
00874 
00875   SmallPtrSet<BasicBlock*, 8> PredsScanned;
00876   typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
00877   AvailablePredsTy AvailablePreds;
00878   BasicBlock *OneUnavailablePred = 0;
00879 
00880   // If we got here, the loaded value is transparent through to the start of the
00881   // block.  Check to see if it is available in any of the predecessor blocks.
00882   for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
00883        PI != PE; ++PI) {
00884     BasicBlock *PredBB = *PI;
00885 
00886     // If we already scanned this predecessor, skip it.
00887     if (!PredsScanned.insert(PredBB))
00888       continue;
00889 
00890     // Scan the predecessor to see if the value is available in the pred.
00891     BBIt = PredBB->end();
00892     MDNode *ThisTBAATag = 0;
00893     Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6,
00894                                                     0, &ThisTBAATag);
00895     if (!PredAvailable) {
00896       OneUnavailablePred = PredBB;
00897       continue;
00898     }
00899 
00900     // If tbaa tags disagree or are not present, forget about them.
00901     if (TBAATag != ThisTBAATag) TBAATag = 0;
00902 
00903     // If so, this load is partially redundant.  Remember this info so that we
00904     // can create a PHI node.
00905     AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
00906   }
00907 
00908   // If the loaded value isn't available in any predecessor, it isn't partially
00909   // redundant.
00910   if (AvailablePreds.empty()) return false;
00911 
00912   // Okay, the loaded value is available in at least one (and maybe all!)
00913   // predecessors.  If the value is unavailable in more than one unique
00914   // predecessor, we want to insert a merge block for those common predecessors.
00915   // This ensures that we only have to insert one reload, thus not increasing
00916   // code size.
00917   BasicBlock *UnavailablePred = 0;
00918 
00919   // If there is exactly one predecessor where the value is unavailable, the
00920   // already computed 'OneUnavailablePred' block is it.  If it ends in an
00921   // unconditional branch, we know that it isn't a critical edge.
00922   if (PredsScanned.size() == AvailablePreds.size()+1 &&
00923       OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
00924     UnavailablePred = OneUnavailablePred;
00925   } else if (PredsScanned.size() != AvailablePreds.size()) {
00926     // Otherwise, we had multiple unavailable predecessors or we had a critical
00927     // edge from the one.
00928     SmallVector<BasicBlock*, 8> PredsToSplit;
00929     SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
00930 
00931     for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
00932       AvailablePredSet.insert(AvailablePreds[i].first);
00933 
00934     // Add all the unavailable predecessors to the PredsToSplit list.
00935     for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
00936          PI != PE; ++PI) {
00937       BasicBlock *P = *PI;
00938       // If the predecessor is an indirect goto, we can't split the edge.
00939       if (isa<IndirectBrInst>(P->getTerminator()))
00940         return false;
00941 
00942       if (!AvailablePredSet.count(P))
00943         PredsToSplit.push_back(P);
00944     }
00945 
00946     // Split them out to their own block.
00947     UnavailablePred =
00948       SplitBlockPredecessors(LoadBB, PredsToSplit, "thread-pre-split", this);
00949   }
00950 
00951   // If the value isn't available in all predecessors, then there will be
00952   // exactly one where it isn't available.  Insert a load on that edge and add
00953   // it to the AvailablePreds list.
00954   if (UnavailablePred) {
00955     assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
00956            "Can't handle critical edge here!");
00957     LoadInst *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", false,
00958                                  LI->getAlignment(),
00959                                  UnavailablePred->getTerminator());
00960     NewVal->setDebugLoc(LI->getDebugLoc());
00961     if (TBAATag)
00962       NewVal->setMetadata(LLVMContext::MD_tbaa, TBAATag);
00963 
00964     AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
00965   }
00966 
00967   // Now we know that each predecessor of this block has a value in
00968   // AvailablePreds, sort them for efficient access as we're walking the preds.
00969   array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
00970 
00971   // Create a PHI node at the start of the block for the PRE'd load value.
00972   pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
00973   PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "",
00974                                 LoadBB->begin());
00975   PN->takeName(LI);
00976   PN->setDebugLoc(LI->getDebugLoc());
00977 
00978   // Insert new entries into the PHI for each predecessor.  A single block may
00979   // have multiple entries here.
00980   for (pred_iterator PI = PB; PI != PE; ++PI) {
00981     BasicBlock *P = *PI;
00982     AvailablePredsTy::iterator I =
00983       std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
00984                        std::make_pair(P, (Value*)0));
00985 
00986     assert(I != AvailablePreds.end() && I->first == P &&
00987            "Didn't find entry for predecessor!");
00988 
00989     PN->addIncoming(I->second, I->first);
00990   }
00991 
00992   //cerr << "PRE: " << *LI << *PN << "\n";
00993 
00994   LI->replaceAllUsesWith(PN);
00995   LI->eraseFromParent();
00996 
00997   return true;
00998 }
00999 
01000 /// FindMostPopularDest - The specified list contains multiple possible
01001 /// threadable destinations.  Pick the one that occurs the most frequently in
01002 /// the list.
01003 static BasicBlock *
01004 FindMostPopularDest(BasicBlock *BB,
01005                     const SmallVectorImpl<std::pair<BasicBlock*,
01006                                   BasicBlock*> > &PredToDestList) {
01007   assert(!PredToDestList.empty());
01008 
01009   // Determine popularity.  If there are multiple possible destinations, we
01010   // explicitly choose to ignore 'undef' destinations.  We prefer to thread
01011   // blocks with known and real destinations to threading undef.  We'll handle
01012   // them later if interesting.
01013   DenseMap<BasicBlock*, unsigned> DestPopularity;
01014   for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
01015     if (PredToDestList[i].second)
01016       DestPopularity[PredToDestList[i].second]++;
01017 
01018   // Find the most popular dest.
01019   DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
01020   BasicBlock *MostPopularDest = DPI->first;
01021   unsigned Popularity = DPI->second;
01022   SmallVector<BasicBlock*, 4> SamePopularity;
01023 
01024   for (++DPI; DPI != DestPopularity.end(); ++DPI) {
01025     // If the popularity of this entry isn't higher than the popularity we've
01026     // seen so far, ignore it.
01027     if (DPI->second < Popularity)
01028       ; // ignore.
01029     else if (DPI->second == Popularity) {
01030       // If it is the same as what we've seen so far, keep track of it.
01031       SamePopularity.push_back(DPI->first);
01032     } else {
01033       // If it is more popular, remember it.
01034       SamePopularity.clear();
01035       MostPopularDest = DPI->first;
01036       Popularity = DPI->second;
01037     }
01038   }
01039 
01040   // Okay, now we know the most popular destination.  If there is more than one
01041   // destination, we need to determine one.  This is arbitrary, but we need
01042   // to make a deterministic decision.  Pick the first one that appears in the
01043   // successor list.
01044   if (!SamePopularity.empty()) {
01045     SamePopularity.push_back(MostPopularDest);
01046     TerminatorInst *TI = BB->getTerminator();
01047     for (unsigned i = 0; ; ++i) {
01048       assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
01049 
01050       if (std::find(SamePopularity.begin(), SamePopularity.end(),
01051                     TI->getSuccessor(i)) == SamePopularity.end())
01052         continue;
01053 
01054       MostPopularDest = TI->getSuccessor(i);
01055       break;
01056     }
01057   }
01058 
01059   // Okay, we have finally picked the most popular destination.
01060   return MostPopularDest;
01061 }
01062 
01063 bool JumpThreading::ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
01064                                            ConstantPreference Preference) {
01065   // If threading this would thread across a loop header, don't even try to
01066   // thread the edge.
01067   if (LoopHeaders.count(BB))
01068     return false;
01069 
01070   PredValueInfoTy PredValues;
01071   if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference))
01072     return false;
01073 
01074   assert(!PredValues.empty() &&
01075          "ComputeValueKnownInPredecessors returned true with no values");
01076 
01077   DEBUG(dbgs() << "IN BB: " << *BB;
01078         for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
01079           dbgs() << "  BB '" << BB->getName() << "': FOUND condition = "
01080             << *PredValues[i].first
01081             << " for pred '" << PredValues[i].second->getName() << "'.\n";
01082         });
01083 
01084   // Decide what we want to thread through.  Convert our list of known values to
01085   // a list of known destinations for each pred.  This also discards duplicate
01086   // predecessors and keeps track of the undefined inputs (which are represented
01087   // as a null dest in the PredToDestList).
01088   SmallPtrSet<BasicBlock*, 16> SeenPreds;
01089   SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
01090 
01091   BasicBlock *OnlyDest = 0;
01092   BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
01093 
01094   for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
01095     BasicBlock *Pred = PredValues[i].second;
01096     if (!SeenPreds.insert(Pred))
01097       continue;  // Duplicate predecessor entry.
01098 
01099     // If the predecessor ends with an indirect goto, we can't change its
01100     // destination.
01101     if (isa<IndirectBrInst>(Pred->getTerminator()))
01102       continue;
01103 
01104     Constant *Val = PredValues[i].first;
01105 
01106     BasicBlock *DestBB;
01107     if (isa<UndefValue>(Val))
01108       DestBB = 0;
01109     else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
01110       DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
01111     else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
01112       DestBB = SI->findCaseValue(cast<ConstantInt>(Val)).getCaseSuccessor();
01113     } else {
01114       assert(isa<IndirectBrInst>(BB->getTerminator())
01115               && "Unexpected terminator");
01116       DestBB = cast<BlockAddress>(Val)->getBasicBlock();
01117     }
01118 
01119     // If we have exactly one destination, remember it for efficiency below.
01120     if (PredToDestList.empty())
01121       OnlyDest = DestBB;
01122     else if (OnlyDest != DestBB)
01123       OnlyDest = MultipleDestSentinel;
01124 
01125     PredToDestList.push_back(std::make_pair(Pred, DestBB));
01126   }
01127 
01128   // If all edges were unthreadable, we fail.
01129   if (PredToDestList.empty())
01130     return false;
01131 
01132   // Determine which is the most common successor.  If we have many inputs and
01133   // this block is a switch, we want to start by threading the batch that goes
01134   // to the most popular destination first.  If we only know about one
01135   // threadable destination (the common case) we can avoid this.
01136   BasicBlock *MostPopularDest = OnlyDest;
01137 
01138   if (MostPopularDest == MultipleDestSentinel)
01139     MostPopularDest = FindMostPopularDest(BB, PredToDestList);
01140 
01141   // Now that we know what the most popular destination is, factor all
01142   // predecessors that will jump to it into a single predecessor.
01143   SmallVector<BasicBlock*, 16> PredsToFactor;
01144   for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
01145     if (PredToDestList[i].second == MostPopularDest) {
01146       BasicBlock *Pred = PredToDestList[i].first;
01147 
01148       // This predecessor may be a switch or something else that has multiple
01149       // edges to the block.  Factor each of these edges by listing them
01150       // according to # occurrences in PredsToFactor.
01151       TerminatorInst *PredTI = Pred->getTerminator();
01152       for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
01153         if (PredTI->getSuccessor(i) == BB)
01154           PredsToFactor.push_back(Pred);
01155     }
01156 
01157   // If the threadable edges are branching on an undefined value, we get to pick
01158   // the destination that these predecessors should get to.
01159   if (MostPopularDest == 0)
01160     MostPopularDest = BB->getTerminator()->
01161                             getSuccessor(GetBestDestForJumpOnUndef(BB));
01162 
01163   // Ok, try to thread it!
01164   return ThreadEdge(BB, PredsToFactor, MostPopularDest);
01165 }
01166 
01167 /// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
01168 /// a PHI node in the current block.  See if there are any simplifications we
01169 /// can do based on inputs to the phi node.
01170 ///
01171 bool JumpThreading::ProcessBranchOnPHI(PHINode *PN) {
01172   BasicBlock *BB = PN->getParent();
01173 
01174   // TODO: We could make use of this to do it once for blocks with common PHI
01175   // values.
01176   SmallVector<BasicBlock*, 1> PredBBs;
01177   PredBBs.resize(1);
01178 
01179   // If any of the predecessor blocks end in an unconditional branch, we can
01180   // *duplicate* the conditional branch into that block in order to further
01181   // encourage jump threading and to eliminate cases where we have branch on a
01182   // phi of an icmp (branch on icmp is much better).
01183   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01184     BasicBlock *PredBB = PN->getIncomingBlock(i);
01185     if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
01186       if (PredBr->isUnconditional()) {
01187         PredBBs[0] = PredBB;
01188         // Try to duplicate BB into PredBB.
01189         if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
01190           return true;
01191       }
01192   }
01193 
01194   return false;
01195 }
01196 
01197 /// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
01198 /// a xor instruction in the current block.  See if there are any
01199 /// simplifications we can do based on inputs to the xor.
01200 ///
01201 bool JumpThreading::ProcessBranchOnXOR(BinaryOperator *BO) {
01202   BasicBlock *BB = BO->getParent();
01203 
01204   // If either the LHS or RHS of the xor is a constant, don't do this
01205   // optimization.
01206   if (isa<ConstantInt>(BO->getOperand(0)) ||
01207       isa<ConstantInt>(BO->getOperand(1)))
01208     return false;
01209 
01210   // If the first instruction in BB isn't a phi, we won't be able to infer
01211   // anything special about any particular predecessor.
01212   if (!isa<PHINode>(BB->front()))
01213     return false;
01214 
01215   // If we have a xor as the branch input to this block, and we know that the
01216   // LHS or RHS of the xor in any predecessor is true/false, then we can clone
01217   // the condition into the predecessor and fix that value to true, saving some
01218   // logical ops on that path and encouraging other paths to simplify.
01219   //
01220   // This copies something like this:
01221   //
01222   //  BB:
01223   //    %X = phi i1 [1],  [%X']
01224   //    %Y = icmp eq i32 %A, %B
01225   //    %Z = xor i1 %X, %Y
01226   //    br i1 %Z, ...
01227   //
01228   // Into:
01229   //  BB':
01230   //    %Y = icmp ne i32 %A, %B
01231   //    br i1 %Z, ...
01232 
01233   PredValueInfoTy XorOpValues;
01234   bool isLHS = true;
01235   if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
01236                                        WantInteger)) {
01237     assert(XorOpValues.empty());
01238     if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
01239                                          WantInteger))
01240       return false;
01241     isLHS = false;
01242   }
01243 
01244   assert(!XorOpValues.empty() &&
01245          "ComputeValueKnownInPredecessors returned true with no values");
01246 
01247   // Scan the information to see which is most popular: true or false.  The
01248   // predecessors can be of the set true, false, or undef.
01249   unsigned NumTrue = 0, NumFalse = 0;
01250   for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
01251     if (isa<UndefValue>(XorOpValues[i].first))
01252       // Ignore undefs for the count.
01253       continue;
01254     if (cast<ConstantInt>(XorOpValues[i].first)->isZero())
01255       ++NumFalse;
01256     else
01257       ++NumTrue;
01258   }
01259 
01260   // Determine which value to split on, true, false, or undef if neither.
01261   ConstantInt *SplitVal = 0;
01262   if (NumTrue > NumFalse)
01263     SplitVal = ConstantInt::getTrue(BB->getContext());
01264   else if (NumTrue != 0 || NumFalse != 0)
01265     SplitVal = ConstantInt::getFalse(BB->getContext());
01266 
01267   // Collect all of the blocks that this can be folded into so that we can
01268   // factor this once and clone it once.
01269   SmallVector<BasicBlock*, 8> BlocksToFoldInto;
01270   for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
01271     if (XorOpValues[i].first != SplitVal &&
01272         !isa<UndefValue>(XorOpValues[i].first))
01273       continue;
01274 
01275     BlocksToFoldInto.push_back(XorOpValues[i].second);
01276   }
01277 
01278   // If we inferred a value for all of the predecessors, then duplication won't
01279   // help us.  However, we can just replace the LHS or RHS with the constant.
01280   if (BlocksToFoldInto.size() ==
01281       cast<PHINode>(BB->front()).getNumIncomingValues()) {
01282     if (SplitVal == 0) {
01283       // If all preds provide undef, just nuke the xor, because it is undef too.
01284       BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
01285       BO->eraseFromParent();
01286     } else if (SplitVal->isZero()) {
01287       // If all preds provide 0, replace the xor with the other input.
01288       BO->replaceAllUsesWith(BO->getOperand(isLHS));
01289       BO->eraseFromParent();
01290     } else {
01291       // If all preds provide 1, set the computed value to 1.
01292       BO->setOperand(!isLHS, SplitVal);
01293     }
01294 
01295     return true;
01296   }
01297 
01298   // Try to duplicate BB into PredBB.
01299   return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
01300 }
01301 
01302 
01303 /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
01304 /// predecessor to the PHIBB block.  If it has PHI nodes, add entries for
01305 /// NewPred using the entries from OldPred (suitably mapped).
01306 static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
01307                                             BasicBlock *OldPred,
01308                                             BasicBlock *NewPred,
01309                                      DenseMap<Instruction*, Value*> &ValueMap) {
01310   for (BasicBlock::iterator PNI = PHIBB->begin();
01311        PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
01312     // Ok, we have a PHI node.  Figure out what the incoming value was for the
01313     // DestBlock.
01314     Value *IV = PN->getIncomingValueForBlock(OldPred);
01315 
01316     // Remap the value if necessary.
01317     if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
01318       DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
01319       if (I != ValueMap.end())
01320         IV = I->second;
01321     }
01322 
01323     PN->addIncoming(IV, NewPred);
01324   }
01325 }
01326 
01327 /// ThreadEdge - We have decided that it is safe and profitable to factor the
01328 /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
01329 /// across BB.  Transform the IR to reflect this change.
01330 bool JumpThreading::ThreadEdge(BasicBlock *BB,
01331                                const SmallVectorImpl<BasicBlock*> &PredBBs,
01332                                BasicBlock *SuccBB) {
01333   // If threading to the same block as we come from, we would infinite loop.
01334   if (SuccBB == BB) {
01335     DEBUG(dbgs() << "  Not threading across BB '" << BB->getName()
01336           << "' - would thread to self!\n");
01337     return false;
01338   }
01339 
01340   // If threading this would thread across a loop header, don't thread the edge.
01341   // See the comments above FindLoopHeaders for justifications and caveats.
01342   if (LoopHeaders.count(BB)) {
01343     DEBUG(dbgs() << "  Not threading across loop header BB '" << BB->getName()
01344           << "' to dest BB '" << SuccBB->getName()
01345           << "' - it might create an irreducible loop!\n");
01346     return false;
01347   }
01348 
01349   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB, Threshold);
01350   if (JumpThreadCost > Threshold) {
01351     DEBUG(dbgs() << "  Not threading BB '" << BB->getName()
01352           << "' - Cost is too high: " << JumpThreadCost << "\n");
01353     return false;
01354   }
01355 
01356   // And finally, do it!  Start by factoring the predecessors is needed.
01357   BasicBlock *PredBB;
01358   if (PredBBs.size() == 1)
01359     PredBB = PredBBs[0];
01360   else {
01361     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
01362           << " common predecessors.\n");
01363     PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm", this);
01364   }
01365 
01366   // And finally, do it!
01367   DEBUG(dbgs() << "  Threading edge from '" << PredBB->getName() << "' to '"
01368         << SuccBB->getName() << "' with cost: " << JumpThreadCost
01369         << ", across block:\n    "
01370         << *BB << "\n");
01371 
01372   LVI->threadEdge(PredBB, BB, SuccBB);
01373 
01374   // We are going to have to map operands from the original BB block to the new
01375   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
01376   // account for entry from PredBB.
01377   DenseMap<Instruction*, Value*> ValueMapping;
01378 
01379   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
01380                                          BB->getName()+".thread",
01381                                          BB->getParent(), BB);
01382   NewBB->moveAfter(PredBB);
01383 
01384   BasicBlock::iterator BI = BB->begin();
01385   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
01386     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
01387 
01388   // Clone the non-phi instructions of BB into NewBB, keeping track of the
01389   // mapping and using it to remap operands in the cloned instructions.
01390   for (; !isa<TerminatorInst>(BI); ++BI) {
01391     Instruction *New = BI->clone();
01392     New->setName(BI->getName());
01393     NewBB->getInstList().push_back(New);
01394     ValueMapping[BI] = New;
01395 
01396     // Remap operands to patch up intra-block references.
01397     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
01398       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
01399         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
01400         if (I != ValueMapping.end())
01401           New->setOperand(i, I->second);
01402       }
01403   }
01404 
01405   // We didn't copy the terminator from BB over to NewBB, because there is now
01406   // an unconditional jump to SuccBB.  Insert the unconditional jump.
01407   BranchInst *NewBI =BranchInst::Create(SuccBB, NewBB);
01408   NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
01409 
01410   // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
01411   // PHI nodes for NewBB now.
01412   AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
01413 
01414   // If there were values defined in BB that are used outside the block, then we
01415   // now have to update all uses of the value to use either the original value,
01416   // the cloned value, or some PHI derived value.  This can require arbitrary
01417   // PHI insertion, of which we are prepared to do, clean these up now.
01418   SSAUpdater SSAUpdate;
01419   SmallVector<Use*, 16> UsesToRename;
01420   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
01421     // Scan all uses of this instruction to see if it is used outside of its
01422     // block, and if so, record them in UsesToRename.
01423     for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
01424          ++UI) {
01425       Instruction *User = cast<Instruction>(*UI);
01426       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
01427         if (UserPN->getIncomingBlock(UI) == BB)
01428           continue;
01429       } else if (User->getParent() == BB)
01430         continue;
01431 
01432       UsesToRename.push_back(&UI.getUse());
01433     }
01434 
01435     // If there are no uses outside the block, we're done with this instruction.
01436     if (UsesToRename.empty())
01437       continue;
01438 
01439     DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
01440 
01441     // We found a use of I outside of BB.  Rename all uses of I that are outside
01442     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
01443     // with the two values we know.
01444     SSAUpdate.Initialize(I->getType(), I->getName());
01445     SSAUpdate.AddAvailableValue(BB, I);
01446     SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
01447 
01448     while (!UsesToRename.empty())
01449       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
01450     DEBUG(dbgs() << "\n");
01451   }
01452 
01453 
01454   // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
01455   // NewBB instead of BB.  This eliminates predecessors from BB, which requires
01456   // us to simplify any PHI nodes in BB.
01457   TerminatorInst *PredTerm = PredBB->getTerminator();
01458   for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
01459     if (PredTerm->getSuccessor(i) == BB) {
01460       BB->removePredecessor(PredBB, true);
01461       PredTerm->setSuccessor(i, NewBB);
01462     }
01463 
01464   // At this point, the IR is fully up to date and consistent.  Do a quick scan
01465   // over the new instructions and zap any that are constants or dead.  This
01466   // frequently happens because of phi translation.
01467   SimplifyInstructionsInBlock(NewBB, TD, TLI);
01468 
01469   // Threaded an edge!
01470   ++NumThreads;
01471   return true;
01472 }
01473 
01474 /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
01475 /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
01476 /// If we can duplicate the contents of BB up into PredBB do so now, this
01477 /// improves the odds that the branch will be on an analyzable instruction like
01478 /// a compare.
01479 bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
01480                                  const SmallVectorImpl<BasicBlock *> &PredBBs) {
01481   assert(!PredBBs.empty() && "Can't handle an empty set");
01482 
01483   // If BB is a loop header, then duplicating this block outside the loop would
01484   // cause us to transform this into an irreducible loop, don't do this.
01485   // See the comments above FindLoopHeaders for justifications and caveats.
01486   if (LoopHeaders.count(BB)) {
01487     DEBUG(dbgs() << "  Not duplicating loop header '" << BB->getName()
01488           << "' into predecessor block '" << PredBBs[0]->getName()
01489           << "' - it might create an irreducible loop!\n");
01490     return false;
01491   }
01492 
01493   unsigned DuplicationCost = getJumpThreadDuplicationCost(BB, Threshold);
01494   if (DuplicationCost > Threshold) {
01495     DEBUG(dbgs() << "  Not duplicating BB '" << BB->getName()
01496           << "' - Cost is too high: " << DuplicationCost << "\n");
01497     return false;
01498   }
01499 
01500   // And finally, do it!  Start by factoring the predecessors is needed.
01501   BasicBlock *PredBB;
01502   if (PredBBs.size() == 1)
01503     PredBB = PredBBs[0];
01504   else {
01505     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
01506           << " common predecessors.\n");
01507     PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm", this);
01508   }
01509 
01510   // Okay, we decided to do this!  Clone all the instructions in BB onto the end
01511   // of PredBB.
01512   DEBUG(dbgs() << "  Duplicating block '" << BB->getName() << "' into end of '"
01513         << PredBB->getName() << "' to eliminate branch on phi.  Cost: "
01514         << DuplicationCost << " block is:" << *BB << "\n");
01515 
01516   // Unless PredBB ends with an unconditional branch, split the edge so that we
01517   // can just clone the bits from BB into the end of the new PredBB.
01518   BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
01519 
01520   if (OldPredBranch == 0 || !OldPredBranch->isUnconditional()) {
01521     PredBB = SplitEdge(PredBB, BB, this);
01522     OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
01523   }
01524 
01525   // We are going to have to map operands from the original BB block into the
01526   // PredBB block.  Evaluate PHI nodes in BB.
01527   DenseMap<Instruction*, Value*> ValueMapping;
01528 
01529   BasicBlock::iterator BI = BB->begin();
01530   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
01531     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
01532 
01533   // Clone the non-phi instructions of BB into PredBB, keeping track of the
01534   // mapping and using it to remap operands in the cloned instructions.
01535   for (; BI != BB->end(); ++BI) {
01536     Instruction *New = BI->clone();
01537 
01538     // Remap operands to patch up intra-block references.
01539     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
01540       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
01541         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
01542         if (I != ValueMapping.end())
01543           New->setOperand(i, I->second);
01544       }
01545 
01546     // If this instruction can be simplified after the operands are updated,
01547     // just use the simplified value instead.  This frequently happens due to
01548     // phi translation.
01549     if (Value *IV = SimplifyInstruction(New, TD)) {
01550       delete New;
01551       ValueMapping[BI] = IV;
01552     } else {
01553       // Otherwise, insert the new instruction into the block.
01554       New->setName(BI->getName());
01555       PredBB->getInstList().insert(OldPredBranch, New);
01556       ValueMapping[BI] = New;
01557     }
01558   }
01559 
01560   // Check to see if the targets of the branch had PHI nodes. If so, we need to
01561   // add entries to the PHI nodes for branch from PredBB now.
01562   BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
01563   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
01564                                   ValueMapping);
01565   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
01566                                   ValueMapping);
01567 
01568   // If there were values defined in BB that are used outside the block, then we
01569   // now have to update all uses of the value to use either the original value,
01570   // the cloned value, or some PHI derived value.  This can require arbitrary
01571   // PHI insertion, of which we are prepared to do, clean these up now.
01572   SSAUpdater SSAUpdate;
01573   SmallVector<Use*, 16> UsesToRename;
01574   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
01575     // Scan all uses of this instruction to see if it is used outside of its
01576     // block, and if so, record them in UsesToRename.
01577     for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
01578          ++UI) {
01579       Instruction *User = cast<Instruction>(*UI);
01580       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
01581         if (UserPN->getIncomingBlock(UI) == BB)
01582           continue;
01583       } else if (User->getParent() == BB)
01584         continue;
01585 
01586       UsesToRename.push_back(&UI.getUse());
01587     }
01588 
01589     // If there are no uses outside the block, we're done with this instruction.
01590     if (UsesToRename.empty())
01591       continue;
01592 
01593     DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
01594 
01595     // We found a use of I outside of BB.  Rename all uses of I that are outside
01596     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
01597     // with the two values we know.
01598     SSAUpdate.Initialize(I->getType(), I->getName());
01599     SSAUpdate.AddAvailableValue(BB, I);
01600     SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
01601 
01602     while (!UsesToRename.empty())
01603       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
01604     DEBUG(dbgs() << "\n");
01605   }
01606 
01607   // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
01608   // that we nuked.
01609   BB->removePredecessor(PredBB, true);
01610 
01611   // Remove the unconditional branch at the end of the PredBB block.
01612   OldPredBranch->eraseFromParent();
01613 
01614   ++NumDupes;
01615   return true;
01616 }
01617 
01618