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