LLVM API Documentation

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