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