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