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