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