LLVM API Documentation

LazyValueInfo.cpp
Go to the documentation of this file.
00001 //===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
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 defines the interface for lazy computation of value constraint
00011 // information.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Analysis/LazyValueInfo.h"
00016 #include "llvm/ADT/DenseSet.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/Analysis/AssumptionCache.h"
00019 #include "llvm/Analysis/ConstantFolding.h"
00020 #include "llvm/Analysis/TargetLibraryInfo.h"
00021 #include "llvm/Analysis/ValueTracking.h"
00022 #include "llvm/IR/CFG.h"
00023 #include "llvm/IR/ConstantRange.h"
00024 #include "llvm/IR/Constants.h"
00025 #include "llvm/IR/DataLayout.h"
00026 #include "llvm/IR/Dominators.h"
00027 #include "llvm/IR/Instructions.h"
00028 #include "llvm/IR/IntrinsicInst.h"
00029 #include "llvm/IR/PatternMatch.h"
00030 #include "llvm/IR/ValueHandle.h"
00031 #include "llvm/Support/Debug.h"
00032 #include "llvm/Support/raw_ostream.h"
00033 #include <map>
00034 #include <stack>
00035 using namespace llvm;
00036 using namespace PatternMatch;
00037 
00038 #define DEBUG_TYPE "lazy-value-info"
00039 
00040 char LazyValueInfo::ID = 0;
00041 INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
00042                 "Lazy Value Information Analysis", false, true)
00043 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00044 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
00045 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
00046                 "Lazy Value Information Analysis", false, true)
00047 
00048 namespace llvm {
00049   FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
00050 }
00051 
00052 
00053 //===----------------------------------------------------------------------===//
00054 //                               LVILatticeVal
00055 //===----------------------------------------------------------------------===//
00056 
00057 /// This is the information tracked by LazyValueInfo for each value.
00058 ///
00059 /// FIXME: This is basically just for bringup, this can be made a lot more rich
00060 /// in the future.
00061 ///
00062 namespace {
00063 class LVILatticeVal {
00064   enum LatticeValueTy {
00065     /// This Value has no known value yet.
00066     undefined,
00067     
00068     /// This Value has a specific constant value.
00069     constant,
00070     
00071     /// This Value is known to not have the specified value.
00072     notconstant,
00073 
00074     /// The Value falls within this range.
00075     constantrange,
00076 
00077     /// This value is not known to be constant, and we know that it has a value.
00078     overdefined
00079   };
00080   
00081   /// Val: This stores the current lattice value along with the Constant* for
00082   /// the constant if this is a 'constant' or 'notconstant' value.
00083   LatticeValueTy Tag;
00084   Constant *Val;
00085   ConstantRange Range;
00086   
00087 public:
00088   LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
00089 
00090   static LVILatticeVal get(Constant *C) {
00091     LVILatticeVal Res;
00092     if (!isa<UndefValue>(C))
00093       Res.markConstant(C);
00094     return Res;
00095   }
00096   static LVILatticeVal getNot(Constant *C) {
00097     LVILatticeVal Res;
00098     if (!isa<UndefValue>(C))
00099       Res.markNotConstant(C);
00100     return Res;
00101   }
00102   static LVILatticeVal getRange(ConstantRange CR) {
00103     LVILatticeVal Res;
00104     Res.markConstantRange(CR);
00105     return Res;
00106   }
00107   
00108   bool isUndefined() const     { return Tag == undefined; }
00109   bool isConstant() const      { return Tag == constant; }
00110   bool isNotConstant() const   { return Tag == notconstant; }
00111   bool isConstantRange() const { return Tag == constantrange; }
00112   bool isOverdefined() const   { return Tag == overdefined; }
00113   
00114   Constant *getConstant() const {
00115     assert(isConstant() && "Cannot get the constant of a non-constant!");
00116     return Val;
00117   }
00118   
00119   Constant *getNotConstant() const {
00120     assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
00121     return Val;
00122   }
00123   
00124   ConstantRange getConstantRange() const {
00125     assert(isConstantRange() &&
00126            "Cannot get the constant-range of a non-constant-range!");
00127     return Range;
00128   }
00129   
00130   /// Return true if this is a change in status.
00131   bool markOverdefined() {
00132     if (isOverdefined())
00133       return false;
00134     Tag = overdefined;
00135     return true;
00136   }
00137 
00138   /// Return true if this is a change in status.
00139   bool markConstant(Constant *V) {
00140     assert(V && "Marking constant with NULL");
00141     if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
00142       return markConstantRange(ConstantRange(CI->getValue()));
00143     if (isa<UndefValue>(V))
00144       return false;
00145 
00146     assert((!isConstant() || getConstant() == V) &&
00147            "Marking constant with different value");
00148     assert(isUndefined());
00149     Tag = constant;
00150     Val = V;
00151     return true;
00152   }
00153   
00154   /// Return true if this is a change in status.
00155   bool markNotConstant(Constant *V) {
00156     assert(V && "Marking constant with NULL");
00157     if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
00158       return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
00159     if (isa<UndefValue>(V))
00160       return false;
00161 
00162     assert((!isConstant() || getConstant() != V) &&
00163            "Marking constant !constant with same value");
00164     assert((!isNotConstant() || getNotConstant() == V) &&
00165            "Marking !constant with different value");
00166     assert(isUndefined() || isConstant());
00167     Tag = notconstant;
00168     Val = V;
00169     return true;
00170   }
00171   
00172   /// Return true if this is a change in status.
00173   bool markConstantRange(const ConstantRange NewR) {
00174     if (isConstantRange()) {
00175       if (NewR.isEmptySet())
00176         return markOverdefined();
00177       
00178       bool changed = Range != NewR;
00179       Range = NewR;
00180       return changed;
00181     }
00182     
00183     assert(isUndefined());
00184     if (NewR.isEmptySet())
00185       return markOverdefined();
00186     
00187     Tag = constantrange;
00188     Range = NewR;
00189     return true;
00190   }
00191   
00192   /// Merge the specified lattice value into this one, updating this
00193   /// one and returning true if anything changed.
00194   bool mergeIn(const LVILatticeVal &RHS) {
00195     if (RHS.isUndefined() || isOverdefined()) return false;
00196     if (RHS.isOverdefined()) return markOverdefined();
00197 
00198     if (isUndefined()) {
00199       Tag = RHS.Tag;
00200       Val = RHS.Val;
00201       Range = RHS.Range;
00202       return true;
00203     }
00204 
00205     if (isConstant()) {
00206       if (RHS.isConstant()) {
00207         if (Val == RHS.Val)
00208           return false;
00209         return markOverdefined();
00210       }
00211 
00212       if (RHS.isNotConstant()) {
00213         if (Val == RHS.Val)
00214           return markOverdefined();
00215 
00216         // Unless we can prove that the two Constants are different, we must
00217         // move to overdefined.
00218         // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
00219         if (ConstantInt *Res = dyn_cast<ConstantInt>(
00220                 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
00221                                                 getConstant(),
00222                                                 RHS.getNotConstant())))
00223           if (Res->isOne())
00224             return markNotConstant(RHS.getNotConstant());
00225 
00226         return markOverdefined();
00227       }
00228 
00229       // RHS is a ConstantRange, LHS is a non-integer Constant.
00230 
00231       // FIXME: consider the case where RHS is a range [1, 0) and LHS is
00232       // a function. The correct result is to pick up RHS.
00233 
00234       return markOverdefined();
00235     }
00236 
00237     if (isNotConstant()) {
00238       if (RHS.isConstant()) {
00239         if (Val == RHS.Val)
00240           return markOverdefined();
00241 
00242         // Unless we can prove that the two Constants are different, we must
00243         // move to overdefined.
00244         // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
00245         if (ConstantInt *Res = dyn_cast<ConstantInt>(
00246                 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
00247                                                 getNotConstant(),
00248                                                 RHS.getConstant())))
00249           if (Res->isOne())
00250             return false;
00251 
00252         return markOverdefined();
00253       }
00254 
00255       if (RHS.isNotConstant()) {
00256         if (Val == RHS.Val)
00257           return false;
00258         return markOverdefined();
00259       }
00260 
00261       return markOverdefined();
00262     }
00263 
00264     assert(isConstantRange() && "New LVILattice type?");
00265     if (!RHS.isConstantRange())
00266       return markOverdefined();
00267 
00268     ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
00269     if (NewR.isFullSet())
00270       return markOverdefined();
00271     return markConstantRange(NewR);
00272   }
00273 };
00274   
00275 } // end anonymous namespace.
00276 
00277 namespace llvm {
00278 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
00279     LLVM_ATTRIBUTE_USED;
00280 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
00281   if (Val.isUndefined())
00282     return OS << "undefined";
00283   if (Val.isOverdefined())
00284     return OS << "overdefined";
00285 
00286   if (Val.isNotConstant())
00287     return OS << "notconstant<" << *Val.getNotConstant() << '>';
00288   else if (Val.isConstantRange())
00289     return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
00290               << Val.getConstantRange().getUpper() << '>';
00291   return OS << "constant<" << *Val.getConstant() << '>';
00292 }
00293 }
00294 
00295 //===----------------------------------------------------------------------===//
00296 //                          LazyValueInfoCache Decl
00297 //===----------------------------------------------------------------------===//
00298 
00299 namespace {
00300   /// A callback value handle updates the cache when values are erased.
00301   class LazyValueInfoCache;
00302   struct LVIValueHandle : public CallbackVH {
00303     LazyValueInfoCache *Parent;
00304       
00305     LVIValueHandle(Value *V, LazyValueInfoCache *P)
00306       : CallbackVH(V), Parent(P) { }
00307 
00308     void deleted() override;
00309     void allUsesReplacedWith(Value *V) override {
00310       deleted();
00311     }
00312   };
00313 }
00314 
00315 namespace { 
00316   /// This is the cache kept by LazyValueInfo which
00317   /// maintains information about queries across the clients' queries.
00318   class LazyValueInfoCache {
00319     /// This is all of the cached block information for exactly one Value*.
00320     /// The entries are sorted by the BasicBlock* of the
00321     /// entries, allowing us to do a lookup with a binary search.
00322     typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
00323 
00324     /// This is all of the cached information for all values,
00325     /// mapped from Value* to key information.
00326     std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
00327     
00328     /// This tracks, on a per-block basis, the set of values that are
00329     /// over-defined at the end of that block.  This is required
00330     /// for cache updating.
00331     typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
00332     DenseSet<OverDefinedPairTy> OverDefinedCache;
00333 
00334     /// Keep track of all blocks that we have ever seen, so we
00335     /// don't spend time removing unused blocks from our caches.
00336     DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
00337 
00338     /// This stack holds the state of the value solver during a query.
00339     /// It basically emulates the callstack of the naive
00340     /// recursive value lookup process.
00341     std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
00342 
00343     /// Keeps track of which block-value pairs are in BlockValueStack.
00344     DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
00345 
00346     /// Push BV onto BlockValueStack unless it's already in there.
00347     /// Returns true on success.
00348     bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
00349       if (BlockValueSet.count(BV))
00350         return false;  // It's already in the stack.
00351 
00352       BlockValueStack.push(BV);
00353       BlockValueSet.insert(BV);
00354       return true;
00355     }
00356 
00357     /// A pointer to the cache of @llvm.assume calls.
00358     AssumptionCache *AC;
00359     /// An optional DL pointer.
00360     const DataLayout *DL;
00361     /// An optional DT pointer.
00362     DominatorTree *DT;
00363     
00364     friend struct LVIValueHandle;
00365 
00366     void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
00367       SeenBlocks.insert(BB);
00368       lookup(Val)[BB] = Result;
00369       if (Result.isOverdefined())
00370         OverDefinedCache.insert(std::make_pair(BB, Val));
00371     }
00372 
00373     LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
00374     bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
00375                       LVILatticeVal &Result,
00376                       Instruction *CxtI = nullptr);
00377     bool hasBlockValue(Value *Val, BasicBlock *BB);
00378 
00379     // These methods process one work item and may add more. A false value
00380     // returned means that the work item was not completely processed and must
00381     // be revisited after going through the new items.
00382     bool solveBlockValue(Value *Val, BasicBlock *BB);
00383     bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
00384                                  Value *Val, BasicBlock *BB);
00385     bool solveBlockValuePHINode(LVILatticeVal &BBLV,
00386                                 PHINode *PN, BasicBlock *BB);
00387     bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
00388                                       Instruction *BBI, BasicBlock *BB);
00389     void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
00390                                             Instruction *BBI);
00391 
00392     void solve();
00393     
00394     ValueCacheEntryTy &lookup(Value *V) {
00395       return ValueCache[LVIValueHandle(V, this)];
00396     }
00397 
00398   public:
00399     /// This is the query interface to determine the lattice
00400     /// value for the specified Value* at the end of the specified block.
00401     LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
00402                                   Instruction *CxtI = nullptr);
00403 
00404     /// This is the query interface to determine the lattice
00405     /// value for the specified Value* at the specified instruction (generally
00406     /// from an assume intrinsic).
00407     LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
00408 
00409     /// This is the query interface to determine the lattice
00410     /// value for the specified Value* that is true on the specified edge.
00411     LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
00412                                  Instruction *CxtI = nullptr);
00413     
00414     /// This is the update interface to inform the cache that an edge from
00415     /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
00416     void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
00417     
00418     /// This is part of the update interface to inform the cache
00419     /// that a block has been deleted.
00420     void eraseBlock(BasicBlock *BB);
00421     
00422     /// clear - Empty the cache.
00423     void clear() {
00424       SeenBlocks.clear();
00425       ValueCache.clear();
00426       OverDefinedCache.clear();
00427     }
00428 
00429     LazyValueInfoCache(AssumptionCache *AC, const DataLayout *DL = nullptr,
00430                        DominatorTree *DT = nullptr)
00431         : AC(AC), DL(DL), DT(DT) {}
00432   };
00433 } // end anonymous namespace
00434 
00435 void LVIValueHandle::deleted() {
00436   typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
00437   
00438   SmallVector<OverDefinedPairTy, 4> ToErase;
00439   for (const OverDefinedPairTy &P : Parent->OverDefinedCache)
00440     if (P.second == getValPtr())
00441       ToErase.push_back(P);
00442   for (const OverDefinedPairTy &P : ToErase)
00443     Parent->OverDefinedCache.erase(P);
00444   
00445   // This erasure deallocates *this, so it MUST happen after we're done
00446   // using any and all members of *this.
00447   Parent->ValueCache.erase(*this);
00448 }
00449 
00450 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
00451   // Shortcut if we have never seen this block.
00452   DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
00453   if (I == SeenBlocks.end())
00454     return;
00455   SeenBlocks.erase(I);
00456 
00457   SmallVector<OverDefinedPairTy, 4> ToErase;
00458   for (const OverDefinedPairTy& P : OverDefinedCache)
00459     if (P.first == BB)
00460       ToErase.push_back(P);
00461   for (const OverDefinedPairTy &P : ToErase)
00462     OverDefinedCache.erase(P);
00463 
00464   for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
00465        I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
00466     I->second.erase(BB);
00467 }
00468 
00469 void LazyValueInfoCache::solve() {
00470   while (!BlockValueStack.empty()) {
00471     std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
00472     assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
00473 
00474     if (solveBlockValue(e.second, e.first)) {
00475       // The work item was completely processed.
00476       assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
00477       assert(lookup(e.second).count(e.first) && "Result should be in cache!");
00478 
00479       BlockValueStack.pop();
00480       BlockValueSet.erase(e);
00481     } else {
00482       // More work needs to be done before revisiting.
00483       assert(BlockValueStack.top() != e && "Stack should have been pushed!");
00484     }
00485   }
00486 }
00487 
00488 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
00489   // If already a constant, there is nothing to compute.
00490   if (isa<Constant>(Val))
00491     return true;
00492 
00493   LVIValueHandle ValHandle(Val, this);
00494   std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
00495     ValueCache.find(ValHandle);
00496   if (I == ValueCache.end()) return false;
00497   return I->second.count(BB);
00498 }
00499 
00500 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
00501   // If already a constant, there is nothing to compute.
00502   if (Constant *VC = dyn_cast<Constant>(Val))
00503     return LVILatticeVal::get(VC);
00504 
00505   SeenBlocks.insert(BB);
00506   return lookup(Val)[BB];
00507 }
00508 
00509 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
00510   if (isa<Constant>(Val))
00511     return true;
00512 
00513   if (lookup(Val).count(BB)) {
00514     // If we have a cached value, use that.
00515     DEBUG(dbgs() << "  reuse BB '" << BB->getName()
00516                  << "' val=" << lookup(Val)[BB] << '\n');
00517 
00518     // Since we're reusing a cached value, we don't need to update the
00519     // OverDefinedCache. The cache will have been properly updated whenever the
00520     // cached value was inserted.
00521     return true;
00522   }
00523 
00524   // Hold off inserting this value into the Cache in case we have to return
00525   // false and come back later.
00526   LVILatticeVal Res;
00527   
00528   Instruction *BBI = dyn_cast<Instruction>(Val);
00529   if (!BBI || BBI->getParent() != BB) {
00530     if (!solveBlockValueNonLocal(Res, Val, BB))
00531       return false;
00532    insertResult(Val, BB, Res);
00533    return true;
00534   }
00535 
00536   if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
00537     if (!solveBlockValuePHINode(Res, PN, BB))
00538       return false;
00539     insertResult(Val, BB, Res);
00540     return true;
00541   }
00542 
00543   if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
00544     Res = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
00545     insertResult(Val, BB, Res);
00546     return true;
00547   }
00548 
00549   // We can only analyze the definitions of certain classes of instructions
00550   // (integral binops and casts at the moment), so bail if this isn't one.
00551   LVILatticeVal Result;
00552   if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
00553      !BBI->getType()->isIntegerTy()) {
00554     DEBUG(dbgs() << " compute BB '" << BB->getName()
00555                  << "' - overdefined because inst def found.\n");
00556     Res.markOverdefined();
00557     insertResult(Val, BB, Res);
00558     return true;
00559   }
00560 
00561   // FIXME: We're currently limited to binops with a constant RHS.  This should
00562   // be improved.
00563   BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
00564   if (BO && !isa<ConstantInt>(BO->getOperand(1))) { 
00565     DEBUG(dbgs() << " compute BB '" << BB->getName()
00566                  << "' - overdefined because inst def found.\n");
00567 
00568     Res.markOverdefined();
00569     insertResult(Val, BB, Res);
00570     return true;
00571   }
00572 
00573   if (!solveBlockValueConstantRange(Res, BBI, BB))
00574     return false;
00575   insertResult(Val, BB, Res);
00576   return true;
00577 }
00578 
00579 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
00580   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
00581     return L->getPointerAddressSpace() == 0 &&
00582         GetUnderlyingObject(L->getPointerOperand()) == Ptr;
00583   }
00584   if (StoreInst *S = dyn_cast<StoreInst>(I)) {
00585     return S->getPointerAddressSpace() == 0 &&
00586         GetUnderlyingObject(S->getPointerOperand()) == Ptr;
00587   }
00588   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
00589     if (MI->isVolatile()) return false;
00590 
00591     // FIXME: check whether it has a valuerange that excludes zero?
00592     ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
00593     if (!Len || Len->isZero()) return false;
00594 
00595     if (MI->getDestAddressSpace() == 0)
00596       if (GetUnderlyingObject(MI->getRawDest()) == Ptr)
00597         return true;
00598     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
00599       if (MTI->getSourceAddressSpace() == 0)
00600         if (GetUnderlyingObject(MTI->getRawSource()) == Ptr)
00601           return true;
00602   }
00603   return false;
00604 }
00605 
00606 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
00607                                                  Value *Val, BasicBlock *BB) {
00608   LVILatticeVal Result;  // Start Undefined.
00609 
00610   // If this is a pointer, and there's a load from that pointer in this BB,
00611   // then we know that the pointer can't be NULL.
00612   bool NotNull = false;
00613   if (Val->getType()->isPointerTy()) {
00614     if (isKnownNonNull(Val)) {
00615       NotNull = true;
00616     } else {
00617       Value *UnderlyingVal = GetUnderlyingObject(Val);
00618       // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
00619       // inside InstructionDereferencesPointer either.
00620       if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, nullptr, 1)) {
00621         for (Instruction &I : *BB) {
00622           if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
00623             NotNull = true;
00624             break;
00625           }
00626         }
00627       }
00628     }
00629   }
00630 
00631   // If this is the entry block, we must be asking about an argument.  The
00632   // value is overdefined.
00633   if (BB == &BB->getParent()->getEntryBlock()) {
00634     assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
00635     if (NotNull) {
00636       PointerType *PTy = cast<PointerType>(Val->getType());
00637       Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
00638     } else {
00639       Result.markOverdefined();
00640     }
00641     BBLV = Result;
00642     return true;
00643   }
00644 
00645   // Loop over all of our predecessors, merging what we know from them into
00646   // result.
00647   bool EdgesMissing = false;
00648   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
00649     LVILatticeVal EdgeResult;
00650     EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
00651     if (EdgesMissing)
00652       continue;
00653 
00654     Result.mergeIn(EdgeResult);
00655 
00656     // If we hit overdefined, exit early.  The BlockVals entry is already set
00657     // to overdefined.
00658     if (Result.isOverdefined()) {
00659       DEBUG(dbgs() << " compute BB '" << BB->getName()
00660             << "' - overdefined because of pred.\n");
00661       // If we previously determined that this is a pointer that can't be null
00662       // then return that rather than giving up entirely.
00663       if (NotNull) {
00664         PointerType *PTy = cast<PointerType>(Val->getType());
00665         Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
00666       }
00667       
00668       BBLV = Result;
00669       return true;
00670     }
00671   }
00672   if (EdgesMissing)
00673     return false;
00674 
00675   // Return the merged value, which is more precise than 'overdefined'.
00676   assert(!Result.isOverdefined());
00677   BBLV = Result;
00678   return true;
00679 }
00680   
00681 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
00682                                                 PHINode *PN, BasicBlock *BB) {
00683   LVILatticeVal Result;  // Start Undefined.
00684 
00685   // Loop over all of our predecessors, merging what we know from them into
00686   // result.
00687   bool EdgesMissing = false;
00688   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00689     BasicBlock *PhiBB = PN->getIncomingBlock(i);
00690     Value *PhiVal = PN->getIncomingValue(i);
00691     LVILatticeVal EdgeResult;
00692     // Note that we can provide PN as the context value to getEdgeValue, even
00693     // though the results will be cached, because PN is the value being used as
00694     // the cache key in the caller.
00695     EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
00696     if (EdgesMissing)
00697       continue;
00698 
00699     Result.mergeIn(EdgeResult);
00700 
00701     // If we hit overdefined, exit early.  The BlockVals entry is already set
00702     // to overdefined.
00703     if (Result.isOverdefined()) {
00704       DEBUG(dbgs() << " compute BB '" << BB->getName()
00705             << "' - overdefined because of pred.\n");
00706       
00707       BBLV = Result;
00708       return true;
00709     }
00710   }
00711   if (EdgesMissing)
00712     return false;
00713 
00714   // Return the merged value, which is more precise than 'overdefined'.
00715   assert(!Result.isOverdefined() && "Possible PHI in entry block?");
00716   BBLV = Result;
00717   return true;
00718 }
00719 
00720 static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
00721                                       LVILatticeVal &Result,
00722                                       bool isTrueDest = true);
00723 
00724 // If we can determine a constant range for the value Val in the context
00725 // provided by the instruction BBI, then merge it into BBLV. If we did find a
00726 // constant range, return true.
00727 void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(Value *Val,
00728                                                             LVILatticeVal &BBLV,
00729                                                             Instruction *BBI) {
00730   BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
00731   if (!BBI)
00732     return;
00733 
00734   for (auto &AssumeVH : AC->assumptions()) {
00735     if (!AssumeVH)
00736       continue;
00737     auto *I = cast<CallInst>(AssumeVH);
00738     if (!isValidAssumeForContext(I, BBI, DL, DT))
00739       continue;
00740 
00741     Value *C = I->getArgOperand(0);
00742     if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
00743       LVILatticeVal Result;
00744       if (getValueFromFromCondition(Val, ICI, Result)) {
00745         if (BBLV.isOverdefined())
00746           BBLV = Result;
00747         else
00748           BBLV.mergeIn(Result);
00749       }
00750     }
00751   }
00752 }
00753 
00754 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
00755                                                       Instruction *BBI,
00756                                                       BasicBlock *BB) {
00757   // Figure out the range of the LHS.  If that fails, bail.
00758   if (!hasBlockValue(BBI->getOperand(0), BB)) {
00759     if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
00760       return false;
00761     BBLV.markOverdefined();
00762     return true;
00763   }
00764 
00765   LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
00766   mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
00767   if (!LHSVal.isConstantRange()) {
00768     BBLV.markOverdefined();
00769     return true;
00770   }
00771   
00772   ConstantRange LHSRange = LHSVal.getConstantRange();
00773   ConstantRange RHSRange(1);
00774   IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
00775   if (isa<BinaryOperator>(BBI)) {
00776     if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
00777       RHSRange = ConstantRange(RHS->getValue());
00778     } else {
00779       BBLV.markOverdefined();
00780       return true;
00781     }
00782   }
00783 
00784   // NOTE: We're currently limited by the set of operations that ConstantRange
00785   // can evaluate symbolically.  Enhancing that set will allows us to analyze
00786   // more definitions.
00787   LVILatticeVal Result;
00788   switch (BBI->getOpcode()) {
00789   case Instruction::Add:
00790     Result.markConstantRange(LHSRange.add(RHSRange));
00791     break;
00792   case Instruction::Sub:
00793     Result.markConstantRange(LHSRange.sub(RHSRange));
00794     break;
00795   case Instruction::Mul:
00796     Result.markConstantRange(LHSRange.multiply(RHSRange));
00797     break;
00798   case Instruction::UDiv:
00799     Result.markConstantRange(LHSRange.udiv(RHSRange));
00800     break;
00801   case Instruction::Shl:
00802     Result.markConstantRange(LHSRange.shl(RHSRange));
00803     break;
00804   case Instruction::LShr:
00805     Result.markConstantRange(LHSRange.lshr(RHSRange));
00806     break;
00807   case Instruction::Trunc:
00808     Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
00809     break;
00810   case Instruction::SExt:
00811     Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
00812     break;
00813   case Instruction::ZExt:
00814     Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
00815     break;
00816   case Instruction::BitCast:
00817     Result.markConstantRange(LHSRange);
00818     break;
00819   case Instruction::And:
00820     Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
00821     break;
00822   case Instruction::Or:
00823     Result.markConstantRange(LHSRange.binaryOr(RHSRange));
00824     break;
00825   
00826   // Unhandled instructions are overdefined.
00827   default:
00828     DEBUG(dbgs() << " compute BB '" << BB->getName()
00829                  << "' - overdefined because inst def found.\n");
00830     Result.markOverdefined();
00831     break;
00832   }
00833   
00834   BBLV = Result;
00835   return true;
00836 }
00837 
00838 bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
00839                                LVILatticeVal &Result, bool isTrueDest) {
00840   if (ICI && isa<Constant>(ICI->getOperand(1))) {
00841     if (ICI->isEquality() && ICI->getOperand(0) == Val) {
00842       // We know that V has the RHS constant if this is a true SETEQ or
00843       // false SETNE. 
00844       if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
00845         Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
00846       else
00847         Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
00848       return true;
00849     }
00850 
00851     // Recognize the range checking idiom that InstCombine produces.
00852     // (X-C1) u< C2 --> [C1, C1+C2)
00853     ConstantInt *NegOffset = nullptr;
00854     if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
00855       match(ICI->getOperand(0), m_Add(m_Specific(Val),
00856                                       m_ConstantInt(NegOffset)));
00857 
00858     ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
00859     if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
00860       // Calculate the range of values that would satisfy the comparison.
00861       ConstantRange CmpRange(CI->getValue());
00862       ConstantRange TrueValues =
00863         ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
00864 
00865       if (NegOffset) // Apply the offset from above.
00866         TrueValues = TrueValues.subtract(NegOffset->getValue());
00867 
00868       // If we're interested in the false dest, invert the condition.
00869       if (!isTrueDest) TrueValues = TrueValues.inverse();
00870 
00871       Result = LVILatticeVal::getRange(TrueValues);
00872       return true;
00873     }
00874   }
00875 
00876   return false;
00877 }
00878 
00879 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
00880 /// Val is not constrained on the edge.
00881 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
00882                               BasicBlock *BBTo, LVILatticeVal &Result) {
00883   // TODO: Handle more complex conditionals.  If (v == 0 || v2 < 1) is false, we
00884   // know that v != 0.
00885   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
00886     // If this is a conditional branch and only one successor goes to BBTo, then
00887     // we may be able to infer something from the condition.
00888     if (BI->isConditional() &&
00889         BI->getSuccessor(0) != BI->getSuccessor(1)) {
00890       bool isTrueDest = BI->getSuccessor(0) == BBTo;
00891       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
00892              "BBTo isn't a successor of BBFrom");
00893       
00894       // If V is the condition of the branch itself, then we know exactly what
00895       // it is.
00896       if (BI->getCondition() == Val) {
00897         Result = LVILatticeVal::get(ConstantInt::get(
00898                               Type::getInt1Ty(Val->getContext()), isTrueDest));
00899         return true;
00900       }
00901       
00902       // If the condition of the branch is an equality comparison, we may be
00903       // able to infer the value.
00904       if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
00905         if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
00906           return true;
00907     }
00908   }
00909 
00910   // If the edge was formed by a switch on the value, then we may know exactly
00911   // what it is.
00912   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
00913     if (SI->getCondition() != Val)
00914       return false;
00915 
00916     bool DefaultCase = SI->getDefaultDest() == BBTo;
00917     unsigned BitWidth = Val->getType()->getIntegerBitWidth();
00918     ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
00919 
00920     for (SwitchInst::CaseIt i : SI->cases()) {
00921       ConstantRange EdgeVal(i.getCaseValue()->getValue());
00922       if (DefaultCase) {
00923         // It is possible that the default destination is the destination of
00924         // some cases. There is no need to perform difference for those cases.
00925         if (i.getCaseSuccessor() != BBTo)
00926           EdgesVals = EdgesVals.difference(EdgeVal);
00927       } else if (i.getCaseSuccessor() == BBTo)
00928         EdgesVals = EdgesVals.unionWith(EdgeVal);
00929     }
00930     Result = LVILatticeVal::getRange(EdgesVals);
00931     return true;
00932   }
00933   return false;
00934 }
00935 
00936 /// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
00937 /// the basic block if the edge does not constrain Val.
00938 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
00939                                       BasicBlock *BBTo, LVILatticeVal &Result,
00940                                       Instruction *CxtI) {
00941   // If already a constant, there is nothing to compute.
00942   if (Constant *VC = dyn_cast<Constant>(Val)) {
00943     Result = LVILatticeVal::get(VC);
00944     return true;
00945   }
00946 
00947   if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
00948     if (!Result.isConstantRange() ||
00949         Result.getConstantRange().getSingleElement())
00950       return true;
00951 
00952     // FIXME: this check should be moved to the beginning of the function when
00953     // LVI better supports recursive values. Even for the single value case, we
00954     // can intersect to detect dead code (an empty range).
00955     if (!hasBlockValue(Val, BBFrom)) {
00956       if (pushBlockValue(std::make_pair(BBFrom, Val)))
00957         return false;
00958       Result.markOverdefined();
00959       return true;
00960     }
00961 
00962     // Try to intersect ranges of the BB and the constraint on the edge.
00963     LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
00964     mergeAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
00965     // See note on the use of the CxtI with mergeAssumeBlockValueConstantRange,
00966     // and caching, below.
00967     mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
00968     if (!InBlock.isConstantRange())
00969       return true;
00970 
00971     ConstantRange Range =
00972       Result.getConstantRange().intersectWith(InBlock.getConstantRange());
00973     Result = LVILatticeVal::getRange(Range);
00974     return true;
00975   }
00976 
00977   if (!hasBlockValue(Val, BBFrom)) {
00978     if (pushBlockValue(std::make_pair(BBFrom, Val)))
00979       return false;
00980     Result.markOverdefined();
00981     return true;
00982   }
00983 
00984   // If we couldn't compute the value on the edge, use the value from the BB.
00985   Result = getBlockValue(Val, BBFrom);
00986   mergeAssumeBlockValueConstantRange(Val, Result, BBFrom->getTerminator());
00987   // We can use the context instruction (generically the ultimate instruction
00988   // the calling pass is trying to simplify) here, even though the result of
00989   // this function is generally cached when called from the solve* functions
00990   // (and that cached result might be used with queries using a different
00991   // context instruction), because when this function is called from the solve*
00992   // functions, the context instruction is not provided. When called from
00993   // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
00994   // but then the result is not cached.
00995   mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
00996   return true;
00997 }
00998 
00999 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
01000                                                   Instruction *CxtI) {
01001   DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
01002         << BB->getName() << "'\n");
01003   
01004   assert(BlockValueStack.empty() && BlockValueSet.empty());
01005   pushBlockValue(std::make_pair(BB, V));
01006 
01007   solve();
01008   LVILatticeVal Result = getBlockValue(V, BB);
01009   mergeAssumeBlockValueConstantRange(V, Result, CxtI);
01010 
01011   DEBUG(dbgs() << "  Result = " << Result << "\n");
01012   return Result;
01013 }
01014 
01015 LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
01016   DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
01017         << CxtI->getName() << "'\n");
01018 
01019   LVILatticeVal Result;
01020   mergeAssumeBlockValueConstantRange(V, Result, CxtI);
01021 
01022   DEBUG(dbgs() << "  Result = " << Result << "\n");
01023   return Result;
01024 }
01025 
01026 LVILatticeVal LazyValueInfoCache::
01027 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
01028                Instruction *CxtI) {
01029   DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
01030         << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
01031   
01032   LVILatticeVal Result;
01033   if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
01034     solve();
01035     bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
01036     (void)WasFastQuery;
01037     assert(WasFastQuery && "More work to do after problem solved?");
01038   }
01039 
01040   DEBUG(dbgs() << "  Result = " << Result << "\n");
01041   return Result;
01042 }
01043 
01044 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
01045                                     BasicBlock *NewSucc) {
01046   // When an edge in the graph has been threaded, values that we could not 
01047   // determine a value for before (i.e. were marked overdefined) may be possible
01048   // to solve now.  We do NOT try to proactively update these values.  Instead,
01049   // we clear their entries from the cache, and allow lazy updating to recompute
01050   // them when needed.
01051   
01052   // The updating process is fairly simple: we need to drop cached info
01053   // for all values that were marked overdefined in OldSucc, and for those same
01054   // values in any successor of OldSucc (except NewSucc) in which they were
01055   // also marked overdefined.
01056   std::vector<BasicBlock*> worklist;
01057   worklist.push_back(OldSucc);
01058   
01059   DenseSet<Value*> ClearSet;
01060   for (OverDefinedPairTy &P : OverDefinedCache)
01061     if (P.first == OldSucc)
01062       ClearSet.insert(P.second);
01063   
01064   // Use a worklist to perform a depth-first search of OldSucc's successors.
01065   // NOTE: We do not need a visited list since any blocks we have already
01066   // visited will have had their overdefined markers cleared already, and we
01067   // thus won't loop to their successors.
01068   while (!worklist.empty()) {
01069     BasicBlock *ToUpdate = worklist.back();
01070     worklist.pop_back();
01071     
01072     // Skip blocks only accessible through NewSucc.
01073     if (ToUpdate == NewSucc) continue;
01074     
01075     bool changed = false;
01076     for (Value *V : ClearSet) {
01077       // If a value was marked overdefined in OldSucc, and is here too...
01078       DenseSet<OverDefinedPairTy>::iterator OI =
01079         OverDefinedCache.find(std::make_pair(ToUpdate, V));
01080       if (OI == OverDefinedCache.end()) continue;
01081 
01082       // Remove it from the caches.
01083       ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(V, this)];
01084       ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
01085 
01086       assert(CI != Entry.end() && "Couldn't find entry to update?");
01087       Entry.erase(CI);
01088       OverDefinedCache.erase(OI);
01089 
01090       // If we removed anything, then we potentially need to update 
01091       // blocks successors too.
01092       changed = true;
01093     }
01094 
01095     if (!changed) continue;
01096     
01097     worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
01098   }
01099 }
01100 
01101 //===----------------------------------------------------------------------===//
01102 //                            LazyValueInfo Impl
01103 //===----------------------------------------------------------------------===//
01104 
01105 /// This lazily constructs the LazyValueInfoCache.
01106 static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
01107                                     const DataLayout *DL = nullptr,
01108                                     DominatorTree *DT = nullptr) {
01109   if (!PImpl)
01110     PImpl = new LazyValueInfoCache(AC, DL, DT);
01111   return *static_cast<LazyValueInfoCache*>(PImpl);
01112 }
01113 
01114 bool LazyValueInfo::runOnFunction(Function &F) {
01115   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
01116 
01117   DominatorTreeWrapperPass *DTWP =
01118       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
01119   DT = DTWP ? &DTWP->getDomTree() : nullptr;
01120 
01121   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01122   DL = DLP ? &DLP->getDataLayout() : nullptr;
01123 
01124   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
01125 
01126   if (PImpl)
01127     getCache(PImpl, AC, DL, DT).clear();
01128 
01129   // Fully lazy.
01130   return false;
01131 }
01132 
01133 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
01134   AU.setPreservesAll();
01135   AU.addRequired<AssumptionCacheTracker>();
01136   AU.addRequired<TargetLibraryInfoWrapperPass>();
01137 }
01138 
01139 void LazyValueInfo::releaseMemory() {
01140   // If the cache was allocated, free it.
01141   if (PImpl) {
01142     delete &getCache(PImpl, AC);
01143     PImpl = nullptr;
01144   }
01145 }
01146 
01147 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
01148                                      Instruction *CxtI) {
01149   LVILatticeVal Result =
01150       getCache(PImpl, AC, DL, DT).getValueInBlock(V, BB, CxtI);
01151 
01152   if (Result.isConstant())
01153     return Result.getConstant();
01154   if (Result.isConstantRange()) {
01155     ConstantRange CR = Result.getConstantRange();
01156     if (const APInt *SingleVal = CR.getSingleElement())
01157       return ConstantInt::get(V->getContext(), *SingleVal);
01158   }
01159   return nullptr;
01160 }
01161 
01162 /// Determine whether the specified value is known to be a
01163 /// constant on the specified edge.  Return null if not.
01164 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
01165                                            BasicBlock *ToBB,
01166                                            Instruction *CxtI) {
01167   LVILatticeVal Result =
01168       getCache(PImpl, AC, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
01169 
01170   if (Result.isConstant())
01171     return Result.getConstant();
01172   if (Result.isConstantRange()) {
01173     ConstantRange CR = Result.getConstantRange();
01174     if (const APInt *SingleVal = CR.getSingleElement())
01175       return ConstantInt::get(V->getContext(), *SingleVal);
01176   }
01177   return nullptr;
01178 }
01179 
01180 static LazyValueInfo::Tristate
01181 getPredicateResult(unsigned Pred, Constant *C, LVILatticeVal &Result,
01182                    const DataLayout *DL, TargetLibraryInfo *TLI) {
01183 
01184   // If we know the value is a constant, evaluate the conditional.
01185   Constant *Res = nullptr;
01186   if (Result.isConstant()) {
01187     Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
01188                                           TLI);
01189     if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
01190       return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
01191     return LazyValueInfo::Unknown;
01192   }
01193   
01194   if (Result.isConstantRange()) {
01195     ConstantInt *CI = dyn_cast<ConstantInt>(C);
01196     if (!CI) return LazyValueInfo::Unknown;
01197     
01198     ConstantRange CR = Result.getConstantRange();
01199     if (Pred == ICmpInst::ICMP_EQ) {
01200       if (!CR.contains(CI->getValue()))
01201         return LazyValueInfo::False;
01202       
01203       if (CR.isSingleElement() && CR.contains(CI->getValue()))
01204         return LazyValueInfo::True;
01205     } else if (Pred == ICmpInst::ICMP_NE) {
01206       if (!CR.contains(CI->getValue()))
01207         return LazyValueInfo::True;
01208       
01209       if (CR.isSingleElement() && CR.contains(CI->getValue()))
01210         return LazyValueInfo::False;
01211     }
01212     
01213     // Handle more complex predicates.
01214     ConstantRange TrueValues =
01215         ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
01216     if (TrueValues.contains(CR))
01217       return LazyValueInfo::True;
01218     if (TrueValues.inverse().contains(CR))
01219       return LazyValueInfo::False;
01220     return LazyValueInfo::Unknown;
01221   }
01222   
01223   if (Result.isNotConstant()) {
01224     // If this is an equality comparison, we can try to fold it knowing that
01225     // "V != C1".
01226     if (Pred == ICmpInst::ICMP_EQ) {
01227       // !C1 == C -> false iff C1 == C.
01228       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
01229                                             Result.getNotConstant(), C, DL,
01230                                             TLI);
01231       if (Res->isNullValue())
01232         return LazyValueInfo::False;
01233     } else if (Pred == ICmpInst::ICMP_NE) {
01234       // !C1 != C -> true iff C1 == C.
01235       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
01236                                             Result.getNotConstant(), C, DL,
01237                                             TLI);
01238       if (Res->isNullValue())
01239         return LazyValueInfo::True;
01240     }
01241     return LazyValueInfo::Unknown;
01242   }
01243   
01244   return LazyValueInfo::Unknown;
01245 }
01246 
01247 /// Determine whether the specified value comparison with a constant is known to
01248 /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
01249 LazyValueInfo::Tristate
01250 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
01251                                   BasicBlock *FromBB, BasicBlock *ToBB,
01252                                   Instruction *CxtI) {
01253   LVILatticeVal Result =
01254       getCache(PImpl, AC, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
01255 
01256   return getPredicateResult(Pred, C, Result, DL, TLI);
01257 }
01258 
01259 LazyValueInfo::Tristate
01260 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
01261                               Instruction *CxtI) {
01262   LVILatticeVal Result = getCache(PImpl, AC, DL, DT).getValueAt(V, CxtI);
01263 
01264   return getPredicateResult(Pred, C, Result, DL, TLI);
01265 }
01266 
01267 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
01268                                BasicBlock *NewSucc) {
01269   if (PImpl)
01270     getCache(PImpl, AC, DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
01271 }
01272 
01273 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
01274   if (PImpl)
01275     getCache(PImpl, AC, DL, DT).eraseBlock(BB);
01276 }