1 //===- LazyValueInfo.cpp - Value constraint analysis ----------------------===//
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/ConstantFolding.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/IR/CFG.h"
21 #include "llvm/IR/ConstantRange.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/IR/ValueHandle.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetLibraryInfo.h"
34 using namespace PatternMatch;
36 #define DEBUG_TYPE "lazy-value-info"
38 char LazyValueInfo::ID = 0;
39 INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
40 "Lazy Value Information Analysis", false, true)
41 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
42 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
43 "Lazy Value Information Analysis", false, true)
46 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
50 //===----------------------------------------------------------------------===//
52 //===----------------------------------------------------------------------===//
54 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
57 /// FIXME: This is basically just for bringup, this can be made a lot more rich
63 /// undefined - This Value has no known value yet.
66 /// constant - This Value has a specific constant value.
68 /// notconstant - This Value is known to not have the specified value.
71 /// constantrange - The Value falls within this range.
74 /// overdefined - This value is not known to be constant, and we know that
79 /// Val: This stores the current lattice value along with the Constant* for
80 /// the constant if this is a 'constant' or 'notconstant' value.
86 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
88 static LVILatticeVal get(Constant *C) {
90 if (!isa<UndefValue>(C))
94 static LVILatticeVal getNot(Constant *C) {
96 if (!isa<UndefValue>(C))
97 Res.markNotConstant(C);
100 static LVILatticeVal getRange(ConstantRange CR) {
102 Res.markConstantRange(CR);
106 bool isUndefined() const { return Tag == undefined; }
107 bool isConstant() const { return Tag == constant; }
108 bool isNotConstant() const { return Tag == notconstant; }
109 bool isConstantRange() const { return Tag == constantrange; }
110 bool isOverdefined() const { return Tag == overdefined; }
112 Constant *getConstant() const {
113 assert(isConstant() && "Cannot get the constant of a non-constant!");
117 Constant *getNotConstant() const {
118 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
122 ConstantRange getConstantRange() const {
123 assert(isConstantRange() &&
124 "Cannot get the constant-range of a non-constant-range!");
128 /// markOverdefined - Return true if this is a change in status.
129 bool markOverdefined() {
136 /// markConstant - Return true if this is a change in status.
137 bool markConstant(Constant *V) {
138 assert(V && "Marking constant with NULL");
139 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
140 return markConstantRange(ConstantRange(CI->getValue()));
141 if (isa<UndefValue>(V))
144 assert((!isConstant() || getConstant() == V) &&
145 "Marking constant with different value");
146 assert(isUndefined());
152 /// markNotConstant - Return true if this is a change in status.
153 bool markNotConstant(Constant *V) {
154 assert(V && "Marking constant with NULL");
155 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
156 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
157 if (isa<UndefValue>(V))
160 assert((!isConstant() || getConstant() != V) &&
161 "Marking constant !constant with same value");
162 assert((!isNotConstant() || getNotConstant() == V) &&
163 "Marking !constant with different value");
164 assert(isUndefined() || isConstant());
170 /// markConstantRange - Return true if this is a change in status.
171 bool markConstantRange(const ConstantRange NewR) {
172 if (isConstantRange()) {
173 if (NewR.isEmptySet())
174 return markOverdefined();
176 bool changed = Range != NewR;
181 assert(isUndefined());
182 if (NewR.isEmptySet())
183 return markOverdefined();
190 /// mergeIn - Merge the specified lattice value into this one, updating this
191 /// one and returning true if anything changed.
192 bool mergeIn(const LVILatticeVal &RHS) {
193 if (RHS.isUndefined() || isOverdefined()) return false;
194 if (RHS.isOverdefined()) return markOverdefined();
204 if (RHS.isConstant()) {
207 return markOverdefined();
210 if (RHS.isNotConstant()) {
212 return markOverdefined();
214 // Unless we can prove that the two Constants are different, we must
215 // move to overdefined.
216 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
217 if (ConstantInt *Res = dyn_cast<ConstantInt>(
218 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
220 RHS.getNotConstant())))
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 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
243 if (ConstantInt *Res = dyn_cast<ConstantInt>(
244 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
250 return markOverdefined();
253 if (RHS.isNotConstant()) {
256 return markOverdefined();
259 return markOverdefined();
262 assert(isConstantRange() && "New LVILattice type?");
263 if (!RHS.isConstantRange())
264 return markOverdefined();
266 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
267 if (NewR.isFullSet())
268 return markOverdefined();
269 return markConstantRange(NewR);
273 } // end anonymous namespace.
276 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
278 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
279 if (Val.isUndefined())
280 return OS << "undefined";
281 if (Val.isOverdefined())
282 return OS << "overdefined";
284 if (Val.isNotConstant())
285 return OS << "notconstant<" << *Val.getNotConstant() << '>';
286 else if (Val.isConstantRange())
287 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
288 << Val.getConstantRange().getUpper() << '>';
289 return OS << "constant<" << *Val.getConstant() << '>';
293 //===----------------------------------------------------------------------===//
294 // LazyValueInfoCache Decl
295 //===----------------------------------------------------------------------===//
298 /// LVIValueHandle - A callback value handle updates the cache when
299 /// values are erased.
300 class LazyValueInfoCache;
301 struct LVIValueHandle : public CallbackVH {
302 LazyValueInfoCache *Parent;
304 LVIValueHandle(Value *V, LazyValueInfoCache *P)
305 : CallbackVH(V), Parent(P) { }
307 void deleted() override;
308 void allUsesReplacedWith(Value *V) override {
315 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
316 /// maintains information about queries across the clients' queries.
317 class LazyValueInfoCache {
318 /// ValueCacheEntryTy - This is all of the cached block information for
319 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
320 /// entries, allowing us to do a lookup with a binary search.
321 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
323 /// ValueCache - This is all of the cached information for all values,
324 /// mapped from Value* to key information.
325 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
327 /// OverDefinedCache - This tracks, on a per-block basis, the set of
328 /// values that are over-defined at the end of that block. This is required
329 /// for cache updating.
330 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
331 DenseSet<OverDefinedPairTy> OverDefinedCache;
333 /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
334 /// don't spend time removing unused blocks from our caches.
335 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
337 /// BlockValueStack - This stack holds the state of the value solver
338 /// during a query. It basically emulates the callstack of the naive
339 /// recursive value lookup process.
340 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
342 friend struct LVIValueHandle;
344 /// OverDefinedCacheUpdater - A helper object that ensures that the
345 /// OverDefinedCache is updated whenever solveBlockValue returns.
346 struct OverDefinedCacheUpdater {
347 LazyValueInfoCache *Parent;
352 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
353 LazyValueInfoCache *P)
354 : Parent(P), Val(V), BB(B), BBLV(LV) { }
356 bool markResult(bool changed) {
357 if (changed && BBLV.isOverdefined())
358 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
365 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
366 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
367 LVILatticeVal &Result);
368 bool hasBlockValue(Value *Val, BasicBlock *BB);
370 // These methods process one work item and may add more. A false value
371 // returned means that the work item was not completely processed and must
372 // be revisited after going through the new items.
373 bool solveBlockValue(Value *Val, BasicBlock *BB);
374 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
375 Value *Val, BasicBlock *BB);
376 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
377 PHINode *PN, BasicBlock *BB);
378 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
379 Instruction *BBI, BasicBlock *BB);
383 ValueCacheEntryTy &lookup(Value *V) {
384 return ValueCache[LVIValueHandle(V, this)];
388 /// getValueInBlock - This is the query interface to determine the lattice
389 /// value for the specified Value* at the end of the specified block.
390 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
392 /// getValueOnEdge - This is the query interface to determine the lattice
393 /// value for the specified Value* that is true on the specified edge.
394 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
396 /// threadEdge - This is the update interface to inform the cache that an
397 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
399 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
401 /// eraseBlock - This is part of the update interface to inform the cache
402 /// that a block has been deleted.
403 void eraseBlock(BasicBlock *BB);
405 /// clear - Empty the cache.
409 OverDefinedCache.clear();
412 } // end anonymous namespace
414 void LVIValueHandle::deleted() {
415 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
417 SmallVector<OverDefinedPairTy, 4> ToErase;
418 for (DenseSet<OverDefinedPairTy>::iterator
419 I = Parent->OverDefinedCache.begin(),
420 E = Parent->OverDefinedCache.end();
422 if (I->second == getValPtr())
423 ToErase.push_back(*I);
426 for (SmallVectorImpl<OverDefinedPairTy>::iterator I = ToErase.begin(),
427 E = ToErase.end(); I != E; ++I)
428 Parent->OverDefinedCache.erase(*I);
430 // This erasure deallocates *this, so it MUST happen after we're done
431 // using any and all members of *this.
432 Parent->ValueCache.erase(*this);
435 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
436 // Shortcut if we have never seen this block.
437 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
438 if (I == SeenBlocks.end())
442 SmallVector<OverDefinedPairTy, 4> ToErase;
443 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
444 E = OverDefinedCache.end(); I != E; ++I) {
446 ToErase.push_back(*I);
449 for (SmallVectorImpl<OverDefinedPairTy>::iterator I = ToErase.begin(),
450 E = ToErase.end(); I != E; ++I)
451 OverDefinedCache.erase(*I);
453 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
454 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
458 void LazyValueInfoCache::solve() {
459 while (!BlockValueStack.empty()) {
460 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
461 if (solveBlockValue(e.second, e.first)) {
462 assert(BlockValueStack.top() == e);
463 BlockValueStack.pop();
468 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
469 // If already a constant, there is nothing to compute.
470 if (isa<Constant>(Val))
473 LVIValueHandle ValHandle(Val, this);
474 std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
475 ValueCache.find(ValHandle);
476 if (I == ValueCache.end()) return false;
477 return I->second.count(BB);
480 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
481 // If already a constant, there is nothing to compute.
482 if (Constant *VC = dyn_cast<Constant>(Val))
483 return LVILatticeVal::get(VC);
485 SeenBlocks.insert(BB);
486 return lookup(Val)[BB];
489 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
490 if (isa<Constant>(Val))
493 ValueCacheEntryTy &Cache = lookup(Val);
494 SeenBlocks.insert(BB);
495 LVILatticeVal &BBLV = Cache[BB];
497 // OverDefinedCacheUpdater is a helper object that will update
498 // the OverDefinedCache for us when this method exits. Make sure to
499 // call markResult on it as we exist, passing a bool to indicate if the
500 // cache needs updating, i.e. if we have solve a new value or not.
501 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
503 // Once this BB is encountered, Val's value for this BB will not be Undefined
504 // any longer. When we encounter this BB again, if Val's value is Overdefined,
505 // we need to compute its value again.
507 // For example, considering this control flow,
508 // BB1->BB2, BB1->BB3, BB2->BB3, BB2->BB4
510 // Suppose we have "icmp slt %v, 0" in BB1, and "icmp sgt %v, 0" in BB3. At
511 // the very beginning, when analyzing edge BB2->BB3, we don't know %v's value
512 // in BB2, and the data flow algorithm tries to compute BB2's predecessors, so
513 // then we know %v has negative value on edge BB1->BB2. And then we return to
514 // check BB2 again, and at this moment BB2 has Overdefined value for %v in
515 // BB2. So we should have to follow data flow propagation algorithm to get the
516 // value on edge BB1->BB2 propagated to BB2, and finally %v on BB2 has a
517 // constant range describing a negative value.
519 if (!BBLV.isUndefined() && !BBLV.isOverdefined()) {
520 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
522 // Since we're reusing a cached value here, we don't need to update the
523 // OverDefinedCahce. The cache will have been properly updated
524 // whenever the cached value was inserted.
525 ODCacheUpdater.markResult(false);
529 // Otherwise, this is the first time we're seeing this block. Reset the
530 // lattice value to overdefined, so that cycles will terminate and be
531 // conservatively correct.
532 BBLV.markOverdefined();
534 Instruction *BBI = dyn_cast<Instruction>(Val);
535 if (!BBI || BBI->getParent() != BB) {
536 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
539 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
540 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
543 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
544 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
545 return ODCacheUpdater.markResult(true);
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 BBLV.markOverdefined();
556 return ODCacheUpdater.markResult(true);
559 // FIXME: We're currently limited to binops with a constant RHS. This should
561 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
562 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
563 DEBUG(dbgs() << " compute BB '" << BB->getName()
564 << "' - overdefined because inst def found.\n");
566 BBLV.markOverdefined();
567 return ODCacheUpdater.markResult(true);
570 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
573 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
574 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
575 return L->getPointerAddressSpace() == 0 &&
576 GetUnderlyingObject(L->getPointerOperand()) == Ptr;
578 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
579 return S->getPointerAddressSpace() == 0 &&
580 GetUnderlyingObject(S->getPointerOperand()) == Ptr;
582 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
583 if (MI->isVolatile()) return false;
585 // FIXME: check whether it has a valuerange that excludes zero?
586 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
587 if (!Len || Len->isZero()) return false;
589 if (MI->getDestAddressSpace() == 0)
590 if (GetUnderlyingObject(MI->getRawDest()) == Ptr)
592 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
593 if (MTI->getSourceAddressSpace() == 0)
594 if (GetUnderlyingObject(MTI->getRawSource()) == 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 Value *UnderlyingVal = GetUnderlyingObject(Val);
612 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
613 // inside InstructionDereferencesPointer either.
614 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, nullptr, 1)) {
615 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
617 if (InstructionDereferencesPointer(BI, 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);
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 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
691 Result.mergeIn(EdgeResult);
693 // If we hit overdefined, exit early. The BlockVals entry is already set
695 if (Result.isOverdefined()) {
696 DEBUG(dbgs() << " compute BB '" << BB->getName()
697 << "' - overdefined because of pred.\n");
706 // Return the merged value, which is more precise than 'overdefined'.
707 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
712 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
715 // Figure out the range of the LHS. If that fails, bail.
716 if (!hasBlockValue(BBI->getOperand(0), BB)) {
717 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
721 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
722 if (!LHSVal.isConstantRange()) {
723 BBLV.markOverdefined();
727 ConstantRange LHSRange = LHSVal.getConstantRange();
728 ConstantRange RHSRange(1);
729 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
730 if (isa<BinaryOperator>(BBI)) {
731 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
732 RHSRange = ConstantRange(RHS->getValue());
734 BBLV.markOverdefined();
739 // NOTE: We're currently limited by the set of operations that ConstantRange
740 // can evaluate symbolically. Enhancing that set will allows us to analyze
742 LVILatticeVal Result;
743 switch (BBI->getOpcode()) {
744 case Instruction::Add:
745 Result.markConstantRange(LHSRange.add(RHSRange));
747 case Instruction::Sub:
748 Result.markConstantRange(LHSRange.sub(RHSRange));
750 case Instruction::Mul:
751 Result.markConstantRange(LHSRange.multiply(RHSRange));
753 case Instruction::UDiv:
754 Result.markConstantRange(LHSRange.udiv(RHSRange));
756 case Instruction::Shl:
757 Result.markConstantRange(LHSRange.shl(RHSRange));
759 case Instruction::LShr:
760 Result.markConstantRange(LHSRange.lshr(RHSRange));
762 case Instruction::Trunc:
763 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
765 case Instruction::SExt:
766 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
768 case Instruction::ZExt:
769 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
771 case Instruction::BitCast:
772 Result.markConstantRange(LHSRange);
774 case Instruction::And:
775 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
777 case Instruction::Or:
778 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
781 // Unhandled instructions are overdefined.
783 DEBUG(dbgs() << " compute BB '" << BB->getName()
784 << "' - overdefined because inst def found.\n");
785 Result.markOverdefined();
793 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
794 /// Val is not constrained on the edge.
795 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
796 BasicBlock *BBTo, LVILatticeVal &Result) {
797 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
799 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
800 // If this is a conditional branch and only one successor goes to BBTo, then
801 // we maybe able to infer something from the condition.
802 if (BI->isConditional() &&
803 BI->getSuccessor(0) != BI->getSuccessor(1)) {
804 bool isTrueDest = BI->getSuccessor(0) == BBTo;
805 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
806 "BBTo isn't a successor of BBFrom");
808 // If V is the condition of the branch itself, then we know exactly what
810 if (BI->getCondition() == Val) {
811 Result = LVILatticeVal::get(ConstantInt::get(
812 Type::getInt1Ty(Val->getContext()), isTrueDest));
816 // If the condition of the branch is an equality comparison, we may be
817 // able to infer the value.
818 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
819 if (ICI && isa<Constant>(ICI->getOperand(1))) {
820 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
821 // We know that V has the RHS constant if this is a true SETEQ or
823 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
824 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
826 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
830 // Recognize the range checking idiom that InstCombine produces.
831 // (X-C1) u< C2 --> [C1, C1+C2)
832 ConstantInt *NegOffset = nullptr;
833 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
834 match(ICI->getOperand(0), m_Add(m_Specific(Val),
835 m_ConstantInt(NegOffset)));
837 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
838 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
839 // Calculate the range of values that would satisfy the comparison.
840 ConstantRange CmpRange(CI->getValue());
841 ConstantRange TrueValues =
842 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
844 if (NegOffset) // Apply the offset from above.
845 TrueValues = TrueValues.subtract(NegOffset->getValue());
847 // If we're interested in the false dest, invert the condition.
848 if (!isTrueDest) TrueValues = TrueValues.inverse();
850 Result = LVILatticeVal::getRange(TrueValues);
857 // If the edge was formed by a switch on the value, then we may know exactly
859 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
860 if (SI->getCondition() != Val)
863 bool DefaultCase = SI->getDefaultDest() == BBTo;
864 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
865 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
867 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
869 ConstantRange EdgeVal(i.getCaseValue()->getValue());
871 // It is possible that the default destination is the destination of
872 // some cases. There is no need to perform difference for those cases.
873 if (i.getCaseSuccessor() != BBTo)
874 EdgesVals = EdgesVals.difference(EdgeVal);
875 } else if (i.getCaseSuccessor() == BBTo)
876 EdgesVals = EdgesVals.unionWith(EdgeVal);
878 Result = LVILatticeVal::getRange(EdgesVals);
884 /// \brief Compute the value of Val on the edge BBFrom -> BBTo, or the value at
885 /// the basic block if the edge does not constraint Val.
886 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
887 BasicBlock *BBTo, LVILatticeVal &Result) {
888 // If already a constant, there is nothing to compute.
889 if (Constant *VC = dyn_cast<Constant>(Val)) {
890 Result = LVILatticeVal::get(VC);
894 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
895 if (!Result.isConstantRange() ||
896 Result.getConstantRange().getSingleElement())
899 // FIXME: this check should be moved to the beginning of the function when
900 // LVI better supports recursive values. Even for the single value case, we
901 // can intersect to detect dead code (an empty range).
902 if (!hasBlockValue(Val, BBFrom)) {
903 BlockValueStack.push(std::make_pair(BBFrom, Val));
907 // Try to intersect ranges of the BB and the constraint on the edge.
908 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
909 if (!InBlock.isConstantRange())
912 ConstantRange Range =
913 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
914 Result = LVILatticeVal::getRange(Range);
918 if (!hasBlockValue(Val, BBFrom)) {
919 BlockValueStack.push(std::make_pair(BBFrom, Val));
923 // if we couldn't compute the value on the edge, use the value from the BB
924 Result = getBlockValue(Val, BBFrom);
928 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
929 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
930 << BB->getName() << "'\n");
932 BlockValueStack.push(std::make_pair(BB, V));
934 LVILatticeVal Result = getBlockValue(V, BB);
936 DEBUG(dbgs() << " Result = " << Result << "\n");
940 LVILatticeVal LazyValueInfoCache::
941 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
942 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
943 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
945 LVILatticeVal Result;
946 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
948 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
950 assert(WasFastQuery && "More work to do after problem solved?");
953 DEBUG(dbgs() << " Result = " << Result << "\n");
957 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
958 BasicBlock *NewSucc) {
959 // When an edge in the graph has been threaded, values that we could not
960 // determine a value for before (i.e. were marked overdefined) may be possible
961 // to solve now. We do NOT try to proactively update these values. Instead,
962 // we clear their entries from the cache, and allow lazy updating to recompute
965 // The updating process is fairly simple: we need to dropped cached info
966 // for all values that were marked overdefined in OldSucc, and for those same
967 // values in any successor of OldSucc (except NewSucc) in which they were
968 // also marked overdefined.
969 std::vector<BasicBlock*> worklist;
970 worklist.push_back(OldSucc);
972 DenseSet<Value*> ClearSet;
973 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
974 E = OverDefinedCache.end(); I != E; ++I) {
975 if (I->first == OldSucc)
976 ClearSet.insert(I->second);
979 // Use a worklist to perform a depth-first search of OldSucc's successors.
980 // NOTE: We do not need a visited list since any blocks we have already
981 // visited will have had their overdefined markers cleared already, and we
982 // thus won't loop to their successors.
983 while (!worklist.empty()) {
984 BasicBlock *ToUpdate = worklist.back();
987 // Skip blocks only accessible through NewSucc.
988 if (ToUpdate == NewSucc) continue;
990 bool changed = false;
991 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
993 // If a value was marked overdefined in OldSucc, and is here too...
994 DenseSet<OverDefinedPairTy>::iterator OI =
995 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
996 if (OI == OverDefinedCache.end()) continue;
998 // Remove it from the caches.
999 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
1000 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
1002 assert(CI != Entry.end() && "Couldn't find entry to update?");
1004 OverDefinedCache.erase(OI);
1006 // If we removed anything, then we potentially need to update
1007 // blocks successors too.
1011 if (!changed) continue;
1013 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1017 //===----------------------------------------------------------------------===//
1018 // LazyValueInfo Impl
1019 //===----------------------------------------------------------------------===//
1021 /// getCache - This lazily constructs the LazyValueInfoCache.
1022 static LazyValueInfoCache &getCache(void *&PImpl) {
1024 PImpl = new LazyValueInfoCache();
1025 return *static_cast<LazyValueInfoCache*>(PImpl);
1028 bool LazyValueInfo::runOnFunction(Function &F) {
1030 getCache(PImpl).clear();
1032 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1033 DL = DLP ? &DLP->getDataLayout() : nullptr;
1034 TLI = &getAnalysis<TargetLibraryInfo>();
1040 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1041 AU.setPreservesAll();
1042 AU.addRequired<TargetLibraryInfo>();
1045 void LazyValueInfo::releaseMemory() {
1046 // If the cache was allocated, free it.
1048 delete &getCache(PImpl);
1053 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1054 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1056 if (Result.isConstant())
1057 return Result.getConstant();
1058 if (Result.isConstantRange()) {
1059 ConstantRange CR = Result.getConstantRange();
1060 if (const APInt *SingleVal = CR.getSingleElement())
1061 return ConstantInt::get(V->getContext(), *SingleVal);
1066 /// getConstantOnEdge - Determine whether the specified value is known to be a
1067 /// constant on the specified edge. Return null if not.
1068 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1070 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1072 if (Result.isConstant())
1073 return Result.getConstant();
1074 if (Result.isConstantRange()) {
1075 ConstantRange CR = Result.getConstantRange();
1076 if (const APInt *SingleVal = CR.getSingleElement())
1077 return ConstantInt::get(V->getContext(), *SingleVal);
1082 /// getPredicateOnEdge - Determine whether the specified value comparison
1083 /// with a constant is known to be true or false on the specified CFG edge.
1084 /// Pred is a CmpInst predicate.
1085 LazyValueInfo::Tristate
1086 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1087 BasicBlock *FromBB, BasicBlock *ToBB) {
1088 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1090 // If we know the value is a constant, evaluate the conditional.
1091 Constant *Res = nullptr;
1092 if (Result.isConstant()) {
1093 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
1095 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1096 return ResCI->isZero() ? False : True;
1100 if (Result.isConstantRange()) {
1101 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1102 if (!CI) return Unknown;
1104 ConstantRange CR = Result.getConstantRange();
1105 if (Pred == ICmpInst::ICMP_EQ) {
1106 if (!CR.contains(CI->getValue()))
1109 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1111 } else if (Pred == ICmpInst::ICMP_NE) {
1112 if (!CR.contains(CI->getValue()))
1115 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1119 // Handle more complex predicates.
1120 ConstantRange TrueValues =
1121 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1122 if (TrueValues.contains(CR))
1124 if (TrueValues.inverse().contains(CR))
1129 if (Result.isNotConstant()) {
1130 // If this is an equality comparison, we can try to fold it knowing that
1132 if (Pred == ICmpInst::ICMP_EQ) {
1133 // !C1 == C -> false iff C1 == C.
1134 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1135 Result.getNotConstant(), C, DL,
1137 if (Res->isNullValue())
1139 } else if (Pred == ICmpInst::ICMP_NE) {
1140 // !C1 != C -> true iff C1 == C.
1141 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1142 Result.getNotConstant(), C, DL,
1144 if (Res->isNullValue())
1153 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1154 BasicBlock *NewSucc) {
1155 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1158 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1159 if (PImpl) getCache(PImpl).eraseBlock(BB);