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