Add a "seen blocks" cache to LVI to avoid a linear scan over the whole cache just...
[oota-llvm.git] / lib / Analysis / LazyValueInfo.cpp
1 //===- LazyValueInfo.cpp - Value constraint analysis ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interface for lazy computation of value constraint
11 // information.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "lazy-value-info"
16 #include "llvm/Analysis/LazyValueInfo.h"
17 #include "llvm/Analysis/ValueTracking.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetLibraryInfo.h"
24 #include "llvm/Support/CFG.h"
25 #include "llvm/Support/ConstantRange.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/ValueHandle.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include <map>
33 #include <stack>
34 using namespace llvm;
35
36 char LazyValueInfo::ID = 0;
37 INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
38                 "Lazy Value Information Analysis", false, true)
39 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
40 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
41                 "Lazy Value Information Analysis", false, true)
42
43 namespace llvm {
44   FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
45 }
46
47
48 //===----------------------------------------------------------------------===//
49 //                               LVILatticeVal
50 //===----------------------------------------------------------------------===//
51
52 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
53 /// value.
54 ///
55 /// FIXME: This is basically just for bringup, this can be made a lot more rich
56 /// in the future.
57 ///
58 namespace {
59 class LVILatticeVal {
60   enum LatticeValueTy {
61     /// undefined - This Value has no known value yet.
62     undefined,
63     
64     /// constant - This Value has a specific constant value.
65     constant,
66     /// notconstant - This Value is known to not have the specified value.
67     notconstant,
68
69     /// constantrange - The Value falls within this range.
70     constantrange,
71
72     /// overdefined - This value is not known to be constant, and we know that
73     /// it has a value.
74     overdefined
75   };
76   
77   /// Val: This stores the current lattice value along with the Constant* for
78   /// the constant if this is a 'constant' or 'notconstant' value.
79   LatticeValueTy Tag;
80   Constant *Val;
81   ConstantRange Range;
82   
83 public:
84   LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
85
86   static LVILatticeVal get(Constant *C) {
87     LVILatticeVal Res;
88     if (!isa<UndefValue>(C))
89       Res.markConstant(C);
90     return Res;
91   }
92   static LVILatticeVal getNot(Constant *C) {
93     LVILatticeVal Res;
94     if (!isa<UndefValue>(C))
95       Res.markNotConstant(C);
96     return Res;
97   }
98   static LVILatticeVal getRange(ConstantRange CR) {
99     LVILatticeVal Res;
100     Res.markConstantRange(CR);
101     return Res;
102   }
103   
104   bool isUndefined() const     { return Tag == undefined; }
105   bool isConstant() const      { return Tag == constant; }
106   bool isNotConstant() const   { return Tag == notconstant; }
107   bool isConstantRange() const { return Tag == constantrange; }
108   bool isOverdefined() const   { return Tag == overdefined; }
109   
110   Constant *getConstant() const {
111     assert(isConstant() && "Cannot get the constant of a non-constant!");
112     return Val;
113   }
114   
115   Constant *getNotConstant() const {
116     assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
117     return Val;
118   }
119   
120   ConstantRange getConstantRange() const {
121     assert(isConstantRange() &&
122            "Cannot get the constant-range of a non-constant-range!");
123     return Range;
124   }
125   
126   /// markOverdefined - Return true if this is a change in status.
127   bool markOverdefined() {
128     if (isOverdefined())
129       return false;
130     Tag = overdefined;
131     return true;
132   }
133
134   /// markConstant - Return true if this is a change in status.
135   bool markConstant(Constant *V) {
136     assert(V && "Marking constant with NULL");
137     if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
138       return markConstantRange(ConstantRange(CI->getValue()));
139     if (isa<UndefValue>(V))
140       return false;
141
142     assert((!isConstant() || getConstant() == V) &&
143            "Marking constant with different value");
144     assert(isUndefined());
145     Tag = constant;
146     Val = V;
147     return true;
148   }
149   
150   /// markNotConstant - Return true if this is a change in status.
151   bool markNotConstant(Constant *V) {
152     assert(V && "Marking constant with NULL");
153     if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
154       return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
155     if (isa<UndefValue>(V))
156       return false;
157
158     assert((!isConstant() || getConstant() != V) &&
159            "Marking constant !constant with same value");
160     assert((!isNotConstant() || getNotConstant() == V) &&
161            "Marking !constant with different value");
162     assert(isUndefined() || isConstant());
163     Tag = notconstant;
164     Val = V;
165     return true;
166   }
167   
168   /// markConstantRange - Return true if this is a change in status.
169   bool markConstantRange(const ConstantRange NewR) {
170     if (isConstantRange()) {
171       if (NewR.isEmptySet())
172         return markOverdefined();
173       
174       bool changed = Range == NewR;
175       Range = NewR;
176       return changed;
177     }
178     
179     assert(isUndefined());
180     if (NewR.isEmptySet())
181       return markOverdefined();
182     
183     Tag = constantrange;
184     Range = NewR;
185     return true;
186   }
187   
188   /// mergeIn - Merge the specified lattice value into this one, updating this
189   /// one and returning true if anything changed.
190   bool mergeIn(const LVILatticeVal &RHS) {
191     if (RHS.isUndefined() || isOverdefined()) return false;
192     if (RHS.isOverdefined()) return markOverdefined();
193
194     if (isUndefined()) {
195       Tag = RHS.Tag;
196       Val = RHS.Val;
197       Range = RHS.Range;
198       return true;
199     }
200
201     if (isConstant()) {
202       if (RHS.isConstant()) {
203         if (Val == RHS.Val)
204           return false;
205         return markOverdefined();
206       }
207
208       if (RHS.isNotConstant()) {
209         if (Val == RHS.Val)
210           return markOverdefined();
211
212         // Unless we can prove that the two Constants are different, we must
213         // move to overdefined.
214         // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
215         if (ConstantInt *Res = dyn_cast<ConstantInt>(
216                 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
217                                                 getConstant(),
218                                                 RHS.getNotConstant())))
219           if (Res->isOne())
220             return markNotConstant(RHS.getNotConstant());
221
222         return markOverdefined();
223       }
224
225       // RHS is a ConstantRange, LHS is a non-integer Constant.
226
227       // FIXME: consider the case where RHS is a range [1, 0) and LHS is
228       // a function. The correct result is to pick up RHS.
229
230       return markOverdefined();
231     }
232
233     if (isNotConstant()) {
234       if (RHS.isConstant()) {
235         if (Val == RHS.Val)
236           return markOverdefined();
237
238         // Unless we can prove that the two Constants are different, we must
239         // move to overdefined.
240         // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
241         if (ConstantInt *Res = dyn_cast<ConstantInt>(
242                 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
243                                                 getNotConstant(),
244                                                 RHS.getConstant())))
245           if (Res->isOne())
246             return false;
247
248         return markOverdefined();
249       }
250
251       if (RHS.isNotConstant()) {
252         if (Val == RHS.Val)
253           return false;
254         return markOverdefined();
255       }
256
257       return markOverdefined();
258     }
259
260     assert(isConstantRange() && "New LVILattice type?");
261     if (!RHS.isConstantRange())
262       return markOverdefined();
263
264     ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
265     if (NewR.isFullSet())
266       return markOverdefined();
267     return markConstantRange(NewR);
268   }
269 };
270   
271 } // end anonymous namespace.
272
273 namespace llvm {
274 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
275     LLVM_ATTRIBUTE_USED;
276 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
277   if (Val.isUndefined())
278     return OS << "undefined";
279   if (Val.isOverdefined())
280     return OS << "overdefined";
281
282   if (Val.isNotConstant())
283     return OS << "notconstant<" << *Val.getNotConstant() << '>';
284   else if (Val.isConstantRange())
285     return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
286               << Val.getConstantRange().getUpper() << '>';
287   return OS << "constant<" << *Val.getConstant() << '>';
288 }
289 }
290
291 //===----------------------------------------------------------------------===//
292 //                          LazyValueInfoCache Decl
293 //===----------------------------------------------------------------------===//
294
295 namespace {
296   /// LVIValueHandle - A callback value handle update the cache when
297   /// values are erased.
298   class LazyValueInfoCache;
299   struct LVIValueHandle : public CallbackVH {
300     LazyValueInfoCache *Parent;
301       
302     LVIValueHandle(Value *V, LazyValueInfoCache *P)
303       : CallbackVH(V), Parent(P) { }
304       
305     void deleted();
306     void allUsesReplacedWith(Value *V) {
307       deleted();
308     }
309   };
310 }
311
312 namespace llvm {
313   template<>
314   struct DenseMapInfo<LVIValueHandle> {
315     typedef DenseMapInfo<Value*> PointerInfo;
316     static inline LVIValueHandle getEmptyKey() {
317       return LVIValueHandle(PointerInfo::getEmptyKey(),
318                             static_cast<LazyValueInfoCache*>(0));
319     }
320     static inline LVIValueHandle getTombstoneKey() {
321       return LVIValueHandle(PointerInfo::getTombstoneKey(),
322                             static_cast<LazyValueInfoCache*>(0));
323     }
324     static unsigned getHashValue(const LVIValueHandle &Val) {
325       return PointerInfo::getHashValue(Val);
326     }
327     static bool isEqual(const LVIValueHandle &LHS, const LVIValueHandle &RHS) {
328       return LHS == RHS;
329     }
330   };
331   
332   template<>
333   struct DenseMapInfo<std::pair<AssertingVH<BasicBlock>, Value*> > {
334     typedef std::pair<AssertingVH<BasicBlock>, Value*> PairTy;
335     typedef DenseMapInfo<AssertingVH<BasicBlock> > APointerInfo;
336     typedef DenseMapInfo<Value*> BPointerInfo;
337     static inline PairTy getEmptyKey() {
338       return std::make_pair(APointerInfo::getEmptyKey(),
339                             BPointerInfo::getEmptyKey());
340     }
341     static inline PairTy getTombstoneKey() {
342       return std::make_pair(APointerInfo::getTombstoneKey(), 
343                             BPointerInfo::getTombstoneKey());
344     }
345     static unsigned getHashValue( const PairTy &Val) {
346       return APointerInfo::getHashValue(Val.first) ^ 
347              BPointerInfo::getHashValue(Val.second);
348     }
349     static bool isEqual(const PairTy &LHS, const PairTy &RHS) {
350       return APointerInfo::isEqual(LHS.first, RHS.first) &&
351              BPointerInfo::isEqual(LHS.second, RHS.second);
352     }
353   };
354 }
355
356 namespace { 
357   /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
358   /// maintains information about queries across the clients' queries.
359   class LazyValueInfoCache {
360     /// ValueCacheEntryTy - This is all of the cached block information for
361     /// exactly one Value*.  The entries are sorted by the BasicBlock* of the
362     /// entries, allowing us to do a lookup with a binary search.
363     typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
364
365     /// ValueCache - This is all of the cached information for all values,
366     /// mapped from Value* to key information.
367     DenseMap<LVIValueHandle, ValueCacheEntryTy> ValueCache;
368     
369     /// OverDefinedCache - This tracks, on a per-block basis, the set of 
370     /// values that are over-defined at the end of that block.  This is required
371     /// for cache updating.
372     typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
373     DenseSet<OverDefinedPairTy> OverDefinedCache;
374
375     /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
376     /// don't spend time removing unused blocks from our caches.
377     DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
378
379     /// BlockValueStack - This stack holds the state of the value solver
380     /// during a query.  It basically emulates the callstack of the naive
381     /// recursive value lookup process.
382     std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
383     
384     friend struct LVIValueHandle;
385     
386     /// OverDefinedCacheUpdater - A helper object that ensures that the
387     /// OverDefinedCache is updated whenever solveBlockValue returns.
388     struct OverDefinedCacheUpdater {
389       LazyValueInfoCache *Parent;
390       Value *Val;
391       BasicBlock *BB;
392       LVILatticeVal &BBLV;
393       
394       OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
395                        LazyValueInfoCache *P)
396         : Parent(P), Val(V), BB(B), BBLV(LV) { }
397       
398       bool markResult(bool changed) { 
399         if (changed && BBLV.isOverdefined())
400           Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
401         return changed;
402       }
403     };
404     
405
406
407     LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
408     bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
409                       LVILatticeVal &Result);
410     bool hasBlockValue(Value *Val, BasicBlock *BB);
411
412     // These methods process one work item and may add more. A false value
413     // returned means that the work item was not completely processed and must
414     // be revisited after going through the new items.
415     bool solveBlockValue(Value *Val, BasicBlock *BB);
416     bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
417                                  Value *Val, BasicBlock *BB);
418     bool solveBlockValuePHINode(LVILatticeVal &BBLV,
419                                 PHINode *PN, BasicBlock *BB);
420     bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
421                                       Instruction *BBI, BasicBlock *BB);
422
423     void solve();
424     
425     ValueCacheEntryTy &lookup(Value *V) {
426       return ValueCache[LVIValueHandle(V, this)];
427     }
428
429   public:
430     /// getValueInBlock - This is the query interface to determine the lattice
431     /// value for the specified Value* at the end of the specified block.
432     LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
433
434     /// getValueOnEdge - This is the query interface to determine the lattice
435     /// value for the specified Value* that is true on the specified edge.
436     LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
437     
438     /// threadEdge - This is the update interface to inform the cache that an
439     /// edge from PredBB to OldSucc has been threaded to be from PredBB to
440     /// NewSucc.
441     void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
442     
443     /// eraseBlock - This is part of the update interface to inform the cache
444     /// that a block has been deleted.
445     void eraseBlock(BasicBlock *BB);
446     
447     /// clear - Empty the cache.
448     void clear() {
449       ValueCache.clear();
450       OverDefinedCache.clear();
451     }
452   };
453 } // end anonymous namespace
454
455 void LVIValueHandle::deleted() {
456   typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
457   
458   SmallVector<OverDefinedPairTy, 4> ToErase;
459   for (DenseSet<OverDefinedPairTy>::iterator 
460        I = Parent->OverDefinedCache.begin(),
461        E = Parent->OverDefinedCache.end();
462        I != E; ++I) {
463     if (I->second == getValPtr())
464       ToErase.push_back(*I);
465   }
466   
467   for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
468        E = ToErase.end(); I != E; ++I)
469     Parent->OverDefinedCache.erase(*I);
470   
471   // This erasure deallocates *this, so it MUST happen after we're done
472   // using any and all members of *this.
473   Parent->ValueCache.erase(*this);
474 }
475
476 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
477   // Shortcut if we have never seen this block.
478   DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
479   if (I == SeenBlocks.end())
480     return;
481   SeenBlocks.erase(I);
482
483   SmallVector<OverDefinedPairTy, 4> ToErase;
484   for (DenseSet<OverDefinedPairTy>::iterator  I = OverDefinedCache.begin(),
485        E = OverDefinedCache.end(); I != E; ++I) {
486     if (I->first == BB)
487       ToErase.push_back(*I);
488   }
489   
490   for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
491        E = ToErase.end(); I != E; ++I)
492     OverDefinedCache.erase(*I);
493
494   for (DenseMap<LVIValueHandle, ValueCacheEntryTy>::iterator
495        I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
496     I->second.erase(BB);
497 }
498
499 void LazyValueInfoCache::solve() {
500   while (!BlockValueStack.empty()) {
501     std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
502     if (solveBlockValue(e.second, e.first))
503       BlockValueStack.pop();
504   }
505 }
506
507 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
508   // If already a constant, there is nothing to compute.
509   if (isa<Constant>(Val))
510     return true;
511
512   LVIValueHandle ValHandle(Val, this);
513   if (!ValueCache.count(ValHandle)) return false;
514   return ValueCache[ValHandle].count(BB);
515 }
516
517 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
518   // If already a constant, there is nothing to compute.
519   if (Constant *VC = dyn_cast<Constant>(Val))
520     return LVILatticeVal::get(VC);
521
522   SeenBlocks.insert(BB);
523   return lookup(Val)[BB];
524 }
525
526 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
527   if (isa<Constant>(Val))
528     return true;
529
530   ValueCacheEntryTy &Cache = lookup(Val);
531   SeenBlocks.insert(BB);
532   LVILatticeVal &BBLV = Cache[BB];
533   
534   // OverDefinedCacheUpdater is a helper object that will update
535   // the OverDefinedCache for us when this method exits.  Make sure to
536   // call markResult on it as we exist, passing a bool to indicate if the
537   // cache needs updating, i.e. if we have solve a new value or not.
538   OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
539
540   // If we've already computed this block's value, return it.
541   if (!BBLV.isUndefined()) {
542     DEBUG(dbgs() << "  reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
543     
544     // Since we're reusing a cached value here, we don't need to update the 
545     // OverDefinedCahce.  The cache will have been properly updated 
546     // whenever the cached value was inserted.
547     ODCacheUpdater.markResult(false);
548     return true;
549   }
550
551   // Otherwise, this is the first time we're seeing this block.  Reset the
552   // lattice value to overdefined, so that cycles will terminate and be
553   // conservatively correct.
554   BBLV.markOverdefined();
555   
556   Instruction *BBI = dyn_cast<Instruction>(Val);
557   if (BBI == 0 || BBI->getParent() != BB) {
558     return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
559   }
560
561   if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
562     return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
563   }
564
565   if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
566     BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
567     return ODCacheUpdater.markResult(true);
568   }
569
570   // We can only analyze the definitions of certain classes of instructions
571   // (integral binops and casts at the moment), so bail if this isn't one.
572   LVILatticeVal Result;
573   if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
574      !BBI->getType()->isIntegerTy()) {
575     DEBUG(dbgs() << " compute BB '" << BB->getName()
576                  << "' - overdefined because inst def found.\n");
577     BBLV.markOverdefined();
578     return ODCacheUpdater.markResult(true);
579   }
580
581   // FIXME: We're currently limited to binops with a constant RHS.  This should
582   // be improved.
583   BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
584   if (BO && !isa<ConstantInt>(BO->getOperand(1))) { 
585     DEBUG(dbgs() << " compute BB '" << BB->getName()
586                  << "' - overdefined because inst def found.\n");
587
588     BBLV.markOverdefined();
589     return ODCacheUpdater.markResult(true);
590   }
591
592   return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
593 }
594
595 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
596   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
597     return L->getPointerAddressSpace() == 0 &&
598         GetUnderlyingObject(L->getPointerOperand()) ==
599         GetUnderlyingObject(Ptr);
600   }
601   if (StoreInst *S = dyn_cast<StoreInst>(I)) {
602     return S->getPointerAddressSpace() == 0 &&
603         GetUnderlyingObject(S->getPointerOperand()) ==
604         GetUnderlyingObject(Ptr);
605   }
606   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
607     if (MI->isVolatile()) return false;
608
609     // FIXME: check whether it has a valuerange that excludes zero?
610     ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
611     if (!Len || Len->isZero()) return false;
612
613     if (MI->getDestAddressSpace() == 0)
614       if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
615         return true;
616     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
617       if (MTI->getSourceAddressSpace() == 0)
618         if (MTI->getRawSource() == Ptr || MTI->getSource() == Ptr)
619           return true;
620   }
621   return false;
622 }
623
624 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
625                                                  Value *Val, BasicBlock *BB) {
626   LVILatticeVal Result;  // Start Undefined.
627
628   // If this is a pointer, and there's a load from that pointer in this BB,
629   // then we know that the pointer can't be NULL.
630   bool NotNull = false;
631   if (Val->getType()->isPointerTy()) {
632     if (isa<AllocaInst>(Val)) {
633       NotNull = true;
634     } else {
635       for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
636         if (InstructionDereferencesPointer(BI, Val)) {
637           NotNull = true;
638           break;
639         }
640       }
641     }
642   }
643
644   // If this is the entry block, we must be asking about an argument.  The
645   // value is overdefined.
646   if (BB == &BB->getParent()->getEntryBlock()) {
647     assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
648     if (NotNull) {
649       PointerType *PTy = cast<PointerType>(Val->getType());
650       Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
651     } else {
652       Result.markOverdefined();
653     }
654     BBLV = Result;
655     return true;
656   }
657
658   // Loop over all of our predecessors, merging what we know from them into
659   // result.
660   bool EdgesMissing = false;
661   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
662     LVILatticeVal EdgeResult;
663     EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
664     if (EdgesMissing)
665       continue;
666
667     Result.mergeIn(EdgeResult);
668
669     // If we hit overdefined, exit early.  The BlockVals entry is already set
670     // to overdefined.
671     if (Result.isOverdefined()) {
672       DEBUG(dbgs() << " compute BB '" << BB->getName()
673             << "' - overdefined because of pred.\n");
674       // If we previously determined that this is a pointer that can't be null
675       // then return that rather than giving up entirely.
676       if (NotNull) {
677         PointerType *PTy = cast<PointerType>(Val->getType());
678         Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
679       }
680       
681       BBLV = Result;
682       return true;
683     }
684   }
685   if (EdgesMissing)
686     return false;
687
688   // Return the merged value, which is more precise than 'overdefined'.
689   assert(!Result.isOverdefined());
690   BBLV = Result;
691   return true;
692 }
693   
694 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
695                                                 PHINode *PN, BasicBlock *BB) {
696   LVILatticeVal Result;  // Start Undefined.
697
698   // Loop over all of our predecessors, merging what we know from them into
699   // result.
700   bool EdgesMissing = false;
701   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
702     BasicBlock *PhiBB = PN->getIncomingBlock(i);
703     Value *PhiVal = PN->getIncomingValue(i);
704     LVILatticeVal EdgeResult;
705     EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
706     if (EdgesMissing)
707       continue;
708
709     Result.mergeIn(EdgeResult);
710
711     // If we hit overdefined, exit early.  The BlockVals entry is already set
712     // to overdefined.
713     if (Result.isOverdefined()) {
714       DEBUG(dbgs() << " compute BB '" << BB->getName()
715             << "' - overdefined because of pred.\n");
716       
717       BBLV = Result;
718       return true;
719     }
720   }
721   if (EdgesMissing)
722     return false;
723
724   // Return the merged value, which is more precise than 'overdefined'.
725   assert(!Result.isOverdefined() && "Possible PHI in entry block?");
726   BBLV = Result;
727   return true;
728 }
729
730 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
731                                                       Instruction *BBI,
732                                                       BasicBlock *BB) {
733   // Figure out the range of the LHS.  If that fails, bail.
734   if (!hasBlockValue(BBI->getOperand(0), BB)) {
735     BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
736     return false;
737   }
738
739   LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
740   if (!LHSVal.isConstantRange()) {
741     BBLV.markOverdefined();
742     return true;
743   }
744   
745   ConstantRange LHSRange = LHSVal.getConstantRange();
746   ConstantRange RHSRange(1);
747   IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
748   if (isa<BinaryOperator>(BBI)) {
749     if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
750       RHSRange = ConstantRange(RHS->getValue());
751     } else {
752       BBLV.markOverdefined();
753       return true;
754     }
755   }
756
757   // NOTE: We're currently limited by the set of operations that ConstantRange
758   // can evaluate symbolically.  Enhancing that set will allows us to analyze
759   // more definitions.
760   LVILatticeVal Result;
761   switch (BBI->getOpcode()) {
762   case Instruction::Add:
763     Result.markConstantRange(LHSRange.add(RHSRange));
764     break;
765   case Instruction::Sub:
766     Result.markConstantRange(LHSRange.sub(RHSRange));
767     break;
768   case Instruction::Mul:
769     Result.markConstantRange(LHSRange.multiply(RHSRange));
770     break;
771   case Instruction::UDiv:
772     Result.markConstantRange(LHSRange.udiv(RHSRange));
773     break;
774   case Instruction::Shl:
775     Result.markConstantRange(LHSRange.shl(RHSRange));
776     break;
777   case Instruction::LShr:
778     Result.markConstantRange(LHSRange.lshr(RHSRange));
779     break;
780   case Instruction::Trunc:
781     Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
782     break;
783   case Instruction::SExt:
784     Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
785     break;
786   case Instruction::ZExt:
787     Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
788     break;
789   case Instruction::BitCast:
790     Result.markConstantRange(LHSRange);
791     break;
792   case Instruction::And:
793     Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
794     break;
795   case Instruction::Or:
796     Result.markConstantRange(LHSRange.binaryOr(RHSRange));
797     break;
798   
799   // Unhandled instructions are overdefined.
800   default:
801     DEBUG(dbgs() << " compute BB '" << BB->getName()
802                  << "' - overdefined because inst def found.\n");
803     Result.markOverdefined();
804     break;
805   }
806   
807   BBLV = Result;
808   return true;
809 }
810
811 /// getEdgeValue - This method attempts to infer more complex 
812 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
813                                       BasicBlock *BBTo, LVILatticeVal &Result) {
814   // If already a constant, there is nothing to compute.
815   if (Constant *VC = dyn_cast<Constant>(Val)) {
816     Result = LVILatticeVal::get(VC);
817     return true;
818   }
819   
820   // TODO: Handle more complex conditionals.  If (v == 0 || v2 < 1) is false, we
821   // know that v != 0.
822   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
823     // If this is a conditional branch and only one successor goes to BBTo, then
824     // we maybe able to infer something from the condition. 
825     if (BI->isConditional() &&
826         BI->getSuccessor(0) != BI->getSuccessor(1)) {
827       bool isTrueDest = BI->getSuccessor(0) == BBTo;
828       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
829              "BBTo isn't a successor of BBFrom");
830       
831       // If V is the condition of the branch itself, then we know exactly what
832       // it is.
833       if (BI->getCondition() == Val) {
834         Result = LVILatticeVal::get(ConstantInt::get(
835                               Type::getInt1Ty(Val->getContext()), isTrueDest));
836         return true;
837       }
838       
839       // If the condition of the branch is an equality comparison, we may be
840       // able to infer the value.
841       ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
842       if (ICI && ICI->getOperand(0) == Val &&
843           isa<Constant>(ICI->getOperand(1))) {
844         if (ICI->isEquality()) {
845           // We know that V has the RHS constant if this is a true SETEQ or
846           // false SETNE. 
847           if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
848             Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
849           else
850             Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
851           return true;
852         }
853
854         if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
855           // Calculate the range of values that would satisfy the comparison.
856           ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
857           ConstantRange TrueValues =
858             ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
859
860           // If we're interested in the false dest, invert the condition.
861           if (!isTrueDest) TrueValues = TrueValues.inverse();
862           
863           // Figure out the possible values of the query BEFORE this branch.  
864           if (!hasBlockValue(Val, BBFrom)) {
865             BlockValueStack.push(std::make_pair(BBFrom, Val));
866             return false;
867           }
868           
869           LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
870           if (!InBlock.isConstantRange()) {
871             Result = LVILatticeVal::getRange(TrueValues);
872             return true;
873           }
874
875           // Find all potential values that satisfy both the input and output
876           // conditions.
877           ConstantRange PossibleValues =
878             TrueValues.intersectWith(InBlock.getConstantRange());
879
880           Result = LVILatticeVal::getRange(PossibleValues);
881           return true;
882         }
883       }
884     }
885   }
886
887   // If the edge was formed by a switch on the value, then we may know exactly
888   // what it is.
889   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
890     if (SI->getCondition() == Val) {
891       // We don't know anything in the default case.
892       if (SI->getDefaultDest() == BBTo) {
893         Result.markOverdefined();
894         return true;
895       }
896       
897       // We only know something if there is exactly one value that goes from
898       // BBFrom to BBTo.
899       unsigned NumEdges = 0;
900       ConstantInt *EdgeVal = 0;
901       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
902         if (SI->getSuccessor(i) != BBTo) continue;
903         if (NumEdges++) break;
904         EdgeVal = SI->getCaseValue(i);
905       }
906       assert(EdgeVal && "Missing successor?");
907       if (NumEdges == 1) {
908         Result = LVILatticeVal::get(EdgeVal);
909         return true;
910       }
911     }
912   }
913   
914   // Otherwise see if the value is known in the block.
915   if (hasBlockValue(Val, BBFrom)) {
916     Result = getBlockValue(Val, BBFrom);
917     return true;
918   }
919   BlockValueStack.push(std::make_pair(BBFrom, Val));
920   return false;
921 }
922
923 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
924   DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
925         << BB->getName() << "'\n");
926   
927   BlockValueStack.push(std::make_pair(BB, V));
928   solve();
929   LVILatticeVal Result = getBlockValue(V, BB);
930
931   DEBUG(dbgs() << "  Result = " << Result << "\n");
932   return Result;
933 }
934
935 LVILatticeVal LazyValueInfoCache::
936 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
937   DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
938         << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
939   
940   LVILatticeVal Result;
941   if (!getEdgeValue(V, FromBB, ToBB, Result)) {
942     solve();
943     bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
944     (void)WasFastQuery;
945     assert(WasFastQuery && "More work to do after problem solved?");
946   }
947
948   DEBUG(dbgs() << "  Result = " << Result << "\n");
949   return Result;
950 }
951
952 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
953                                     BasicBlock *NewSucc) {
954   // When an edge in the graph has been threaded, values that we could not 
955   // determine a value for before (i.e. were marked overdefined) may be possible
956   // to solve now.  We do NOT try to proactively update these values.  Instead,
957   // we clear their entries from the cache, and allow lazy updating to recompute
958   // them when needed.
959   
960   // The updating process is fairly simple: we need to dropped cached info
961   // for all values that were marked overdefined in OldSucc, and for those same
962   // values in any successor of OldSucc (except NewSucc) in which they were
963   // also marked overdefined.
964   std::vector<BasicBlock*> worklist;
965   worklist.push_back(OldSucc);
966   
967   DenseSet<Value*> ClearSet;
968   for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
969        E = OverDefinedCache.end(); I != E; ++I) {
970     if (I->first == OldSucc)
971       ClearSet.insert(I->second);
972   }
973   
974   // Use a worklist to perform a depth-first search of OldSucc's successors.
975   // NOTE: We do not need a visited list since any blocks we have already
976   // visited will have had their overdefined markers cleared already, and we
977   // thus won't loop to their successors.
978   while (!worklist.empty()) {
979     BasicBlock *ToUpdate = worklist.back();
980     worklist.pop_back();
981     
982     // Skip blocks only accessible through NewSucc.
983     if (ToUpdate == NewSucc) continue;
984     
985     bool changed = false;
986     for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
987          I != E; ++I) {
988       // If a value was marked overdefined in OldSucc, and is here too...
989       DenseSet<OverDefinedPairTy>::iterator OI =
990         OverDefinedCache.find(std::make_pair(ToUpdate, *I));
991       if (OI == OverDefinedCache.end()) continue;
992
993       // Remove it from the caches.
994       ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
995       ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
996
997       assert(CI != Entry.end() && "Couldn't find entry to update?");
998       Entry.erase(CI);
999       OverDefinedCache.erase(OI);
1000
1001       // If we removed anything, then we potentially need to update 
1002       // blocks successors too.
1003       changed = true;
1004     }
1005
1006     if (!changed) continue;
1007     
1008     worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1009   }
1010 }
1011
1012 //===----------------------------------------------------------------------===//
1013 //                            LazyValueInfo Impl
1014 //===----------------------------------------------------------------------===//
1015
1016 /// getCache - This lazily constructs the LazyValueInfoCache.
1017 static LazyValueInfoCache &getCache(void *&PImpl) {
1018   if (!PImpl)
1019     PImpl = new LazyValueInfoCache();
1020   return *static_cast<LazyValueInfoCache*>(PImpl);
1021 }
1022
1023 bool LazyValueInfo::runOnFunction(Function &F) {
1024   if (PImpl)
1025     getCache(PImpl).clear();
1026
1027   TD = getAnalysisIfAvailable<TargetData>();
1028   TLI = &getAnalysis<TargetLibraryInfo>();
1029
1030   // Fully lazy.
1031   return false;
1032 }
1033
1034 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1035   AU.setPreservesAll();
1036   AU.addRequired<TargetLibraryInfo>();
1037 }
1038
1039 void LazyValueInfo::releaseMemory() {
1040   // If the cache was allocated, free it.
1041   if (PImpl) {
1042     delete &getCache(PImpl);
1043     PImpl = 0;
1044   }
1045 }
1046
1047 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1048   LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1049   
1050   if (Result.isConstant())
1051     return Result.getConstant();
1052   if (Result.isConstantRange()) {
1053     ConstantRange CR = Result.getConstantRange();
1054     if (const APInt *SingleVal = CR.getSingleElement())
1055       return ConstantInt::get(V->getContext(), *SingleVal);
1056   }
1057   return 0;
1058 }
1059
1060 /// getConstantOnEdge - Determine whether the specified value is known to be a
1061 /// constant on the specified edge.  Return null if not.
1062 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1063                                            BasicBlock *ToBB) {
1064   LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1065   
1066   if (Result.isConstant())
1067     return Result.getConstant();
1068   if (Result.isConstantRange()) {
1069     ConstantRange CR = Result.getConstantRange();
1070     if (const APInt *SingleVal = CR.getSingleElement())
1071       return ConstantInt::get(V->getContext(), *SingleVal);
1072   }
1073   return 0;
1074 }
1075
1076 /// getPredicateOnEdge - Determine whether the specified value comparison
1077 /// with a constant is known to be true or false on the specified CFG edge.
1078 /// Pred is a CmpInst predicate.
1079 LazyValueInfo::Tristate
1080 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1081                                   BasicBlock *FromBB, BasicBlock *ToBB) {
1082   LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1083   
1084   // If we know the value is a constant, evaluate the conditional.
1085   Constant *Res = 0;
1086   if (Result.isConstant()) {
1087     Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD,
1088                                           TLI);
1089     if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1090       return ResCI->isZero() ? False : True;
1091     return Unknown;
1092   }
1093   
1094   if (Result.isConstantRange()) {
1095     ConstantInt *CI = dyn_cast<ConstantInt>(C);
1096     if (!CI) return Unknown;
1097     
1098     ConstantRange CR = Result.getConstantRange();
1099     if (Pred == ICmpInst::ICMP_EQ) {
1100       if (!CR.contains(CI->getValue()))
1101         return False;
1102       
1103       if (CR.isSingleElement() && CR.contains(CI->getValue()))
1104         return True;
1105     } else if (Pred == ICmpInst::ICMP_NE) {
1106       if (!CR.contains(CI->getValue()))
1107         return True;
1108       
1109       if (CR.isSingleElement() && CR.contains(CI->getValue()))
1110         return False;
1111     }
1112     
1113     // Handle more complex predicates.
1114     ConstantRange TrueValues =
1115         ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1116     if (TrueValues.contains(CR))
1117       return True;
1118     if (TrueValues.inverse().contains(CR))
1119       return False;
1120     return Unknown;
1121   }
1122   
1123   if (Result.isNotConstant()) {
1124     // If this is an equality comparison, we can try to fold it knowing that
1125     // "V != C1".
1126     if (Pred == ICmpInst::ICMP_EQ) {
1127       // !C1 == C -> false iff C1 == C.
1128       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1129                                             Result.getNotConstant(), C, TD,
1130                                             TLI);
1131       if (Res->isNullValue())
1132         return False;
1133     } else if (Pred == ICmpInst::ICMP_NE) {
1134       // !C1 != C -> true iff C1 == C.
1135       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1136                                             Result.getNotConstant(), C, TD,
1137                                             TLI);
1138       if (Res->isNullValue())
1139         return True;
1140     }
1141     return Unknown;
1142   }
1143   
1144   return Unknown;
1145 }
1146
1147 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1148                                BasicBlock *NewSucc) {
1149   if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1150 }
1151
1152 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1153   if (PImpl) getCache(PImpl).eraseBlock(BB);
1154 }