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