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