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