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