1 //===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interface for lazy computation of value constraint
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/LazyValueInfo.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/CFG.h"
23 #include "llvm/IR/ConstantRange.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/PatternMatch.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
36 using namespace PatternMatch;
38 #define DEBUG_TYPE "lazy-value-info"
40 char LazyValueInfo::ID = 0;
41 INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
42 "Lazy Value Information Analysis", false, true)
43 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
44 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
45 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
46 "Lazy Value Information Analysis", false, true)
49 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
53 //===----------------------------------------------------------------------===//
55 //===----------------------------------------------------------------------===//
57 /// This is the information tracked by LazyValueInfo for each value.
59 /// FIXME: This is basically just for bringup, this can be made a lot more rich
65 /// This Value has no known value yet.
68 /// This Value has a specific constant value.
71 /// This Value is known to not have the specified value.
74 /// The Value falls within this range.
77 /// This value is not known to be constant, and we know that it has a value.
81 /// Val: This stores the current lattice value along with the Constant* for
82 /// the constant if this is a 'constant' or 'notconstant' value.
88 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
90 static LVILatticeVal get(Constant *C) {
92 if (!isa<UndefValue>(C))
96 static LVILatticeVal getNot(Constant *C) {
98 if (!isa<UndefValue>(C))
99 Res.markNotConstant(C);
102 static LVILatticeVal getRange(ConstantRange CR) {
104 Res.markConstantRange(CR);
108 bool isUndefined() const { return Tag == undefined; }
109 bool isConstant() const { return Tag == constant; }
110 bool isNotConstant() const { return Tag == notconstant; }
111 bool isConstantRange() const { return Tag == constantrange; }
112 bool isOverdefined() const { return Tag == overdefined; }
114 Constant *getConstant() const {
115 assert(isConstant() && "Cannot get the constant of a non-constant!");
119 Constant *getNotConstant() const {
120 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
124 ConstantRange getConstantRange() const {
125 assert(isConstantRange() &&
126 "Cannot get the constant-range of a non-constant-range!");
130 /// Return true if this is a change in status.
131 bool markOverdefined() {
138 /// Return true if this is a change in status.
139 bool markConstant(Constant *V) {
140 assert(V && "Marking constant with NULL");
141 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
142 return markConstantRange(ConstantRange(CI->getValue()));
143 if (isa<UndefValue>(V))
146 assert((!isConstant() || getConstant() == V) &&
147 "Marking constant with different value");
148 assert(isUndefined());
154 /// Return true if this is a change in status.
155 bool markNotConstant(Constant *V) {
156 assert(V && "Marking constant with NULL");
157 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
158 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
159 if (isa<UndefValue>(V))
162 assert((!isConstant() || getConstant() != V) &&
163 "Marking constant !constant with same value");
164 assert((!isNotConstant() || getNotConstant() == V) &&
165 "Marking !constant with different value");
166 assert(isUndefined() || isConstant());
172 /// Return true if this is a change in status.
173 bool markConstantRange(const ConstantRange NewR) {
174 if (isConstantRange()) {
175 if (NewR.isEmptySet())
176 return markOverdefined();
178 bool changed = Range != NewR;
183 assert(isUndefined());
184 if (NewR.isEmptySet())
185 return markOverdefined();
192 /// Merge the specified lattice value into this one, updating this
193 /// one and returning true if anything changed.
194 bool mergeIn(const LVILatticeVal &RHS) {
195 if (RHS.isUndefined() || isOverdefined()) return false;
196 if (RHS.isOverdefined()) return markOverdefined();
206 if (RHS.isConstant()) {
209 return markOverdefined();
212 if (RHS.isNotConstant()) {
214 return markOverdefined();
216 // Unless we can prove that the two Constants are different, we must
217 // move to overdefined.
218 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
219 if (ConstantInt *Res = dyn_cast<ConstantInt>(
220 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
222 RHS.getNotConstant())))
224 return markNotConstant(RHS.getNotConstant());
226 return markOverdefined();
229 // RHS is a ConstantRange, LHS is a non-integer Constant.
231 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
232 // a function. The correct result is to pick up RHS.
234 return markOverdefined();
237 if (isNotConstant()) {
238 if (RHS.isConstant()) {
240 return markOverdefined();
242 // Unless we can prove that the two Constants are different, we must
243 // move to overdefined.
244 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
245 if (ConstantInt *Res = dyn_cast<ConstantInt>(
246 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
252 return markOverdefined();
255 if (RHS.isNotConstant()) {
258 return markOverdefined();
261 return markOverdefined();
264 assert(isConstantRange() && "New LVILattice type?");
265 if (!RHS.isConstantRange())
266 return markOverdefined();
268 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
269 if (NewR.isFullSet())
270 return markOverdefined();
271 return markConstantRange(NewR);
275 } // end anonymous namespace.
278 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
280 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
281 if (Val.isUndefined())
282 return OS << "undefined";
283 if (Val.isOverdefined())
284 return OS << "overdefined";
286 if (Val.isNotConstant())
287 return OS << "notconstant<" << *Val.getNotConstant() << '>';
288 else if (Val.isConstantRange())
289 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
290 << Val.getConstantRange().getUpper() << '>';
291 return OS << "constant<" << *Val.getConstant() << '>';
295 //===----------------------------------------------------------------------===//
296 // LazyValueInfoCache Decl
297 //===----------------------------------------------------------------------===//
300 /// A callback value handle updates the cache when values are erased.
301 class LazyValueInfoCache;
302 struct LVIValueHandle : public CallbackVH {
303 LazyValueInfoCache *Parent;
305 LVIValueHandle(Value *V, LazyValueInfoCache *P)
306 : CallbackVH(V), Parent(P) { }
308 void deleted() override;
309 void allUsesReplacedWith(Value *V) override {
316 /// This is the cache kept by LazyValueInfo which
317 /// maintains information about queries across the clients' queries.
318 class LazyValueInfoCache {
319 /// This is all of the cached block information for exactly one Value*.
320 /// The entries are sorted by the BasicBlock* of the
321 /// entries, allowing us to do a lookup with a binary search.
322 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
324 /// This is all of the cached information for all values,
325 /// mapped from Value* to key information.
326 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
328 /// This tracks, on a per-block basis, the set of values that are
329 /// over-defined at the end of that block. This is required
330 /// for cache updating.
331 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
332 DenseSet<OverDefinedPairTy> OverDefinedCache;
334 /// Keep track of all blocks that we have ever seen, so we
335 /// don't spend time removing unused blocks from our caches.
336 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
338 /// This stack holds the state of the value solver during a query.
339 /// It basically emulates the callstack of the naive
340 /// recursive value lookup process.
341 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
343 /// Keeps track of which block-value pairs are in BlockValueStack.
344 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
346 /// Push BV onto BlockValueStack unless it's already in there.
347 /// Returns true on success.
348 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
349 if (!BlockValueSet.insert(BV).second)
350 return false; // It's already in the stack.
352 BlockValueStack.push(BV);
356 /// A pointer to the cache of @llvm.assume calls.
358 /// An optional DL pointer.
359 const DataLayout *DL;
360 /// An optional DT pointer.
363 friend struct LVIValueHandle;
365 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
366 SeenBlocks.insert(BB);
367 lookup(Val)[BB] = Result;
368 if (Result.isOverdefined())
369 OverDefinedCache.insert(std::make_pair(BB, Val));
372 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
373 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
374 LVILatticeVal &Result,
375 Instruction *CxtI = nullptr);
376 bool hasBlockValue(Value *Val, BasicBlock *BB);
378 // These methods process one work item and may add more. A false value
379 // returned means that the work item was not completely processed and must
380 // be revisited after going through the new items.
381 bool solveBlockValue(Value *Val, BasicBlock *BB);
382 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
383 Value *Val, BasicBlock *BB);
384 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
385 PHINode *PN, BasicBlock *BB);
386 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
387 Instruction *BBI, BasicBlock *BB);
388 void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
393 ValueCacheEntryTy &lookup(Value *V) {
394 return ValueCache[LVIValueHandle(V, this)];
398 /// This is the query interface to determine the lattice
399 /// value for the specified Value* at the end of the specified block.
400 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
401 Instruction *CxtI = nullptr);
403 /// This is the query interface to determine the lattice
404 /// value for the specified Value* at the specified instruction (generally
405 /// from an assume intrinsic).
406 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
408 /// This is the query interface to determine the lattice
409 /// value for the specified Value* that is true on the specified edge.
410 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
411 Instruction *CxtI = nullptr);
413 /// This is the update interface to inform the cache that an edge from
414 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
415 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
417 /// This is part of the update interface to inform the cache
418 /// that a block has been deleted.
419 void eraseBlock(BasicBlock *BB);
421 /// clear - Empty the cache.
425 OverDefinedCache.clear();
428 LazyValueInfoCache(AssumptionCache *AC, const DataLayout *DL = nullptr,
429 DominatorTree *DT = nullptr)
430 : AC(AC), DL(DL), DT(DT) {}
432 } // end anonymous namespace
434 void LVIValueHandle::deleted() {
435 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
437 SmallVector<OverDefinedPairTy, 4> ToErase;
438 for (const OverDefinedPairTy &P : Parent->OverDefinedCache)
439 if (P.second == getValPtr())
440 ToErase.push_back(P);
441 for (const OverDefinedPairTy &P : ToErase)
442 Parent->OverDefinedCache.erase(P);
444 // This erasure deallocates *this, so it MUST happen after we're done
445 // using any and all members of *this.
446 Parent->ValueCache.erase(*this);
449 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
450 // Shortcut if we have never seen this block.
451 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
452 if (I == SeenBlocks.end())
456 SmallVector<OverDefinedPairTy, 4> ToErase;
457 for (const OverDefinedPairTy& P : OverDefinedCache)
459 ToErase.push_back(P);
460 for (const OverDefinedPairTy &P : ToErase)
461 OverDefinedCache.erase(P);
463 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
464 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
468 void LazyValueInfoCache::solve() {
469 while (!BlockValueStack.empty()) {
470 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
471 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
473 if (solveBlockValue(e.second, e.first)) {
474 // The work item was completely processed.
475 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
476 assert(lookup(e.second).count(e.first) && "Result should be in cache!");
478 BlockValueStack.pop();
479 BlockValueSet.erase(e);
481 // More work needs to be done before revisiting.
482 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
487 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
488 // If already a constant, there is nothing to compute.
489 if (isa<Constant>(Val))
492 LVIValueHandle ValHandle(Val, this);
493 std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
494 ValueCache.find(ValHandle);
495 if (I == ValueCache.end()) return false;
496 return I->second.count(BB);
499 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
500 // If already a constant, there is nothing to compute.
501 if (Constant *VC = dyn_cast<Constant>(Val))
502 return LVILatticeVal::get(VC);
504 SeenBlocks.insert(BB);
505 return lookup(Val)[BB];
508 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
509 if (isa<Constant>(Val))
512 if (lookup(Val).count(BB)) {
513 // If we have a cached value, use that.
514 DEBUG(dbgs() << " reuse BB '" << BB->getName()
515 << "' val=" << lookup(Val)[BB] << '\n');
517 // Since we're reusing a cached value, we don't need to update the
518 // OverDefinedCache. The cache will have been properly updated whenever the
519 // cached value was inserted.
523 // Hold off inserting this value into the Cache in case we have to return
524 // false and come back later.
527 Instruction *BBI = dyn_cast<Instruction>(Val);
528 if (!BBI || BBI->getParent() != BB) {
529 if (!solveBlockValueNonLocal(Res, Val, BB))
531 insertResult(Val, BB, Res);
535 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
536 if (!solveBlockValuePHINode(Res, PN, BB))
538 insertResult(Val, BB, Res);
542 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
543 Res = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
544 insertResult(Val, BB, Res);
548 // We can only analyze the definitions of certain classes of instructions
549 // (integral binops and casts at the moment), so bail if this isn't one.
550 LVILatticeVal Result;
551 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
552 !BBI->getType()->isIntegerTy()) {
553 DEBUG(dbgs() << " compute BB '" << BB->getName()
554 << "' - overdefined because inst def found.\n");
555 Res.markOverdefined();
556 insertResult(Val, BB, Res);
560 // FIXME: We're currently limited to binops with a constant RHS. This should
562 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
563 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
564 DEBUG(dbgs() << " compute BB '" << BB->getName()
565 << "' - overdefined because inst def found.\n");
567 Res.markOverdefined();
568 insertResult(Val, BB, Res);
572 if (!solveBlockValueConstantRange(Res, BBI, BB))
574 insertResult(Val, BB, Res);
578 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
579 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
580 return L->getPointerAddressSpace() == 0 &&
581 GetUnderlyingObject(L->getPointerOperand()) == Ptr;
583 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
584 return S->getPointerAddressSpace() == 0 &&
585 GetUnderlyingObject(S->getPointerOperand()) == Ptr;
587 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
588 if (MI->isVolatile()) return false;
590 // FIXME: check whether it has a valuerange that excludes zero?
591 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
592 if (!Len || Len->isZero()) return false;
594 if (MI->getDestAddressSpace() == 0)
595 if (GetUnderlyingObject(MI->getRawDest()) == Ptr)
597 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
598 if (MTI->getSourceAddressSpace() == 0)
599 if (GetUnderlyingObject(MTI->getRawSource()) == Ptr)
605 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
606 Value *Val, BasicBlock *BB) {
607 LVILatticeVal Result; // Start Undefined.
609 // If this is a pointer, and there's a load from that pointer in this BB,
610 // then we know that the pointer can't be NULL.
611 bool NotNull = false;
612 if (Val->getType()->isPointerTy()) {
613 if (isKnownNonNull(Val)) {
616 Value *UnderlyingVal = GetUnderlyingObject(Val);
617 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
618 // inside InstructionDereferencesPointer either.
619 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, nullptr, 1)) {
620 for (Instruction &I : *BB) {
621 if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
630 // If this is the entry block, we must be asking about an argument. The
631 // value is overdefined.
632 if (BB == &BB->getParent()->getEntryBlock()) {
633 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
635 PointerType *PTy = cast<PointerType>(Val->getType());
636 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
638 Result.markOverdefined();
644 // Loop over all of our predecessors, merging what we know from them into
646 bool EdgesMissing = false;
647 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
648 LVILatticeVal EdgeResult;
649 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
653 Result.mergeIn(EdgeResult);
655 // If we hit overdefined, exit early. The BlockVals entry is already set
657 if (Result.isOverdefined()) {
658 DEBUG(dbgs() << " compute BB '" << BB->getName()
659 << "' - overdefined because of pred.\n");
660 // If we previously determined that this is a pointer that can't be null
661 // then return that rather than giving up entirely.
663 PointerType *PTy = cast<PointerType>(Val->getType());
664 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
674 // Return the merged value, which is more precise than 'overdefined'.
675 assert(!Result.isOverdefined());
680 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
681 PHINode *PN, BasicBlock *BB) {
682 LVILatticeVal Result; // Start Undefined.
684 // Loop over all of our predecessors, merging what we know from them into
686 bool EdgesMissing = false;
687 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
688 BasicBlock *PhiBB = PN->getIncomingBlock(i);
689 Value *PhiVal = PN->getIncomingValue(i);
690 LVILatticeVal EdgeResult;
691 // Note that we can provide PN as the context value to getEdgeValue, even
692 // though the results will be cached, because PN is the value being used as
693 // the cache key in the caller.
694 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
698 Result.mergeIn(EdgeResult);
700 // If we hit overdefined, exit early. The BlockVals entry is already set
702 if (Result.isOverdefined()) {
703 DEBUG(dbgs() << " compute BB '" << BB->getName()
704 << "' - overdefined because of pred.\n");
713 // Return the merged value, which is more precise than 'overdefined'.
714 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
719 static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
720 LVILatticeVal &Result,
721 bool isTrueDest = true);
723 // If we can determine a constant range for the value Val in the context
724 // provided by the instruction BBI, then merge it into BBLV. If we did find a
725 // constant range, return true.
726 void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(Value *Val,
729 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
733 for (auto &AssumeVH : AC->assumptions()) {
736 auto *I = cast<CallInst>(AssumeVH);
737 if (!isValidAssumeForContext(I, BBI, DL, DT))
740 Value *C = I->getArgOperand(0);
741 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
742 LVILatticeVal Result;
743 if (getValueFromFromCondition(Val, ICI, Result)) {
744 if (BBLV.isOverdefined())
747 BBLV.mergeIn(Result);
753 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
756 // Figure out the range of the LHS. If that fails, bail.
757 if (!hasBlockValue(BBI->getOperand(0), BB)) {
758 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
760 BBLV.markOverdefined();
764 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
765 mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
766 if (!LHSVal.isConstantRange()) {
767 BBLV.markOverdefined();
771 ConstantRange LHSRange = LHSVal.getConstantRange();
772 ConstantRange RHSRange(1);
773 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
774 if (isa<BinaryOperator>(BBI)) {
775 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
776 RHSRange = ConstantRange(RHS->getValue());
778 BBLV.markOverdefined();
783 // NOTE: We're currently limited by the set of operations that ConstantRange
784 // can evaluate symbolically. Enhancing that set will allows us to analyze
786 LVILatticeVal Result;
787 switch (BBI->getOpcode()) {
788 case Instruction::Add:
789 Result.markConstantRange(LHSRange.add(RHSRange));
791 case Instruction::Sub:
792 Result.markConstantRange(LHSRange.sub(RHSRange));
794 case Instruction::Mul:
795 Result.markConstantRange(LHSRange.multiply(RHSRange));
797 case Instruction::UDiv:
798 Result.markConstantRange(LHSRange.udiv(RHSRange));
800 case Instruction::Shl:
801 Result.markConstantRange(LHSRange.shl(RHSRange));
803 case Instruction::LShr:
804 Result.markConstantRange(LHSRange.lshr(RHSRange));
806 case Instruction::Trunc:
807 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
809 case Instruction::SExt:
810 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
812 case Instruction::ZExt:
813 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
815 case Instruction::BitCast:
816 Result.markConstantRange(LHSRange);
818 case Instruction::And:
819 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
821 case Instruction::Or:
822 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
825 // Unhandled instructions are overdefined.
827 DEBUG(dbgs() << " compute BB '" << BB->getName()
828 << "' - overdefined because inst def found.\n");
829 Result.markOverdefined();
837 bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
838 LVILatticeVal &Result, bool isTrueDest) {
839 if (ICI && isa<Constant>(ICI->getOperand(1))) {
840 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
841 // We know that V has the RHS constant if this is a true SETEQ or
843 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
844 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
846 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
850 // Recognize the range checking idiom that InstCombine produces.
851 // (X-C1) u< C2 --> [C1, C1+C2)
852 ConstantInt *NegOffset = nullptr;
853 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
854 match(ICI->getOperand(0), m_Add(m_Specific(Val),
855 m_ConstantInt(NegOffset)));
857 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
858 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
859 // Calculate the range of values that would satisfy the comparison.
860 ConstantRange CmpRange(CI->getValue());
861 ConstantRange TrueValues =
862 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
864 if (NegOffset) // Apply the offset from above.
865 TrueValues = TrueValues.subtract(NegOffset->getValue());
867 // If we're interested in the false dest, invert the condition.
868 if (!isTrueDest) TrueValues = TrueValues.inverse();
870 Result = LVILatticeVal::getRange(TrueValues);
878 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
879 /// Val is not constrained on the edge.
880 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
881 BasicBlock *BBTo, LVILatticeVal &Result) {
882 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
884 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
885 // If this is a conditional branch and only one successor goes to BBTo, then
886 // we may be able to infer something from the condition.
887 if (BI->isConditional() &&
888 BI->getSuccessor(0) != BI->getSuccessor(1)) {
889 bool isTrueDest = BI->getSuccessor(0) == BBTo;
890 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
891 "BBTo isn't a successor of BBFrom");
893 // If V is the condition of the branch itself, then we know exactly what
895 if (BI->getCondition() == Val) {
896 Result = LVILatticeVal::get(ConstantInt::get(
897 Type::getInt1Ty(Val->getContext()), isTrueDest));
901 // If the condition of the branch is an equality comparison, we may be
902 // able to infer the value.
903 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
904 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
909 // If the edge was formed by a switch on the value, then we may know exactly
911 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
912 if (SI->getCondition() != Val)
915 bool DefaultCase = SI->getDefaultDest() == BBTo;
916 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
917 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
919 for (SwitchInst::CaseIt i : SI->cases()) {
920 ConstantRange EdgeVal(i.getCaseValue()->getValue());
922 // It is possible that the default destination is the destination of
923 // some cases. There is no need to perform difference for those cases.
924 if (i.getCaseSuccessor() != BBTo)
925 EdgesVals = EdgesVals.difference(EdgeVal);
926 } else if (i.getCaseSuccessor() == BBTo)
927 EdgesVals = EdgesVals.unionWith(EdgeVal);
929 Result = LVILatticeVal::getRange(EdgesVals);
935 /// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
936 /// the basic block if the edge does not constrain Val.
937 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
938 BasicBlock *BBTo, LVILatticeVal &Result,
940 // If already a constant, there is nothing to compute.
941 if (Constant *VC = dyn_cast<Constant>(Val)) {
942 Result = LVILatticeVal::get(VC);
946 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
947 if (!Result.isConstantRange() ||
948 Result.getConstantRange().getSingleElement())
951 // FIXME: this check should be moved to the beginning of the function when
952 // LVI better supports recursive values. Even for the single value case, we
953 // can intersect to detect dead code (an empty range).
954 if (!hasBlockValue(Val, BBFrom)) {
955 if (pushBlockValue(std::make_pair(BBFrom, Val)))
957 Result.markOverdefined();
961 // Try to intersect ranges of the BB and the constraint on the edge.
962 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
963 mergeAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
964 // See note on the use of the CxtI with mergeAssumeBlockValueConstantRange,
965 // and caching, below.
966 mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
967 if (!InBlock.isConstantRange())
970 ConstantRange Range =
971 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
972 Result = LVILatticeVal::getRange(Range);
976 if (!hasBlockValue(Val, BBFrom)) {
977 if (pushBlockValue(std::make_pair(BBFrom, Val)))
979 Result.markOverdefined();
983 // If we couldn't compute the value on the edge, use the value from the BB.
984 Result = getBlockValue(Val, BBFrom);
985 mergeAssumeBlockValueConstantRange(Val, Result, BBFrom->getTerminator());
986 // We can use the context instruction (generically the ultimate instruction
987 // the calling pass is trying to simplify) here, even though the result of
988 // this function is generally cached when called from the solve* functions
989 // (and that cached result might be used with queries using a different
990 // context instruction), because when this function is called from the solve*
991 // functions, the context instruction is not provided. When called from
992 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
993 // but then the result is not cached.
994 mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
998 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
1000 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1001 << BB->getName() << "'\n");
1003 assert(BlockValueStack.empty() && BlockValueSet.empty());
1004 pushBlockValue(std::make_pair(BB, V));
1007 LVILatticeVal Result = getBlockValue(V, BB);
1008 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1010 DEBUG(dbgs() << " Result = " << Result << "\n");
1014 LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1015 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1016 << CxtI->getName() << "'\n");
1018 LVILatticeVal Result;
1019 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1021 DEBUG(dbgs() << " Result = " << Result << "\n");
1025 LVILatticeVal LazyValueInfoCache::
1026 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1027 Instruction *CxtI) {
1028 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1029 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
1031 LVILatticeVal Result;
1032 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
1034 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
1036 assert(WasFastQuery && "More work to do after problem solved?");
1039 DEBUG(dbgs() << " Result = " << Result << "\n");
1043 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1044 BasicBlock *NewSucc) {
1045 // When an edge in the graph has been threaded, values that we could not
1046 // determine a value for before (i.e. were marked overdefined) may be possible
1047 // to solve now. We do NOT try to proactively update these values. Instead,
1048 // we clear their entries from the cache, and allow lazy updating to recompute
1049 // them when needed.
1051 // The updating process is fairly simple: we need to drop cached info
1052 // for all values that were marked overdefined in OldSucc, and for those same
1053 // values in any successor of OldSucc (except NewSucc) in which they were
1054 // also marked overdefined.
1055 std::vector<BasicBlock*> worklist;
1056 worklist.push_back(OldSucc);
1058 DenseSet<Value*> ClearSet;
1059 for (OverDefinedPairTy &P : OverDefinedCache)
1060 if (P.first == OldSucc)
1061 ClearSet.insert(P.second);
1063 // Use a worklist to perform a depth-first search of OldSucc's successors.
1064 // NOTE: We do not need a visited list since any blocks we have already
1065 // visited will have had their overdefined markers cleared already, and we
1066 // thus won't loop to their successors.
1067 while (!worklist.empty()) {
1068 BasicBlock *ToUpdate = worklist.back();
1069 worklist.pop_back();
1071 // Skip blocks only accessible through NewSucc.
1072 if (ToUpdate == NewSucc) continue;
1074 bool changed = false;
1075 for (Value *V : ClearSet) {
1076 // If a value was marked overdefined in OldSucc, and is here too...
1077 DenseSet<OverDefinedPairTy>::iterator OI =
1078 OverDefinedCache.find(std::make_pair(ToUpdate, V));
1079 if (OI == OverDefinedCache.end()) continue;
1081 // Remove it from the caches.
1082 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(V, this)];
1083 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
1085 assert(CI != Entry.end() && "Couldn't find entry to update?");
1087 OverDefinedCache.erase(OI);
1089 // If we removed anything, then we potentially need to update
1090 // blocks successors too.
1094 if (!changed) continue;
1096 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1100 //===----------------------------------------------------------------------===//
1101 // LazyValueInfo Impl
1102 //===----------------------------------------------------------------------===//
1104 /// This lazily constructs the LazyValueInfoCache.
1105 static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
1106 const DataLayout *DL = nullptr,
1107 DominatorTree *DT = nullptr) {
1109 PImpl = new LazyValueInfoCache(AC, DL, DT);
1110 return *static_cast<LazyValueInfoCache*>(PImpl);
1113 bool LazyValueInfo::runOnFunction(Function &F) {
1114 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1116 DominatorTreeWrapperPass *DTWP =
1117 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1118 DT = DTWP ? &DTWP->getDomTree() : nullptr;
1120 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1121 DL = DLP ? &DLP->getDataLayout() : nullptr;
1123 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1126 getCache(PImpl, AC, DL, DT).clear();
1132 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1133 AU.setPreservesAll();
1134 AU.addRequired<AssumptionCacheTracker>();
1135 AU.addRequired<TargetLibraryInfoWrapperPass>();
1138 void LazyValueInfo::releaseMemory() {
1139 // If the cache was allocated, free it.
1141 delete &getCache(PImpl, AC);
1146 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1147 Instruction *CxtI) {
1148 LVILatticeVal Result =
1149 getCache(PImpl, AC, DL, DT).getValueInBlock(V, BB, CxtI);
1151 if (Result.isConstant())
1152 return Result.getConstant();
1153 if (Result.isConstantRange()) {
1154 ConstantRange CR = Result.getConstantRange();
1155 if (const APInt *SingleVal = CR.getSingleElement())
1156 return ConstantInt::get(V->getContext(), *SingleVal);
1161 /// Determine whether the specified value is known to be a
1162 /// constant on the specified edge. Return null if not.
1163 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1165 Instruction *CxtI) {
1166 LVILatticeVal Result =
1167 getCache(PImpl, AC, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1169 if (Result.isConstant())
1170 return Result.getConstant();
1171 if (Result.isConstantRange()) {
1172 ConstantRange CR = Result.getConstantRange();
1173 if (const APInt *SingleVal = CR.getSingleElement())
1174 return ConstantInt::get(V->getContext(), *SingleVal);
1179 static LazyValueInfo::Tristate
1180 getPredicateResult(unsigned Pred, Constant *C, LVILatticeVal &Result,
1181 const DataLayout *DL, TargetLibraryInfo *TLI) {
1183 // If we know the value is a constant, evaluate the conditional.
1184 Constant *Res = nullptr;
1185 if (Result.isConstant()) {
1186 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
1188 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1189 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1190 return LazyValueInfo::Unknown;
1193 if (Result.isConstantRange()) {
1194 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1195 if (!CI) return LazyValueInfo::Unknown;
1197 ConstantRange CR = Result.getConstantRange();
1198 if (Pred == ICmpInst::ICMP_EQ) {
1199 if (!CR.contains(CI->getValue()))
1200 return LazyValueInfo::False;
1202 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1203 return LazyValueInfo::True;
1204 } else if (Pred == ICmpInst::ICMP_NE) {
1205 if (!CR.contains(CI->getValue()))
1206 return LazyValueInfo::True;
1208 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1209 return LazyValueInfo::False;
1212 // Handle more complex predicates.
1213 ConstantRange TrueValues =
1214 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1215 if (TrueValues.contains(CR))
1216 return LazyValueInfo::True;
1217 if (TrueValues.inverse().contains(CR))
1218 return LazyValueInfo::False;
1219 return LazyValueInfo::Unknown;
1222 if (Result.isNotConstant()) {
1223 // If this is an equality comparison, we can try to fold it knowing that
1225 if (Pred == ICmpInst::ICMP_EQ) {
1226 // !C1 == C -> false iff C1 == C.
1227 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1228 Result.getNotConstant(), C, DL,
1230 if (Res->isNullValue())
1231 return LazyValueInfo::False;
1232 } else if (Pred == ICmpInst::ICMP_NE) {
1233 // !C1 != C -> true iff C1 == C.
1234 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1235 Result.getNotConstant(), C, DL,
1237 if (Res->isNullValue())
1238 return LazyValueInfo::True;
1240 return LazyValueInfo::Unknown;
1243 return LazyValueInfo::Unknown;
1246 /// Determine whether the specified value comparison with a constant is known to
1247 /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1248 LazyValueInfo::Tristate
1249 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1250 BasicBlock *FromBB, BasicBlock *ToBB,
1251 Instruction *CxtI) {
1252 LVILatticeVal Result =
1253 getCache(PImpl, AC, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1255 return getPredicateResult(Pred, C, Result, DL, TLI);
1258 LazyValueInfo::Tristate
1259 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1260 Instruction *CxtI) {
1261 LVILatticeVal Result = getCache(PImpl, AC, DL, DT).getValueAt(V, CxtI);
1263 return getPredicateResult(Pred, C, Result, DL, TLI);
1266 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1267 BasicBlock *NewSucc) {
1269 getCache(PImpl, AC, DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1272 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1274 getCache(PImpl, AC, DL, DT).eraseBlock(BB);