1 //===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interface for lazy computation of value constraint
10 // information.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/LazyValueInfo.h"
15 #include "llvm/ADT/DenseSet.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/ValueLattice.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/AssemblyAnnotationWriter.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/ConstantRange.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/IR/ValueHandle.h"
36 #include "llvm/InitializePasses.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <map>
41 using namespace llvm;
42 using namespace PatternMatch;
43 
44 #define DEBUG_TYPE "lazy-value-info"
45 
46 // This is the number of worklist items we will process to try to discover an
47 // answer for a given value.
48 static const unsigned MaxProcessedPerValue = 500;
49 
50 char LazyValueInfoWrapperPass::ID = 0;
51 LazyValueInfoWrapperPass::LazyValueInfoWrapperPass() : FunctionPass(ID) {
52   initializeLazyValueInfoWrapperPassPass(*PassRegistry::getPassRegistry());
53 }
54 INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
55                 "Lazy Value Information Analysis", false, true)
56 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
57 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
58 INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
59                 "Lazy Value Information Analysis", false, true)
60 
61 namespace llvm {
62   FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
63 }
64 
65 AnalysisKey LazyValueAnalysis::Key;
66 
67 /// Returns true if this lattice value represents at most one possible value.
68 /// This is as precise as any lattice value can get while still representing
69 /// reachable code.
70 static bool hasSingleValue(const ValueLatticeElement &Val) {
71   if (Val.isConstantRange() &&
72       Val.getConstantRange().isSingleElement())
73     // Integer constants are single element ranges
74     return true;
75   if (Val.isConstant())
76     // Non integer constants
77     return true;
78   return false;
79 }
80 
81 /// Combine two sets of facts about the same value into a single set of
82 /// facts.  Note that this method is not suitable for merging facts along
83 /// different paths in a CFG; that's what the mergeIn function is for.  This
84 /// is for merging facts gathered about the same value at the same location
85 /// through two independent means.
86 /// Notes:
87 /// * This method does not promise to return the most precise possible lattice
88 ///   value implied by A and B.  It is allowed to return any lattice element
89 ///   which is at least as strong as *either* A or B (unless our facts
90 ///   conflict, see below).
91 /// * Due to unreachable code, the intersection of two lattice values could be
92 ///   contradictory.  If this happens, we return some valid lattice value so as
93 ///   not confuse the rest of LVI.  Ideally, we'd always return Undefined, but
94 ///   we do not make this guarantee.  TODO: This would be a useful enhancement.
95 static ValueLatticeElement intersect(const ValueLatticeElement &A,
96                                      const ValueLatticeElement &B) {
97   // Undefined is the strongest state.  It means the value is known to be along
98   // an unreachable path.
99   if (A.isUnknown())
100     return A;
101   if (B.isUnknown())
102     return B;
103 
104   // If we gave up for one, but got a useable fact from the other, use it.
105   if (A.isOverdefined())
106     return B;
107   if (B.isOverdefined())
108     return A;
109 
110   // Can't get any more precise than constants.
111   if (hasSingleValue(A))
112     return A;
113   if (hasSingleValue(B))
114     return B;
115 
116   // Could be either constant range or not constant here.
117   if (!A.isConstantRange() || !B.isConstantRange()) {
118     // TODO: Arbitrary choice, could be improved
119     return A;
120   }
121 
122   // Intersect two constant ranges
123   ConstantRange Range =
124       A.getConstantRange().intersectWith(B.getConstantRange());
125   // Note: An empty range is implicitly converted to overdefined internally.
126   // TODO: We could instead use Undefined here since we've proven a conflict
127   // and thus know this path must be unreachable.
128   return ValueLatticeElement::getRange(
129       std::move(Range), /*MayIncludeUndef=*/A.isConstantRangeIncludingUndef() |
130                             B.isConstantRangeIncludingUndef());
131 }
132 
133 //===----------------------------------------------------------------------===//
134 //                          LazyValueInfoCache Decl
135 //===----------------------------------------------------------------------===//
136 
137 namespace {
138   /// A callback value handle updates the cache when values are erased.
139   class LazyValueInfoCache;
140   struct LVIValueHandle final : public CallbackVH {
141     // Needs to access getValPtr(), which is protected.
142     friend struct DenseMapInfo<LVIValueHandle>;
143 
144     LazyValueInfoCache *Parent;
145 
146     LVIValueHandle(Value *V, LazyValueInfoCache *P)
147       : CallbackVH(V), Parent(P) { }
148 
149     void deleted() override;
150     void allUsesReplacedWith(Value *V) override {
151       deleted();
152     }
153   };
154 } // end anonymous namespace
155 
156 namespace {
157   /// This is the cache kept by LazyValueInfo which
158   /// maintains information about queries across the clients' queries.
159   class LazyValueInfoCache {
160     /// This is all of the cached block information for exactly one Value*.
161     /// The entries are sorted by the BasicBlock* of the
162     /// entries, allowing us to do a lookup with a binary search.
163     /// Over-defined lattice values are recorded in OverDefinedCache to reduce
164     /// memory overhead.
165     struct ValueCacheEntryTy {
166       ValueCacheEntryTy(Value *V, LazyValueInfoCache *P) : Handle(V, P) {}
167       LVIValueHandle Handle;
168       SmallDenseMap<PoisoningVH<BasicBlock>, ValueLatticeElement, 4> BlockVals;
169     };
170 
171     /// This tracks, on a per-block basis, the set of values that are
172     /// over-defined at the end of that block.
173     typedef DenseMap<PoisoningVH<BasicBlock>, SmallPtrSet<Value *, 4>>
174         OverDefinedCacheTy;
175     /// Keep track of all blocks that we have ever seen, so we
176     /// don't spend time removing unused blocks from our caches.
177     DenseSet<PoisoningVH<BasicBlock> > SeenBlocks;
178 
179     /// This is all of the cached information for all values,
180     /// mapped from Value* to key information.
181     DenseMap<Value *, std::unique_ptr<ValueCacheEntryTy>> ValueCache;
182     OverDefinedCacheTy OverDefinedCache;
183 
184 
185   public:
186     void insertResult(Value *Val, BasicBlock *BB,
187                       const ValueLatticeElement &Result) {
188       SeenBlocks.insert(BB);
189 
190       // Insert over-defined values into their own cache to reduce memory
191       // overhead.
192       if (Result.isOverdefined())
193         OverDefinedCache[BB].insert(Val);
194       else {
195         auto It = ValueCache.find_as(Val);
196         if (It == ValueCache.end()) {
197           ValueCache[Val] = std::make_unique<ValueCacheEntryTy>(Val, this);
198           It = ValueCache.find_as(Val);
199           assert(It != ValueCache.end() && "Val was just added to the map!");
200         }
201         It->second->BlockVals[BB] = Result;
202       }
203     }
204 
205     bool isOverdefined(Value *V, BasicBlock *BB) const {
206       auto ODI = OverDefinedCache.find(BB);
207 
208       if (ODI == OverDefinedCache.end())
209         return false;
210 
211       return ODI->second.count(V);
212     }
213 
214     bool hasCachedValueInfo(Value *V, BasicBlock *BB) const {
215       if (isOverdefined(V, BB))
216         return true;
217 
218       auto I = ValueCache.find_as(V);
219       if (I == ValueCache.end())
220         return false;
221 
222       return I->second->BlockVals.count(BB);
223     }
224 
225     ValueLatticeElement getCachedValueInfo(Value *V, BasicBlock *BB) const {
226       if (isOverdefined(V, BB))
227         return ValueLatticeElement::getOverdefined();
228 
229       auto I = ValueCache.find_as(V);
230       if (I == ValueCache.end())
231         return ValueLatticeElement();
232       auto BBI = I->second->BlockVals.find(BB);
233       if (BBI == I->second->BlockVals.end())
234         return ValueLatticeElement();
235       return BBI->second;
236     }
237 
238     /// clear - Empty the cache.
239     void clear() {
240       SeenBlocks.clear();
241       ValueCache.clear();
242       OverDefinedCache.clear();
243     }
244 
245     /// Inform the cache that a given value has been deleted.
246     void eraseValue(Value *V);
247 
248     /// This is part of the update interface to inform the cache
249     /// that a block has been deleted.
250     void eraseBlock(BasicBlock *BB);
251 
252     /// Updates the cache to remove any influence an overdefined value in
253     /// OldSucc might have (unless also overdefined in NewSucc).  This just
254     /// flushes elements from the cache and does not add any.
255     void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
256 
257     friend struct LVIValueHandle;
258   };
259 }
260 
261 void LazyValueInfoCache::eraseValue(Value *V) {
262   for (auto I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E;) {
263     // Copy and increment the iterator immediately so we can erase behind
264     // ourselves.
265     auto Iter = I++;
266     SmallPtrSetImpl<Value *> &ValueSet = Iter->second;
267     ValueSet.erase(V);
268     if (ValueSet.empty())
269       OverDefinedCache.erase(Iter);
270   }
271 
272   ValueCache.erase(V);
273 }
274 
275 void LVIValueHandle::deleted() {
276   // This erasure deallocates *this, so it MUST happen after we're done
277   // using any and all members of *this.
278   Parent->eraseValue(*this);
279 }
280 
281 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
282   // Shortcut if we have never seen this block.
283   DenseSet<PoisoningVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
284   if (I == SeenBlocks.end())
285     return;
286   SeenBlocks.erase(I);
287 
288   auto ODI = OverDefinedCache.find(BB);
289   if (ODI != OverDefinedCache.end())
290     OverDefinedCache.erase(ODI);
291 
292   for (auto &I : ValueCache)
293     I.second->BlockVals.erase(BB);
294 }
295 
296 void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
297                                         BasicBlock *NewSucc) {
298   // When an edge in the graph has been threaded, values that we could not
299   // determine a value for before (i.e. were marked overdefined) may be
300   // possible to solve now. We do NOT try to proactively update these values.
301   // Instead, we clear their entries from the cache, and allow lazy updating to
302   // recompute them when needed.
303 
304   // The updating process is fairly simple: we need to drop cached info
305   // for all values that were marked overdefined in OldSucc, and for those same
306   // values in any successor of OldSucc (except NewSucc) in which they were
307   // also marked overdefined.
308   std::vector<BasicBlock*> worklist;
309   worklist.push_back(OldSucc);
310 
311   auto I = OverDefinedCache.find(OldSucc);
312   if (I == OverDefinedCache.end())
313     return; // Nothing to process here.
314   SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
315 
316   // Use a worklist to perform a depth-first search of OldSucc's successors.
317   // NOTE: We do not need a visited list since any blocks we have already
318   // visited will have had their overdefined markers cleared already, and we
319   // thus won't loop to their successors.
320   while (!worklist.empty()) {
321     BasicBlock *ToUpdate = worklist.back();
322     worklist.pop_back();
323 
324     // Skip blocks only accessible through NewSucc.
325     if (ToUpdate == NewSucc) continue;
326 
327     // If a value was marked overdefined in OldSucc, and is here too...
328     auto OI = OverDefinedCache.find(ToUpdate);
329     if (OI == OverDefinedCache.end())
330       continue;
331     SmallPtrSetImpl<Value *> &ValueSet = OI->second;
332 
333     bool changed = false;
334     for (Value *V : ValsToClear) {
335       if (!ValueSet.erase(V))
336         continue;
337 
338       // If we removed anything, then we potentially need to update
339       // blocks successors too.
340       changed = true;
341 
342       if (ValueSet.empty()) {
343         OverDefinedCache.erase(OI);
344         break;
345       }
346     }
347 
348     if (!changed) continue;
349 
350     worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
351   }
352 }
353 
354 
355 namespace {
356 /// An assembly annotator class to print LazyValueCache information in
357 /// comments.
358 class LazyValueInfoImpl;
359 class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
360   LazyValueInfoImpl *LVIImpl;
361   // While analyzing which blocks we can solve values for, we need the dominator
362   // information. Since this is an optional parameter in LVI, we require this
363   // DomTreeAnalysis pass in the printer pass, and pass the dominator
364   // tree to the LazyValueInfoAnnotatedWriter.
365   DominatorTree &DT;
366 
367 public:
368   LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
369       : LVIImpl(L), DT(DTree) {}
370 
371   virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
372                                         formatted_raw_ostream &OS);
373 
374   virtual void emitInstructionAnnot(const Instruction *I,
375                                     formatted_raw_ostream &OS);
376 };
377 }
378 namespace {
379   // The actual implementation of the lazy analysis and update.  Note that the
380   // inheritance from LazyValueInfoCache is intended to be temporary while
381   // splitting the code and then transitioning to a has-a relationship.
382   class LazyValueInfoImpl {
383 
384     /// Cached results from previous queries
385     LazyValueInfoCache TheCache;
386 
387     /// This stack holds the state of the value solver during a query.
388     /// It basically emulates the callstack of the naive
389     /// recursive value lookup process.
390     SmallVector<std::pair<BasicBlock*, Value*>, 8> BlockValueStack;
391 
392     /// Keeps track of which block-value pairs are in BlockValueStack.
393     DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
394 
395     /// Push BV onto BlockValueStack unless it's already in there.
396     /// Returns true on success.
397     bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
398       if (!BlockValueSet.insert(BV).second)
399         return false;  // It's already in the stack.
400 
401       LLVM_DEBUG(dbgs() << "PUSH: " << *BV.second << " in "
402                         << BV.first->getName() << "\n");
403       BlockValueStack.push_back(BV);
404       return true;
405     }
406 
407     AssumptionCache *AC;  ///< A pointer to the cache of @llvm.assume calls.
408     const DataLayout &DL; ///< A mandatory DataLayout
409     DominatorTree *DT;    ///< An optional DT pointer.
410     DominatorTree *DisabledDT; ///< Stores DT if it's disabled.
411 
412   ValueLatticeElement getBlockValue(Value *Val, BasicBlock *BB);
413   bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
414                     ValueLatticeElement &Result, Instruction *CxtI = nullptr);
415   bool hasBlockValue(Value *Val, BasicBlock *BB);
416 
417   // These methods process one work item and may add more. A false value
418   // returned means that the work item was not completely processed and must
419   // be revisited after going through the new items.
420   bool solveBlockValue(Value *Val, BasicBlock *BB);
421   bool solveBlockValueImpl(ValueLatticeElement &Res, Value *Val,
422                            BasicBlock *BB);
423   bool solveBlockValueNonLocal(ValueLatticeElement &BBLV, Value *Val,
424                                BasicBlock *BB);
425   bool solveBlockValuePHINode(ValueLatticeElement &BBLV, PHINode *PN,
426                               BasicBlock *BB);
427   bool solveBlockValueSelect(ValueLatticeElement &BBLV, SelectInst *S,
428                              BasicBlock *BB);
429   Optional<ConstantRange> getRangeForOperand(unsigned Op, Instruction *I,
430                                              BasicBlock *BB);
431   bool solveBlockValueBinaryOpImpl(
432       ValueLatticeElement &BBLV, Instruction *I, BasicBlock *BB,
433       std::function<ConstantRange(const ConstantRange &,
434                                   const ConstantRange &)> OpFn);
435   bool solveBlockValueBinaryOp(ValueLatticeElement &BBLV, BinaryOperator *BBI,
436                                BasicBlock *BB);
437   bool solveBlockValueCast(ValueLatticeElement &BBLV, CastInst *CI,
438                            BasicBlock *BB);
439   bool solveBlockValueOverflowIntrinsic(
440       ValueLatticeElement &BBLV, WithOverflowInst *WO, BasicBlock *BB);
441   bool solveBlockValueSaturatingIntrinsic(ValueLatticeElement &BBLV,
442                                           SaturatingInst *SI, BasicBlock *BB);
443   bool solveBlockValueIntrinsic(ValueLatticeElement &BBLV, IntrinsicInst *II,
444                                 BasicBlock *BB);
445   bool solveBlockValueExtractValue(ValueLatticeElement &BBLV,
446                                    ExtractValueInst *EVI, BasicBlock *BB);
447   void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
448                                                      ValueLatticeElement &BBLV,
449                                                      Instruction *BBI);
450 
451   void solve();
452 
453   public:
454     /// This is the query interface to determine the lattice
455     /// value for the specified Value* at the end of the specified block.
456     ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB,
457                                         Instruction *CxtI = nullptr);
458 
459     /// This is the query interface to determine the lattice
460     /// value for the specified Value* at the specified instruction (generally
461     /// from an assume intrinsic).
462     ValueLatticeElement getValueAt(Value *V, Instruction *CxtI);
463 
464     /// This is the query interface to determine the lattice
465     /// value for the specified Value* that is true on the specified edge.
466     ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB,
467                                        BasicBlock *ToBB,
468                                    Instruction *CxtI = nullptr);
469 
470     /// Complete flush all previously computed values
471     void clear() {
472       TheCache.clear();
473     }
474 
475     /// Printing the LazyValueInfo Analysis.
476     void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
477         LazyValueInfoAnnotatedWriter Writer(this, DTree);
478         F.print(OS, &Writer);
479     }
480 
481     /// This is part of the update interface to inform the cache
482     /// that a block has been deleted.
483     void eraseBlock(BasicBlock *BB) {
484       TheCache.eraseBlock(BB);
485     }
486 
487     /// Disables use of the DominatorTree within LVI.
488     void disableDT() {
489       if (DT) {
490         assert(!DisabledDT && "Both DT and DisabledDT are not nullptr!");
491         std::swap(DT, DisabledDT);
492       }
493     }
494 
495     /// Enables use of the DominatorTree within LVI. Does nothing if the class
496     /// instance was initialized without a DT pointer.
497     void enableDT() {
498       if (DisabledDT) {
499         assert(!DT && "Both DT and DisabledDT are not nullptr!");
500         std::swap(DT, DisabledDT);
501       }
502     }
503 
504     /// This is the update interface to inform the cache that an edge from
505     /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
506     void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
507 
508     LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
509                        DominatorTree *DT = nullptr)
510         : AC(AC), DL(DL), DT(DT), DisabledDT(nullptr) {}
511   };
512 } // end anonymous namespace
513 
514 
515 void LazyValueInfoImpl::solve() {
516   SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack(
517       BlockValueStack.begin(), BlockValueStack.end());
518 
519   unsigned processedCount = 0;
520   while (!BlockValueStack.empty()) {
521     processedCount++;
522     // Abort if we have to process too many values to get a result for this one.
523     // Because of the design of the overdefined cache currently being per-block
524     // to avoid naming-related issues (IE it wants to try to give different
525     // results for the same name in different blocks), overdefined results don't
526     // get cached globally, which in turn means we will often try to rediscover
527     // the same overdefined result again and again.  Once something like
528     // PredicateInfo is used in LVI or CVP, we should be able to make the
529     // overdefined cache global, and remove this throttle.
530     if (processedCount > MaxProcessedPerValue) {
531       LLVM_DEBUG(
532           dbgs() << "Giving up on stack because we are getting too deep\n");
533       // Fill in the original values
534       while (!StartingStack.empty()) {
535         std::pair<BasicBlock *, Value *> &e = StartingStack.back();
536         TheCache.insertResult(e.second, e.first,
537                               ValueLatticeElement::getOverdefined());
538         StartingStack.pop_back();
539       }
540       BlockValueSet.clear();
541       BlockValueStack.clear();
542       return;
543     }
544     std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
545     assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
546 
547     if (solveBlockValue(e.second, e.first)) {
548       // The work item was completely processed.
549       assert(BlockValueStack.back() == e && "Nothing should have been pushed!");
550       assert(TheCache.hasCachedValueInfo(e.second, e.first) &&
551              "Result should be in cache!");
552 
553       LLVM_DEBUG(
554           dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "
555                  << TheCache.getCachedValueInfo(e.second, e.first) << "\n");
556 
557       BlockValueStack.pop_back();
558       BlockValueSet.erase(e);
559     } else {
560       // More work needs to be done before revisiting.
561       assert(BlockValueStack.back() != e && "Stack should have been pushed!");
562     }
563   }
564 }
565 
566 bool LazyValueInfoImpl::hasBlockValue(Value *Val, BasicBlock *BB) {
567   // If already a constant, there is nothing to compute.
568   if (isa<Constant>(Val))
569     return true;
570 
571   return TheCache.hasCachedValueInfo(Val, BB);
572 }
573 
574 ValueLatticeElement LazyValueInfoImpl::getBlockValue(Value *Val,
575                                                      BasicBlock *BB) {
576   // If already a constant, there is nothing to compute.
577   if (Constant *VC = dyn_cast<Constant>(Val))
578     return ValueLatticeElement::get(VC);
579 
580   return TheCache.getCachedValueInfo(Val, BB);
581 }
582 
583 static ValueLatticeElement getFromRangeMetadata(Instruction *BBI) {
584   switch (BBI->getOpcode()) {
585   default: break;
586   case Instruction::Load:
587   case Instruction::Call:
588   case Instruction::Invoke:
589     if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
590       if (isa<IntegerType>(BBI->getType())) {
591         return ValueLatticeElement::getRange(
592             getConstantRangeFromMetadata(*Ranges));
593       }
594     break;
595   };
596   // Nothing known - will be intersected with other facts
597   return ValueLatticeElement::getOverdefined();
598 }
599 
600 bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
601   assert(!isa<Constant>(Val) && "Value should not be constant");
602   assert(!TheCache.hasCachedValueInfo(Val, BB) &&
603          "Value should not be in cache");
604 
605   // Hold off inserting this value into the Cache in case we have to return
606   // false and come back later.
607   ValueLatticeElement Res;
608   if (!solveBlockValueImpl(Res, Val, BB))
609     // Work pushed, will revisit
610     return false;
611 
612   TheCache.insertResult(Val, BB, Res);
613   return true;
614 }
615 
616 bool LazyValueInfoImpl::solveBlockValueImpl(ValueLatticeElement &Res,
617                                             Value *Val, BasicBlock *BB) {
618 
619   Instruction *BBI = dyn_cast<Instruction>(Val);
620   if (!BBI || BBI->getParent() != BB)
621     return solveBlockValueNonLocal(Res, Val, BB);
622 
623   if (PHINode *PN = dyn_cast<PHINode>(BBI))
624     return solveBlockValuePHINode(Res, PN, BB);
625 
626   if (auto *SI = dyn_cast<SelectInst>(BBI))
627     return solveBlockValueSelect(Res, SI, BB);
628 
629   // If this value is a nonnull pointer, record it's range and bailout.  Note
630   // that for all other pointer typed values, we terminate the search at the
631   // definition.  We could easily extend this to look through geps, bitcasts,
632   // and the like to prove non-nullness, but it's not clear that's worth it
633   // compile time wise.  The context-insensitive value walk done inside
634   // isKnownNonZero gets most of the profitable cases at much less expense.
635   // This does mean that we have a sensitivity to where the defining
636   // instruction is placed, even if it could legally be hoisted much higher.
637   // That is unfortunate.
638   PointerType *PT = dyn_cast<PointerType>(BBI->getType());
639   if (PT && isKnownNonZero(BBI, DL)) {
640     Res = ValueLatticeElement::getNot(ConstantPointerNull::get(PT));
641     return true;
642   }
643   if (BBI->getType()->isIntegerTy()) {
644     if (auto *CI = dyn_cast<CastInst>(BBI))
645       return solveBlockValueCast(Res, CI, BB);
646 
647     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
648       return solveBlockValueBinaryOp(Res, BO, BB);
649 
650     if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
651       return solveBlockValueExtractValue(Res, EVI, BB);
652 
653     if (auto *II = dyn_cast<IntrinsicInst>(BBI))
654       return solveBlockValueIntrinsic(Res, II, BB);
655   }
656 
657   LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
658                     << "' - unknown inst def found.\n");
659   Res = getFromRangeMetadata(BBI);
660   return true;
661 }
662 
663 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
664   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
665     return L->getPointerAddressSpace() == 0 &&
666            GetUnderlyingObject(L->getPointerOperand(),
667                                L->getModule()->getDataLayout()) == Ptr;
668   }
669   if (StoreInst *S = dyn_cast<StoreInst>(I)) {
670     return S->getPointerAddressSpace() == 0 &&
671            GetUnderlyingObject(S->getPointerOperand(),
672                                S->getModule()->getDataLayout()) == Ptr;
673   }
674   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
675     if (MI->isVolatile()) return false;
676 
677     // FIXME: check whether it has a valuerange that excludes zero?
678     ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
679     if (!Len || Len->isZero()) return false;
680 
681     if (MI->getDestAddressSpace() == 0)
682       if (GetUnderlyingObject(MI->getRawDest(),
683                               MI->getModule()->getDataLayout()) == Ptr)
684         return true;
685     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
686       if (MTI->getSourceAddressSpace() == 0)
687         if (GetUnderlyingObject(MTI->getRawSource(),
688                                 MTI->getModule()->getDataLayout()) == Ptr)
689           return true;
690   }
691   return false;
692 }
693 
694 /// Return true if the allocation associated with Val is ever dereferenced
695 /// within the given basic block.  This establishes the fact Val is not null,
696 /// but does not imply that the memory at Val is dereferenceable.  (Val may
697 /// point off the end of the dereferenceable part of the object.)
698 static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
699   assert(Val->getType()->isPointerTy());
700 
701   const DataLayout &DL = BB->getModule()->getDataLayout();
702   Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
703   // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
704   // inside InstructionDereferencesPointer either.
705   if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
706     for (Instruction &I : *BB)
707       if (InstructionDereferencesPointer(&I, UnderlyingVal))
708         return true;
709   return false;
710 }
711 
712 bool LazyValueInfoImpl::solveBlockValueNonLocal(ValueLatticeElement &BBLV,
713                                                  Value *Val, BasicBlock *BB) {
714   ValueLatticeElement Result;  // Start Undefined.
715 
716   // If this is the entry block, we must be asking about an argument.  The
717   // value is overdefined.
718   if (BB == &BB->getParent()->getEntryBlock()) {
719     assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
720     // Before giving up, see if we can prove the pointer non-null local to
721     // this particular block.
722     PointerType *PTy = dyn_cast<PointerType>(Val->getType());
723     if (PTy &&
724         (isKnownNonZero(Val, DL) ||
725           (isObjectDereferencedInBlock(Val, BB) &&
726            !NullPointerIsDefined(BB->getParent(), PTy->getAddressSpace())))) {
727       Result = ValueLatticeElement::getNot(ConstantPointerNull::get(PTy));
728     } else {
729       Result = ValueLatticeElement::getOverdefined();
730     }
731     BBLV = Result;
732     return true;
733   }
734 
735   // Loop over all of our predecessors, merging what we know from them into
736   // result.  If we encounter an unexplored predecessor, we eagerly explore it
737   // in a depth first manner.  In practice, this has the effect of discovering
738   // paths we can't analyze eagerly without spending compile times analyzing
739   // other paths.  This heuristic benefits from the fact that predecessors are
740   // frequently arranged such that dominating ones come first and we quickly
741   // find a path to function entry.  TODO: We should consider explicitly
742   // canonicalizing to make this true rather than relying on this happy
743   // accident.
744   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
745     ValueLatticeElement EdgeResult;
746     if (!getEdgeValue(Val, *PI, BB, EdgeResult))
747       // Explore that input, then return here
748       return false;
749 
750     Result.mergeIn(EdgeResult, DL);
751 
752     // If we hit overdefined, exit early.  The BlockVals entry is already set
753     // to overdefined.
754     if (Result.isOverdefined()) {
755       LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
756                         << "' - overdefined because of pred (non local).\n");
757       // Before giving up, see if we can prove the pointer non-null local to
758       // this particular block.
759       PointerType *PTy = dyn_cast<PointerType>(Val->getType());
760       if (PTy && isObjectDereferencedInBlock(Val, BB) &&
761           !NullPointerIsDefined(BB->getParent(), PTy->getAddressSpace())) {
762         Result = ValueLatticeElement::getNot(ConstantPointerNull::get(PTy));
763       }
764 
765       BBLV = Result;
766       return true;
767     }
768   }
769 
770   // Return the merged value, which is more precise than 'overdefined'.
771   assert(!Result.isOverdefined());
772   BBLV = Result;
773   return true;
774 }
775 
776 bool LazyValueInfoImpl::solveBlockValuePHINode(ValueLatticeElement &BBLV,
777                                                PHINode *PN, BasicBlock *BB) {
778   ValueLatticeElement Result;  // Start Undefined.
779 
780   // Loop over all of our predecessors, merging what we know from them into
781   // result.  See the comment about the chosen traversal order in
782   // solveBlockValueNonLocal; the same reasoning applies here.
783   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
784     BasicBlock *PhiBB = PN->getIncomingBlock(i);
785     Value *PhiVal = PN->getIncomingValue(i);
786     ValueLatticeElement EdgeResult;
787     // Note that we can provide PN as the context value to getEdgeValue, even
788     // though the results will be cached, because PN is the value being used as
789     // the cache key in the caller.
790     if (!getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN))
791       // Explore that input, then return here
792       return false;
793 
794     Result.mergeIn(EdgeResult, DL);
795 
796     // If we hit overdefined, exit early.  The BlockVals entry is already set
797     // to overdefined.
798     if (Result.isOverdefined()) {
799       LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
800                         << "' - overdefined because of pred (local).\n");
801 
802       BBLV = Result;
803       return true;
804     }
805   }
806 
807   // Return the merged value, which is more precise than 'overdefined'.
808   assert(!Result.isOverdefined() && "Possible PHI in entry block?");
809   BBLV = Result;
810   return true;
811 }
812 
813 static ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
814                                                  bool isTrueDest = true);
815 
816 // If we can determine a constraint on the value given conditions assumed by
817 // the program, intersect those constraints with BBLV
818 void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
819         Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
820   BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
821   if (!BBI)
822     return;
823 
824   for (auto &AssumeVH : AC->assumptionsFor(Val)) {
825     if (!AssumeVH)
826       continue;
827     auto *I = cast<CallInst>(AssumeVH);
828     if (!isValidAssumeForContext(I, BBI, DT))
829       continue;
830 
831     BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
832   }
833 
834   // If guards are not used in the module, don't spend time looking for them
835   auto *GuardDecl = BBI->getModule()->getFunction(
836           Intrinsic::getName(Intrinsic::experimental_guard));
837   if (!GuardDecl || GuardDecl->use_empty())
838     return;
839 
840   if (BBI->getIterator() == BBI->getParent()->begin())
841     return;
842   for (Instruction &I : make_range(std::next(BBI->getIterator().getReverse()),
843                                    BBI->getParent()->rend())) {
844     Value *Cond = nullptr;
845     if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
846       BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
847   }
848 }
849 
850 bool LazyValueInfoImpl::solveBlockValueSelect(ValueLatticeElement &BBLV,
851                                               SelectInst *SI, BasicBlock *BB) {
852 
853   // Recurse on our inputs if needed
854   if (!hasBlockValue(SI->getTrueValue(), BB)) {
855     if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
856       return false;
857     BBLV = ValueLatticeElement::getOverdefined();
858     return true;
859   }
860   ValueLatticeElement TrueVal = getBlockValue(SI->getTrueValue(), BB);
861   // If we hit overdefined, don't ask more queries.  We want to avoid poisoning
862   // extra slots in the table if we can.
863   if (TrueVal.isOverdefined()) {
864     BBLV = ValueLatticeElement::getOverdefined();
865     return true;
866   }
867 
868   if (!hasBlockValue(SI->getFalseValue(), BB)) {
869     if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
870       return false;
871     BBLV = ValueLatticeElement::getOverdefined();
872     return true;
873   }
874   ValueLatticeElement FalseVal = getBlockValue(SI->getFalseValue(), BB);
875   // If we hit overdefined, don't ask more queries.  We want to avoid poisoning
876   // extra slots in the table if we can.
877   if (FalseVal.isOverdefined()) {
878     BBLV = ValueLatticeElement::getOverdefined();
879     return true;
880   }
881 
882   if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
883     const ConstantRange &TrueCR = TrueVal.getConstantRange();
884     const ConstantRange &FalseCR = FalseVal.getConstantRange();
885     Value *LHS = nullptr;
886     Value *RHS = nullptr;
887     SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
888     // Is this a min specifically of our two inputs?  (Avoid the risk of
889     // ValueTracking getting smarter looking back past our immediate inputs.)
890     if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
891         LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
892       ConstantRange ResultCR = [&]() {
893         switch (SPR.Flavor) {
894         default:
895           llvm_unreachable("unexpected minmax type!");
896         case SPF_SMIN:                   /// Signed minimum
897           return TrueCR.smin(FalseCR);
898         case SPF_UMIN:                   /// Unsigned minimum
899           return TrueCR.umin(FalseCR);
900         case SPF_SMAX:                   /// Signed maximum
901           return TrueCR.smax(FalseCR);
902         case SPF_UMAX:                   /// Unsigned maximum
903           return TrueCR.umax(FalseCR);
904         };
905       }();
906       BBLV = ValueLatticeElement::getRange(
907           ResultCR, TrueVal.isConstantRangeIncludingUndef() |
908                         FalseVal.isConstantRangeIncludingUndef());
909       return true;
910     }
911 
912     if (SPR.Flavor == SPF_ABS) {
913       if (LHS == SI->getTrueValue()) {
914         BBLV = ValueLatticeElement::getRange(
915             TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
916         return true;
917       }
918       if (LHS == SI->getFalseValue()) {
919         BBLV = ValueLatticeElement::getRange(
920             FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
921         return true;
922       }
923     }
924 
925     if (SPR.Flavor == SPF_NABS) {
926       ConstantRange Zero(APInt::getNullValue(TrueCR.getBitWidth()));
927       if (LHS == SI->getTrueValue()) {
928         BBLV = ValueLatticeElement::getRange(
929             Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
930         return true;
931       }
932       if (LHS == SI->getFalseValue()) {
933         BBLV = ValueLatticeElement::getRange(
934             Zero.sub(FalseCR.abs()), FalseVal.isConstantRangeIncludingUndef());
935         return true;
936       }
937     }
938   }
939 
940   // Can we constrain the facts about the true and false values by using the
941   // condition itself?  This shows up with idioms like e.g. select(a > 5, a, 5).
942   // TODO: We could potentially refine an overdefined true value above.
943   Value *Cond = SI->getCondition();
944   TrueVal = intersect(TrueVal,
945                       getValueFromCondition(SI->getTrueValue(), Cond, true));
946   FalseVal = intersect(FalseVal,
947                        getValueFromCondition(SI->getFalseValue(), Cond, false));
948 
949   // Handle clamp idioms such as:
950   //   %24 = constantrange<0, 17>
951   //   %39 = icmp eq i32 %24, 0
952   //   %40 = add i32 %24, -1
953   //   %siv.next = select i1 %39, i32 16, i32 %40
954   //   %siv.next = constantrange<0, 17> not <-1, 17>
955   // In general, this can handle any clamp idiom which tests the edge
956   // condition via an equality or inequality.
957   if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
958     ICmpInst::Predicate Pred = ICI->getPredicate();
959     Value *A = ICI->getOperand(0);
960     if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
961       auto addConstants = [](ConstantInt *A, ConstantInt *B) {
962         assert(A->getType() == B->getType());
963         return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
964       };
965       // See if either input is A + C2, subject to the constraint from the
966       // condition that A != C when that input is used.  We can assume that
967       // that input doesn't include C + C2.
968       ConstantInt *CIAdded;
969       switch (Pred) {
970       default: break;
971       case ICmpInst::ICMP_EQ:
972         if (match(SI->getFalseValue(), m_Add(m_Specific(A),
973                                              m_ConstantInt(CIAdded)))) {
974           auto ResNot = addConstants(CIBase, CIAdded);
975           FalseVal = intersect(FalseVal,
976                                ValueLatticeElement::getNot(ResNot));
977         }
978         break;
979       case ICmpInst::ICMP_NE:
980         if (match(SI->getTrueValue(), m_Add(m_Specific(A),
981                                             m_ConstantInt(CIAdded)))) {
982           auto ResNot = addConstants(CIBase, CIAdded);
983           TrueVal = intersect(TrueVal,
984                               ValueLatticeElement::getNot(ResNot));
985         }
986         break;
987       };
988     }
989   }
990 
991   ValueLatticeElement Result;  // Start Undefined.
992   Result.mergeIn(TrueVal, DL);
993   Result.mergeIn(FalseVal, DL);
994   BBLV = Result;
995   return true;
996 }
997 
998 Optional<ConstantRange> LazyValueInfoImpl::getRangeForOperand(unsigned Op,
999                                                               Instruction *I,
1000                                                               BasicBlock *BB) {
1001   if (!hasBlockValue(I->getOperand(Op), BB))
1002     if (pushBlockValue(std::make_pair(BB, I->getOperand(Op))))
1003       return None;
1004 
1005   const unsigned OperandBitWidth =
1006     DL.getTypeSizeInBits(I->getOperand(Op)->getType());
1007   ConstantRange Range = ConstantRange::getFull(OperandBitWidth);
1008   if (hasBlockValue(I->getOperand(Op), BB)) {
1009     ValueLatticeElement Val = getBlockValue(I->getOperand(Op), BB);
1010     intersectAssumeOrGuardBlockValueConstantRange(I->getOperand(Op), Val, I);
1011     if (Val.isConstantRange())
1012       Range = Val.getConstantRange();
1013   }
1014   return Range;
1015 }
1016 
1017 bool LazyValueInfoImpl::solveBlockValueCast(ValueLatticeElement &BBLV,
1018                                             CastInst *CI,
1019                                             BasicBlock *BB) {
1020   if (!CI->getOperand(0)->getType()->isSized()) {
1021     // Without knowing how wide the input is, we can't analyze it in any useful
1022     // way.
1023     BBLV = ValueLatticeElement::getOverdefined();
1024     return true;
1025   }
1026 
1027   // Filter out casts we don't know how to reason about before attempting to
1028   // recurse on our operand.  This can cut a long search short if we know we're
1029   // not going to be able to get any useful information anways.
1030   switch (CI->getOpcode()) {
1031   case Instruction::Trunc:
1032   case Instruction::SExt:
1033   case Instruction::ZExt:
1034   case Instruction::BitCast:
1035     break;
1036   default:
1037     // Unhandled instructions are overdefined.
1038     LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1039                       << "' - overdefined (unknown cast).\n");
1040     BBLV = ValueLatticeElement::getOverdefined();
1041     return true;
1042   }
1043 
1044   // Figure out the range of the LHS.  If that fails, we still apply the
1045   // transfer rule on the full set since we may be able to locally infer
1046   // interesting facts.
1047   Optional<ConstantRange> LHSRes = getRangeForOperand(0, CI, BB);
1048   if (!LHSRes.hasValue())
1049     // More work to do before applying this transfer rule.
1050     return false;
1051   ConstantRange LHSRange = LHSRes.getValue();
1052 
1053   const unsigned ResultBitWidth = CI->getType()->getIntegerBitWidth();
1054 
1055   // NOTE: We're currently limited by the set of operations that ConstantRange
1056   // can evaluate symbolically.  Enhancing that set will allows us to analyze
1057   // more definitions.
1058   BBLV = ValueLatticeElement::getRange(LHSRange.castOp(CI->getOpcode(),
1059                                                        ResultBitWidth));
1060   return true;
1061 }
1062 
1063 bool LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
1064     ValueLatticeElement &BBLV, Instruction *I, BasicBlock *BB,
1065     std::function<ConstantRange(const ConstantRange &,
1066                                 const ConstantRange &)> OpFn) {
1067   // Figure out the ranges of the operands.  If that fails, use a
1068   // conservative range, but apply the transfer rule anyways.  This
1069   // lets us pick up facts from expressions like "and i32 (call i32
1070   // @foo()), 32"
1071   Optional<ConstantRange> LHSRes = getRangeForOperand(0, I, BB);
1072   Optional<ConstantRange> RHSRes = getRangeForOperand(1, I, BB);
1073   if (!LHSRes.hasValue() || !RHSRes.hasValue())
1074     // More work to do before applying this transfer rule.
1075     return false;
1076 
1077   ConstantRange LHSRange = LHSRes.getValue();
1078   ConstantRange RHSRange = RHSRes.getValue();
1079   BBLV = ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
1080   return true;
1081 }
1082 
1083 bool LazyValueInfoImpl::solveBlockValueBinaryOp(ValueLatticeElement &BBLV,
1084                                                 BinaryOperator *BO,
1085                                                 BasicBlock *BB) {
1086 
1087   assert(BO->getOperand(0)->getType()->isSized() &&
1088          "all operands to binary operators are sized");
1089   if (BO->getOpcode() == Instruction::Xor) {
1090     // Xor is the only operation not supported by ConstantRange::binaryOp().
1091     LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1092                       << "' - overdefined (unknown binary operator).\n");
1093     BBLV = ValueLatticeElement::getOverdefined();
1094     return true;
1095   }
1096 
1097   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO)) {
1098     unsigned NoWrapKind = 0;
1099     if (OBO->hasNoUnsignedWrap())
1100       NoWrapKind |= OverflowingBinaryOperator::NoUnsignedWrap;
1101     if (OBO->hasNoSignedWrap())
1102       NoWrapKind |= OverflowingBinaryOperator::NoSignedWrap;
1103 
1104     return solveBlockValueBinaryOpImpl(
1105         BBLV, BO, BB,
1106         [BO, NoWrapKind](const ConstantRange &CR1, const ConstantRange &CR2) {
1107           return CR1.overflowingBinaryOp(BO->getOpcode(), CR2, NoWrapKind);
1108         });
1109   }
1110 
1111   return solveBlockValueBinaryOpImpl(
1112       BBLV, BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
1113         return CR1.binaryOp(BO->getOpcode(), CR2);
1114       });
1115 }
1116 
1117 bool LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(
1118     ValueLatticeElement &BBLV, WithOverflowInst *WO, BasicBlock *BB) {
1119   return solveBlockValueBinaryOpImpl(BBLV, WO, BB,
1120       [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
1121         return CR1.binaryOp(WO->getBinaryOp(), CR2);
1122       });
1123 }
1124 
1125 bool LazyValueInfoImpl::solveBlockValueSaturatingIntrinsic(
1126     ValueLatticeElement &BBLV, SaturatingInst *SI, BasicBlock *BB) {
1127   switch (SI->getIntrinsicID()) {
1128   case Intrinsic::uadd_sat:
1129     return solveBlockValueBinaryOpImpl(
1130         BBLV, SI, BB, [](const ConstantRange &CR1, const ConstantRange &CR2) {
1131           return CR1.uadd_sat(CR2);
1132         });
1133   case Intrinsic::usub_sat:
1134     return solveBlockValueBinaryOpImpl(
1135         BBLV, SI, BB, [](const ConstantRange &CR1, const ConstantRange &CR2) {
1136           return CR1.usub_sat(CR2);
1137         });
1138   case Intrinsic::sadd_sat:
1139     return solveBlockValueBinaryOpImpl(
1140         BBLV, SI, BB, [](const ConstantRange &CR1, const ConstantRange &CR2) {
1141           return CR1.sadd_sat(CR2);
1142         });
1143   case Intrinsic::ssub_sat:
1144     return solveBlockValueBinaryOpImpl(
1145         BBLV, SI, BB, [](const ConstantRange &CR1, const ConstantRange &CR2) {
1146           return CR1.ssub_sat(CR2);
1147         });
1148   default:
1149     llvm_unreachable("All llvm.sat intrinsic are handled.");
1150   }
1151 }
1152 
1153 bool LazyValueInfoImpl::solveBlockValueIntrinsic(ValueLatticeElement &BBLV,
1154                                                  IntrinsicInst *II,
1155                                                  BasicBlock *BB) {
1156   if (auto *SI = dyn_cast<SaturatingInst>(II))
1157     return solveBlockValueSaturatingIntrinsic(BBLV, SI, BB);
1158 
1159   LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1160                     << "' - overdefined (unknown intrinsic).\n");
1161   BBLV = ValueLatticeElement::getOverdefined();
1162   return true;
1163 }
1164 
1165 bool LazyValueInfoImpl::solveBlockValueExtractValue(
1166     ValueLatticeElement &BBLV, ExtractValueInst *EVI, BasicBlock *BB) {
1167   if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1168     if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 0)
1169       return solveBlockValueOverflowIntrinsic(BBLV, WO, BB);
1170 
1171   // Handle extractvalue of insertvalue to allow further simplification
1172   // based on replaced with.overflow intrinsics.
1173   if (Value *V = SimplifyExtractValueInst(
1174           EVI->getAggregateOperand(), EVI->getIndices(),
1175           EVI->getModule()->getDataLayout())) {
1176     if (!hasBlockValue(V, BB)) {
1177       if (pushBlockValue({ BB, V }))
1178         return false;
1179       BBLV = ValueLatticeElement::getOverdefined();
1180       return true;
1181     }
1182     BBLV = getBlockValue(V, BB);
1183     return true;
1184   }
1185 
1186   LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1187                     << "' - overdefined (unknown extractvalue).\n");
1188   BBLV = ValueLatticeElement::getOverdefined();
1189   return true;
1190 }
1191 
1192 static ValueLatticeElement getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1193                                                      bool isTrueDest) {
1194   Value *LHS = ICI->getOperand(0);
1195   Value *RHS = ICI->getOperand(1);
1196   CmpInst::Predicate Predicate = ICI->getPredicate();
1197 
1198   if (isa<Constant>(RHS)) {
1199     if (ICI->isEquality() && LHS == Val) {
1200       // We know that V has the RHS constant if this is a true SETEQ or
1201       // false SETNE.
1202       if (isTrueDest == (Predicate == ICmpInst::ICMP_EQ))
1203         return ValueLatticeElement::get(cast<Constant>(RHS));
1204       else if (!isa<UndefValue>(RHS))
1205         return ValueLatticeElement::getNot(cast<Constant>(RHS));
1206     }
1207   }
1208 
1209   if (!Val->getType()->isIntegerTy())
1210     return ValueLatticeElement::getOverdefined();
1211 
1212   // Use ConstantRange::makeAllowedICmpRegion in order to determine the possible
1213   // range of Val guaranteed by the condition. Recognize comparisons in the from
1214   // of:
1215   //  icmp <pred> Val, ...
1216   //  icmp <pred> (add Val, Offset), ...
1217   // The latter is the range checking idiom that InstCombine produces. Subtract
1218   // the offset from the allowed range for RHS in this case.
1219 
1220   // Val or (add Val, Offset) can be on either hand of the comparison
1221   if (LHS != Val && !match(LHS, m_Add(m_Specific(Val), m_ConstantInt()))) {
1222     std::swap(LHS, RHS);
1223     Predicate = CmpInst::getSwappedPredicate(Predicate);
1224   }
1225 
1226   ConstantInt *Offset = nullptr;
1227   if (LHS != Val)
1228     match(LHS, m_Add(m_Specific(Val), m_ConstantInt(Offset)));
1229 
1230   if (LHS == Val || Offset) {
1231     // Calculate the range of values that are allowed by the comparison
1232     ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1233                            /*isFullSet=*/true);
1234     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1235       RHSRange = ConstantRange(CI->getValue());
1236     else if (Instruction *I = dyn_cast<Instruction>(RHS))
1237       if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1238         RHSRange = getConstantRangeFromMetadata(*Ranges);
1239 
1240     // If we're interested in the false dest, invert the condition
1241     CmpInst::Predicate Pred =
1242             isTrueDest ? Predicate : CmpInst::getInversePredicate(Predicate);
1243     ConstantRange TrueValues =
1244             ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1245 
1246     if (Offset) // Apply the offset from above.
1247       TrueValues = TrueValues.subtract(Offset->getValue());
1248 
1249     return ValueLatticeElement::getRange(std::move(TrueValues));
1250   }
1251 
1252   return ValueLatticeElement::getOverdefined();
1253 }
1254 
1255 // Handle conditions of the form
1256 // extractvalue(op.with.overflow(%x, C), 1).
1257 static ValueLatticeElement getValueFromOverflowCondition(
1258     Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
1259   // TODO: This only works with a constant RHS for now. We could also compute
1260   // the range of the RHS, but this doesn't fit into the current structure of
1261   // the edge value calculation.
1262   const APInt *C;
1263   if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
1264     return ValueLatticeElement::getOverdefined();
1265 
1266   // Calculate the possible values of %x for which no overflow occurs.
1267   ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(
1268       WO->getBinaryOp(), *C, WO->getNoWrapKind());
1269 
1270   // If overflow is false, %x is constrained to NWR. If overflow is true, %x is
1271   // constrained to it's inverse (all values that might cause overflow).
1272   if (IsTrueDest)
1273     NWR = NWR.inverse();
1274   return ValueLatticeElement::getRange(NWR);
1275 }
1276 
1277 static ValueLatticeElement
1278 getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1279                       SmallDenseMap<Value*, ValueLatticeElement> &Visited);
1280 
1281 static ValueLatticeElement
1282 getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1283                           SmallDenseMap<Value*, ValueLatticeElement> &Visited) {
1284   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1285     return getValueFromICmpCondition(Val, ICI, isTrueDest);
1286 
1287   if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
1288     if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1289       if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
1290         return getValueFromOverflowCondition(Val, WO, isTrueDest);
1291 
1292   // Handle conditions in the form of (cond1 && cond2), we know that on the
1293   // true dest path both of the conditions hold. Similarly for conditions of
1294   // the form (cond1 || cond2), we know that on the false dest path neither
1295   // condition holds.
1296   BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond);
1297   if (!BO || (isTrueDest && BO->getOpcode() != BinaryOperator::And) ||
1298              (!isTrueDest && BO->getOpcode() != BinaryOperator::Or))
1299     return ValueLatticeElement::getOverdefined();
1300 
1301   // Prevent infinite recursion if Cond references itself as in this example:
1302   //  Cond: "%tmp4 = and i1 %tmp4, undef"
1303   //    BL: "%tmp4 = and i1 %tmp4, undef"
1304   //    BR: "i1 undef"
1305   Value *BL = BO->getOperand(0);
1306   Value *BR = BO->getOperand(1);
1307   if (BL == Cond || BR == Cond)
1308     return ValueLatticeElement::getOverdefined();
1309 
1310   return intersect(getValueFromCondition(Val, BL, isTrueDest, Visited),
1311                    getValueFromCondition(Val, BR, isTrueDest, Visited));
1312 }
1313 
1314 static ValueLatticeElement
1315 getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1316                       SmallDenseMap<Value*, ValueLatticeElement> &Visited) {
1317   auto I = Visited.find(Cond);
1318   if (I != Visited.end())
1319     return I->second;
1320 
1321   auto Result = getValueFromConditionImpl(Val, Cond, isTrueDest, Visited);
1322   Visited[Cond] = Result;
1323   return Result;
1324 }
1325 
1326 ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
1327                                           bool isTrueDest) {
1328   assert(Cond && "precondition");
1329   SmallDenseMap<Value*, ValueLatticeElement> Visited;
1330   return getValueFromCondition(Val, Cond, isTrueDest, Visited);
1331 }
1332 
1333 // Return true if Usr has Op as an operand, otherwise false.
1334 static bool usesOperand(User *Usr, Value *Op) {
1335   return find(Usr->operands(), Op) != Usr->op_end();
1336 }
1337 
1338 // Return true if the instruction type of Val is supported by
1339 // constantFoldUser(). Currently CastInst and BinaryOperator only.  Call this
1340 // before calling constantFoldUser() to find out if it's even worth attempting
1341 // to call it.
1342 static bool isOperationFoldable(User *Usr) {
1343   return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr);
1344 }
1345 
1346 // Check if Usr can be simplified to an integer constant when the value of one
1347 // of its operands Op is an integer constant OpConstVal. If so, return it as an
1348 // lattice value range with a single element or otherwise return an overdefined
1349 // lattice value.
1350 static ValueLatticeElement constantFoldUser(User *Usr, Value *Op,
1351                                             const APInt &OpConstVal,
1352                                             const DataLayout &DL) {
1353   assert(isOperationFoldable(Usr) && "Precondition");
1354   Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
1355   // Check if Usr can be simplified to a constant.
1356   if (auto *CI = dyn_cast<CastInst>(Usr)) {
1357     assert(CI->getOperand(0) == Op && "Operand 0 isn't Op");
1358     if (auto *C = dyn_cast_or_null<ConstantInt>(
1359             SimplifyCastInst(CI->getOpcode(), OpConst,
1360                              CI->getDestTy(), DL))) {
1361       return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1362     }
1363   } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
1364     bool Op0Match = BO->getOperand(0) == Op;
1365     bool Op1Match = BO->getOperand(1) == Op;
1366     assert((Op0Match || Op1Match) &&
1367            "Operand 0 nor Operand 1 isn't a match");
1368     Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
1369     Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
1370     if (auto *C = dyn_cast_or_null<ConstantInt>(
1371             SimplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
1372       return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1373     }
1374   }
1375   return ValueLatticeElement::getOverdefined();
1376 }
1377 
1378 /// Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
1379 /// Val is not constrained on the edge.  Result is unspecified if return value
1380 /// is false.
1381 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1382                               BasicBlock *BBTo, ValueLatticeElement &Result) {
1383   // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1384   // know that v != 0.
1385   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1386     // If this is a conditional branch and only one successor goes to BBTo, then
1387     // we may be able to infer something from the condition.
1388     if (BI->isConditional() &&
1389         BI->getSuccessor(0) != BI->getSuccessor(1)) {
1390       bool isTrueDest = BI->getSuccessor(0) == BBTo;
1391       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1392              "BBTo isn't a successor of BBFrom");
1393       Value *Condition = BI->getCondition();
1394 
1395       // If V is the condition of the branch itself, then we know exactly what
1396       // it is.
1397       if (Condition == Val) {
1398         Result = ValueLatticeElement::get(ConstantInt::get(
1399                               Type::getInt1Ty(Val->getContext()), isTrueDest));
1400         return true;
1401       }
1402 
1403       // If the condition of the branch is an equality comparison, we may be
1404       // able to infer the value.
1405       Result = getValueFromCondition(Val, Condition, isTrueDest);
1406       if (!Result.isOverdefined())
1407         return true;
1408 
1409       if (User *Usr = dyn_cast<User>(Val)) {
1410         assert(Result.isOverdefined() && "Result isn't overdefined");
1411         // Check with isOperationFoldable() first to avoid linearly iterating
1412         // over the operands unnecessarily which can be expensive for
1413         // instructions with many operands.
1414         if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
1415           const DataLayout &DL = BBTo->getModule()->getDataLayout();
1416           if (usesOperand(Usr, Condition)) {
1417             // If Val has Condition as an operand and Val can be folded into a
1418             // constant with either Condition == true or Condition == false,
1419             // propagate the constant.
1420             // eg.
1421             //   ; %Val is true on the edge to %then.
1422             //   %Val = and i1 %Condition, true.
1423             //   br %Condition, label %then, label %else
1424             APInt ConditionVal(1, isTrueDest ? 1 : 0);
1425             Result = constantFoldUser(Usr, Condition, ConditionVal, DL);
1426           } else {
1427             // If one of Val's operand has an inferred value, we may be able to
1428             // infer the value of Val.
1429             // eg.
1430             //    ; %Val is 94 on the edge to %then.
1431             //    %Val = add i8 %Op, 1
1432             //    %Condition = icmp eq i8 %Op, 93
1433             //    br i1 %Condition, label %then, label %else
1434             for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
1435               Value *Op = Usr->getOperand(i);
1436               ValueLatticeElement OpLatticeVal =
1437                   getValueFromCondition(Op, Condition, isTrueDest);
1438               if (Optional<APInt> OpConst = OpLatticeVal.asConstantInteger()) {
1439                 Result = constantFoldUser(Usr, Op, OpConst.getValue(), DL);
1440                 break;
1441               }
1442             }
1443           }
1444         }
1445       }
1446       if (!Result.isOverdefined())
1447         return true;
1448     }
1449   }
1450 
1451   // If the edge was formed by a switch on the value, then we may know exactly
1452   // what it is.
1453   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1454     Value *Condition = SI->getCondition();
1455     if (!isa<IntegerType>(Val->getType()))
1456       return false;
1457     bool ValUsesConditionAndMayBeFoldable = false;
1458     if (Condition != Val) {
1459       // Check if Val has Condition as an operand.
1460       if (User *Usr = dyn_cast<User>(Val))
1461         ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
1462             usesOperand(Usr, Condition);
1463       if (!ValUsesConditionAndMayBeFoldable)
1464         return false;
1465     }
1466     assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
1467            "Condition != Val nor Val doesn't use Condition");
1468 
1469     bool DefaultCase = SI->getDefaultDest() == BBTo;
1470     unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1471     ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1472 
1473     for (auto Case : SI->cases()) {
1474       APInt CaseValue = Case.getCaseValue()->getValue();
1475       ConstantRange EdgeVal(CaseValue);
1476       if (ValUsesConditionAndMayBeFoldable) {
1477         User *Usr = cast<User>(Val);
1478         const DataLayout &DL = BBTo->getModule()->getDataLayout();
1479         ValueLatticeElement EdgeLatticeVal =
1480             constantFoldUser(Usr, Condition, CaseValue, DL);
1481         if (EdgeLatticeVal.isOverdefined())
1482           return false;
1483         EdgeVal = EdgeLatticeVal.getConstantRange();
1484       }
1485       if (DefaultCase) {
1486         // It is possible that the default destination is the destination of
1487         // some cases. We cannot perform difference for those cases.
1488         // We know Condition != CaseValue in BBTo.  In some cases we can use
1489         // this to infer Val == f(Condition) is != f(CaseValue).  For now, we
1490         // only do this when f is identity (i.e. Val == Condition), but we
1491         // should be able to do this for any injective f.
1492         if (Case.getCaseSuccessor() != BBTo && Condition == Val)
1493           EdgesVals = EdgesVals.difference(EdgeVal);
1494       } else if (Case.getCaseSuccessor() == BBTo)
1495         EdgesVals = EdgesVals.unionWith(EdgeVal);
1496     }
1497     Result = ValueLatticeElement::getRange(std::move(EdgesVals));
1498     return true;
1499   }
1500   return false;
1501 }
1502 
1503 /// Compute the value of Val on the edge BBFrom -> BBTo or the value at
1504 /// the basic block if the edge does not constrain Val.
1505 bool LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
1506                                      BasicBlock *BBTo,
1507                                      ValueLatticeElement &Result,
1508                                      Instruction *CxtI) {
1509   // If already a constant, there is nothing to compute.
1510   if (Constant *VC = dyn_cast<Constant>(Val)) {
1511     Result = ValueLatticeElement::get(VC);
1512     return true;
1513   }
1514 
1515   ValueLatticeElement LocalResult;
1516   if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1517     // If we couldn't constrain the value on the edge, LocalResult doesn't
1518     // provide any information.
1519     LocalResult = ValueLatticeElement::getOverdefined();
1520 
1521   if (hasSingleValue(LocalResult)) {
1522     // Can't get any more precise here
1523     Result = LocalResult;
1524     return true;
1525   }
1526 
1527   if (!hasBlockValue(Val, BBFrom)) {
1528     if (pushBlockValue(std::make_pair(BBFrom, Val)))
1529       return false;
1530     // No new information.
1531     Result = LocalResult;
1532     return true;
1533   }
1534 
1535   // Try to intersect ranges of the BB and the constraint on the edge.
1536   ValueLatticeElement InBlock = getBlockValue(Val, BBFrom);
1537   intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock,
1538                                                 BBFrom->getTerminator());
1539   // We can use the context instruction (generically the ultimate instruction
1540   // the calling pass is trying to simplify) here, even though the result of
1541   // this function is generally cached when called from the solve* functions
1542   // (and that cached result might be used with queries using a different
1543   // context instruction), because when this function is called from the solve*
1544   // functions, the context instruction is not provided. When called from
1545   // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
1546   // but then the result is not cached.
1547   intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
1548 
1549   Result = intersect(LocalResult, InBlock);
1550   return true;
1551 }
1552 
1553 ValueLatticeElement LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
1554                                                        Instruction *CxtI) {
1555   LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1556                     << BB->getName() << "'\n");
1557 
1558   assert(BlockValueStack.empty() && BlockValueSet.empty());
1559   if (!hasBlockValue(V, BB)) {
1560     pushBlockValue(std::make_pair(BB, V));
1561     solve();
1562   }
1563   ValueLatticeElement Result = getBlockValue(V, BB);
1564   intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1565 
1566   LLVM_DEBUG(dbgs() << "  Result = " << Result << "\n");
1567   return Result;
1568 }
1569 
1570 ValueLatticeElement LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
1571   LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CxtI->getName()
1572                     << "'\n");
1573 
1574   if (auto *C = dyn_cast<Constant>(V))
1575     return ValueLatticeElement::get(C);
1576 
1577   ValueLatticeElement Result = ValueLatticeElement::getOverdefined();
1578   if (auto *I = dyn_cast<Instruction>(V))
1579     Result = getFromRangeMetadata(I);
1580   intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1581 
1582   LLVM_DEBUG(dbgs() << "  Result = " << Result << "\n");
1583   return Result;
1584 }
1585 
1586 ValueLatticeElement LazyValueInfoImpl::
1587 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1588                Instruction *CxtI) {
1589   LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1590                     << FromBB->getName() << "' to '" << ToBB->getName()
1591                     << "'\n");
1592 
1593   ValueLatticeElement Result;
1594   if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
1595     solve();
1596     bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
1597     (void)WasFastQuery;
1598     assert(WasFastQuery && "More work to do after problem solved?");
1599   }
1600 
1601   LLVM_DEBUG(dbgs() << "  Result = " << Result << "\n");
1602   return Result;
1603 }
1604 
1605 void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1606                                    BasicBlock *NewSucc) {
1607   TheCache.threadEdgeImpl(OldSucc, NewSucc);
1608 }
1609 
1610 //===----------------------------------------------------------------------===//
1611 //                            LazyValueInfo Impl
1612 //===----------------------------------------------------------------------===//
1613 
1614 /// This lazily constructs the LazyValueInfoImpl.
1615 static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
1616                                   const DataLayout *DL,
1617                                   DominatorTree *DT = nullptr) {
1618   if (!PImpl) {
1619     assert(DL && "getCache() called with a null DataLayout");
1620     PImpl = new LazyValueInfoImpl(AC, *DL, DT);
1621   }
1622   return *static_cast<LazyValueInfoImpl*>(PImpl);
1623 }
1624 
1625 bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
1626   Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1627   const DataLayout &DL = F.getParent()->getDataLayout();
1628 
1629   DominatorTreeWrapperPass *DTWP =
1630       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1631   Info.DT = DTWP ? &DTWP->getDomTree() : nullptr;
1632   Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1633 
1634   if (Info.PImpl)
1635     getImpl(Info.PImpl, Info.AC, &DL, Info.DT).clear();
1636 
1637   // Fully lazy.
1638   return false;
1639 }
1640 
1641 void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1642   AU.setPreservesAll();
1643   AU.addRequired<AssumptionCacheTracker>();
1644   AU.addRequired<TargetLibraryInfoWrapperPass>();
1645 }
1646 
1647 LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1648 
1649 LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1650 
1651 void LazyValueInfo::releaseMemory() {
1652   // If the cache was allocated, free it.
1653   if (PImpl) {
1654     delete &getImpl(PImpl, AC, nullptr);
1655     PImpl = nullptr;
1656   }
1657 }
1658 
1659 bool LazyValueInfo::invalidate(Function &F, const PreservedAnalyses &PA,
1660                                FunctionAnalysisManager::Invalidator &Inv) {
1661   // We need to invalidate if we have either failed to preserve this analyses
1662   // result directly or if any of its dependencies have been invalidated.
1663   auto PAC = PA.getChecker<LazyValueAnalysis>();
1664   if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
1665       (DT && Inv.invalidate<DominatorTreeAnalysis>(F, PA)))
1666     return true;
1667 
1668   return false;
1669 }
1670 
1671 void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1672 
1673 LazyValueInfo LazyValueAnalysis::run(Function &F,
1674                                      FunctionAnalysisManager &FAM) {
1675   auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1676   auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1677   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1678 
1679   return LazyValueInfo(&AC, &F.getParent()->getDataLayout(), &TLI, DT);
1680 }
1681 
1682 /// Returns true if we can statically tell that this value will never be a
1683 /// "useful" constant.  In practice, this means we've got something like an
1684 /// alloca or a malloc call for which a comparison against a constant can
1685 /// only be guarding dead code.  Note that we are potentially giving up some
1686 /// precision in dead code (a constant result) in favour of avoiding a
1687 /// expensive search for a easily answered common query.
1688 static bool isKnownNonConstant(Value *V) {
1689   V = V->stripPointerCasts();
1690   // The return val of alloc cannot be a Constant.
1691   if (isa<AllocaInst>(V))
1692     return true;
1693   return false;
1694 }
1695 
1696 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1697                                      Instruction *CxtI) {
1698   // Bail out early if V is known not to be a Constant.
1699   if (isKnownNonConstant(V))
1700     return nullptr;
1701 
1702   const DataLayout &DL = BB->getModule()->getDataLayout();
1703   ValueLatticeElement Result =
1704       getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1705 
1706   if (Result.isConstant())
1707     return Result.getConstant();
1708   if (Result.isConstantRange()) {
1709     const ConstantRange &CR = Result.getConstantRange();
1710     if (const APInt *SingleVal = CR.getSingleElement())
1711       return ConstantInt::get(V->getContext(), *SingleVal);
1712   }
1713   return nullptr;
1714 }
1715 
1716 ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
1717                                               Instruction *CxtI,
1718                                               bool UndefAllowed) {
1719   assert(V->getType()->isIntegerTy());
1720   unsigned Width = V->getType()->getIntegerBitWidth();
1721   const DataLayout &DL = BB->getModule()->getDataLayout();
1722   ValueLatticeElement Result =
1723       getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1724   if (Result.isUnknown())
1725     return ConstantRange::getEmpty(Width);
1726   if (Result.isConstantRange(UndefAllowed))
1727     return Result.getConstantRange(UndefAllowed);
1728   // We represent ConstantInt constants as constant ranges but other kinds
1729   // of integer constants, i.e. ConstantExpr will be tagged as constants
1730   assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1731          "ConstantInt value must be represented as constantrange");
1732   return ConstantRange::getFull(Width);
1733 }
1734 
1735 /// Determine whether the specified value is known to be a
1736 /// constant on the specified edge. Return null if not.
1737 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1738                                            BasicBlock *ToBB,
1739                                            Instruction *CxtI) {
1740   const DataLayout &DL = FromBB->getModule()->getDataLayout();
1741   ValueLatticeElement Result =
1742       getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1743 
1744   if (Result.isConstant())
1745     return Result.getConstant();
1746   if (Result.isConstantRange()) {
1747     const ConstantRange &CR = Result.getConstantRange();
1748     if (const APInt *SingleVal = CR.getSingleElement())
1749       return ConstantInt::get(V->getContext(), *SingleVal);
1750   }
1751   return nullptr;
1752 }
1753 
1754 ConstantRange LazyValueInfo::getConstantRangeOnEdge(Value *V,
1755                                                     BasicBlock *FromBB,
1756                                                     BasicBlock *ToBB,
1757                                                     Instruction *CxtI) {
1758   unsigned Width = V->getType()->getIntegerBitWidth();
1759   const DataLayout &DL = FromBB->getModule()->getDataLayout();
1760   ValueLatticeElement Result =
1761       getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1762 
1763   if (Result.isUnknown())
1764     return ConstantRange::getEmpty(Width);
1765   if (Result.isConstantRange())
1766     return Result.getConstantRange();
1767   // We represent ConstantInt constants as constant ranges but other kinds
1768   // of integer constants, i.e. ConstantExpr will be tagged as constants
1769   assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1770          "ConstantInt value must be represented as constantrange");
1771   return ConstantRange::getFull(Width);
1772 }
1773 
1774 static LazyValueInfo::Tristate
1775 getPredicateResult(unsigned Pred, Constant *C, const ValueLatticeElement &Val,
1776                    const DataLayout &DL, TargetLibraryInfo *TLI) {
1777   // If we know the value is a constant, evaluate the conditional.
1778   Constant *Res = nullptr;
1779   if (Val.isConstant()) {
1780     Res = ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL, TLI);
1781     if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1782       return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1783     return LazyValueInfo::Unknown;
1784   }
1785 
1786   if (Val.isConstantRange()) {
1787     ConstantInt *CI = dyn_cast<ConstantInt>(C);
1788     if (!CI) return LazyValueInfo::Unknown;
1789 
1790     const ConstantRange &CR = Val.getConstantRange();
1791     if (Pred == ICmpInst::ICMP_EQ) {
1792       if (!CR.contains(CI->getValue()))
1793         return LazyValueInfo::False;
1794 
1795       if (CR.isSingleElement())
1796         return LazyValueInfo::True;
1797     } else if (Pred == ICmpInst::ICMP_NE) {
1798       if (!CR.contains(CI->getValue()))
1799         return LazyValueInfo::True;
1800 
1801       if (CR.isSingleElement())
1802         return LazyValueInfo::False;
1803     } else {
1804       // Handle more complex predicates.
1805       ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
1806           (ICmpInst::Predicate)Pred, CI->getValue());
1807       if (TrueValues.contains(CR))
1808         return LazyValueInfo::True;
1809       if (TrueValues.inverse().contains(CR))
1810         return LazyValueInfo::False;
1811     }
1812     return LazyValueInfo::Unknown;
1813   }
1814 
1815   if (Val.isNotConstant()) {
1816     // If this is an equality comparison, we can try to fold it knowing that
1817     // "V != C1".
1818     if (Pred == ICmpInst::ICMP_EQ) {
1819       // !C1 == C -> false iff C1 == C.
1820       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1821                                             Val.getNotConstant(), C, DL,
1822                                             TLI);
1823       if (Res->isNullValue())
1824         return LazyValueInfo::False;
1825     } else if (Pred == ICmpInst::ICMP_NE) {
1826       // !C1 != C -> true iff C1 == C.
1827       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1828                                             Val.getNotConstant(), C, DL,
1829                                             TLI);
1830       if (Res->isNullValue())
1831         return LazyValueInfo::True;
1832     }
1833     return LazyValueInfo::Unknown;
1834   }
1835 
1836   return LazyValueInfo::Unknown;
1837 }
1838 
1839 /// Determine whether the specified value comparison with a constant is known to
1840 /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1841 LazyValueInfo::Tristate
1842 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1843                                   BasicBlock *FromBB, BasicBlock *ToBB,
1844                                   Instruction *CxtI) {
1845   const DataLayout &DL = FromBB->getModule()->getDataLayout();
1846   ValueLatticeElement Result =
1847       getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1848 
1849   return getPredicateResult(Pred, C, Result, DL, TLI);
1850 }
1851 
1852 LazyValueInfo::Tristate
1853 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1854                               Instruction *CxtI) {
1855   // Is or is not NonNull are common predicates being queried. If
1856   // isKnownNonZero can tell us the result of the predicate, we can
1857   // return it quickly. But this is only a fastpath, and falling
1858   // through would still be correct.
1859   const DataLayout &DL = CxtI->getModule()->getDataLayout();
1860   if (V->getType()->isPointerTy() && C->isNullValue() &&
1861       isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
1862     if (Pred == ICmpInst::ICMP_EQ)
1863       return LazyValueInfo::False;
1864     else if (Pred == ICmpInst::ICMP_NE)
1865       return LazyValueInfo::True;
1866   }
1867   ValueLatticeElement Result = getImpl(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
1868   Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1869   if (Ret != Unknown)
1870     return Ret;
1871 
1872   // Note: The following bit of code is somewhat distinct from the rest of LVI;
1873   // LVI as a whole tries to compute a lattice value which is conservatively
1874   // correct at a given location.  In this case, we have a predicate which we
1875   // weren't able to prove about the merged result, and we're pushing that
1876   // predicate back along each incoming edge to see if we can prove it
1877   // separately for each input.  As a motivating example, consider:
1878   // bb1:
1879   //   %v1 = ... ; constantrange<1, 5>
1880   //   br label %merge
1881   // bb2:
1882   //   %v2 = ... ; constantrange<10, 20>
1883   //   br label %merge
1884   // merge:
1885   //   %phi = phi [%v1, %v2] ; constantrange<1,20>
1886   //   %pred = icmp eq i32 %phi, 8
1887   // We can't tell from the lattice value for '%phi' that '%pred' is false
1888   // along each path, but by checking the predicate over each input separately,
1889   // we can.
1890   // We limit the search to one step backwards from the current BB and value.
1891   // We could consider extending this to search further backwards through the
1892   // CFG and/or value graph, but there are non-obvious compile time vs quality
1893   // tradeoffs.
1894   if (CxtI) {
1895     BasicBlock *BB = CxtI->getParent();
1896 
1897     // Function entry or an unreachable block.  Bail to avoid confusing
1898     // analysis below.
1899     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1900     if (PI == PE)
1901       return Unknown;
1902 
1903     // If V is a PHI node in the same block as the context, we need to ask
1904     // questions about the predicate as applied to the incoming value along
1905     // each edge. This is useful for eliminating cases where the predicate is
1906     // known along all incoming edges.
1907     if (auto *PHI = dyn_cast<PHINode>(V))
1908       if (PHI->getParent() == BB) {
1909         Tristate Baseline = Unknown;
1910         for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1911           Value *Incoming = PHI->getIncomingValue(i);
1912           BasicBlock *PredBB = PHI->getIncomingBlock(i);
1913           // Note that PredBB may be BB itself.
1914           Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1915                                                CxtI);
1916 
1917           // Keep going as long as we've seen a consistent known result for
1918           // all inputs.
1919           Baseline = (i == 0) ? Result /* First iteration */
1920             : (Baseline == Result ? Baseline : Unknown); /* All others */
1921           if (Baseline == Unknown)
1922             break;
1923         }
1924         if (Baseline != Unknown)
1925           return Baseline;
1926       }
1927 
1928     // For a comparison where the V is outside this block, it's possible
1929     // that we've branched on it before. Look to see if the value is known
1930     // on all incoming edges.
1931     if (!isa<Instruction>(V) ||
1932         cast<Instruction>(V)->getParent() != BB) {
1933       // For predecessor edge, determine if the comparison is true or false
1934       // on that edge. If they're all true or all false, we can conclude
1935       // the value of the comparison in this block.
1936       Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1937       if (Baseline != Unknown) {
1938         // Check that all remaining incoming values match the first one.
1939         while (++PI != PE) {
1940           Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1941           if (Ret != Baseline) break;
1942         }
1943         // If we terminated early, then one of the values didn't match.
1944         if (PI == PE) {
1945           return Baseline;
1946         }
1947       }
1948     }
1949   }
1950   return Unknown;
1951 }
1952 
1953 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1954                                BasicBlock *NewSucc) {
1955   if (PImpl) {
1956     const DataLayout &DL = PredBB->getModule()->getDataLayout();
1957     getImpl(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1958   }
1959 }
1960 
1961 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1962   if (PImpl) {
1963     const DataLayout &DL = BB->getModule()->getDataLayout();
1964     getImpl(PImpl, AC, &DL, DT).eraseBlock(BB);
1965   }
1966 }
1967 
1968 
1969 void LazyValueInfo::printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
1970   if (PImpl) {
1971     getImpl(PImpl, AC, DL, DT).printLVI(F, DTree, OS);
1972   }
1973 }
1974 
1975 void LazyValueInfo::disableDT() {
1976   if (PImpl)
1977     getImpl(PImpl, AC, DL, DT).disableDT();
1978 }
1979 
1980 void LazyValueInfo::enableDT() {
1981   if (PImpl)
1982     getImpl(PImpl, AC, DL, DT).enableDT();
1983 }
1984 
1985 // Print the LVI for the function arguments at the start of each basic block.
1986 void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
1987     const BasicBlock *BB, formatted_raw_ostream &OS) {
1988   // Find if there are latticevalues defined for arguments of the function.
1989   auto *F = BB->getParent();
1990   for (auto &Arg : F->args()) {
1991     ValueLatticeElement Result = LVIImpl->getValueInBlock(
1992         const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
1993     if (Result.isUnknown())
1994       continue;
1995     OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
1996   }
1997 }
1998 
1999 // This function prints the LVI analysis for the instruction I at the beginning
2000 // of various basic blocks. It relies on calculated values that are stored in
2001 // the LazyValueInfoCache, and in the absence of cached values, recalculate the
2002 // LazyValueInfo for `I`, and print that info.
2003 void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
2004     const Instruction *I, formatted_raw_ostream &OS) {
2005 
2006   auto *ParentBB = I->getParent();
2007   SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
2008   // We can generate (solve) LVI values only for blocks that are dominated by
2009   // the I's parent. However, to avoid generating LVI for all dominating blocks,
2010   // that contain redundant/uninteresting information, we print LVI for
2011   // blocks that may use this LVI information (such as immediate successor
2012   // blocks, and blocks that contain uses of `I`).
2013   auto printResult = [&](const BasicBlock *BB) {
2014     if (!BlocksContainingLVI.insert(BB).second)
2015       return;
2016     ValueLatticeElement Result = LVIImpl->getValueInBlock(
2017         const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
2018       OS << "; LatticeVal for: '" << *I << "' in BB: '";
2019       BB->printAsOperand(OS, false);
2020       OS << "' is: " << Result << "\n";
2021   };
2022 
2023   printResult(ParentBB);
2024   // Print the LVI analysis results for the immediate successor blocks, that
2025   // are dominated by `ParentBB`.
2026   for (auto *BBSucc : successors(ParentBB))
2027     if (DT.dominates(ParentBB, BBSucc))
2028       printResult(BBSucc);
2029 
2030   // Print LVI in blocks where `I` is used.
2031   for (auto *U : I->users())
2032     if (auto *UseI = dyn_cast<Instruction>(U))
2033       if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
2034         printResult(UseI->getParent());
2035 
2036 }
2037 
2038 namespace {
2039 // Printer class for LazyValueInfo results.
2040 class LazyValueInfoPrinter : public FunctionPass {
2041 public:
2042   static char ID; // Pass identification, replacement for typeid
2043   LazyValueInfoPrinter() : FunctionPass(ID) {
2044     initializeLazyValueInfoPrinterPass(*PassRegistry::getPassRegistry());
2045   }
2046 
2047   void getAnalysisUsage(AnalysisUsage &AU) const override {
2048     AU.setPreservesAll();
2049     AU.addRequired<LazyValueInfoWrapperPass>();
2050     AU.addRequired<DominatorTreeWrapperPass>();
2051   }
2052 
2053   // Get the mandatory dominator tree analysis and pass this in to the
2054   // LVIPrinter. We cannot rely on the LVI's DT, since it's optional.
2055   bool runOnFunction(Function &F) override {
2056     dbgs() << "LVI for function '" << F.getName() << "':\n";
2057     auto &LVI = getAnalysis<LazyValueInfoWrapperPass>().getLVI();
2058     auto &DTree = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2059     LVI.printLVI(F, DTree, dbgs());
2060     return false;
2061   }
2062 };
2063 }
2064 
2065 char LazyValueInfoPrinter::ID = 0;
2066 INITIALIZE_PASS_BEGIN(LazyValueInfoPrinter, "print-lazy-value-info",
2067                 "Lazy Value Info Printer Pass", false, false)
2068 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
2069 INITIALIZE_PASS_END(LazyValueInfoPrinter, "print-lazy-value-info",
2070                 "Lazy Value Info Printer Pass", false, false)
2071