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.
451 OverDefinedCache.clear();
454 } // end anonymous namespace
456 void LVIValueHandle::deleted() {
457 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
459 SmallVector<OverDefinedPairTy, 4> ToErase;
460 for (DenseSet<OverDefinedPairTy>::iterator
461 I = Parent->OverDefinedCache.begin(),
462 E = Parent->OverDefinedCache.end();
464 if (I->second == getValPtr())
465 ToErase.push_back(*I);
468 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
469 E = ToErase.end(); I != E; ++I)
470 Parent->OverDefinedCache.erase(*I);
472 // This erasure deallocates *this, so it MUST happen after we're done
473 // using any and all members of *this.
474 Parent->ValueCache.erase(*this);
477 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
478 // Shortcut if we have never seen this block.
479 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
480 if (I == SeenBlocks.end())
484 SmallVector<OverDefinedPairTy, 4> ToErase;
485 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
486 E = OverDefinedCache.end(); I != E; ++I) {
488 ToErase.push_back(*I);
491 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
492 E = ToErase.end(); I != E; ++I)
493 OverDefinedCache.erase(*I);
495 for (DenseMap<LVIValueHandle, ValueCacheEntryTy>::iterator
496 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
500 void LazyValueInfoCache::solve() {
501 while (!BlockValueStack.empty()) {
502 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
503 if (solveBlockValue(e.second, e.first))
504 BlockValueStack.pop();
508 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
509 // If already a constant, there is nothing to compute.
510 if (isa<Constant>(Val))
513 LVIValueHandle ValHandle(Val, this);
514 if (!ValueCache.count(ValHandle)) return false;
515 return ValueCache[ValHandle].count(BB);
518 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
519 // If already a constant, there is nothing to compute.
520 if (Constant *VC = dyn_cast<Constant>(Val))
521 return LVILatticeVal::get(VC);
523 SeenBlocks.insert(BB);
524 return lookup(Val)[BB];
527 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
528 if (isa<Constant>(Val))
531 ValueCacheEntryTy &Cache = lookup(Val);
532 SeenBlocks.insert(BB);
533 LVILatticeVal &BBLV = Cache[BB];
535 // OverDefinedCacheUpdater is a helper object that will update
536 // the OverDefinedCache for us when this method exits. Make sure to
537 // call markResult on it as we exist, passing a bool to indicate if the
538 // cache needs updating, i.e. if we have solve a new value or not.
539 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
541 // If we've already computed this block's value, return it.
542 if (!BBLV.isUndefined()) {
543 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
545 // Since we're reusing a cached value here, we don't need to update the
546 // OverDefinedCahce. The cache will have been properly updated
547 // whenever the cached value was inserted.
548 ODCacheUpdater.markResult(false);
552 // Otherwise, this is the first time we're seeing this block. Reset the
553 // lattice value to overdefined, so that cycles will terminate and be
554 // conservatively correct.
555 BBLV.markOverdefined();
557 Instruction *BBI = dyn_cast<Instruction>(Val);
558 if (BBI == 0 || BBI->getParent() != BB) {
559 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
562 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
563 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
566 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
567 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
568 return ODCacheUpdater.markResult(true);
571 // We can only analyze the definitions of certain classes of instructions
572 // (integral binops and casts at the moment), so bail if this isn't one.
573 LVILatticeVal Result;
574 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
575 !BBI->getType()->isIntegerTy()) {
576 DEBUG(dbgs() << " compute BB '" << BB->getName()
577 << "' - overdefined because inst def found.\n");
578 BBLV.markOverdefined();
579 return ODCacheUpdater.markResult(true);
582 // FIXME: We're currently limited to binops with a constant RHS. This should
584 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
585 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
586 DEBUG(dbgs() << " compute BB '" << BB->getName()
587 << "' - overdefined because inst def found.\n");
589 BBLV.markOverdefined();
590 return ODCacheUpdater.markResult(true);
593 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
596 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
597 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
598 return L->getPointerAddressSpace() == 0 &&
599 GetUnderlyingObject(L->getPointerOperand()) ==
600 GetUnderlyingObject(Ptr);
602 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
603 return S->getPointerAddressSpace() == 0 &&
604 GetUnderlyingObject(S->getPointerOperand()) ==
605 GetUnderlyingObject(Ptr);
607 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
608 if (MI->isVolatile()) return false;
610 // FIXME: check whether it has a valuerange that excludes zero?
611 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
612 if (!Len || Len->isZero()) return false;
614 if (MI->getDestAddressSpace() == 0)
615 if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
617 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
618 if (MTI->getSourceAddressSpace() == 0)
619 if (MTI->getRawSource() == Ptr || MTI->getSource() == Ptr)
625 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
626 Value *Val, BasicBlock *BB) {
627 LVILatticeVal Result; // Start Undefined.
629 // If this is a pointer, and there's a load from that pointer in this BB,
630 // then we know that the pointer can't be NULL.
631 bool NotNull = false;
632 if (Val->getType()->isPointerTy()) {
633 if (isa<AllocaInst>(Val)) {
636 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
637 if (InstructionDereferencesPointer(BI, Val)) {
645 // If this is the entry block, we must be asking about an argument. The
646 // value is overdefined.
647 if (BB == &BB->getParent()->getEntryBlock()) {
648 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
650 PointerType *PTy = cast<PointerType>(Val->getType());
651 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
653 Result.markOverdefined();
659 // Loop over all of our predecessors, merging what we know from them into
661 bool EdgesMissing = false;
662 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
663 LVILatticeVal EdgeResult;
664 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
668 Result.mergeIn(EdgeResult);
670 // If we hit overdefined, exit early. The BlockVals entry is already set
672 if (Result.isOverdefined()) {
673 DEBUG(dbgs() << " compute BB '" << BB->getName()
674 << "' - overdefined because of pred.\n");
675 // If we previously determined that this is a pointer that can't be null
676 // then return that rather than giving up entirely.
678 PointerType *PTy = cast<PointerType>(Val->getType());
679 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
689 // Return the merged value, which is more precise than 'overdefined'.
690 assert(!Result.isOverdefined());
695 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
696 PHINode *PN, BasicBlock *BB) {
697 LVILatticeVal Result; // Start Undefined.
699 // Loop over all of our predecessors, merging what we know from them into
701 bool EdgesMissing = false;
702 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
703 BasicBlock *PhiBB = PN->getIncomingBlock(i);
704 Value *PhiVal = PN->getIncomingValue(i);
705 LVILatticeVal EdgeResult;
706 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
710 Result.mergeIn(EdgeResult);
712 // If we hit overdefined, exit early. The BlockVals entry is already set
714 if (Result.isOverdefined()) {
715 DEBUG(dbgs() << " compute BB '" << BB->getName()
716 << "' - overdefined because of pred.\n");
725 // Return the merged value, which is more precise than 'overdefined'.
726 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
731 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
734 // Figure out the range of the LHS. If that fails, bail.
735 if (!hasBlockValue(BBI->getOperand(0), BB)) {
736 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
740 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
741 if (!LHSVal.isConstantRange()) {
742 BBLV.markOverdefined();
746 ConstantRange LHSRange = LHSVal.getConstantRange();
747 ConstantRange RHSRange(1);
748 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
749 if (isa<BinaryOperator>(BBI)) {
750 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
751 RHSRange = ConstantRange(RHS->getValue());
753 BBLV.markOverdefined();
758 // NOTE: We're currently limited by the set of operations that ConstantRange
759 // can evaluate symbolically. Enhancing that set will allows us to analyze
761 LVILatticeVal Result;
762 switch (BBI->getOpcode()) {
763 case Instruction::Add:
764 Result.markConstantRange(LHSRange.add(RHSRange));
766 case Instruction::Sub:
767 Result.markConstantRange(LHSRange.sub(RHSRange));
769 case Instruction::Mul:
770 Result.markConstantRange(LHSRange.multiply(RHSRange));
772 case Instruction::UDiv:
773 Result.markConstantRange(LHSRange.udiv(RHSRange));
775 case Instruction::Shl:
776 Result.markConstantRange(LHSRange.shl(RHSRange));
778 case Instruction::LShr:
779 Result.markConstantRange(LHSRange.lshr(RHSRange));
781 case Instruction::Trunc:
782 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
784 case Instruction::SExt:
785 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
787 case Instruction::ZExt:
788 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
790 case Instruction::BitCast:
791 Result.markConstantRange(LHSRange);
793 case Instruction::And:
794 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
796 case Instruction::Or:
797 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
800 // Unhandled instructions are overdefined.
802 DEBUG(dbgs() << " compute BB '" << BB->getName()
803 << "' - overdefined because inst def found.\n");
804 Result.markOverdefined();
812 /// getEdgeValue - This method attempts to infer more complex
813 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
814 BasicBlock *BBTo, LVILatticeVal &Result) {
815 // If already a constant, there is nothing to compute.
816 if (Constant *VC = dyn_cast<Constant>(Val)) {
817 Result = LVILatticeVal::get(VC);
821 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
823 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
824 // If this is a conditional branch and only one successor goes to BBTo, then
825 // we maybe able to infer something from the condition.
826 if (BI->isConditional() &&
827 BI->getSuccessor(0) != BI->getSuccessor(1)) {
828 bool isTrueDest = BI->getSuccessor(0) == BBTo;
829 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
830 "BBTo isn't a successor of BBFrom");
832 // If V is the condition of the branch itself, then we know exactly what
834 if (BI->getCondition() == Val) {
835 Result = LVILatticeVal::get(ConstantInt::get(
836 Type::getInt1Ty(Val->getContext()), isTrueDest));
840 // If the condition of the branch is an equality comparison, we may be
841 // able to infer the value.
842 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
843 if (ICI && ICI->getOperand(0) == Val &&
844 isa<Constant>(ICI->getOperand(1))) {
845 if (ICI->isEquality()) {
846 // We know that V has the RHS constant if this is a true SETEQ or
848 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
849 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
851 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
855 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
856 // Calculate the range of values that would satisfy the comparison.
857 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
858 ConstantRange TrueValues =
859 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
861 // If we're interested in the false dest, invert the condition.
862 if (!isTrueDest) TrueValues = TrueValues.inverse();
864 // Figure out the possible values of the query BEFORE this branch.
865 if (!hasBlockValue(Val, BBFrom)) {
866 BlockValueStack.push(std::make_pair(BBFrom, Val));
870 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
871 if (!InBlock.isConstantRange()) {
872 Result = LVILatticeVal::getRange(TrueValues);
876 // Find all potential values that satisfy both the input and output
878 ConstantRange PossibleValues =
879 TrueValues.intersectWith(InBlock.getConstantRange());
881 Result = LVILatticeVal::getRange(PossibleValues);
888 // If the edge was formed by a switch on the value, then we may know exactly
890 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
891 if (SI->getCondition() == Val) {
892 // We don't know anything in the default case.
893 if (SI->getDefaultDest() == BBTo) {
894 Result.markOverdefined();
898 // We only know something if there is exactly one value that goes from
900 unsigned NumEdges = 0;
901 ConstantInt *EdgeVal = 0;
902 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
903 if (SI->getSuccessor(i) != BBTo) continue;
904 if (NumEdges++) break;
905 EdgeVal = SI->getCaseValue(i);
907 assert(EdgeVal && "Missing successor?");
909 Result = LVILatticeVal::get(EdgeVal);
915 // Otherwise see if the value is known in the block.
916 if (hasBlockValue(Val, BBFrom)) {
917 Result = getBlockValue(Val, BBFrom);
920 BlockValueStack.push(std::make_pair(BBFrom, Val));
924 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
925 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
926 << BB->getName() << "'\n");
928 BlockValueStack.push(std::make_pair(BB, V));
930 LVILatticeVal Result = getBlockValue(V, BB);
932 DEBUG(dbgs() << " Result = " << Result << "\n");
936 LVILatticeVal LazyValueInfoCache::
937 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
938 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
939 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
941 LVILatticeVal Result;
942 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
944 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
946 assert(WasFastQuery && "More work to do after problem solved?");
949 DEBUG(dbgs() << " Result = " << Result << "\n");
953 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
954 BasicBlock *NewSucc) {
955 // When an edge in the graph has been threaded, values that we could not
956 // determine a value for before (i.e. were marked overdefined) may be possible
957 // to solve now. We do NOT try to proactively update these values. Instead,
958 // we clear their entries from the cache, and allow lazy updating to recompute
961 // The updating process is fairly simple: we need to dropped cached info
962 // for all values that were marked overdefined in OldSucc, and for those same
963 // values in any successor of OldSucc (except NewSucc) in which they were
964 // also marked overdefined.
965 std::vector<BasicBlock*> worklist;
966 worklist.push_back(OldSucc);
968 DenseSet<Value*> ClearSet;
969 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
970 E = OverDefinedCache.end(); I != E; ++I) {
971 if (I->first == OldSucc)
972 ClearSet.insert(I->second);
975 // Use a worklist to perform a depth-first search of OldSucc's successors.
976 // NOTE: We do not need a visited list since any blocks we have already
977 // visited will have had their overdefined markers cleared already, and we
978 // thus won't loop to their successors.
979 while (!worklist.empty()) {
980 BasicBlock *ToUpdate = worklist.back();
983 // Skip blocks only accessible through NewSucc.
984 if (ToUpdate == NewSucc) continue;
986 bool changed = false;
987 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
989 // If a value was marked overdefined in OldSucc, and is here too...
990 DenseSet<OverDefinedPairTy>::iterator OI =
991 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
992 if (OI == OverDefinedCache.end()) continue;
994 // Remove it from the caches.
995 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
996 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
998 assert(CI != Entry.end() && "Couldn't find entry to update?");
1000 OverDefinedCache.erase(OI);
1002 // If we removed anything, then we potentially need to update
1003 // blocks successors too.
1007 if (!changed) continue;
1009 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1013 //===----------------------------------------------------------------------===//
1014 // LazyValueInfo Impl
1015 //===----------------------------------------------------------------------===//
1017 /// getCache - This lazily constructs the LazyValueInfoCache.
1018 static LazyValueInfoCache &getCache(void *&PImpl) {
1020 PImpl = new LazyValueInfoCache();
1021 return *static_cast<LazyValueInfoCache*>(PImpl);
1024 bool LazyValueInfo::runOnFunction(Function &F) {
1026 getCache(PImpl).clear();
1028 TD = getAnalysisIfAvailable<TargetData>();
1029 TLI = &getAnalysis<TargetLibraryInfo>();
1035 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1036 AU.setPreservesAll();
1037 AU.addRequired<TargetLibraryInfo>();
1040 void LazyValueInfo::releaseMemory() {
1041 // If the cache was allocated, free it.
1043 delete &getCache(PImpl);
1048 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1049 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1051 if (Result.isConstant())
1052 return Result.getConstant();
1053 if (Result.isConstantRange()) {
1054 ConstantRange CR = Result.getConstantRange();
1055 if (const APInt *SingleVal = CR.getSingleElement())
1056 return ConstantInt::get(V->getContext(), *SingleVal);
1061 /// getConstantOnEdge - Determine whether the specified value is known to be a
1062 /// constant on the specified edge. Return null if not.
1063 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1065 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1067 if (Result.isConstant())
1068 return Result.getConstant();
1069 if (Result.isConstantRange()) {
1070 ConstantRange CR = Result.getConstantRange();
1071 if (const APInt *SingleVal = CR.getSingleElement())
1072 return ConstantInt::get(V->getContext(), *SingleVal);
1077 /// getPredicateOnEdge - Determine whether the specified value comparison
1078 /// with a constant is known to be true or false on the specified CFG edge.
1079 /// Pred is a CmpInst predicate.
1080 LazyValueInfo::Tristate
1081 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1082 BasicBlock *FromBB, BasicBlock *ToBB) {
1083 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1085 // If we know the value is a constant, evaluate the conditional.
1087 if (Result.isConstant()) {
1088 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD,
1090 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1091 return ResCI->isZero() ? False : True;
1095 if (Result.isConstantRange()) {
1096 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1097 if (!CI) return Unknown;
1099 ConstantRange CR = Result.getConstantRange();
1100 if (Pred == ICmpInst::ICMP_EQ) {
1101 if (!CR.contains(CI->getValue()))
1104 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1106 } else if (Pred == ICmpInst::ICMP_NE) {
1107 if (!CR.contains(CI->getValue()))
1110 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1114 // Handle more complex predicates.
1115 ConstantRange TrueValues =
1116 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1117 if (TrueValues.contains(CR))
1119 if (TrueValues.inverse().contains(CR))
1124 if (Result.isNotConstant()) {
1125 // If this is an equality comparison, we can try to fold it knowing that
1127 if (Pred == ICmpInst::ICMP_EQ) {
1128 // !C1 == C -> false iff C1 == C.
1129 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1130 Result.getNotConstant(), C, TD,
1132 if (Res->isNullValue())
1134 } else if (Pred == ICmpInst::ICMP_NE) {
1135 // !C1 != C -> true iff C1 == C.
1136 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1137 Result.getNotConstant(), C, TD,
1139 if (Res->isNullValue())
1148 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1149 BasicBlock *NewSucc) {
1150 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1153 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1154 if (PImpl) getCache(PImpl).eraseBlock(BB);