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