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, const DataLayout &DL) {
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 if (ConstantInt *Res =
219 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
220 CmpInst::ICMP_NE, getConstant(), RHS.getNotConstant(), DL)))
222 return markNotConstant(RHS.getNotConstant());
224 return markOverdefined();
227 // RHS is a ConstantRange, LHS is a non-integer Constant.
229 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
230 // a function. The correct result is to pick up RHS.
232 return markOverdefined();
235 if (isNotConstant()) {
236 if (RHS.isConstant()) {
238 return markOverdefined();
240 // Unless we can prove that the two Constants are different, we must
241 // move to overdefined.
242 if (ConstantInt *Res =
243 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
244 CmpInst::ICMP_NE, getNotConstant(), RHS.getConstant(), DL)))
248 return markOverdefined();
251 if (RHS.isNotConstant()) {
254 return markOverdefined();
257 return markOverdefined();
260 assert(isConstantRange() && "New LVILattice type?");
261 if (!RHS.isConstantRange())
262 return markOverdefined();
264 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
265 if (NewR.isFullSet())
266 return markOverdefined();
267 return markConstantRange(NewR);
271 } // end anonymous namespace.
274 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
276 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
277 if (Val.isUndefined())
278 return OS << "undefined";
279 if (Val.isOverdefined())
280 return OS << "overdefined";
282 if (Val.isNotConstant())
283 return OS << "notconstant<" << *Val.getNotConstant() << '>';
284 else if (Val.isConstantRange())
285 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
286 << Val.getConstantRange().getUpper() << '>';
287 return OS << "constant<" << *Val.getConstant() << '>';
291 //===----------------------------------------------------------------------===//
292 // LazyValueInfoCache Decl
293 //===----------------------------------------------------------------------===//
296 /// A callback value handle updates the cache when values are erased.
297 class LazyValueInfoCache;
298 struct LVIValueHandle final : public CallbackVH {
299 LazyValueInfoCache *Parent;
301 LVIValueHandle(Value *V, LazyValueInfoCache *P)
302 : CallbackVH(V), Parent(P) { }
304 void deleted() override;
305 void allUsesReplacedWith(Value *V) override {
312 /// This is the cache kept by LazyValueInfo which
313 /// maintains information about queries across the clients' queries.
314 class LazyValueInfoCache {
315 /// This is all of the cached block information for exactly one Value*.
316 /// The entries are sorted by the BasicBlock* of the
317 /// entries, allowing us to do a lookup with a binary search.
318 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
320 /// This is all of the cached information for all values,
321 /// mapped from Value* to key information.
322 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
324 /// This tracks, on a per-block basis, the set of values that are
325 /// over-defined at the end of that block. This is required
326 /// for cache updating.
327 typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
329 OverDefinedCacheTy OverDefinedCache;
331 /// Keep track of all blocks that we have ever seen, so we
332 /// don't spend time removing unused blocks from our caches.
333 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
335 /// This stack holds the state of the value solver during a query.
336 /// It basically emulates the callstack of the naive
337 /// recursive value lookup process.
338 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
340 /// Keeps track of which block-value pairs are in BlockValueStack.
341 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
343 /// Push BV onto BlockValueStack unless it's already in there.
344 /// Returns true on success.
345 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
346 if (!BlockValueSet.insert(BV).second)
347 return false; // It's already in the stack.
349 BlockValueStack.push(BV);
353 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
354 const DataLayout &DL; ///< A mandatory DataLayout
355 DominatorTree *DT; ///< An optional DT pointer.
357 friend struct LVIValueHandle;
359 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
360 SeenBlocks.insert(BB);
361 lookup(Val)[BB] = Result;
362 if (Result.isOverdefined())
363 OverDefinedCache[BB].insert(Val);
366 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
367 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
368 LVILatticeVal &Result,
369 Instruction *CxtI = nullptr);
370 bool hasBlockValue(Value *Val, BasicBlock *BB);
372 // These methods process one work item and may add more. A false value
373 // returned means that the work item was not completely processed and must
374 // be revisited after going through the new items.
375 bool solveBlockValue(Value *Val, BasicBlock *BB);
376 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
377 Value *Val, BasicBlock *BB);
378 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
379 PHINode *PN, BasicBlock *BB);
380 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
381 Instruction *BBI, BasicBlock *BB);
382 void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
387 ValueCacheEntryTy &lookup(Value *V) {
388 return ValueCache[LVIValueHandle(V, this)];
392 /// This is the query interface to determine the lattice
393 /// value for the specified Value* at the end of the specified block.
394 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
395 Instruction *CxtI = nullptr);
397 /// This is the query interface to determine the lattice
398 /// value for the specified Value* at the specified instruction (generally
399 /// from an assume intrinsic).
400 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
402 /// This is the query interface to determine the lattice
403 /// value for the specified Value* that is true on the specified edge.
404 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
405 Instruction *CxtI = nullptr);
407 /// This is the update interface to inform the cache that an edge from
408 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
409 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
411 /// This is part of the update interface to inform the cache
412 /// that a block has been deleted.
413 void eraseBlock(BasicBlock *BB);
415 /// clear - Empty the cache.
419 OverDefinedCache.clear();
422 LazyValueInfoCache(AssumptionCache *AC, const DataLayout &DL,
423 DominatorTree *DT = nullptr)
424 : AC(AC), DL(DL), DT(DT) {}
426 } // end anonymous namespace
428 void LVIValueHandle::deleted() {
429 SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
430 for (auto &I : Parent->OverDefinedCache) {
431 SmallPtrSetImpl<Value *> &ValueSet = I.second;
432 if (ValueSet.count(getValPtr()))
433 ValueSet.erase(getValPtr());
434 if (ValueSet.empty())
435 ToErase.push_back(I.first);
437 for (auto &BB : ToErase)
438 Parent->OverDefinedCache.erase(BB);
440 // This erasure deallocates *this, so it MUST happen after we're done
441 // using any and all members of *this.
442 Parent->ValueCache.erase(*this);
445 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
446 // Shortcut if we have never seen this block.
447 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
448 if (I == SeenBlocks.end())
452 auto ODI = OverDefinedCache.find(BB);
453 if (ODI != OverDefinedCache.end())
454 OverDefinedCache.erase(ODI);
456 for (auto I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
460 void LazyValueInfoCache::solve() {
461 while (!BlockValueStack.empty()) {
462 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
463 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
465 if (solveBlockValue(e.second, e.first)) {
466 // The work item was completely processed.
467 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
468 assert(lookup(e.second).count(e.first) && "Result should be in cache!");
470 BlockValueStack.pop();
471 BlockValueSet.erase(e);
473 // More work needs to be done before revisiting.
474 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
479 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
480 // If already a constant, there is nothing to compute.
481 if (isa<Constant>(Val))
484 LVIValueHandle ValHandle(Val, this);
485 auto I = ValueCache.find(ValHandle);
486 if (I == ValueCache.end()) return false;
487 return I->second.count(BB);
490 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
491 // If already a constant, there is nothing to compute.
492 if (Constant *VC = dyn_cast<Constant>(Val))
493 return LVILatticeVal::get(VC);
495 SeenBlocks.insert(BB);
496 return lookup(Val)[BB];
499 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
500 if (isa<Constant>(Val))
503 if (lookup(Val).count(BB)) {
504 // If we have a cached value, use that.
505 DEBUG(dbgs() << " reuse BB '" << BB->getName()
506 << "' val=" << lookup(Val)[BB] << '\n');
508 // Since we're reusing a cached value, we don't need to update the
509 // OverDefinedCache. The cache will have been properly updated whenever the
510 // cached value was inserted.
514 // Hold off inserting this value into the Cache in case we have to return
515 // false and come back later.
518 Instruction *BBI = dyn_cast<Instruction>(Val);
519 if (!BBI || BBI->getParent() != BB) {
520 if (!solveBlockValueNonLocal(Res, Val, BB))
522 insertResult(Val, BB, Res);
526 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
527 if (!solveBlockValuePHINode(Res, PN, BB))
529 insertResult(Val, BB, Res);
533 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
534 Res = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
535 insertResult(Val, BB, Res);
539 // We can only analyze the definitions of certain classes of instructions
540 // (integral binops and casts at the moment), so bail if this isn't one.
541 LVILatticeVal Result;
542 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
543 !BBI->getType()->isIntegerTy()) {
544 DEBUG(dbgs() << " compute BB '" << BB->getName()
545 << "' - overdefined because inst def found.\n");
546 Res.markOverdefined();
547 insertResult(Val, BB, Res);
551 // FIXME: We're currently limited to binops with a constant RHS. This should
553 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
554 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
555 DEBUG(dbgs() << " compute BB '" << BB->getName()
556 << "' - overdefined because inst def found.\n");
558 Res.markOverdefined();
559 insertResult(Val, BB, Res);
563 if (!solveBlockValueConstantRange(Res, BBI, BB))
565 insertResult(Val, BB, Res);
569 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
570 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
571 return L->getPointerAddressSpace() == 0 &&
572 GetUnderlyingObject(L->getPointerOperand(),
573 L->getModule()->getDataLayout()) == Ptr;
575 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
576 return S->getPointerAddressSpace() == 0 &&
577 GetUnderlyingObject(S->getPointerOperand(),
578 S->getModule()->getDataLayout()) == Ptr;
580 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
581 if (MI->isVolatile()) return false;
583 // FIXME: check whether it has a valuerange that excludes zero?
584 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
585 if (!Len || Len->isZero()) return false;
587 if (MI->getDestAddressSpace() == 0)
588 if (GetUnderlyingObject(MI->getRawDest(),
589 MI->getModule()->getDataLayout()) == Ptr)
591 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
592 if (MTI->getSourceAddressSpace() == 0)
593 if (GetUnderlyingObject(MTI->getRawSource(),
594 MTI->getModule()->getDataLayout()) == Ptr)
600 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
601 Value *Val, BasicBlock *BB) {
602 LVILatticeVal Result; // Start Undefined.
604 // If this is a pointer, and there's a load from that pointer in this BB,
605 // then we know that the pointer can't be NULL.
606 bool NotNull = false;
607 if (Val->getType()->isPointerTy()) {
608 if (isKnownNonNull(Val)) {
611 const DataLayout &DL = BB->getModule()->getDataLayout();
612 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
613 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
614 // inside InstructionDereferencesPointer either.
615 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1)) {
616 for (Instruction &I : *BB) {
617 if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
626 // If this is the entry block, we must be asking about an argument. The
627 // value is overdefined.
628 if (BB == &BB->getParent()->getEntryBlock()) {
629 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
631 PointerType *PTy = cast<PointerType>(Val->getType());
632 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
634 Result.markOverdefined();
640 // Loop over all of our predecessors, merging what we know from them into
642 bool EdgesMissing = false;
643 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
644 LVILatticeVal EdgeResult;
645 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
649 Result.mergeIn(EdgeResult, DL);
651 // If we hit overdefined, exit early. The BlockVals entry is already set
653 if (Result.isOverdefined()) {
654 DEBUG(dbgs() << " compute BB '" << BB->getName()
655 << "' - overdefined because of pred.\n");
656 // If we previously determined that this is a pointer that can't be null
657 // then return that rather than giving up entirely.
659 PointerType *PTy = cast<PointerType>(Val->getType());
660 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
670 // Return the merged value, which is more precise than 'overdefined'.
671 assert(!Result.isOverdefined());
676 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
677 PHINode *PN, BasicBlock *BB) {
678 LVILatticeVal Result; // Start Undefined.
680 // Loop over all of our predecessors, merging what we know from them into
682 bool EdgesMissing = false;
683 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
684 BasicBlock *PhiBB = PN->getIncomingBlock(i);
685 Value *PhiVal = PN->getIncomingValue(i);
686 LVILatticeVal EdgeResult;
687 // Note that we can provide PN as the context value to getEdgeValue, even
688 // though the results will be cached, because PN is the value being used as
689 // the cache key in the caller.
690 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
694 Result.mergeIn(EdgeResult, DL);
696 // If we hit overdefined, exit early. The BlockVals entry is already set
698 if (Result.isOverdefined()) {
699 DEBUG(dbgs() << " compute BB '" << BB->getName()
700 << "' - overdefined because of pred.\n");
709 // Return the merged value, which is more precise than 'overdefined'.
710 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
715 static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
716 LVILatticeVal &Result,
717 bool isTrueDest = true);
719 // If we can determine a constant range for the value Val in the context
720 // provided by the instruction BBI, then merge it into BBLV. If we did find a
721 // constant range, return true.
722 void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(Value *Val,
725 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
729 for (auto &AssumeVH : AC->assumptions()) {
732 auto *I = cast<CallInst>(AssumeVH);
733 if (!isValidAssumeForContext(I, BBI, DT))
736 Value *C = I->getArgOperand(0);
737 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
738 LVILatticeVal Result;
739 if (getValueFromFromCondition(Val, ICI, Result)) {
740 if (BBLV.isOverdefined())
743 BBLV.mergeIn(Result, DL);
749 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
752 // Figure out the range of the LHS. If that fails, bail.
753 if (!hasBlockValue(BBI->getOperand(0), BB)) {
754 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
756 BBLV.markOverdefined();
760 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
761 mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
762 if (!LHSVal.isConstantRange()) {
763 BBLV.markOverdefined();
767 ConstantRange LHSRange = LHSVal.getConstantRange();
768 ConstantRange RHSRange(1);
769 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
770 if (isa<BinaryOperator>(BBI)) {
771 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
772 RHSRange = ConstantRange(RHS->getValue());
774 BBLV.markOverdefined();
779 // NOTE: We're currently limited by the set of operations that ConstantRange
780 // can evaluate symbolically. Enhancing that set will allows us to analyze
782 LVILatticeVal Result;
783 switch (BBI->getOpcode()) {
784 case Instruction::Add:
785 Result.markConstantRange(LHSRange.add(RHSRange));
787 case Instruction::Sub:
788 Result.markConstantRange(LHSRange.sub(RHSRange));
790 case Instruction::Mul:
791 Result.markConstantRange(LHSRange.multiply(RHSRange));
793 case Instruction::UDiv:
794 Result.markConstantRange(LHSRange.udiv(RHSRange));
796 case Instruction::Shl:
797 Result.markConstantRange(LHSRange.shl(RHSRange));
799 case Instruction::LShr:
800 Result.markConstantRange(LHSRange.lshr(RHSRange));
802 case Instruction::Trunc:
803 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
805 case Instruction::SExt:
806 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
808 case Instruction::ZExt:
809 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
811 case Instruction::BitCast:
812 Result.markConstantRange(LHSRange);
814 case Instruction::And:
815 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
817 case Instruction::Or:
818 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
821 // Unhandled instructions are overdefined.
823 DEBUG(dbgs() << " compute BB '" << BB->getName()
824 << "' - overdefined because inst def found.\n");
825 Result.markOverdefined();
833 bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
834 LVILatticeVal &Result, bool isTrueDest) {
835 if (ICI && isa<Constant>(ICI->getOperand(1))) {
836 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
837 // We know that V has the RHS constant if this is a true SETEQ or
839 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
840 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
842 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
846 // Recognize the range checking idiom that InstCombine produces.
847 // (X-C1) u< C2 --> [C1, C1+C2)
848 ConstantInt *NegOffset = nullptr;
849 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
850 match(ICI->getOperand(0), m_Add(m_Specific(Val),
851 m_ConstantInt(NegOffset)));
853 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
854 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
855 // Calculate the range of values that are allowed by the comparison
856 ConstantRange CmpRange(CI->getValue());
857 ConstantRange TrueValues =
858 ConstantRange::makeAllowedICmpRegion(ICI->getPredicate(), CmpRange);
860 if (NegOffset) // Apply the offset from above.
861 TrueValues = TrueValues.subtract(NegOffset->getValue());
863 // If we're interested in the false dest, invert the condition.
864 if (!isTrueDest) TrueValues = TrueValues.inverse();
866 Result = LVILatticeVal::getRange(TrueValues);
874 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
875 /// Val is not constrained on the edge.
876 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
877 BasicBlock *BBTo, LVILatticeVal &Result) {
878 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
880 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
881 // If this is a conditional branch and only one successor goes to BBTo, then
882 // we may be able to infer something from the condition.
883 if (BI->isConditional() &&
884 BI->getSuccessor(0) != BI->getSuccessor(1)) {
885 bool isTrueDest = BI->getSuccessor(0) == BBTo;
886 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
887 "BBTo isn't a successor of BBFrom");
889 // If V is the condition of the branch itself, then we know exactly what
891 if (BI->getCondition() == Val) {
892 Result = LVILatticeVal::get(ConstantInt::get(
893 Type::getInt1Ty(Val->getContext()), isTrueDest));
897 // If the condition of the branch is an equality comparison, we may be
898 // able to infer the value.
899 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
900 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
905 // If the edge was formed by a switch on the value, then we may know exactly
907 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
908 if (SI->getCondition() != Val)
911 bool DefaultCase = SI->getDefaultDest() == BBTo;
912 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
913 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
915 for (SwitchInst::CaseIt i : SI->cases()) {
916 ConstantRange EdgeVal(i.getCaseValue()->getValue());
918 // It is possible that the default destination is the destination of
919 // some cases. There is no need to perform difference for those cases.
920 if (i.getCaseSuccessor() != BBTo)
921 EdgesVals = EdgesVals.difference(EdgeVal);
922 } else if (i.getCaseSuccessor() == BBTo)
923 EdgesVals = EdgesVals.unionWith(EdgeVal);
925 Result = LVILatticeVal::getRange(EdgesVals);
931 /// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
932 /// the basic block if the edge does not constrain Val.
933 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
934 BasicBlock *BBTo, LVILatticeVal &Result,
936 // If already a constant, there is nothing to compute.
937 if (Constant *VC = dyn_cast<Constant>(Val)) {
938 Result = LVILatticeVal::get(VC);
942 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
943 if (!Result.isConstantRange() ||
944 Result.getConstantRange().getSingleElement())
947 // FIXME: this check should be moved to the beginning of the function when
948 // LVI better supports recursive values. Even for the single value case, we
949 // can intersect to detect dead code (an empty range).
950 if (!hasBlockValue(Val, BBFrom)) {
951 if (pushBlockValue(std::make_pair(BBFrom, Val)))
953 Result.markOverdefined();
957 // Try to intersect ranges of the BB and the constraint on the edge.
958 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
959 mergeAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
960 // See note on the use of the CxtI with mergeAssumeBlockValueConstantRange,
961 // and caching, below.
962 mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
963 if (!InBlock.isConstantRange())
966 ConstantRange Range =
967 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
968 Result = LVILatticeVal::getRange(Range);
972 if (!hasBlockValue(Val, BBFrom)) {
973 if (pushBlockValue(std::make_pair(BBFrom, Val)))
975 Result.markOverdefined();
979 // If we couldn't compute the value on the edge, use the value from the BB.
980 Result = getBlockValue(Val, BBFrom);
981 mergeAssumeBlockValueConstantRange(Val, Result, BBFrom->getTerminator());
982 // We can use the context instruction (generically the ultimate instruction
983 // the calling pass is trying to simplify) here, even though the result of
984 // this function is generally cached when called from the solve* functions
985 // (and that cached result might be used with queries using a different
986 // context instruction), because when this function is called from the solve*
987 // functions, the context instruction is not provided. When called from
988 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
989 // but then the result is not cached.
990 mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
994 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
996 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
997 << BB->getName() << "'\n");
999 assert(BlockValueStack.empty() && BlockValueSet.empty());
1000 pushBlockValue(std::make_pair(BB, V));
1003 LVILatticeVal Result = getBlockValue(V, BB);
1004 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1006 DEBUG(dbgs() << " Result = " << Result << "\n");
1010 LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1011 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1012 << CxtI->getName() << "'\n");
1014 LVILatticeVal Result;
1015 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1017 DEBUG(dbgs() << " Result = " << Result << "\n");
1021 LVILatticeVal LazyValueInfoCache::
1022 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1023 Instruction *CxtI) {
1024 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1025 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
1027 LVILatticeVal Result;
1028 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
1030 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
1032 assert(WasFastQuery && "More work to do after problem solved?");
1035 DEBUG(dbgs() << " Result = " << Result << "\n");
1039 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1040 BasicBlock *NewSucc) {
1041 // When an edge in the graph has been threaded, values that we could not
1042 // determine a value for before (i.e. were marked overdefined) may be
1043 // possible to solve now. We do NOT try to proactively update these values.
1044 // Instead, we clear their entries from the cache, and allow lazy updating to
1045 // recompute them when needed.
1047 // The updating process is fairly simple: we need to drop cached info
1048 // for all values that were marked overdefined in OldSucc, and for those same
1049 // values in any successor of OldSucc (except NewSucc) in which they were
1050 // also marked overdefined.
1051 std::vector<BasicBlock*> worklist;
1052 worklist.push_back(OldSucc);
1054 auto I = OverDefinedCache.find(OldSucc);
1055 if (I == OverDefinedCache.end())
1056 return; // Nothing to process here.
1057 SmallPtrSetImpl<Value *> &ClearSet = I->second;
1059 // Use a worklist to perform a depth-first search of OldSucc's successors.
1060 // NOTE: We do not need a visited list since any blocks we have already
1061 // visited will have had their overdefined markers cleared already, and we
1062 // thus won't loop to their successors.
1063 while (!worklist.empty()) {
1064 BasicBlock *ToUpdate = worklist.back();
1065 worklist.pop_back();
1067 // Skip blocks only accessible through NewSucc.
1068 if (ToUpdate == NewSucc) continue;
1070 bool changed = false;
1071 for (Value *V : ClearSet) {
1072 // If a value was marked overdefined in OldSucc, and is here too...
1073 auto OI = OverDefinedCache.find(ToUpdate);
1074 if (OI == OverDefinedCache.end())
1076 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
1077 if (!ValueSet.count(V))
1080 // Remove it from the caches.
1081 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(V, this)];
1082 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
1084 assert(CI != Entry.end() && "Couldn't find entry to update?");
1087 if (ValueSet.empty())
1088 OverDefinedCache.erase(OI);
1090 // If we removed anything, then we potentially need to update
1091 // blocks successors too.
1095 if (!changed) continue;
1097 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1101 //===----------------------------------------------------------------------===//
1102 // LazyValueInfo Impl
1103 //===----------------------------------------------------------------------===//
1105 /// This lazily constructs the LazyValueInfoCache.
1106 static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
1107 const DataLayout *DL,
1108 DominatorTree *DT = nullptr) {
1110 assert(DL && "getCache() called with a null DataLayout");
1111 PImpl = new LazyValueInfoCache(AC, *DL, DT);
1113 return *static_cast<LazyValueInfoCache*>(PImpl);
1116 bool LazyValueInfo::runOnFunction(Function &F) {
1117 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1118 const DataLayout &DL = F.getParent()->getDataLayout();
1120 DominatorTreeWrapperPass *DTWP =
1121 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1122 DT = DTWP ? &DTWP->getDomTree() : nullptr;
1124 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1127 getCache(PImpl, AC, &DL, DT).clear();
1133 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1134 AU.setPreservesAll();
1135 AU.addRequired<AssumptionCacheTracker>();
1136 AU.addRequired<TargetLibraryInfoWrapperPass>();
1139 void LazyValueInfo::releaseMemory() {
1140 // If the cache was allocated, free it.
1142 delete &getCache(PImpl, AC, nullptr);
1147 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1148 Instruction *CxtI) {
1149 const DataLayout &DL = BB->getModule()->getDataLayout();
1150 LVILatticeVal Result =
1151 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1153 if (Result.isConstant())
1154 return Result.getConstant();
1155 if (Result.isConstantRange()) {
1156 ConstantRange CR = Result.getConstantRange();
1157 if (const APInt *SingleVal = CR.getSingleElement())
1158 return ConstantInt::get(V->getContext(), *SingleVal);
1163 /// Determine whether the specified value is known to be a
1164 /// constant on the specified edge. Return null if not.
1165 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1167 Instruction *CxtI) {
1168 const DataLayout &DL = FromBB->getModule()->getDataLayout();
1169 LVILatticeVal Result =
1170 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1172 if (Result.isConstant())
1173 return Result.getConstant();
1174 if (Result.isConstantRange()) {
1175 ConstantRange CR = Result.getConstantRange();
1176 if (const APInt *SingleVal = CR.getSingleElement())
1177 return ConstantInt::get(V->getContext(), *SingleVal);
1182 static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1183 LVILatticeVal &Result,
1184 const DataLayout &DL,
1185 TargetLibraryInfo *TLI) {
1187 // If we know the value is a constant, evaluate the conditional.
1188 Constant *Res = nullptr;
1189 if (Result.isConstant()) {
1190 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
1192 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1193 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1194 return LazyValueInfo::Unknown;
1197 if (Result.isConstantRange()) {
1198 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1199 if (!CI) return LazyValueInfo::Unknown;
1201 ConstantRange CR = Result.getConstantRange();
1202 if (Pred == ICmpInst::ICMP_EQ) {
1203 if (!CR.contains(CI->getValue()))
1204 return LazyValueInfo::False;
1206 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1207 return LazyValueInfo::True;
1208 } else if (Pred == ICmpInst::ICMP_NE) {
1209 if (!CR.contains(CI->getValue()))
1210 return LazyValueInfo::True;
1212 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1213 return LazyValueInfo::False;
1216 // Handle more complex predicates.
1217 ConstantRange TrueValues =
1218 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1219 if (TrueValues.contains(CR))
1220 return LazyValueInfo::True;
1221 if (TrueValues.inverse().contains(CR))
1222 return LazyValueInfo::False;
1223 return LazyValueInfo::Unknown;
1226 if (Result.isNotConstant()) {
1227 // If this is an equality comparison, we can try to fold it knowing that
1229 if (Pred == ICmpInst::ICMP_EQ) {
1230 // !C1 == C -> false iff C1 == C.
1231 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1232 Result.getNotConstant(), C, DL,
1234 if (Res->isNullValue())
1235 return LazyValueInfo::False;
1236 } else if (Pred == ICmpInst::ICMP_NE) {
1237 // !C1 != C -> true iff C1 == C.
1238 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1239 Result.getNotConstant(), C, DL,
1241 if (Res->isNullValue())
1242 return LazyValueInfo::True;
1244 return LazyValueInfo::Unknown;
1247 return LazyValueInfo::Unknown;
1250 /// Determine whether the specified value comparison with a constant is known to
1251 /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1252 LazyValueInfo::Tristate
1253 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1254 BasicBlock *FromBB, BasicBlock *ToBB,
1255 Instruction *CxtI) {
1256 const DataLayout &DL = FromBB->getModule()->getDataLayout();
1257 LVILatticeVal Result =
1258 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1260 return getPredicateResult(Pred, C, Result, DL, TLI);
1263 LazyValueInfo::Tristate
1264 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1265 Instruction *CxtI) {
1266 const DataLayout &DL = CxtI->getModule()->getDataLayout();
1267 LVILatticeVal Result = getCache(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
1268 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1272 // TODO: Move this logic inside getValueAt so that it can be cached rather
1273 // than re-queried on each call. This would also allow us to merge the
1274 // underlying lattice values to get more information.
1276 // For a comparison where the V is outside this block, it's possible
1277 // that we've branched on it before. Look to see if the value is known
1278 // on all incoming edges.
1279 BasicBlock *BB = CxtI->getParent();
1280 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1282 (!isa<Instruction>(V) ||
1283 cast<Instruction>(V)->getParent() != BB)) {
1284 // For predecessor edge, determine if the comparison is true or false
1285 // on that edge. If they're all true or all false, we can conclude
1286 // the value of the comparison in this block.
1287 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1288 if (Baseline != Unknown) {
1289 // Check that all remaining incoming values match the first one.
1290 while (++PI != PE) {
1291 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1292 if (Ret != Baseline) break;
1294 // If we terminated early, then one of the values didn't match.
1304 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1305 BasicBlock *NewSucc) {
1307 const DataLayout &DL = PredBB->getModule()->getDataLayout();
1308 getCache(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1312 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1314 const DataLayout &DL = BB->getModule()->getDataLayout();
1315 getCache(PImpl, AC, &DL, DT).eraseBlock(BB);