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 #define DEBUG_TYPE "lazy-value-info"
16 #include "llvm/Analysis/LazyValueInfo.h"
17 #include "llvm/Analysis/ValueTracking.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetLibraryInfo.h"
24 #include "llvm/Support/CFG.h"
25 #include "llvm/Support/ConstantRange.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/ValueHandle.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/STLExtras.h"
36 char LazyValueInfo::ID = 0;
37 INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
38 "Lazy Value Information Analysis", false, true)
39 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
40 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
41 "Lazy Value Information Analysis", false, true)
44 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
55 /// FIXME: This is basically just for bringup, this can be made a lot more rich
61 /// undefined - This Value has no known value yet.
64 /// constant - This Value has a specific constant value.
66 /// notconstant - This Value is known to not have the specified value.
69 /// constantrange - The Value falls within this range.
72 /// overdefined - This value is not known to be constant, and we know that
77 /// Val: This stores the current lattice value along with the Constant* for
78 /// the constant if this is a 'constant' or 'notconstant' value.
84 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
86 static LVILatticeVal get(Constant *C) {
88 if (!isa<UndefValue>(C))
92 static LVILatticeVal getNot(Constant *C) {
94 if (!isa<UndefValue>(C))
95 Res.markNotConstant(C);
98 static LVILatticeVal getRange(ConstantRange CR) {
100 Res.markConstantRange(CR);
104 bool isUndefined() const { return Tag == undefined; }
105 bool isConstant() const { return Tag == constant; }
106 bool isNotConstant() const { return Tag == notconstant; }
107 bool isConstantRange() const { return Tag == constantrange; }
108 bool isOverdefined() const { return Tag == overdefined; }
110 Constant *getConstant() const {
111 assert(isConstant() && "Cannot get the constant of a non-constant!");
115 Constant *getNotConstant() const {
116 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
120 ConstantRange getConstantRange() const {
121 assert(isConstantRange() &&
122 "Cannot get the constant-range of a non-constant-range!");
126 /// markOverdefined - Return true if this is a change in status.
127 bool markOverdefined() {
134 /// markConstant - Return true if this is a change in status.
135 bool markConstant(Constant *V) {
136 assert(V && "Marking constant with NULL");
137 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
138 return markConstantRange(ConstantRange(CI->getValue()));
139 if (isa<UndefValue>(V))
142 assert((!isConstant() || getConstant() == V) &&
143 "Marking constant with different value");
144 assert(isUndefined());
150 /// markNotConstant - Return true if this is a change in status.
151 bool markNotConstant(Constant *V) {
152 assert(V && "Marking constant with NULL");
153 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
154 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
155 if (isa<UndefValue>(V))
158 assert((!isConstant() || getConstant() != V) &&
159 "Marking constant !constant with same value");
160 assert((!isNotConstant() || getNotConstant() == V) &&
161 "Marking !constant with different value");
162 assert(isUndefined() || isConstant());
168 /// markConstantRange - Return true if this is a change in status.
169 bool markConstantRange(const ConstantRange NewR) {
170 if (isConstantRange()) {
171 if (NewR.isEmptySet())
172 return markOverdefined();
174 bool changed = Range == NewR;
179 assert(isUndefined());
180 if (NewR.isEmptySet())
181 return markOverdefined();
188 /// mergeIn - Merge the specified lattice value into this one, updating this
189 /// one and returning true if anything changed.
190 bool mergeIn(const LVILatticeVal &RHS) {
191 if (RHS.isUndefined() || isOverdefined()) return false;
192 if (RHS.isOverdefined()) return markOverdefined();
202 if (RHS.isConstant()) {
205 return markOverdefined();
208 if (RHS.isNotConstant()) {
210 return markOverdefined();
212 // Unless we can prove that the two Constants are different, we must
213 // move to overdefined.
214 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
215 if (ConstantInt *Res = dyn_cast<ConstantInt>(
216 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
218 RHS.getNotConstant())))
220 return markNotConstant(RHS.getNotConstant());
222 return markOverdefined();
225 // RHS is a ConstantRange, LHS is a non-integer Constant.
227 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
228 // a function. The correct result is to pick up RHS.
230 return markOverdefined();
233 if (isNotConstant()) {
234 if (RHS.isConstant()) {
236 return markOverdefined();
238 // Unless we can prove that the two Constants are different, we must
239 // move to overdefined.
240 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
241 if (ConstantInt *Res = dyn_cast<ConstantInt>(
242 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
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 /// LVIValueHandle - A callback value handle update the cache when
297 /// values are erased.
298 class LazyValueInfoCache;
299 struct LVIValueHandle : public CallbackVH {
300 LazyValueInfoCache *Parent;
302 LVIValueHandle(Value *V, LazyValueInfoCache *P)
303 : CallbackVH(V), Parent(P) { }
306 void allUsesReplacedWith(Value *V) {
314 struct DenseMapInfo<LVIValueHandle> {
315 typedef DenseMapInfo<Value*> PointerInfo;
316 static inline LVIValueHandle getEmptyKey() {
317 return LVIValueHandle(PointerInfo::getEmptyKey(),
318 static_cast<LazyValueInfoCache*>(0));
320 static inline LVIValueHandle getTombstoneKey() {
321 return LVIValueHandle(PointerInfo::getTombstoneKey(),
322 static_cast<LazyValueInfoCache*>(0));
324 static unsigned getHashValue(const LVIValueHandle &Val) {
325 return PointerInfo::getHashValue(Val);
327 static bool isEqual(const LVIValueHandle &LHS, const LVIValueHandle &RHS) {
333 struct DenseMapInfo<std::pair<AssertingVH<BasicBlock>, Value*> > {
334 typedef std::pair<AssertingVH<BasicBlock>, Value*> PairTy;
335 typedef DenseMapInfo<AssertingVH<BasicBlock> > APointerInfo;
336 typedef DenseMapInfo<Value*> BPointerInfo;
337 static inline PairTy getEmptyKey() {
338 return std::make_pair(APointerInfo::getEmptyKey(),
339 BPointerInfo::getEmptyKey());
341 static inline PairTy getTombstoneKey() {
342 return std::make_pair(APointerInfo::getTombstoneKey(),
343 BPointerInfo::getTombstoneKey());
345 static unsigned getHashValue( const PairTy &Val) {
346 return APointerInfo::getHashValue(Val.first) ^
347 BPointerInfo::getHashValue(Val.second);
349 static bool isEqual(const PairTy &LHS, const PairTy &RHS) {
350 return APointerInfo::isEqual(LHS.first, RHS.first) &&
351 BPointerInfo::isEqual(LHS.second, RHS.second);
357 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
358 /// maintains information about queries across the clients' queries.
359 class LazyValueInfoCache {
360 /// ValueCacheEntryTy - This is all of the cached block information for
361 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
362 /// entries, allowing us to do a lookup with a binary search.
363 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
365 /// ValueCache - This is all of the cached information for all values,
366 /// mapped from Value* to key information.
367 DenseMap<LVIValueHandle, ValueCacheEntryTy> ValueCache;
369 /// OverDefinedCache - This tracks, on a per-block basis, the set of
370 /// values that are over-defined at the end of that block. This is required
371 /// for cache updating.
372 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
373 DenseSet<OverDefinedPairTy> OverDefinedCache;
375 /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
376 /// don't spend time removing unused blocks from our caches.
377 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
379 /// BlockValueStack - This stack holds the state of the value solver
380 /// during a query. It basically emulates the callstack of the naive
381 /// recursive value lookup process.
382 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
384 friend struct LVIValueHandle;
386 /// OverDefinedCacheUpdater - A helper object that ensures that the
387 /// OverDefinedCache is updated whenever solveBlockValue returns.
388 struct OverDefinedCacheUpdater {
389 LazyValueInfoCache *Parent;
394 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
395 LazyValueInfoCache *P)
396 : Parent(P), Val(V), BB(B), BBLV(LV) { }
398 bool markResult(bool changed) {
399 if (changed && BBLV.isOverdefined())
400 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
407 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
408 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
409 LVILatticeVal &Result);
410 bool hasBlockValue(Value *Val, BasicBlock *BB);
412 // These methods process one work item and may add more. A false value
413 // returned means that the work item was not completely processed and must
414 // be revisited after going through the new items.
415 bool solveBlockValue(Value *Val, BasicBlock *BB);
416 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
417 Value *Val, BasicBlock *BB);
418 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
419 PHINode *PN, BasicBlock *BB);
420 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
421 Instruction *BBI, BasicBlock *BB);
425 ValueCacheEntryTy &lookup(Value *V) {
426 return ValueCache[LVIValueHandle(V, this)];
430 /// getValueInBlock - This is the query interface to determine the lattice
431 /// value for the specified Value* at the end of the specified block.
432 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
434 /// getValueOnEdge - This is the query interface to determine the lattice
435 /// value for the specified Value* that is true on the specified edge.
436 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
438 /// threadEdge - This is the update interface to inform the cache that an
439 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
441 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
443 /// eraseBlock - This is part of the update interface to inform the cache
444 /// that a block has been deleted.
445 void eraseBlock(BasicBlock *BB);
447 /// clear - Empty the cache.
450 OverDefinedCache.clear();
453 } // end anonymous namespace
455 void LVIValueHandle::deleted() {
456 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
458 SmallVector<OverDefinedPairTy, 4> ToErase;
459 for (DenseSet<OverDefinedPairTy>::iterator
460 I = Parent->OverDefinedCache.begin(),
461 E = Parent->OverDefinedCache.end();
463 if (I->second == getValPtr())
464 ToErase.push_back(*I);
467 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
468 E = ToErase.end(); I != E; ++I)
469 Parent->OverDefinedCache.erase(*I);
471 // This erasure deallocates *this, so it MUST happen after we're done
472 // using any and all members of *this.
473 Parent->ValueCache.erase(*this);
476 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
477 // Shortcut if we have never seen this block.
478 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
479 if (I == SeenBlocks.end())
483 SmallVector<OverDefinedPairTy, 4> ToErase;
484 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
485 E = OverDefinedCache.end(); I != E; ++I) {
487 ToErase.push_back(*I);
490 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
491 E = ToErase.end(); I != E; ++I)
492 OverDefinedCache.erase(*I);
494 for (DenseMap<LVIValueHandle, ValueCacheEntryTy>::iterator
495 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
499 void LazyValueInfoCache::solve() {
500 while (!BlockValueStack.empty()) {
501 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
502 if (solveBlockValue(e.second, e.first))
503 BlockValueStack.pop();
507 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
508 // If already a constant, there is nothing to compute.
509 if (isa<Constant>(Val))
512 LVIValueHandle ValHandle(Val, this);
513 if (!ValueCache.count(ValHandle)) return false;
514 return ValueCache[ValHandle].count(BB);
517 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
518 // If already a constant, there is nothing to compute.
519 if (Constant *VC = dyn_cast<Constant>(Val))
520 return LVILatticeVal::get(VC);
522 SeenBlocks.insert(BB);
523 return lookup(Val)[BB];
526 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
527 if (isa<Constant>(Val))
530 ValueCacheEntryTy &Cache = lookup(Val);
531 SeenBlocks.insert(BB);
532 LVILatticeVal &BBLV = Cache[BB];
534 // OverDefinedCacheUpdater is a helper object that will update
535 // the OverDefinedCache for us when this method exits. Make sure to
536 // call markResult on it as we exist, passing a bool to indicate if the
537 // cache needs updating, i.e. if we have solve a new value or not.
538 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
540 // If we've already computed this block's value, return it.
541 if (!BBLV.isUndefined()) {
542 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
544 // Since we're reusing a cached value here, we don't need to update the
545 // OverDefinedCahce. The cache will have been properly updated
546 // whenever the cached value was inserted.
547 ODCacheUpdater.markResult(false);
551 // Otherwise, this is the first time we're seeing this block. Reset the
552 // lattice value to overdefined, so that cycles will terminate and be
553 // conservatively correct.
554 BBLV.markOverdefined();
556 Instruction *BBI = dyn_cast<Instruction>(Val);
557 if (BBI == 0 || BBI->getParent() != BB) {
558 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
561 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
562 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
565 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
566 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
567 return ODCacheUpdater.markResult(true);
570 // We can only analyze the definitions of certain classes of instructions
571 // (integral binops and casts at the moment), so bail if this isn't one.
572 LVILatticeVal Result;
573 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
574 !BBI->getType()->isIntegerTy()) {
575 DEBUG(dbgs() << " compute BB '" << BB->getName()
576 << "' - overdefined because inst def found.\n");
577 BBLV.markOverdefined();
578 return ODCacheUpdater.markResult(true);
581 // FIXME: We're currently limited to binops with a constant RHS. This should
583 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
584 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
585 DEBUG(dbgs() << " compute BB '" << BB->getName()
586 << "' - overdefined because inst def found.\n");
588 BBLV.markOverdefined();
589 return ODCacheUpdater.markResult(true);
592 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
595 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
596 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
597 return L->getPointerAddressSpace() == 0 &&
598 GetUnderlyingObject(L->getPointerOperand()) ==
599 GetUnderlyingObject(Ptr);
601 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
602 return S->getPointerAddressSpace() == 0 &&
603 GetUnderlyingObject(S->getPointerOperand()) ==
604 GetUnderlyingObject(Ptr);
606 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
607 if (MI->isVolatile()) return false;
609 // FIXME: check whether it has a valuerange that excludes zero?
610 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
611 if (!Len || Len->isZero()) return false;
613 if (MI->getDestAddressSpace() == 0)
614 if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
616 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
617 if (MTI->getSourceAddressSpace() == 0)
618 if (MTI->getRawSource() == Ptr || MTI->getSource() == Ptr)
624 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
625 Value *Val, BasicBlock *BB) {
626 LVILatticeVal Result; // Start Undefined.
628 // If this is a pointer, and there's a load from that pointer in this BB,
629 // then we know that the pointer can't be NULL.
630 bool NotNull = false;
631 if (Val->getType()->isPointerTy()) {
632 if (isa<AllocaInst>(Val)) {
635 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
636 if (InstructionDereferencesPointer(BI, Val)) {
644 // If this is the entry block, we must be asking about an argument. The
645 // value is overdefined.
646 if (BB == &BB->getParent()->getEntryBlock()) {
647 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
649 PointerType *PTy = cast<PointerType>(Val->getType());
650 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
652 Result.markOverdefined();
658 // Loop over all of our predecessors, merging what we know from them into
660 bool EdgesMissing = false;
661 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
662 LVILatticeVal EdgeResult;
663 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
667 Result.mergeIn(EdgeResult);
669 // If we hit overdefined, exit early. The BlockVals entry is already set
671 if (Result.isOverdefined()) {
672 DEBUG(dbgs() << " compute BB '" << BB->getName()
673 << "' - overdefined because of pred.\n");
674 // If we previously determined that this is a pointer that can't be null
675 // then return that rather than giving up entirely.
677 PointerType *PTy = cast<PointerType>(Val->getType());
678 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
688 // Return the merged value, which is more precise than 'overdefined'.
689 assert(!Result.isOverdefined());
694 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
695 PHINode *PN, BasicBlock *BB) {
696 LVILatticeVal Result; // Start Undefined.
698 // Loop over all of our predecessors, merging what we know from them into
700 bool EdgesMissing = false;
701 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
702 BasicBlock *PhiBB = PN->getIncomingBlock(i);
703 Value *PhiVal = PN->getIncomingValue(i);
704 LVILatticeVal EdgeResult;
705 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
709 Result.mergeIn(EdgeResult);
711 // If we hit overdefined, exit early. The BlockVals entry is already set
713 if (Result.isOverdefined()) {
714 DEBUG(dbgs() << " compute BB '" << BB->getName()
715 << "' - overdefined because of pred.\n");
724 // Return the merged value, which is more precise than 'overdefined'.
725 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
730 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
733 // Figure out the range of the LHS. If that fails, bail.
734 if (!hasBlockValue(BBI->getOperand(0), BB)) {
735 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
739 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
740 if (!LHSVal.isConstantRange()) {
741 BBLV.markOverdefined();
745 ConstantRange LHSRange = LHSVal.getConstantRange();
746 ConstantRange RHSRange(1);
747 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
748 if (isa<BinaryOperator>(BBI)) {
749 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
750 RHSRange = ConstantRange(RHS->getValue());
752 BBLV.markOverdefined();
757 // NOTE: We're currently limited by the set of operations that ConstantRange
758 // can evaluate symbolically. Enhancing that set will allows us to analyze
760 LVILatticeVal Result;
761 switch (BBI->getOpcode()) {
762 case Instruction::Add:
763 Result.markConstantRange(LHSRange.add(RHSRange));
765 case Instruction::Sub:
766 Result.markConstantRange(LHSRange.sub(RHSRange));
768 case Instruction::Mul:
769 Result.markConstantRange(LHSRange.multiply(RHSRange));
771 case Instruction::UDiv:
772 Result.markConstantRange(LHSRange.udiv(RHSRange));
774 case Instruction::Shl:
775 Result.markConstantRange(LHSRange.shl(RHSRange));
777 case Instruction::LShr:
778 Result.markConstantRange(LHSRange.lshr(RHSRange));
780 case Instruction::Trunc:
781 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
783 case Instruction::SExt:
784 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
786 case Instruction::ZExt:
787 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
789 case Instruction::BitCast:
790 Result.markConstantRange(LHSRange);
792 case Instruction::And:
793 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
795 case Instruction::Or:
796 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
799 // Unhandled instructions are overdefined.
801 DEBUG(dbgs() << " compute BB '" << BB->getName()
802 << "' - overdefined because inst def found.\n");
803 Result.markOverdefined();
811 /// getEdgeValue - This method attempts to infer more complex
812 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
813 BasicBlock *BBTo, LVILatticeVal &Result) {
814 // If already a constant, there is nothing to compute.
815 if (Constant *VC = dyn_cast<Constant>(Val)) {
816 Result = LVILatticeVal::get(VC);
820 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
822 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
823 // If this is a conditional branch and only one successor goes to BBTo, then
824 // we maybe able to infer something from the condition.
825 if (BI->isConditional() &&
826 BI->getSuccessor(0) != BI->getSuccessor(1)) {
827 bool isTrueDest = BI->getSuccessor(0) == BBTo;
828 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
829 "BBTo isn't a successor of BBFrom");
831 // If V is the condition of the branch itself, then we know exactly what
833 if (BI->getCondition() == Val) {
834 Result = LVILatticeVal::get(ConstantInt::get(
835 Type::getInt1Ty(Val->getContext()), isTrueDest));
839 // If the condition of the branch is an equality comparison, we may be
840 // able to infer the value.
841 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
842 if (ICI && ICI->getOperand(0) == Val &&
843 isa<Constant>(ICI->getOperand(1))) {
844 if (ICI->isEquality()) {
845 // We know that V has the RHS constant if this is a true SETEQ or
847 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
848 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
850 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
854 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
855 // Calculate the range of values that would satisfy the comparison.
856 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
857 ConstantRange TrueValues =
858 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
860 // If we're interested in the false dest, invert the condition.
861 if (!isTrueDest) TrueValues = TrueValues.inverse();
863 // Figure out the possible values of the query BEFORE this branch.
864 if (!hasBlockValue(Val, BBFrom)) {
865 BlockValueStack.push(std::make_pair(BBFrom, Val));
869 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
870 if (!InBlock.isConstantRange()) {
871 Result = LVILatticeVal::getRange(TrueValues);
875 // Find all potential values that satisfy both the input and output
877 ConstantRange PossibleValues =
878 TrueValues.intersectWith(InBlock.getConstantRange());
880 Result = LVILatticeVal::getRange(PossibleValues);
887 // If the edge was formed by a switch on the value, then we may know exactly
889 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
890 if (SI->getCondition() == Val) {
891 // We don't know anything in the default case.
892 if (SI->getDefaultDest() == BBTo) {
893 Result.markOverdefined();
897 // We only know something if there is exactly one value that goes from
899 unsigned NumEdges = 0;
900 ConstantInt *EdgeVal = 0;
901 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
902 if (SI->getSuccessor(i) != BBTo) continue;
903 if (NumEdges++) break;
904 EdgeVal = SI->getCaseValue(i);
906 assert(EdgeVal && "Missing successor?");
908 Result = LVILatticeVal::get(EdgeVal);
914 // Otherwise see if the value is known in the block.
915 if (hasBlockValue(Val, BBFrom)) {
916 Result = getBlockValue(Val, BBFrom);
919 BlockValueStack.push(std::make_pair(BBFrom, Val));
923 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
924 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
925 << BB->getName() << "'\n");
927 BlockValueStack.push(std::make_pair(BB, V));
929 LVILatticeVal Result = getBlockValue(V, BB);
931 DEBUG(dbgs() << " Result = " << Result << "\n");
935 LVILatticeVal LazyValueInfoCache::
936 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
937 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
938 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
940 LVILatticeVal Result;
941 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
943 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
945 assert(WasFastQuery && "More work to do after problem solved?");
948 DEBUG(dbgs() << " Result = " << Result << "\n");
952 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
953 BasicBlock *NewSucc) {
954 // When an edge in the graph has been threaded, values that we could not
955 // determine a value for before (i.e. were marked overdefined) may be possible
956 // to solve now. We do NOT try to proactively update these values. Instead,
957 // we clear their entries from the cache, and allow lazy updating to recompute
960 // The updating process is fairly simple: we need to dropped cached info
961 // for all values that were marked overdefined in OldSucc, and for those same
962 // values in any successor of OldSucc (except NewSucc) in which they were
963 // also marked overdefined.
964 std::vector<BasicBlock*> worklist;
965 worklist.push_back(OldSucc);
967 DenseSet<Value*> ClearSet;
968 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
969 E = OverDefinedCache.end(); I != E; ++I) {
970 if (I->first == OldSucc)
971 ClearSet.insert(I->second);
974 // Use a worklist to perform a depth-first search of OldSucc's successors.
975 // NOTE: We do not need a visited list since any blocks we have already
976 // visited will have had their overdefined markers cleared already, and we
977 // thus won't loop to their successors.
978 while (!worklist.empty()) {
979 BasicBlock *ToUpdate = worklist.back();
982 // Skip blocks only accessible through NewSucc.
983 if (ToUpdate == NewSucc) continue;
985 bool changed = false;
986 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
988 // If a value was marked overdefined in OldSucc, and is here too...
989 DenseSet<OverDefinedPairTy>::iterator OI =
990 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
991 if (OI == OverDefinedCache.end()) continue;
993 // Remove it from the caches.
994 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
995 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
997 assert(CI != Entry.end() && "Couldn't find entry to update?");
999 OverDefinedCache.erase(OI);
1001 // If we removed anything, then we potentially need to update
1002 // blocks successors too.
1006 if (!changed) continue;
1008 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1012 //===----------------------------------------------------------------------===//
1013 // LazyValueInfo Impl
1014 //===----------------------------------------------------------------------===//
1016 /// getCache - This lazily constructs the LazyValueInfoCache.
1017 static LazyValueInfoCache &getCache(void *&PImpl) {
1019 PImpl = new LazyValueInfoCache();
1020 return *static_cast<LazyValueInfoCache*>(PImpl);
1023 bool LazyValueInfo::runOnFunction(Function &F) {
1025 getCache(PImpl).clear();
1027 TD = getAnalysisIfAvailable<TargetData>();
1028 TLI = &getAnalysis<TargetLibraryInfo>();
1034 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1035 AU.setPreservesAll();
1036 AU.addRequired<TargetLibraryInfo>();
1039 void LazyValueInfo::releaseMemory() {
1040 // If the cache was allocated, free it.
1042 delete &getCache(PImpl);
1047 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1048 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1050 if (Result.isConstant())
1051 return Result.getConstant();
1052 if (Result.isConstantRange()) {
1053 ConstantRange CR = Result.getConstantRange();
1054 if (const APInt *SingleVal = CR.getSingleElement())
1055 return ConstantInt::get(V->getContext(), *SingleVal);
1060 /// getConstantOnEdge - Determine whether the specified value is known to be a
1061 /// constant on the specified edge. Return null if not.
1062 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1064 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1066 if (Result.isConstant())
1067 return Result.getConstant();
1068 if (Result.isConstantRange()) {
1069 ConstantRange CR = Result.getConstantRange();
1070 if (const APInt *SingleVal = CR.getSingleElement())
1071 return ConstantInt::get(V->getContext(), *SingleVal);
1076 /// getPredicateOnEdge - Determine whether the specified value comparison
1077 /// with a constant is known to be true or false on the specified CFG edge.
1078 /// Pred is a CmpInst predicate.
1079 LazyValueInfo::Tristate
1080 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1081 BasicBlock *FromBB, BasicBlock *ToBB) {
1082 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1084 // If we know the value is a constant, evaluate the conditional.
1086 if (Result.isConstant()) {
1087 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD,
1089 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1090 return ResCI->isZero() ? False : True;
1094 if (Result.isConstantRange()) {
1095 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1096 if (!CI) return Unknown;
1098 ConstantRange CR = Result.getConstantRange();
1099 if (Pred == ICmpInst::ICMP_EQ) {
1100 if (!CR.contains(CI->getValue()))
1103 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1105 } else if (Pred == ICmpInst::ICMP_NE) {
1106 if (!CR.contains(CI->getValue()))
1109 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1113 // Handle more complex predicates.
1114 ConstantRange TrueValues =
1115 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1116 if (TrueValues.contains(CR))
1118 if (TrueValues.inverse().contains(CR))
1123 if (Result.isNotConstant()) {
1124 // If this is an equality comparison, we can try to fold it knowing that
1126 if (Pred == ICmpInst::ICMP_EQ) {
1127 // !C1 == C -> false iff C1 == C.
1128 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1129 Result.getNotConstant(), C, TD,
1131 if (Res->isNullValue())
1133 } else if (Pred == ICmpInst::ICMP_NE) {
1134 // !C1 != C -> true iff C1 == C.
1135 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1136 Result.getNotConstant(), C, TD,
1138 if (Res->isNullValue())
1147 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1148 BasicBlock *NewSucc) {
1149 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1152 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1153 if (PImpl) getCache(PImpl).eraseBlock(BB);