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/LLVMContext.h"
30 #include "llvm/IR/PatternMatch.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <map>
35 #include <stack>
36 using namespace llvm;
37 using namespace PatternMatch;
38 
39 #define DEBUG_TYPE "lazy-value-info"
40 
41 char LazyValueInfo::ID = 0;
42 INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
43                 "Lazy Value Information Analysis", false, true)
44 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
45 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
46 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
47                 "Lazy Value Information Analysis", false, true)
48 
49 namespace llvm {
50   FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
51 }
52 
53 
54 //===----------------------------------------------------------------------===//
55 //                               LVILatticeVal
56 //===----------------------------------------------------------------------===//
57 
58 /// This is the information tracked by LazyValueInfo for each value.
59 ///
60 /// FIXME: This is basically just for bringup, this can be made a lot more rich
61 /// in the future.
62 ///
63 namespace {
64 class LVILatticeVal {
65   enum LatticeValueTy {
66     /// This Value has no known value yet.
67     undefined,
68 
69     /// This Value has a specific constant value.
70     constant,
71 
72     /// This Value is known to not have the specified value.
73     notconstant,
74 
75     /// The Value falls within this range.
76     constantrange,
77 
78     /// This value is not known to be constant, and we know that it has a value.
79     overdefined
80   };
81 
82   /// Val: This stores the current lattice value along with the Constant* for
83   /// the constant if this is a 'constant' or 'notconstant' value.
84   LatticeValueTy Tag;
85   Constant *Val;
86   ConstantRange Range;
87 
88 public:
89   LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
90 
91   static LVILatticeVal get(Constant *C) {
92     LVILatticeVal Res;
93     if (!isa<UndefValue>(C))
94       Res.markConstant(C);
95     return Res;
96   }
97   static LVILatticeVal getNot(Constant *C) {
98     LVILatticeVal Res;
99     if (!isa<UndefValue>(C))
100       Res.markNotConstant(C);
101     return Res;
102   }
103   static LVILatticeVal getRange(ConstantRange CR) {
104     LVILatticeVal Res;
105     Res.markConstantRange(std::move(CR));
106     return Res;
107   }
108   static LVILatticeVal getOverdefined() {
109     LVILatticeVal Res;
110     Res.markOverdefined();
111     return Res;
112   }
113 
114   bool isUndefined() const     { return Tag == undefined; }
115   bool isConstant() const      { return Tag == constant; }
116   bool isNotConstant() const   { return Tag == notconstant; }
117   bool isConstantRange() const { return Tag == constantrange; }
118   bool isOverdefined() const   { return Tag == overdefined; }
119 
120   Constant *getConstant() const {
121     assert(isConstant() && "Cannot get the constant of a non-constant!");
122     return Val;
123   }
124 
125   Constant *getNotConstant() const {
126     assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
127     return Val;
128   }
129 
130   ConstantRange getConstantRange() const {
131     assert(isConstantRange() &&
132            "Cannot get the constant-range of a non-constant-range!");
133     return Range;
134   }
135 
136   /// Return true if this is a change in status.
137   bool markOverdefined() {
138     if (isOverdefined())
139       return false;
140     Tag = overdefined;
141     return true;
142   }
143 
144   /// Return true if this is a change in status.
145   bool markConstant(Constant *V) {
146     assert(V && "Marking constant with NULL");
147     if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
148       return markConstantRange(ConstantRange(CI->getValue()));
149     if (isa<UndefValue>(V))
150       return false;
151 
152     assert((!isConstant() || getConstant() == V) &&
153            "Marking constant with different value");
154     assert(isUndefined());
155     Tag = constant;
156     Val = V;
157     return true;
158   }
159 
160   /// Return true if this is a change in status.
161   bool markNotConstant(Constant *V) {
162     assert(V && "Marking constant with NULL");
163     if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
164       return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
165     if (isa<UndefValue>(V))
166       return false;
167 
168     assert((!isConstant() || getConstant() != V) &&
169            "Marking constant !constant with same value");
170     assert((!isNotConstant() || getNotConstant() == V) &&
171            "Marking !constant with different value");
172     assert(isUndefined() || isConstant());
173     Tag = notconstant;
174     Val = V;
175     return true;
176   }
177 
178   /// Return true if this is a change in status.
179   bool markConstantRange(ConstantRange NewR) {
180     if (isConstantRange()) {
181       if (NewR.isEmptySet())
182         return markOverdefined();
183 
184       bool changed = Range != NewR;
185       Range = std::move(NewR);
186       return changed;
187     }
188 
189     assert(isUndefined());
190     if (NewR.isEmptySet())
191       return markOverdefined();
192 
193     Tag = constantrange;
194     Range = std::move(NewR);
195     return true;
196   }
197 
198   /// Merge the specified lattice value into this one, updating this
199   /// one and returning true if anything changed.
200   bool mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
201     if (RHS.isUndefined() || isOverdefined()) return false;
202     if (RHS.isOverdefined()) return markOverdefined();
203 
204     if (isUndefined()) {
205       Tag = RHS.Tag;
206       Val = RHS.Val;
207       Range = RHS.Range;
208       return true;
209     }
210 
211     if (isConstant()) {
212       if (RHS.isConstant()) {
213         if (Val == RHS.Val)
214           return false;
215         return markOverdefined();
216       }
217 
218       if (RHS.isNotConstant()) {
219         if (Val == RHS.Val)
220           return markOverdefined();
221 
222         // Unless we can prove that the two Constants are different, we must
223         // move to overdefined.
224         if (ConstantInt *Res =
225                 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
226                     CmpInst::ICMP_NE, getConstant(), RHS.getNotConstant(), DL)))
227           if (Res->isOne())
228             return markNotConstant(RHS.getNotConstant());
229 
230         return markOverdefined();
231       }
232 
233       // RHS is a ConstantRange, LHS is a non-integer Constant.
234 
235       // FIXME: consider the case where RHS is a range [1, 0) and LHS is
236       // a function. The correct result is to pick up RHS.
237 
238       return markOverdefined();
239     }
240 
241     if (isNotConstant()) {
242       if (RHS.isConstant()) {
243         if (Val == RHS.Val)
244           return markOverdefined();
245 
246         // Unless we can prove that the two Constants are different, we must
247         // move to overdefined.
248         if (ConstantInt *Res =
249                 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
250                     CmpInst::ICMP_NE, getNotConstant(), RHS.getConstant(), DL)))
251           if (Res->isOne())
252             return false;
253 
254         return markOverdefined();
255       }
256 
257       if (RHS.isNotConstant()) {
258         if (Val == RHS.Val)
259           return false;
260         return markOverdefined();
261       }
262 
263       return markOverdefined();
264     }
265 
266     assert(isConstantRange() && "New LVILattice type?");
267     if (!RHS.isConstantRange())
268       return markOverdefined();
269 
270     ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
271     if (NewR.isFullSet())
272       return markOverdefined();
273     return markConstantRange(NewR);
274   }
275 };
276 
277 } // end anonymous namespace.
278 
279 namespace llvm {
280 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
281     LLVM_ATTRIBUTE_USED;
282 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
283   if (Val.isUndefined())
284     return OS << "undefined";
285   if (Val.isOverdefined())
286     return OS << "overdefined";
287 
288   if (Val.isNotConstant())
289     return OS << "notconstant<" << *Val.getNotConstant() << '>';
290   else if (Val.isConstantRange())
291     return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
292               << Val.getConstantRange().getUpper() << '>';
293   return OS << "constant<" << *Val.getConstant() << '>';
294 }
295 }
296 
297 /// Returns true if this lattice value represents at most one possible value.
298 /// This is as precise as any lattice value can get while still representing
299 /// reachable code.
300 static bool hasSingleValue(LVILatticeVal Val) {
301   if (Val.isConstantRange() &&
302       Val.getConstantRange().isSingleElement())
303     // Integer constants are single element ranges
304     return true;
305   if (Val.isConstant())
306     // Non integer constants
307     return true;
308   return false;
309 }
310 
311 /// Combine two sets of facts about the same value into a single set of
312 /// facts.  Note that this method is not suitable for merging facts along
313 /// different paths in a CFG; that's what the mergeIn function is for.  This
314 /// is for merging facts gathered about the same value at the same location
315 /// through two independent means.
316 /// Notes:
317 /// * This method does not promise to return the most precise possible lattice
318 ///   value implied by A and B.  It is allowed to return any lattice element
319 ///   which is at least as strong as *either* A or B (unless our facts
320 ///   conflict, see below).
321 /// * Due to unreachable code, the intersection of two lattice values could be
322 ///   contradictory.  If this happens, we return some valid lattice value so as
323 ///   not confuse the rest of LVI.  Ideally, we'd always return Undefined, but
324 ///   we do not make this guarantee.  TODO: This would be a useful enhancement.
325 static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
326   // Undefined is the strongest state.  It means the value is known to be along
327   // an unreachable path.
328   if (A.isUndefined())
329     return A;
330   if (B.isUndefined())
331     return B;
332 
333   // If we gave up for one, but got a useable fact from the other, use it.
334   if (A.isOverdefined())
335     return B;
336   if (B.isOverdefined())
337     return A;
338 
339   // Can't get any more precise than constants.
340   if (hasSingleValue(A))
341     return A;
342   if (hasSingleValue(B))
343     return B;
344 
345   // Could be either constant range or not constant here.
346   if (!A.isConstantRange() || !B.isConstantRange()) {
347     // TODO: Arbitrary choice, could be improved
348     return A;
349   }
350 
351   // Intersect two constant ranges
352   ConstantRange Range =
353     A.getConstantRange().intersectWith(B.getConstantRange());
354   // Note: An empty range is implicitly converted to overdefined internally.
355   // TODO: We could instead use Undefined here since we've proven a conflict
356   // and thus know this path must be unreachable.
357   return LVILatticeVal::getRange(std::move(Range));
358 }
359 
360 //===----------------------------------------------------------------------===//
361 //                          LazyValueInfoCache Decl
362 //===----------------------------------------------------------------------===//
363 
364 namespace {
365   /// A callback value handle updates the cache when values are erased.
366   class LazyValueInfoCache;
367   struct LVIValueHandle final : public CallbackVH {
368     LazyValueInfoCache *Parent;
369 
370     LVIValueHandle(Value *V, LazyValueInfoCache *P)
371       : CallbackVH(V), Parent(P) { }
372 
373     void deleted() override;
374     void allUsesReplacedWith(Value *V) override {
375       deleted();
376     }
377   };
378 }
379 
380 namespace {
381   /// This is the cache kept by LazyValueInfo which
382   /// maintains information about queries across the clients' queries.
383   class LazyValueInfoCache {
384     /// This is all of the cached block information for exactly one Value*.
385     /// The entries are sorted by the BasicBlock* of the
386     /// entries, allowing us to do a lookup with a binary search.
387     /// Over-defined lattice values are recorded in OverDefinedCache to reduce
388     /// memory overhead.
389     typedef SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4>
390         ValueCacheEntryTy;
391 
392     /// This is all of the cached information for all values,
393     /// mapped from Value* to key information.
394     std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
395 
396     /// This tracks, on a per-block basis, the set of values that are
397     /// over-defined at the end of that block.
398     typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
399         OverDefinedCacheTy;
400     OverDefinedCacheTy OverDefinedCache;
401 
402     /// Keep track of all blocks that we have ever seen, so we
403     /// don't spend time removing unused blocks from our caches.
404     DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
405 
406     /// This stack holds the state of the value solver during a query.
407     /// It basically emulates the callstack of the naive
408     /// recursive value lookup process.
409     std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
410 
411     /// Keeps track of which block-value pairs are in BlockValueStack.
412     DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
413 
414     /// Push BV onto BlockValueStack unless it's already in there.
415     /// Returns true on success.
416     bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
417       if (!BlockValueSet.insert(BV).second)
418         return false;  // It's already in the stack.
419 
420       DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
421                    << "\n");
422       BlockValueStack.push(BV);
423       return true;
424     }
425 
426     AssumptionCache *AC;  ///< A pointer to the cache of @llvm.assume calls.
427     const DataLayout &DL; ///< A mandatory DataLayout
428     DominatorTree *DT;    ///< An optional DT pointer.
429 
430     friend struct LVIValueHandle;
431 
432     void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
433       SeenBlocks.insert(BB);
434 
435       // Insert over-defined values into their own cache to reduce memory
436       // overhead.
437       if (Result.isOverdefined())
438         OverDefinedCache[BB].insert(Val);
439       else
440         lookup(Val)[BB] = Result;
441     }
442 
443     LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
444     bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
445                       LVILatticeVal &Result,
446                       Instruction *CxtI = nullptr);
447     bool hasBlockValue(Value *Val, BasicBlock *BB);
448 
449     // These methods process one work item and may add more. A false value
450     // returned means that the work item was not completely processed and must
451     // be revisited after going through the new items.
452     bool solveBlockValue(Value *Val, BasicBlock *BB);
453     bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
454                                  Value *Val, BasicBlock *BB);
455     bool solveBlockValuePHINode(LVILatticeVal &BBLV,
456                                 PHINode *PN, BasicBlock *BB);
457     bool solveBlockValueSelect(LVILatticeVal &BBLV,
458                                SelectInst *S, BasicBlock *BB);
459     bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
460                                       Instruction *BBI, BasicBlock *BB);
461     void intersectAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
462                                             Instruction *BBI);
463 
464     void solve();
465 
466     ValueCacheEntryTy &lookup(Value *V) {
467       return ValueCache[LVIValueHandle(V, this)];
468     }
469 
470     bool isOverdefined(Value *V, BasicBlock *BB) const {
471       auto ODI = OverDefinedCache.find(BB);
472 
473       if (ODI == OverDefinedCache.end())
474         return false;
475 
476       return ODI->second.count(V);
477     }
478 
479     bool hasCachedValueInfo(Value *V, BasicBlock *BB) {
480       if (isOverdefined(V, BB))
481         return true;
482 
483       LVIValueHandle ValHandle(V, this);
484       auto I = ValueCache.find(ValHandle);
485       if (I == ValueCache.end())
486         return false;
487 
488       return I->second.count(BB);
489     }
490 
491     LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) {
492       if (isOverdefined(V, BB))
493         return LVILatticeVal::getOverdefined();
494 
495       return lookup(V)[BB];
496     }
497 
498   public:
499     /// This is the query interface to determine the lattice
500     /// value for the specified Value* at the end of the specified block.
501     LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
502                                   Instruction *CxtI = nullptr);
503 
504     /// This is the query interface to determine the lattice
505     /// value for the specified Value* at the specified instruction (generally
506     /// from an assume intrinsic).
507     LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
508 
509     /// This is the query interface to determine the lattice
510     /// value for the specified Value* that is true on the specified edge.
511     LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
512                                  Instruction *CxtI = nullptr);
513 
514     /// This is the update interface to inform the cache that an edge from
515     /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
516     void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
517 
518     /// This is part of the update interface to inform the cache
519     /// that a block has been deleted.
520     void eraseBlock(BasicBlock *BB);
521 
522     /// clear - Empty the cache.
523     void clear() {
524       SeenBlocks.clear();
525       ValueCache.clear();
526       OverDefinedCache.clear();
527     }
528 
529     LazyValueInfoCache(AssumptionCache *AC, const DataLayout &DL,
530                        DominatorTree *DT = nullptr)
531         : AC(AC), DL(DL), DT(DT) {}
532   };
533 } // end anonymous namespace
534 
535 void LVIValueHandle::deleted() {
536   SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
537   for (auto &I : Parent->OverDefinedCache) {
538     SmallPtrSetImpl<Value *> &ValueSet = I.second;
539     if (ValueSet.count(getValPtr()))
540       ValueSet.erase(getValPtr());
541     if (ValueSet.empty())
542       ToErase.push_back(I.first);
543   }
544   for (auto &BB : ToErase)
545     Parent->OverDefinedCache.erase(BB);
546 
547   // This erasure deallocates *this, so it MUST happen after we're done
548   // using any and all members of *this.
549   Parent->ValueCache.erase(*this);
550 }
551 
552 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
553   // Shortcut if we have never seen this block.
554   DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
555   if (I == SeenBlocks.end())
556     return;
557   SeenBlocks.erase(I);
558 
559   auto ODI = OverDefinedCache.find(BB);
560   if (ODI != OverDefinedCache.end())
561     OverDefinedCache.erase(ODI);
562 
563   for (auto I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
564     I->second.erase(BB);
565 }
566 
567 void LazyValueInfoCache::solve() {
568   while (!BlockValueStack.empty()) {
569     std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
570     assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
571 
572     if (solveBlockValue(e.second, e.first)) {
573       // The work item was completely processed.
574       assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
575       assert(hasCachedValueInfo(e.second, e.first) &&
576              "Result should be in cache!");
577 
578       DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
579                    << " = " << getCachedValueInfo(e.second, e.first) << "\n");
580 
581       BlockValueStack.pop();
582       BlockValueSet.erase(e);
583     } else {
584       // More work needs to be done before revisiting.
585       assert(BlockValueStack.top() != e && "Stack should have been pushed!");
586     }
587   }
588 }
589 
590 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
591   // If already a constant, there is nothing to compute.
592   if (isa<Constant>(Val))
593     return true;
594 
595   return hasCachedValueInfo(Val, BB);
596 }
597 
598 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
599   // If already a constant, there is nothing to compute.
600   if (Constant *VC = dyn_cast<Constant>(Val))
601     return LVILatticeVal::get(VC);
602 
603   SeenBlocks.insert(BB);
604   return getCachedValueInfo(Val, BB);
605 }
606 
607 static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
608   switch (BBI->getOpcode()) {
609   default: break;
610   case Instruction::Load:
611   case Instruction::Call:
612   case Instruction::Invoke:
613     if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
614       if (isa<IntegerType>(BBI->getType())) {
615         return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
616       }
617     break;
618   };
619   // Nothing known - will be intersected with other facts
620   return LVILatticeVal::getOverdefined();
621 }
622 
623 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
624   if (isa<Constant>(Val))
625     return true;
626 
627   if (hasCachedValueInfo(Val, BB)) {
628     // If we have a cached value, use that.
629     DEBUG(dbgs() << "  reuse BB '" << BB->getName()
630                  << "' val=" << getCachedValueInfo(Val, BB) << '\n');
631 
632     // Since we're reusing a cached value, we don't need to update the
633     // OverDefinedCache. The cache will have been properly updated whenever the
634     // cached value was inserted.
635     return true;
636   }
637 
638   // Hold off inserting this value into the Cache in case we have to return
639   // false and come back later.
640   LVILatticeVal Res;
641 
642   Instruction *BBI = dyn_cast<Instruction>(Val);
643   if (!BBI || BBI->getParent() != BB) {
644     if (!solveBlockValueNonLocal(Res, Val, BB))
645       return false;
646    insertResult(Val, BB, Res);
647    return true;
648   }
649 
650   if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
651     if (!solveBlockValuePHINode(Res, PN, BB))
652       return false;
653     insertResult(Val, BB, Res);
654     return true;
655   }
656 
657   if (auto *SI = dyn_cast<SelectInst>(BBI)) {
658     if (!solveBlockValueSelect(Res, SI, BB))
659       return false;
660     insertResult(Val, BB, Res);
661     return true;
662   }
663 
664   // If this value is a nonnull pointer, record it's range and bailout.
665   PointerType *PT = dyn_cast<PointerType>(BBI->getType());
666   if (PT && isKnownNonNull(BBI)) {
667     Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
668     insertResult(Val, BB, Res);
669     return true;
670   }
671 
672   if (isa<CastInst>(BBI) && BBI->getType()->isIntegerTy()) {
673     if (!solveBlockValueConstantRange(Res, BBI, BB))
674       return false;
675     insertResult(Val, BB, Res);
676     return true;
677   }
678 
679   BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
680   if (BO && isa<ConstantInt>(BO->getOperand(1))) {
681     if (!solveBlockValueConstantRange(Res, BBI, BB))
682       return false;
683     insertResult(Val, BB, Res);
684     return true;
685   }
686 
687   DEBUG(dbgs() << " compute BB '" << BB->getName()
688                  << "' - unknown inst def found.\n");
689   Res = getFromRangeMetadata(BBI);
690   insertResult(Val, BB, Res);
691   return true;
692 }
693 
694 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
695   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
696     return L->getPointerAddressSpace() == 0 &&
697            GetUnderlyingObject(L->getPointerOperand(),
698                                L->getModule()->getDataLayout()) == Ptr;
699   }
700   if (StoreInst *S = dyn_cast<StoreInst>(I)) {
701     return S->getPointerAddressSpace() == 0 &&
702            GetUnderlyingObject(S->getPointerOperand(),
703                                S->getModule()->getDataLayout()) == Ptr;
704   }
705   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
706     if (MI->isVolatile()) return false;
707 
708     // FIXME: check whether it has a valuerange that excludes zero?
709     ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
710     if (!Len || Len->isZero()) return false;
711 
712     if (MI->getDestAddressSpace() == 0)
713       if (GetUnderlyingObject(MI->getRawDest(),
714                               MI->getModule()->getDataLayout()) == Ptr)
715         return true;
716     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
717       if (MTI->getSourceAddressSpace() == 0)
718         if (GetUnderlyingObject(MTI->getRawSource(),
719                                 MTI->getModule()->getDataLayout()) == Ptr)
720           return true;
721   }
722   return false;
723 }
724 
725 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
726                                                  Value *Val, BasicBlock *BB) {
727   LVILatticeVal Result;  // Start Undefined.
728 
729   // If this is a pointer, and there's a load from that pointer in this BB,
730   // then we know that the pointer can't be NULL.
731   bool NotNull = false;
732   if (Val->getType()->isPointerTy()) {
733     if (isKnownNonNull(Val)) {
734       NotNull = true;
735     } else {
736       const DataLayout &DL = BB->getModule()->getDataLayout();
737       Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
738       // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
739       // inside InstructionDereferencesPointer either.
740       if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1)) {
741         for (Instruction &I : *BB) {
742           if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
743             NotNull = true;
744             break;
745           }
746         }
747       }
748     }
749   }
750 
751   // If this is the entry block, we must be asking about an argument.  The
752   // value is overdefined.
753   if (BB == &BB->getParent()->getEntryBlock()) {
754     assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
755     if (NotNull) {
756       PointerType *PTy = cast<PointerType>(Val->getType());
757       Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
758     } else {
759       Result.markOverdefined();
760     }
761     BBLV = Result;
762     return true;
763   }
764 
765   // Loop over all of our predecessors, merging what we know from them into
766   // result.
767   bool EdgesMissing = false;
768   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
769     LVILatticeVal EdgeResult;
770     EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
771     if (EdgesMissing)
772       continue;
773 
774     Result.mergeIn(EdgeResult, DL);
775 
776     // If we hit overdefined, exit early.  The BlockVals entry is already set
777     // to overdefined.
778     if (Result.isOverdefined()) {
779       DEBUG(dbgs() << " compute BB '" << BB->getName()
780             << "' - overdefined because of pred (non local).\n");
781       // If we previously determined that this is a pointer that can't be null
782       // then return that rather than giving up entirely.
783       if (NotNull) {
784         PointerType *PTy = cast<PointerType>(Val->getType());
785         Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
786       }
787 
788       BBLV = Result;
789       return true;
790     }
791   }
792   if (EdgesMissing)
793     return false;
794 
795   // Return the merged value, which is more precise than 'overdefined'.
796   assert(!Result.isOverdefined());
797   BBLV = Result;
798   return true;
799 }
800 
801 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
802                                                 PHINode *PN, BasicBlock *BB) {
803   LVILatticeVal Result;  // Start Undefined.
804 
805   // Loop over all of our predecessors, merging what we know from them into
806   // result.
807   bool EdgesMissing = false;
808   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
809     BasicBlock *PhiBB = PN->getIncomingBlock(i);
810     Value *PhiVal = PN->getIncomingValue(i);
811     LVILatticeVal EdgeResult;
812     // Note that we can provide PN as the context value to getEdgeValue, even
813     // though the results will be cached, because PN is the value being used as
814     // the cache key in the caller.
815     EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
816     if (EdgesMissing)
817       continue;
818 
819     Result.mergeIn(EdgeResult, DL);
820 
821     // If we hit overdefined, exit early.  The BlockVals entry is already set
822     // to overdefined.
823     if (Result.isOverdefined()) {
824       DEBUG(dbgs() << " compute BB '" << BB->getName()
825             << "' - overdefined because of pred (local).\n");
826 
827       BBLV = Result;
828       return true;
829     }
830   }
831   if (EdgesMissing)
832     return false;
833 
834   // Return the merged value, which is more precise than 'overdefined'.
835   assert(!Result.isOverdefined() && "Possible PHI in entry block?");
836   BBLV = Result;
837   return true;
838 }
839 
840 static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
841                                       LVILatticeVal &Result,
842                                       bool isTrueDest = true);
843 
844 // If we can determine a constraint on the value given conditions assumed by
845 // the program, intersect those constraints with BBLV
846 void LazyValueInfoCache::intersectAssumeBlockValueConstantRange(Value *Val,
847                                                             LVILatticeVal &BBLV,
848                                                             Instruction *BBI) {
849   BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
850   if (!BBI)
851     return;
852 
853   for (auto &AssumeVH : AC->assumptions()) {
854     if (!AssumeVH)
855       continue;
856     auto *I = cast<CallInst>(AssumeVH);
857     if (!isValidAssumeForContext(I, BBI, DT))
858       continue;
859 
860     Value *C = I->getArgOperand(0);
861     if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
862       LVILatticeVal Result;
863       if (getValueFromFromCondition(Val, ICI, Result))
864         BBLV = intersect(BBLV, Result);
865     }
866   }
867 }
868 
869 bool LazyValueInfoCache::solveBlockValueSelect(LVILatticeVal &BBLV,
870                                                SelectInst *SI, BasicBlock *BB) {
871 
872   // Recurse on our inputs if needed
873   if (!hasBlockValue(SI->getTrueValue(), BB)) {
874     if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
875       return false;
876     BBLV.markOverdefined();
877     return true;
878   }
879   LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
880   // If we hit overdefined, don't ask more queries.  We want to avoid poisoning
881   // extra slots in the table if we can.
882   if (TrueVal.isOverdefined()) {
883     BBLV.markOverdefined();
884     return true;
885   }
886 
887   if (!hasBlockValue(SI->getFalseValue(), BB)) {
888     if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
889       return false;
890     BBLV.markOverdefined();
891     return true;
892   }
893   LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
894   // If we hit overdefined, don't ask more queries.  We want to avoid poisoning
895   // extra slots in the table if we can.
896   if (FalseVal.isOverdefined()) {
897     BBLV.markOverdefined();
898     return true;
899   }
900 
901   if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
902     ConstantRange TrueCR = TrueVal.getConstantRange();
903     ConstantRange FalseCR = FalseVal.getConstantRange();
904     Value *LHS = nullptr;
905     Value *RHS = nullptr;
906     SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
907     // Is this a min specifically of our two inputs?  (Avoid the risk of
908     // ValueTracking getting smarter looking back past our immediate inputs.)
909     if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
910         LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
911       switch (SPR.Flavor) {
912       default:
913         llvm_unreachable("unexpected minmax type!");
914       case SPF_SMIN:                   /// Signed minimum
915         BBLV.markConstantRange(TrueCR.smin(FalseCR));
916         return true;
917       case SPF_UMIN:                   /// Unsigned minimum
918         BBLV.markConstantRange(TrueCR.umin(FalseCR));
919         return true;
920       case SPF_SMAX:                   /// Signed maximum
921         BBLV.markConstantRange(TrueCR.smax(FalseCR));
922         return true;
923       case SPF_UMAX:                   /// Unsigned maximum
924         BBLV.markConstantRange(TrueCR.umax(FalseCR));
925         return true;
926       };
927     }
928 
929     // TODO: ABS, NABS from the SelectPatternResult
930   }
931 
932   // Can we constrain the facts about the true and false values by using the
933   // condition itself?  This shows up with idioms like e.g. select(a > 5, a, 5).
934   // TODO: We could potentially refine an overdefined true value above.
935   if (auto *ICI = dyn_cast<ICmpInst>(SI->getCondition())) {
936     LVILatticeVal TrueValTaken, FalseValTaken;
937     if (!getValueFromFromCondition(SI->getTrueValue(), ICI,
938                                    TrueValTaken, true))
939       TrueValTaken.markOverdefined();
940     if (!getValueFromFromCondition(SI->getFalseValue(), ICI,
941                                    FalseValTaken, false))
942       FalseValTaken.markOverdefined();
943 
944     TrueVal = intersect(TrueVal, TrueValTaken);
945     FalseVal = intersect(FalseVal, FalseValTaken);
946 
947 
948     // Handle clamp idioms such as:
949     //   %24 = constantrange<0, 17>
950     //   %39 = icmp eq i32 %24, 0
951     //   %40 = add i32 %24, -1
952     //   %siv.next = select i1 %39, i32 16, i32 %40
953     //   %siv.next = constantrange<0, 17> not <-1, 17>
954     // In general, this can handle any clamp idiom which tests the edge
955     // condition via an equality or inequality.
956     ICmpInst::Predicate Pred = ICI->getPredicate();
957     Value *A = ICI->getOperand(0);
958     if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
959       auto addConstants = [](ConstantInt *A, ConstantInt *B) {
960         assert(A->getType() == B->getType());
961         return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
962       };
963       // See if either input is A + C2, subject to the constraint from the
964       // condition that A != C when that input is used.  We can assume that
965       // that input doesn't include C + C2.
966       ConstantInt *CIAdded;
967       switch (Pred) {
968       default: break;
969       case ICmpInst::ICMP_EQ:
970         if (match(SI->getFalseValue(), m_Add(m_Specific(A),
971                                              m_ConstantInt(CIAdded)))) {
972           auto ResNot = addConstants(CIBase, CIAdded);
973           FalseVal = intersect(FalseVal,
974                                LVILatticeVal::getNot(ResNot));
975         }
976         break;
977       case ICmpInst::ICMP_NE:
978         if (match(SI->getTrueValue(), m_Add(m_Specific(A),
979                                             m_ConstantInt(CIAdded)))) {
980           auto ResNot = addConstants(CIBase, CIAdded);
981           TrueVal = intersect(TrueVal,
982                               LVILatticeVal::getNot(ResNot));
983         }
984         break;
985       };
986     }
987   }
988 
989   LVILatticeVal Result;  // Start Undefined.
990   Result.mergeIn(TrueVal, DL);
991   Result.mergeIn(FalseVal, DL);
992   BBLV = Result;
993   return true;
994 }
995 
996 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
997                                                       Instruction *BBI,
998                                                       BasicBlock *BB) {
999   // Figure out the range of the LHS.  If that fails, bail.
1000   if (!hasBlockValue(BBI->getOperand(0), BB)) {
1001     if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
1002       return false;
1003     BBLV.markOverdefined();
1004     return true;
1005   }
1006 
1007   LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
1008   intersectAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
1009   if (!LHSVal.isConstantRange()) {
1010     BBLV.markOverdefined();
1011     return true;
1012   }
1013 
1014   ConstantRange LHSRange = LHSVal.getConstantRange();
1015   ConstantRange RHSRange(1);
1016   IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
1017   if (isa<BinaryOperator>(BBI)) {
1018     if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
1019       RHSRange = ConstantRange(RHS->getValue());
1020     } else {
1021       BBLV.markOverdefined();
1022       return true;
1023     }
1024   }
1025 
1026   // NOTE: We're currently limited by the set of operations that ConstantRange
1027   // can evaluate symbolically.  Enhancing that set will allows us to analyze
1028   // more definitions.
1029   LVILatticeVal Result;
1030   switch (BBI->getOpcode()) {
1031   case Instruction::Add:
1032     Result.markConstantRange(LHSRange.add(RHSRange));
1033     break;
1034   case Instruction::Sub:
1035     Result.markConstantRange(LHSRange.sub(RHSRange));
1036     break;
1037   case Instruction::Mul:
1038     Result.markConstantRange(LHSRange.multiply(RHSRange));
1039     break;
1040   case Instruction::UDiv:
1041     Result.markConstantRange(LHSRange.udiv(RHSRange));
1042     break;
1043   case Instruction::Shl:
1044     Result.markConstantRange(LHSRange.shl(RHSRange));
1045     break;
1046   case Instruction::LShr:
1047     Result.markConstantRange(LHSRange.lshr(RHSRange));
1048     break;
1049   case Instruction::Trunc:
1050     Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
1051     break;
1052   case Instruction::SExt:
1053     Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
1054     break;
1055   case Instruction::ZExt:
1056     Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
1057     break;
1058   case Instruction::BitCast:
1059     Result.markConstantRange(LHSRange);
1060     break;
1061   case Instruction::And:
1062     Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
1063     break;
1064   case Instruction::Or:
1065     Result.markConstantRange(LHSRange.binaryOr(RHSRange));
1066     break;
1067 
1068   // Unhandled instructions are overdefined.
1069   default:
1070     DEBUG(dbgs() << " compute BB '" << BB->getName()
1071                  << "' - overdefined because inst def found.\n");
1072     Result.markOverdefined();
1073     break;
1074   }
1075 
1076   BBLV = Result;
1077   return true;
1078 }
1079 
1080 bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
1081                                LVILatticeVal &Result, bool isTrueDest) {
1082   if (ICI && isa<Constant>(ICI->getOperand(1))) {
1083     if (ICI->isEquality() && ICI->getOperand(0) == Val) {
1084       // We know that V has the RHS constant if this is a true SETEQ or
1085       // false SETNE.
1086       if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
1087         Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
1088       else
1089         Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
1090       return true;
1091     }
1092 
1093     // Recognize the range checking idiom that InstCombine produces.
1094     // (X-C1) u< C2 --> [C1, C1+C2)
1095     ConstantInt *NegOffset = nullptr;
1096     if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
1097       match(ICI->getOperand(0), m_Add(m_Specific(Val),
1098                                       m_ConstantInt(NegOffset)));
1099 
1100     ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
1101     if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
1102       // Calculate the range of values that are allowed by the comparison
1103       ConstantRange CmpRange(CI->getValue());
1104       ConstantRange TrueValues =
1105           ConstantRange::makeAllowedICmpRegion(ICI->getPredicate(), CmpRange);
1106 
1107       if (NegOffset) // Apply the offset from above.
1108         TrueValues = TrueValues.subtract(NegOffset->getValue());
1109 
1110       // If we're interested in the false dest, invert the condition.
1111       if (!isTrueDest) TrueValues = TrueValues.inverse();
1112 
1113       Result = LVILatticeVal::getRange(std::move(TrueValues));
1114       return true;
1115     }
1116   }
1117 
1118   return false;
1119 }
1120 
1121 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
1122 /// Val is not constrained on the edge.  Result is unspecified if return value
1123 /// is false.
1124 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1125                               BasicBlock *BBTo, LVILatticeVal &Result) {
1126   // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1127   // know that v != 0.
1128   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1129     // If this is a conditional branch and only one successor goes to BBTo, then
1130     // we may be able to infer something from the condition.
1131     if (BI->isConditional() &&
1132         BI->getSuccessor(0) != BI->getSuccessor(1)) {
1133       bool isTrueDest = BI->getSuccessor(0) == BBTo;
1134       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1135              "BBTo isn't a successor of BBFrom");
1136 
1137       // If V is the condition of the branch itself, then we know exactly what
1138       // it is.
1139       if (BI->getCondition() == Val) {
1140         Result = LVILatticeVal::get(ConstantInt::get(
1141                               Type::getInt1Ty(Val->getContext()), isTrueDest));
1142         return true;
1143       }
1144 
1145       // If the condition of the branch is an equality comparison, we may be
1146       // able to infer the value.
1147       if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
1148         if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
1149           return true;
1150     }
1151   }
1152 
1153   // If the edge was formed by a switch on the value, then we may know exactly
1154   // what it is.
1155   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1156     if (SI->getCondition() != Val)
1157       return false;
1158 
1159     bool DefaultCase = SI->getDefaultDest() == BBTo;
1160     unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1161     ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1162 
1163     for (SwitchInst::CaseIt i : SI->cases()) {
1164       ConstantRange EdgeVal(i.getCaseValue()->getValue());
1165       if (DefaultCase) {
1166         // It is possible that the default destination is the destination of
1167         // some cases. There is no need to perform difference for those cases.
1168         if (i.getCaseSuccessor() != BBTo)
1169           EdgesVals = EdgesVals.difference(EdgeVal);
1170       } else if (i.getCaseSuccessor() == BBTo)
1171         EdgesVals = EdgesVals.unionWith(EdgeVal);
1172     }
1173     Result = LVILatticeVal::getRange(std::move(EdgesVals));
1174     return true;
1175   }
1176   return false;
1177 }
1178 
1179 /// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1180 /// the basic block if the edge does not constrain Val.
1181 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
1182                                       BasicBlock *BBTo, LVILatticeVal &Result,
1183                                       Instruction *CxtI) {
1184   // If already a constant, there is nothing to compute.
1185   if (Constant *VC = dyn_cast<Constant>(Val)) {
1186     Result = LVILatticeVal::get(VC);
1187     return true;
1188   }
1189 
1190   LVILatticeVal LocalResult;
1191   if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1192     // If we couldn't constrain the value on the edge, LocalResult doesn't
1193     // provide any information.
1194     LocalResult.markOverdefined();
1195 
1196   if (hasSingleValue(LocalResult)) {
1197     // Can't get any more precise here
1198     Result = LocalResult;
1199     return true;
1200   }
1201 
1202   if (!hasBlockValue(Val, BBFrom)) {
1203     if (pushBlockValue(std::make_pair(BBFrom, Val)))
1204       return false;
1205     // No new information.
1206     Result = LocalResult;
1207     return true;
1208   }
1209 
1210   // Try to intersect ranges of the BB and the constraint on the edge.
1211   LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
1212   intersectAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
1213   // We can use the context instruction (generically the ultimate instruction
1214   // the calling pass is trying to simplify) here, even though the result of
1215   // this function is generally cached when called from the solve* functions
1216   // (and that cached result might be used with queries using a different
1217   // context instruction), because when this function is called from the solve*
1218   // functions, the context instruction is not provided. When called from
1219   // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
1220   // but then the result is not cached.
1221   intersectAssumeBlockValueConstantRange(Val, InBlock, CxtI);
1222 
1223   Result = intersect(LocalResult, InBlock);
1224   return true;
1225 }
1226 
1227 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
1228                                                   Instruction *CxtI) {
1229   DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1230         << BB->getName() << "'\n");
1231 
1232   assert(BlockValueStack.empty() && BlockValueSet.empty());
1233   if (!hasBlockValue(V, BB)) {
1234     pushBlockValue(std::make_pair(BB, V));
1235     solve();
1236   }
1237   LVILatticeVal Result = getBlockValue(V, BB);
1238   intersectAssumeBlockValueConstantRange(V, Result, CxtI);
1239 
1240   DEBUG(dbgs() << "  Result = " << Result << "\n");
1241   return Result;
1242 }
1243 
1244 LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1245   DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1246         << CxtI->getName() << "'\n");
1247 
1248   if (auto *C = dyn_cast<Constant>(V))
1249     return LVILatticeVal::get(C);
1250 
1251   LVILatticeVal Result = LVILatticeVal::getOverdefined();
1252   if (auto *I = dyn_cast<Instruction>(V))
1253     Result = getFromRangeMetadata(I);
1254   intersectAssumeBlockValueConstantRange(V, Result, CxtI);
1255 
1256   DEBUG(dbgs() << "  Result = " << Result << "\n");
1257   return Result;
1258 }
1259 
1260 LVILatticeVal LazyValueInfoCache::
1261 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1262                Instruction *CxtI) {
1263   DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1264         << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
1265 
1266   LVILatticeVal Result;
1267   if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
1268     solve();
1269     bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
1270     (void)WasFastQuery;
1271     assert(WasFastQuery && "More work to do after problem solved?");
1272   }
1273 
1274   DEBUG(dbgs() << "  Result = " << Result << "\n");
1275   return Result;
1276 }
1277 
1278 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1279                                     BasicBlock *NewSucc) {
1280   // When an edge in the graph has been threaded, values that we could not
1281   // determine a value for before (i.e. were marked overdefined) may be
1282   // possible to solve now. We do NOT try to proactively update these values.
1283   // Instead, we clear their entries from the cache, and allow lazy updating to
1284   // recompute them when needed.
1285 
1286   // The updating process is fairly simple: we need to drop cached info
1287   // for all values that were marked overdefined in OldSucc, and for those same
1288   // values in any successor of OldSucc (except NewSucc) in which they were
1289   // also marked overdefined.
1290   std::vector<BasicBlock*> worklist;
1291   worklist.push_back(OldSucc);
1292 
1293   auto I = OverDefinedCache.find(OldSucc);
1294   if (I == OverDefinedCache.end())
1295     return; // Nothing to process here.
1296   SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
1297 
1298   // Use a worklist to perform a depth-first search of OldSucc's successors.
1299   // NOTE: We do not need a visited list since any blocks we have already
1300   // visited will have had their overdefined markers cleared already, and we
1301   // thus won't loop to their successors.
1302   while (!worklist.empty()) {
1303     BasicBlock *ToUpdate = worklist.back();
1304     worklist.pop_back();
1305 
1306     // Skip blocks only accessible through NewSucc.
1307     if (ToUpdate == NewSucc) continue;
1308 
1309     bool changed = false;
1310     for (Value *V : ValsToClear) {
1311       // If a value was marked overdefined in OldSucc, and is here too...
1312       auto OI = OverDefinedCache.find(ToUpdate);
1313       if (OI == OverDefinedCache.end())
1314         continue;
1315       SmallPtrSetImpl<Value *> &ValueSet = OI->second;
1316       if (!ValueSet.count(V))
1317         continue;
1318 
1319       ValueSet.erase(V);
1320       if (ValueSet.empty())
1321         OverDefinedCache.erase(OI);
1322 
1323       // If we removed anything, then we potentially need to update
1324       // blocks successors too.
1325       changed = true;
1326     }
1327 
1328     if (!changed) continue;
1329 
1330     worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1331   }
1332 }
1333 
1334 //===----------------------------------------------------------------------===//
1335 //                            LazyValueInfo Impl
1336 //===----------------------------------------------------------------------===//
1337 
1338 /// This lazily constructs the LazyValueInfoCache.
1339 static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
1340                                     const DataLayout *DL,
1341                                     DominatorTree *DT = nullptr) {
1342   if (!PImpl) {
1343     assert(DL && "getCache() called with a null DataLayout");
1344     PImpl = new LazyValueInfoCache(AC, *DL, DT);
1345   }
1346   return *static_cast<LazyValueInfoCache*>(PImpl);
1347 }
1348 
1349 bool LazyValueInfo::runOnFunction(Function &F) {
1350   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1351   const DataLayout &DL = F.getParent()->getDataLayout();
1352 
1353   DominatorTreeWrapperPass *DTWP =
1354       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1355   DT = DTWP ? &DTWP->getDomTree() : nullptr;
1356 
1357   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1358 
1359   if (PImpl)
1360     getCache(PImpl, AC, &DL, DT).clear();
1361 
1362   // Fully lazy.
1363   return false;
1364 }
1365 
1366 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1367   AU.setPreservesAll();
1368   AU.addRequired<AssumptionCacheTracker>();
1369   AU.addRequired<TargetLibraryInfoWrapperPass>();
1370 }
1371 
1372 void LazyValueInfo::releaseMemory() {
1373   // If the cache was allocated, free it.
1374   if (PImpl) {
1375     delete &getCache(PImpl, AC, nullptr);
1376     PImpl = nullptr;
1377   }
1378 }
1379 
1380 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1381                                      Instruction *CxtI) {
1382   const DataLayout &DL = BB->getModule()->getDataLayout();
1383   LVILatticeVal Result =
1384       getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1385 
1386   if (Result.isConstant())
1387     return Result.getConstant();
1388   if (Result.isConstantRange()) {
1389     ConstantRange CR = Result.getConstantRange();
1390     if (const APInt *SingleVal = CR.getSingleElement())
1391       return ConstantInt::get(V->getContext(), *SingleVal);
1392   }
1393   return nullptr;
1394 }
1395 
1396 /// Determine whether the specified value is known to be a
1397 /// constant on the specified edge. Return null if not.
1398 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1399                                            BasicBlock *ToBB,
1400                                            Instruction *CxtI) {
1401   const DataLayout &DL = FromBB->getModule()->getDataLayout();
1402   LVILatticeVal Result =
1403       getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1404 
1405   if (Result.isConstant())
1406     return Result.getConstant();
1407   if (Result.isConstantRange()) {
1408     ConstantRange CR = Result.getConstantRange();
1409     if (const APInt *SingleVal = CR.getSingleElement())
1410       return ConstantInt::get(V->getContext(), *SingleVal);
1411   }
1412   return nullptr;
1413 }
1414 
1415 static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1416                                                   LVILatticeVal &Result,
1417                                                   const DataLayout &DL,
1418                                                   TargetLibraryInfo *TLI) {
1419 
1420   // If we know the value is a constant, evaluate the conditional.
1421   Constant *Res = nullptr;
1422   if (Result.isConstant()) {
1423     Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
1424                                           TLI);
1425     if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1426       return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1427     return LazyValueInfo::Unknown;
1428   }
1429 
1430   if (Result.isConstantRange()) {
1431     ConstantInt *CI = dyn_cast<ConstantInt>(C);
1432     if (!CI) return LazyValueInfo::Unknown;
1433 
1434     ConstantRange CR = Result.getConstantRange();
1435     if (Pred == ICmpInst::ICMP_EQ) {
1436       if (!CR.contains(CI->getValue()))
1437         return LazyValueInfo::False;
1438 
1439       if (CR.isSingleElement() && CR.contains(CI->getValue()))
1440         return LazyValueInfo::True;
1441     } else if (Pred == ICmpInst::ICMP_NE) {
1442       if (!CR.contains(CI->getValue()))
1443         return LazyValueInfo::True;
1444 
1445       if (CR.isSingleElement() && CR.contains(CI->getValue()))
1446         return LazyValueInfo::False;
1447     }
1448 
1449     // Handle more complex predicates.
1450     ConstantRange TrueValues =
1451         ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1452     if (TrueValues.contains(CR))
1453       return LazyValueInfo::True;
1454     if (TrueValues.inverse().contains(CR))
1455       return LazyValueInfo::False;
1456     return LazyValueInfo::Unknown;
1457   }
1458 
1459   if (Result.isNotConstant()) {
1460     // If this is an equality comparison, we can try to fold it knowing that
1461     // "V != C1".
1462     if (Pred == ICmpInst::ICMP_EQ) {
1463       // !C1 == C -> false iff C1 == C.
1464       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1465                                             Result.getNotConstant(), C, DL,
1466                                             TLI);
1467       if (Res->isNullValue())
1468         return LazyValueInfo::False;
1469     } else if (Pred == ICmpInst::ICMP_NE) {
1470       // !C1 != C -> true iff C1 == C.
1471       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1472                                             Result.getNotConstant(), C, DL,
1473                                             TLI);
1474       if (Res->isNullValue())
1475         return LazyValueInfo::True;
1476     }
1477     return LazyValueInfo::Unknown;
1478   }
1479 
1480   return LazyValueInfo::Unknown;
1481 }
1482 
1483 /// Determine whether the specified value comparison with a constant is known to
1484 /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1485 LazyValueInfo::Tristate
1486 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1487                                   BasicBlock *FromBB, BasicBlock *ToBB,
1488                                   Instruction *CxtI) {
1489   const DataLayout &DL = FromBB->getModule()->getDataLayout();
1490   LVILatticeVal Result =
1491       getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1492 
1493   return getPredicateResult(Pred, C, Result, DL, TLI);
1494 }
1495 
1496 LazyValueInfo::Tristate
1497 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1498                               Instruction *CxtI) {
1499   const DataLayout &DL = CxtI->getModule()->getDataLayout();
1500   LVILatticeVal Result = getCache(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
1501   Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1502   if (Ret != Unknown)
1503     return Ret;
1504 
1505   // Note: The following bit of code is somewhat distinct from the rest of LVI;
1506   // LVI as a whole tries to compute a lattice value which is conservatively
1507   // correct at a given location.  In this case, we have a predicate which we
1508   // weren't able to prove about the merged result, and we're pushing that
1509   // predicate back along each incoming edge to see if we can prove it
1510   // separately for each input.  As a motivating example, consider:
1511   // bb1:
1512   //   %v1 = ... ; constantrange<1, 5>
1513   //   br label %merge
1514   // bb2:
1515   //   %v2 = ... ; constantrange<10, 20>
1516   //   br label %merge
1517   // merge:
1518   //   %phi = phi [%v1, %v2] ; constantrange<1,20>
1519   //   %pred = icmp eq i32 %phi, 8
1520   // We can't tell from the lattice value for '%phi' that '%pred' is false
1521   // along each path, but by checking the predicate over each input separately,
1522   // we can.
1523   // We limit the search to one step backwards from the current BB and value.
1524   // We could consider extending this to search further backwards through the
1525   // CFG and/or value graph, but there are non-obvious compile time vs quality
1526   // tradeoffs.
1527   if (CxtI) {
1528     BasicBlock *BB = CxtI->getParent();
1529 
1530     // Function entry or an unreachable block.  Bail to avoid confusing
1531     // analysis below.
1532     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1533     if (PI == PE)
1534       return Unknown;
1535 
1536     // If V is a PHI node in the same block as the context, we need to ask
1537     // questions about the predicate as applied to the incoming value along
1538     // each edge. This is useful for eliminating cases where the predicate is
1539     // known along all incoming edges.
1540     if (auto *PHI = dyn_cast<PHINode>(V))
1541       if (PHI->getParent() == BB) {
1542         Tristate Baseline = Unknown;
1543         for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1544           Value *Incoming = PHI->getIncomingValue(i);
1545           BasicBlock *PredBB = PHI->getIncomingBlock(i);
1546           // Note that PredBB may be BB itself.
1547           Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1548                                                CxtI);
1549 
1550           // Keep going as long as we've seen a consistent known result for
1551           // all inputs.
1552           Baseline = (i == 0) ? Result /* First iteration */
1553             : (Baseline == Result ? Baseline : Unknown); /* All others */
1554           if (Baseline == Unknown)
1555             break;
1556         }
1557         if (Baseline != Unknown)
1558           return Baseline;
1559       }
1560 
1561     // For a comparison where the V is outside this block, it's possible
1562     // that we've branched on it before. Look to see if the value is known
1563     // on all incoming edges.
1564     if (!isa<Instruction>(V) ||
1565         cast<Instruction>(V)->getParent() != BB) {
1566       // For predecessor edge, determine if the comparison is true or false
1567       // on that edge. If they're all true or all false, we can conclude
1568       // the value of the comparison in this block.
1569       Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1570       if (Baseline != Unknown) {
1571         // Check that all remaining incoming values match the first one.
1572         while (++PI != PE) {
1573           Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1574           if (Ret != Baseline) break;
1575         }
1576         // If we terminated early, then one of the values didn't match.
1577         if (PI == PE) {
1578           return Baseline;
1579         }
1580       }
1581     }
1582   }
1583   return Unknown;
1584 }
1585 
1586 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1587                                BasicBlock *NewSucc) {
1588   if (PImpl) {
1589     const DataLayout &DL = PredBB->getModule()->getDataLayout();
1590     getCache(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1591   }
1592 }
1593 
1594 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1595   if (PImpl) {
1596     const DataLayout &DL = BB->getModule()->getDataLayout();
1597     getCache(PImpl, AC, &DL, DT).eraseBlock(BB);
1598   }
1599 }
1600