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           if (CondCmp->use_empty())
00795             CondCmp->eraseFromParent();
00796           else if (CondCmp->getParent() == BB) {
00797             // If the fact we just learned is true for all uses of the
00798             // condition, replace it with a constant value
00799             auto *CI = Baseline == LazyValueInfo::True ?
00800               ConstantInt::getTrue(CondCmp->getType()) :
00801               ConstantInt::getFalse(CondCmp->getType());
00802             CondCmp->replaceAllUsesWith(CI);
00803             CondCmp->eraseFromParent();
00804           }
00805           return true;
00806         }
00807       }
00808 
00809     } else if (CondBr && CondConst && CondBr->isConditional()) {
00810       // There might be an invariant in the same block with the conditional
00811       // that can determine the predicate.
00812 
00813       LazyValueInfo::Tristate Ret =
00814         LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
00815                             CondConst, CondCmp);
00816       if (Ret != LazyValueInfo::Unknown) {
00817         unsigned ToRemove = Ret == LazyValueInfo::True ? 1 : 0;
00818         unsigned ToKeep = Ret == LazyValueInfo::True ? 0 : 1;
00819         CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true);
00820         BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
00821         CondBr->eraseFromParent();
00822         return true;
00823       }
00824     }
00825 
00826     if (CondBr && CondConst && TryToUnfoldSelect(CondCmp, BB))
00827       return true;
00828   }
00829 
00830   // Check for some cases that are worth simplifying.  Right now we want to look
00831   // for loads that are used by a switch or by the condition for the branch.  If
00832   // we see one, check to see if it's partially redundant.  If so, insert a PHI
00833   // which can then be used to thread the values.
00834   //
00835   Value *SimplifyValue = CondInst;
00836   if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
00837     if (isa<Constant>(CondCmp->getOperand(1)))
00838       SimplifyValue = CondCmp->getOperand(0);
00839 
00840   // TODO: There are other places where load PRE would be profitable, such as
00841   // more complex comparisons.
00842   if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
00843     if (SimplifyPartiallyRedundantLoad(LI))
00844       return true;
00845 
00846 
00847   // Handle a variety of cases where we are branching on something derived from
00848   // a PHI node in the current block.  If we can prove that any predecessors
00849   // compute a predictable value based on a PHI node, thread those predecessors.
00850   //
00851   if (ProcessThreadableEdges(CondInst, BB, Preference, Terminator))
00852     return true;
00853 
00854   // If this is an otherwise-unfoldable branch on a phi node in the current
00855   // block, see if we can simplify.
00856   if (PHINode *PN = dyn_cast<PHINode>(CondInst))
00857     if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
00858       return ProcessBranchOnPHI(PN);
00859 
00860 
00861   // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
00862   if (CondInst->getOpcode() == Instruction::Xor &&
00863       CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
00864     return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
00865 
00866 
00867   // TODO: If we have: "br (X > 0)"  and we have a predecessor where we know
00868   // "(X == 4)", thread through this block.
00869 
00870   return false;
00871 }
00872 
00873 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
00874 /// load instruction, eliminate it by replacing it with a PHI node.  This is an
00875 /// important optimization that encourages jump threading, and needs to be run
00876 /// interlaced with other jump threading tasks.
00877 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
00878   // Don't hack volatile/atomic loads.
00879   if (!LI->isSimple()) return false;
00880 
00881   // If the load is defined in a block with exactly one predecessor, it can't be
00882   // partially redundant.
00883   BasicBlock *LoadBB = LI->getParent();
00884   if (LoadBB->getSinglePredecessor())
00885     return false;
00886 
00887   // If the load is defined in a landing pad, it can't be partially redundant,
00888   // because the edges between the invoke and the landing pad cannot have other
00889   // instructions between them.
00890   if (LoadBB->isLandingPad())
00891     return false;
00892 
00893   Value *LoadedPtr = LI->getOperand(0);
00894 
00895   // If the loaded operand is defined in the LoadBB, it can't be available.
00896   // TODO: Could do simple PHI translation, that would be fun :)
00897   if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
00898     if (PtrOp->getParent() == LoadBB)
00899       return false;
00900 
00901   // Scan a few instructions up from the load, to see if it is obviously live at
00902   // the entry to its block.
00903   BasicBlock::iterator BBIt = LI;
00904 
00905   if (Value *AvailableVal =
00906         FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
00907     // If the value if the load is locally available within the block, just use
00908     // it.  This frequently occurs for reg2mem'd allocas.
00909     //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
00910 
00911     // If the returned value is the load itself, replace with an undef. This can
00912     // only happen in dead loops.
00913     if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
00914     if (AvailableVal->getType() != LI->getType())
00915       AvailableVal =
00916           CastInst::CreateBitOrPointerCast(AvailableVal, LI->getType(), "", LI);
00917     LI->replaceAllUsesWith(AvailableVal);
00918     LI->eraseFromParent();
00919     return true;
00920   }
00921 
00922   // Otherwise, if we scanned the whole block and got to the top of the block,
00923   // we know the block is locally transparent to the load.  If not, something
00924   // might clobber its value.
00925   if (BBIt != LoadBB->begin())
00926     return false;
00927 
00928   // If all of the loads and stores that feed the value have the same AA tags,
00929   // then we can propagate them onto any newly inserted loads.
00930   AAMDNodes AATags;
00931   LI->getAAMetadata(AATags);
00932 
00933   SmallPtrSet<BasicBlock*, 8> PredsScanned;
00934   typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
00935   AvailablePredsTy AvailablePreds;
00936   BasicBlock *OneUnavailablePred = nullptr;
00937 
00938   // If we got here, the loaded value is transparent through to the start of the
00939   // block.  Check to see if it is available in any of the predecessor blocks.
00940   for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
00941        PI != PE; ++PI) {
00942     BasicBlock *PredBB = *PI;
00943 
00944     // If we already scanned this predecessor, skip it.
00945     if (!PredsScanned.insert(PredBB).second)
00946       continue;
00947 
00948     // Scan the predecessor to see if the value is available in the pred.
00949     BBIt = PredBB->end();
00950     AAMDNodes ThisAATags;
00951     Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6,
00952                                                     nullptr, &ThisAATags);
00953     if (!PredAvailable) {
00954       OneUnavailablePred = PredBB;
00955       continue;
00956     }
00957 
00958     // If AA tags disagree or are not present, forget about them.
00959     if (AATags != ThisAATags) AATags = AAMDNodes();
00960 
00961     // If so, this load is partially redundant.  Remember this info so that we
00962     // can create a PHI node.
00963     AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
00964   }
00965 
00966   // If the loaded value isn't available in any predecessor, it isn't partially
00967   // redundant.
00968   if (AvailablePreds.empty()) return false;
00969 
00970   // Okay, the loaded value is available in at least one (and maybe all!)
00971   // predecessors.  If the value is unavailable in more than one unique
00972   // predecessor, we want to insert a merge block for those common predecessors.
00973   // This ensures that we only have to insert one reload, thus not increasing
00974   // code size.
00975   BasicBlock *UnavailablePred = nullptr;
00976 
00977   // If there is exactly one predecessor where the value is unavailable, the
00978   // already computed 'OneUnavailablePred' block is it.  If it ends in an
00979   // unconditional branch, we know that it isn't a critical edge.
00980   if (PredsScanned.size() == AvailablePreds.size()+1 &&
00981       OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
00982     UnavailablePred = OneUnavailablePred;
00983   } else if (PredsScanned.size() != AvailablePreds.size()) {
00984     // Otherwise, we had multiple unavailable predecessors or we had a critical
00985     // edge from the one.
00986     SmallVector<BasicBlock*, 8> PredsToSplit;
00987     SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
00988 
00989     for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
00990       AvailablePredSet.insert(AvailablePreds[i].first);
00991 
00992     // Add all the unavailable predecessors to the PredsToSplit list.
00993     for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
00994          PI != PE; ++PI) {
00995       BasicBlock *P = *PI;
00996       // If the predecessor is an indirect goto, we can't split the edge.
00997       if (isa<IndirectBrInst>(P->getTerminator()))
00998         return false;
00999 
01000       if (!AvailablePredSet.count(P))
01001         PredsToSplit.push_back(P);
01002     }
01003 
01004     // Split them out to their own block.
01005     UnavailablePred =
01006       SplitBlockPredecessors(LoadBB, PredsToSplit, "thread-pre-split");
01007   }
01008 
01009   // If the value isn't available in all predecessors, then there will be
01010   // exactly one where it isn't available.  Insert a load on that edge and add
01011   // it to the AvailablePreds list.
01012   if (UnavailablePred) {
01013     assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
01014            "Can't handle critical edge here!");
01015     LoadInst *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", false,
01016                                  LI->getAlignment(),
01017                                  UnavailablePred->getTerminator());
01018     NewVal->setDebugLoc(LI->getDebugLoc());
01019     if (AATags)
01020       NewVal->setAAMetadata(AATags);
01021 
01022     AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
01023   }
01024 
01025   // Now we know that each predecessor of this block has a value in
01026   // AvailablePreds, sort them for efficient access as we're walking the preds.
01027   array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
01028 
01029   // Create a PHI node at the start of the block for the PRE'd load value.
01030   pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
01031   PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "",
01032                                 LoadBB->begin());
01033   PN->takeName(LI);
01034   PN->setDebugLoc(LI->getDebugLoc());
01035 
01036   // Insert new entries into the PHI for each predecessor.  A single block may
01037   // have multiple entries here.
01038   for (pred_iterator PI = PB; PI != PE; ++PI) {
01039     BasicBlock *P = *PI;
01040     AvailablePredsTy::iterator I =
01041       std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
01042                        std::make_pair(P, (Value*)nullptr));
01043 
01044     assert(I != AvailablePreds.end() && I->first == P &&
01045            "Didn't find entry for predecessor!");
01046 
01047     // If we have an available predecessor but it requires casting, insert the
01048     // cast in the predecessor and use the cast. Note that we have to update the
01049     // AvailablePreds vector as we go so that all of the PHI entries for this
01050     // predecessor use the same bitcast.
01051     Value *&PredV = I->second;
01052     if (PredV->getType() != LI->getType())
01053       PredV = CastInst::CreateBitOrPointerCast(PredV, LI->getType(), "",
01054                                                P->getTerminator());
01055 
01056     PN->addIncoming(PredV, I->first);
01057   }
01058 
01059   //cerr << "PRE: " << *LI << *PN << "\n";
01060 
01061   LI->replaceAllUsesWith(PN);
01062   LI->eraseFromParent();
01063 
01064   return true;
01065 }
01066 
01067 /// FindMostPopularDest - The specified list contains multiple possible
01068 /// threadable destinations.  Pick the one that occurs the most frequently in
01069 /// the list.
01070 static BasicBlock *
01071 FindMostPopularDest(BasicBlock *BB,
01072                     const SmallVectorImpl<std::pair<BasicBlock*,
01073                                   BasicBlock*> > &PredToDestList) {
01074   assert(!PredToDestList.empty());
01075 
01076   // Determine popularity.  If there are multiple possible destinations, we
01077   // explicitly choose to ignore 'undef' destinations.  We prefer to thread
01078   // blocks with known and real destinations to threading undef.  We'll handle
01079   // them later if interesting.
01080   DenseMap<BasicBlock*, unsigned> DestPopularity;
01081   for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
01082     if (PredToDestList[i].second)
01083       DestPopularity[PredToDestList[i].second]++;
01084 
01085   // Find the most popular dest.
01086   DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
01087   BasicBlock *MostPopularDest = DPI->first;
01088   unsigned Popularity = DPI->second;
01089   SmallVector<BasicBlock*, 4> SamePopularity;
01090 
01091   for (++DPI; DPI != DestPopularity.end(); ++DPI) {
01092     // If the popularity of this entry isn't higher than the popularity we've
01093     // seen so far, ignore it.
01094     if (DPI->second < Popularity)
01095       ; // ignore.
01096     else if (DPI->second == Popularity) {
01097       // If it is the same as what we've seen so far, keep track of it.
01098       SamePopularity.push_back(DPI->first);
01099     } else {
01100       // If it is more popular, remember it.
01101       SamePopularity.clear();
01102       MostPopularDest = DPI->first;
01103       Popularity = DPI->second;
01104     }
01105   }
01106 
01107   // Okay, now we know the most popular destination.  If there is more than one
01108   // destination, we need to determine one.  This is arbitrary, but we need
01109   // to make a deterministic decision.  Pick the first one that appears in the
01110   // successor list.
01111   if (!SamePopularity.empty()) {
01112     SamePopularity.push_back(MostPopularDest);
01113     TerminatorInst *TI = BB->getTerminator();
01114     for (unsigned i = 0; ; ++i) {
01115       assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
01116 
01117       if (std::find(SamePopularity.begin(), SamePopularity.end(),
01118                     TI->getSuccessor(i)) == SamePopularity.end())
01119         continue;
01120 
01121       MostPopularDest = TI->getSuccessor(i);
01122       break;
01123     }
01124   }
01125 
01126   // Okay, we have finally picked the most popular destination.
01127   return MostPopularDest;
01128 }
01129 
01130 bool JumpThreading::ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
01131                                            ConstantPreference Preference,
01132                                            Instruction *CxtI) {
01133   // If threading this would thread across a loop header, don't even try to
01134   // thread the edge.
01135   if (LoopHeaders.count(BB))
01136     return false;
01137 
01138   PredValueInfoTy PredValues;
01139   if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference, CxtI))
01140     return false;
01141 
01142   assert(!PredValues.empty() &&
01143          "ComputeValueKnownInPredecessors returned true with no values");
01144 
01145   DEBUG(dbgs() << "IN BB: " << *BB;
01146         for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
01147           dbgs() << "  BB '" << BB->getName() << "': FOUND condition = "
01148             << *PredValues[i].first
01149             << " for pred '" << PredValues[i].second->getName() << "'.\n";
01150         });
01151 
01152   // Decide what we want to thread through.  Convert our list of known values to
01153   // a list of known destinations for each pred.  This also discards duplicate
01154   // predecessors and keeps track of the undefined inputs (which are represented
01155   // as a null dest in the PredToDestList).
01156   SmallPtrSet<BasicBlock*, 16> SeenPreds;
01157   SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
01158 
01159   BasicBlock *OnlyDest = nullptr;
01160   BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
01161 
01162   for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
01163     BasicBlock *Pred = PredValues[i].second;
01164     if (!SeenPreds.insert(Pred).second)
01165       continue;  // Duplicate predecessor entry.
01166 
01167     // If the predecessor ends with an indirect goto, we can't change its
01168     // destination.
01169     if (isa<IndirectBrInst>(Pred->getTerminator()))
01170       continue;
01171 
01172     Constant *Val = PredValues[i].first;
01173 
01174     BasicBlock *DestBB;
01175     if (isa<UndefValue>(Val))
01176       DestBB = nullptr;
01177     else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
01178       DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
01179     else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
01180       DestBB = SI->findCaseValue(cast<ConstantInt>(Val)).getCaseSuccessor();
01181     } else {
01182       assert(isa<IndirectBrInst>(BB->getTerminator())
01183               && "Unexpected terminator");
01184       DestBB = cast<BlockAddress>(Val)->getBasicBlock();
01185     }
01186 
01187     // If we have exactly one destination, remember it for efficiency below.
01188     if (PredToDestList.empty())
01189       OnlyDest = DestBB;
01190     else if (OnlyDest != DestBB)
01191       OnlyDest = MultipleDestSentinel;
01192 
01193     PredToDestList.push_back(std::make_pair(Pred, DestBB));
01194   }
01195 
01196   // If all edges were unthreadable, we fail.
01197   if (PredToDestList.empty())
01198     return false;
01199 
01200   // Determine which is the most common successor.  If we have many inputs and
01201   // this block is a switch, we want to start by threading the batch that goes
01202   // to the most popular destination first.  If we only know about one
01203   // threadable destination (the common case) we can avoid this.
01204   BasicBlock *MostPopularDest = OnlyDest;
01205 
01206   if (MostPopularDest == MultipleDestSentinel)
01207     MostPopularDest = FindMostPopularDest(BB, PredToDestList);
01208 
01209   // Now that we know what the most popular destination is, factor all
01210   // predecessors that will jump to it into a single predecessor.
01211   SmallVector<BasicBlock*, 16> PredsToFactor;
01212   for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
01213     if (PredToDestList[i].second == MostPopularDest) {
01214       BasicBlock *Pred = PredToDestList[i].first;
01215 
01216       // This predecessor may be a switch or something else that has multiple
01217       // edges to the block.  Factor each of these edges by listing them
01218       // according to # occurrences in PredsToFactor.
01219       TerminatorInst *PredTI = Pred->getTerminator();
01220       for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
01221         if (PredTI->getSuccessor(i) == BB)
01222           PredsToFactor.push_back(Pred);
01223     }
01224 
01225   // If the threadable edges are branching on an undefined value, we get to pick
01226   // the destination that these predecessors should get to.
01227   if (!MostPopularDest)
01228     MostPopularDest = BB->getTerminator()->
01229                             getSuccessor(GetBestDestForJumpOnUndef(BB));
01230 
01231   // Ok, try to thread it!
01232   return ThreadEdge(BB, PredsToFactor, MostPopularDest);
01233 }
01234 
01235 /// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
01236 /// a PHI node in the current block.  See if there are any simplifications we
01237 /// can do based on inputs to the phi node.
01238 ///
01239 bool JumpThreading::ProcessBranchOnPHI(PHINode *PN) {
01240   BasicBlock *BB = PN->getParent();
01241 
01242   // TODO: We could make use of this to do it once for blocks with common PHI
01243   // values.
01244   SmallVector<BasicBlock*, 1> PredBBs;
01245   PredBBs.resize(1);
01246 
01247   // If any of the predecessor blocks end in an unconditional branch, we can
01248   // *duplicate* the conditional branch into that block in order to further
01249   // encourage jump threading and to eliminate cases where we have branch on a
01250   // phi of an icmp (branch on icmp is much better).
01251   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01252     BasicBlock *PredBB = PN->getIncomingBlock(i);
01253     if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
01254       if (PredBr->isUnconditional()) {
01255         PredBBs[0] = PredBB;
01256         // Try to duplicate BB into PredBB.
01257         if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
01258           return true;
01259       }
01260   }
01261 
01262   return false;
01263 }
01264 
01265 /// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
01266 /// a xor instruction in the current block.  See if there are any
01267 /// simplifications we can do based on inputs to the xor.
01268 ///
01269 bool JumpThreading::ProcessBranchOnXOR(BinaryOperator *BO) {
01270   BasicBlock *BB = BO->getParent();
01271 
01272   // If either the LHS or RHS of the xor is a constant, don't do this
01273   // optimization.
01274   if (isa<ConstantInt>(BO->getOperand(0)) ||
01275       isa<ConstantInt>(BO->getOperand(1)))
01276     return false;
01277 
01278   // If the first instruction in BB isn't a phi, we won't be able to infer
01279   // anything special about any particular predecessor.
01280   if (!isa<PHINode>(BB->front()))
01281     return false;
01282 
01283   // If we have a xor as the branch input to this block, and we know that the
01284   // LHS or RHS of the xor in any predecessor is true/false, then we can clone
01285   // the condition into the predecessor and fix that value to true, saving some
01286   // logical ops on that path and encouraging other paths to simplify.
01287   //
01288   // This copies something like this:
01289   //
01290   //  BB:
01291   //    %X = phi i1 [1],  [%X']
01292   //    %Y = icmp eq i32 %A, %B
01293   //    %Z = xor i1 %X, %Y
01294   //    br i1 %Z, ...
01295   //
01296   // Into:
01297   //  BB':
01298   //    %Y = icmp ne i32 %A, %B
01299   //    br i1 %Z, ...
01300 
01301   PredValueInfoTy XorOpValues;
01302   bool isLHS = true;
01303   if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
01304                                        WantInteger, BO)) {
01305     assert(XorOpValues.empty());
01306     if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
01307                                          WantInteger, BO))
01308       return false;
01309     isLHS = false;
01310   }
01311 
01312   assert(!XorOpValues.empty() &&
01313          "ComputeValueKnownInPredecessors returned true with no values");
01314 
01315   // Scan the information to see which is most popular: true or false.  The
01316   // predecessors can be of the set true, false, or undef.
01317   unsigned NumTrue = 0, NumFalse = 0;
01318   for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
01319     if (isa<UndefValue>(XorOpValues[i].first))
01320       // Ignore undefs for the count.
01321       continue;
01322     if (cast<ConstantInt>(XorOpValues[i].first)->isZero())
01323       ++NumFalse;
01324     else
01325       ++NumTrue;
01326   }
01327 
01328   // Determine which value to split on, true, false, or undef if neither.
01329   ConstantInt *SplitVal = nullptr;
01330   if (NumTrue > NumFalse)
01331     SplitVal = ConstantInt::getTrue(BB->getContext());
01332   else if (NumTrue != 0 || NumFalse != 0)
01333     SplitVal = ConstantInt::getFalse(BB->getContext());
01334 
01335   // Collect all of the blocks that this can be folded into so that we can
01336   // factor this once and clone it once.
01337   SmallVector<BasicBlock*, 8> BlocksToFoldInto;
01338   for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
01339     if (XorOpValues[i].first != SplitVal &&
01340         !isa<UndefValue>(XorOpValues[i].first))
01341       continue;
01342 
01343     BlocksToFoldInto.push_back(XorOpValues[i].second);
01344   }
01345 
01346   // If we inferred a value for all of the predecessors, then duplication won't
01347   // help us.  However, we can just replace the LHS or RHS with the constant.
01348   if (BlocksToFoldInto.size() ==
01349       cast<PHINode>(BB->front()).getNumIncomingValues()) {
01350     if (!SplitVal) {
01351       // If all preds provide undef, just nuke the xor, because it is undef too.
01352       BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
01353       BO->eraseFromParent();
01354     } else if (SplitVal->isZero()) {
01355       // If all preds provide 0, replace the xor with the other input.
01356       BO->replaceAllUsesWith(BO->getOperand(isLHS));
01357       BO->eraseFromParent();
01358     } else {
01359       // If all preds provide 1, set the computed value to 1.
01360       BO->setOperand(!isLHS, SplitVal);
01361     }
01362 
01363     return true;
01364   }
01365 
01366   // Try to duplicate BB into PredBB.
01367   return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
01368 }
01369 
01370 
01371 /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
01372 /// predecessor to the PHIBB block.  If it has PHI nodes, add entries for
01373 /// NewPred using the entries from OldPred (suitably mapped).
01374 static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
01375                                             BasicBlock *OldPred,
01376                                             BasicBlock *NewPred,
01377                                      DenseMap<Instruction*, Value*> &ValueMap) {
01378   for (BasicBlock::iterator PNI = PHIBB->begin();
01379        PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
01380     // Ok, we have a PHI node.  Figure out what the incoming value was for the
01381     // DestBlock.
01382     Value *IV = PN->getIncomingValueForBlock(OldPred);
01383 
01384     // Remap the value if necessary.
01385     if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
01386       DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
01387       if (I != ValueMap.end())
01388         IV = I->second;
01389     }
01390 
01391     PN->addIncoming(IV, NewPred);
01392   }
01393 }
01394 
01395 /// ThreadEdge - We have decided that it is safe and profitable to factor the
01396 /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
01397 /// across BB.  Transform the IR to reflect this change.
01398 bool JumpThreading::ThreadEdge(BasicBlock *BB,
01399                                const SmallVectorImpl<BasicBlock*> &PredBBs,
01400                                BasicBlock *SuccBB) {
01401   // If threading to the same block as we come from, we would infinite loop.
01402   if (SuccBB == BB) {
01403     DEBUG(dbgs() << "  Not threading across BB '" << BB->getName()
01404           << "' - would thread to self!\n");
01405     return false;
01406   }
01407 
01408   // If threading this would thread across a loop header, don't thread the edge.
01409   // See the comments above FindLoopHeaders for justifications and caveats.
01410   if (LoopHeaders.count(BB)) {
01411     DEBUG(dbgs() << "  Not threading across loop header BB '" << BB->getName()
01412           << "' to dest BB '" << SuccBB->getName()
01413           << "' - it might create an irreducible loop!\n");
01414     return false;
01415   }
01416 
01417   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB, BBDupThreshold);
01418   if (JumpThreadCost > BBDupThreshold) {
01419     DEBUG(dbgs() << "  Not threading BB '" << BB->getName()
01420           << "' - Cost is too high: " << JumpThreadCost << "\n");
01421     return false;
01422   }
01423 
01424   // And finally, do it!  Start by factoring the predecessors is needed.
01425   BasicBlock *PredBB;
01426   if (PredBBs.size() == 1)
01427     PredBB = PredBBs[0];
01428   else {
01429     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
01430           << " common predecessors.\n");
01431     PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm");
01432   }
01433 
01434   // And finally, do it!
01435   DEBUG(dbgs() << "  Threading edge from '" << PredBB->getName() << "' to '"
01436         << SuccBB->getName() << "' with cost: " << JumpThreadCost
01437         << ", across block:\n    "
01438         << *BB << "\n");
01439 
01440   LVI->threadEdge(PredBB, BB, SuccBB);
01441 
01442   // We are going to have to map operands from the original BB block to the new
01443   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
01444   // account for entry from PredBB.
01445   DenseMap<Instruction*, Value*> ValueMapping;
01446 
01447   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
01448                                          BB->getName()+".thread",
01449                                          BB->getParent(), BB);
01450   NewBB->moveAfter(PredBB);
01451 
01452   BasicBlock::iterator BI = BB->begin();
01453   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
01454     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
01455 
01456   // Clone the non-phi instructions of BB into NewBB, keeping track of the
01457   // mapping and using it to remap operands in the cloned instructions.
01458   for (; !isa<TerminatorInst>(BI); ++BI) {
01459     Instruction *New = BI->clone();
01460     New->setName(BI->getName());
01461     NewBB->getInstList().push_back(New);
01462     ValueMapping[BI] = New;
01463 
01464     // Remap operands to patch up intra-block references.
01465     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
01466       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
01467         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
01468         if (I != ValueMapping.end())
01469           New->setOperand(i, I->second);
01470       }
01471   }
01472 
01473   // We didn't copy the terminator from BB over to NewBB, because there is now
01474   // an unconditional jump to SuccBB.  Insert the unconditional jump.
01475   BranchInst *NewBI =BranchInst::Create(SuccBB, NewBB);
01476   NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
01477 
01478   // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
01479   // PHI nodes for NewBB now.
01480   AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
01481 
01482   // If there were values defined in BB that are used outside the block, then we
01483   // now have to update all uses of the value to use either the original value,
01484   // the cloned value, or some PHI derived value.  This can require arbitrary
01485   // PHI insertion, of which we are prepared to do, clean these up now.
01486   SSAUpdater SSAUpdate;
01487   SmallVector<Use*, 16> UsesToRename;
01488   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
01489     // Scan all uses of this instruction to see if it is used outside of its
01490     // block, and if so, record them in UsesToRename.
01491     for (Use &U : I->uses()) {
01492       Instruction *User = cast<Instruction>(U.getUser());
01493       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
01494         if (UserPN->getIncomingBlock(U) == BB)
01495           continue;
01496       } else if (User->getParent() == BB)
01497         continue;
01498 
01499       UsesToRename.push_back(&U);
01500     }
01501 
01502     // If there are no uses outside the block, we're done with this instruction.
01503     if (UsesToRename.empty())
01504       continue;
01505 
01506     DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
01507 
01508     // We found a use of I outside of BB.  Rename all uses of I that are outside
01509     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
01510     // with the two values we know.
01511     SSAUpdate.Initialize(I->getType(), I->getName());
01512     SSAUpdate.AddAvailableValue(BB, I);
01513     SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
01514 
01515     while (!UsesToRename.empty())
01516       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
01517     DEBUG(dbgs() << "\n");
01518   }
01519 
01520 
01521   // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
01522   // NewBB instead of BB.  This eliminates predecessors from BB, which requires
01523   // us to simplify any PHI nodes in BB.
01524   TerminatorInst *PredTerm = PredBB->getTerminator();
01525   for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
01526     if (PredTerm->getSuccessor(i) == BB) {
01527       BB->removePredecessor(PredBB, true);
01528       PredTerm->setSuccessor(i, NewBB);
01529     }
01530 
01531   // At this point, the IR is fully up to date and consistent.  Do a quick scan
01532   // over the new instructions and zap any that are constants or dead.  This
01533   // frequently happens because of phi translation.
01534   SimplifyInstructionsInBlock(NewBB, TLI);
01535 
01536   // Threaded an edge!
01537   ++NumThreads;
01538   return true;
01539 }
01540 
01541 /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
01542 /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
01543 /// If we can duplicate the contents of BB up into PredBB do so now, this
01544 /// improves the odds that the branch will be on an analyzable instruction like
01545 /// a compare.
01546 bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
01547                                  const SmallVectorImpl<BasicBlock *> &PredBBs) {
01548   assert(!PredBBs.empty() && "Can't handle an empty set");
01549 
01550   // If BB is a loop header, then duplicating this block outside the loop would
01551   // cause us to transform this into an irreducible loop, don't do this.
01552   // See the comments above FindLoopHeaders for justifications and caveats.
01553   if (LoopHeaders.count(BB)) {
01554     DEBUG(dbgs() << "  Not duplicating loop header '" << BB->getName()
01555           << "' into predecessor block '" << PredBBs[0]->getName()
01556           << "' - it might create an irreducible loop!\n");
01557     return false;
01558   }
01559 
01560   unsigned DuplicationCost = getJumpThreadDuplicationCost(BB, BBDupThreshold);
01561   if (DuplicationCost > BBDupThreshold) {
01562     DEBUG(dbgs() << "  Not duplicating BB '" << BB->getName()
01563           << "' - Cost is too high: " << DuplicationCost << "\n");
01564     return false;
01565   }
01566 
01567   // And finally, do it!  Start by factoring the predecessors is needed.
01568   BasicBlock *PredBB;
01569   if (PredBBs.size() == 1)
01570     PredBB = PredBBs[0];
01571   else {
01572     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
01573           << " common predecessors.\n");
01574     PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm");
01575   }
01576 
01577   // Okay, we decided to do this!  Clone all the instructions in BB onto the end
01578   // of PredBB.
01579   DEBUG(dbgs() << "  Duplicating block '" << BB->getName() << "' into end of '"
01580         << PredBB->getName() << "' to eliminate branch on phi.  Cost: "
01581         << DuplicationCost << " block is:" << *BB << "\n");
01582 
01583   // Unless PredBB ends with an unconditional branch, split the edge so that we
01584   // can just clone the bits from BB into the end of the new PredBB.
01585   BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
01586 
01587   if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
01588     PredBB = SplitEdge(PredBB, BB);
01589     OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
01590   }
01591 
01592   // We are going to have to map operands from the original BB block into the
01593   // PredBB block.  Evaluate PHI nodes in BB.
01594   DenseMap<Instruction*, Value*> ValueMapping;
01595 
01596   BasicBlock::iterator BI = BB->begin();
01597   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
01598     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
01599   // Clone the non-phi instructions of BB into PredBB, keeping track of the
01600   // mapping and using it to remap operands in the cloned instructions.
01601   for (; BI != BB->end(); ++BI) {
01602     Instruction *New = BI->clone();
01603 
01604     // Remap operands to patch up intra-block references.
01605     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
01606       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
01607         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
01608         if (I != ValueMapping.end())
01609           New->setOperand(i, I->second);
01610       }
01611 
01612     // If this instruction can be simplified after the operands are updated,
01613     // just use the simplified value instead.  This frequently happens due to
01614     // phi translation.
01615     if (Value *IV =
01616             SimplifyInstruction(New, BB->getModule()->getDataLayout())) {
01617       delete New;
01618       ValueMapping[BI] = IV;
01619     } else {
01620       // Otherwise, insert the new instruction into the block.
01621       New->setName(BI->getName());
01622       PredBB->getInstList().insert(OldPredBranch, New);
01623       ValueMapping[BI] = New;
01624     }
01625   }
01626 
01627   // Check to see if the targets of the branch had PHI nodes. If so, we need to
01628   // add entries to the PHI nodes for branch from PredBB now.
01629   BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
01630   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
01631                                   ValueMapping);
01632   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
01633                                   ValueMapping);
01634 
01635   // If there were values defined in BB that are used outside the block, then we
01636   // now have to update all uses of the value to use either the original value,
01637   // the cloned value, or some PHI derived value.  This can require arbitrary
01638   // PHI insertion, of which we are prepared to do, clean these up now.
01639   SSAUpdater SSAUpdate;
01640   SmallVector<Use*, 16> UsesToRename;
01641   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
01642     // Scan all uses of this instruction to see if it is used outside of its
01643     // block, and if so, record them in UsesToRename.
01644     for (Use &U : I->uses()) {
01645       Instruction *User = cast<Instruction>(U.getUser());
01646       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
01647         if (UserPN->getIncomingBlock(U) == BB)
01648           continue;
01649       } else if (User->getParent() == BB)
01650         continue;
01651 
01652       UsesToRename.push_back(&U);
01653     }
01654 
01655     // If there are no uses outside the block, we're done with this instruction.
01656     if (UsesToRename.empty())
01657       continue;
01658 
01659     DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
01660 
01661     // We found a use of I outside of BB.  Rename all uses of I that are outside
01662     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
01663     // with the two values we know.
01664     SSAUpdate.Initialize(I->getType(), I->getName());
01665     SSAUpdate.AddAvailableValue(BB, I);
01666     SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
01667 
01668     while (!UsesToRename.empty())
01669       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
01670     DEBUG(dbgs() << "\n");
01671   }
01672 
01673   // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
01674   // that we nuked.
01675   BB->removePredecessor(PredBB, true);
01676 
01677   // Remove the unconditional branch at the end of the PredBB block.
01678   OldPredBranch->eraseFromParent();
01679 
01680   ++NumDupes;
01681   return true;
01682 }
01683 
01684 /// TryToUnfoldSelect - Look for blocks of the form
01685 /// bb1:
01686 ///   %a = select
01687 ///   br bb
01688 ///
01689 /// bb2:
01690 ///   %p = phi [%a, %bb] ...
01691 ///   %c = icmp %p
01692 ///   br i1 %c
01693 ///
01694 /// And expand the select into a branch structure if one of its arms allows %c
01695 /// to be folded. This later enables threading from bb1 over bb2.
01696 bool JumpThreading::TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
01697   BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
01698   PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
01699   Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
01700 
01701   if (!CondBr || !CondBr->isConditional() || !CondLHS ||
01702       CondLHS->getParent() != BB)
01703     return false;
01704 
01705   for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
01706     BasicBlock *Pred = CondLHS->getIncomingBlock(I);
01707     SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
01708 
01709     // Look if one of the incoming values is a select in the corresponding
01710     // predecessor.
01711     if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
01712       continue;
01713 
01714     BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
01715     if (!PredTerm || !PredTerm->isUnconditional())
01716       continue;
01717 
01718     // Now check if one of the select values would allow us to constant fold the
01719     // terminator in BB. We don't do the transform if both sides fold, those
01720     // cases will be threaded in any case.
01721     LazyValueInfo::Tristate LHSFolds =
01722         LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
01723                                 CondRHS, Pred, BB, CondCmp);
01724     LazyValueInfo::Tristate RHSFolds =
01725         LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
01726                                 CondRHS, Pred, BB, CondCmp);
01727     if ((LHSFolds != LazyValueInfo::Unknown ||
01728          RHSFolds != LazyValueInfo::Unknown) &&
01729         LHSFolds != RHSFolds) {
01730       // Expand the select.
01731       //
01732       // Pred --
01733       //  |    v
01734       //  |  NewBB
01735       //  |    |
01736       //  |-----
01737       //  v
01738       // BB
01739       BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
01740                                              BB->getParent(), BB);
01741       // Move the unconditional branch to NewBB.
01742       PredTerm->removeFromParent();
01743       NewBB->getInstList().insert(NewBB->end(), PredTerm);
01744       // Create a conditional branch and update PHI nodes.
01745       BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
01746       CondLHS->setIncomingValue(I, SI->getFalseValue());
01747       CondLHS->addIncoming(SI->getTrueValue(), NewBB);
01748       // The select is now dead.
01749       SI->eraseFromParent();
01750 
01751       // Update any other PHI nodes in BB.
01752       for (BasicBlock::iterator BI = BB->begin();
01753            PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
01754         if (Phi != CondLHS)
01755           Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
01756       return true;
01757     }
01758   }
01759   return false;
01760 }