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