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