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