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