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