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