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/Support/CFG.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Support/ValueHandle.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/STLExtras.h"
36 char LazyValueInfo::ID = 0;
37 INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
38 "Lazy Value Information Analysis", false, true)
41 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
49 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
52 /// FIXME: This is basically just for bringup, this can be made a lot more rich
58 /// undefined - This Value has no known value yet.
61 /// constant - This Value has a specific constant value.
63 /// notconstant - This Value is known to not have the specified value.
66 /// constantrange - The Value falls within this range.
69 /// overdefined - This value is not known to be constant, and we know that
74 /// Val: This stores the current lattice value along with the Constant* for
75 /// the constant if this is a 'constant' or 'notconstant' value.
81 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
83 static LVILatticeVal get(Constant *C) {
85 if (!isa<UndefValue>(C))
89 static LVILatticeVal getNot(Constant *C) {
91 if (!isa<UndefValue>(C))
92 Res.markNotConstant(C);
95 static LVILatticeVal getRange(ConstantRange CR) {
97 Res.markConstantRange(CR);
101 bool isUndefined() const { return Tag == undefined; }
102 bool isConstant() const { return Tag == constant; }
103 bool isNotConstant() const { return Tag == notconstant; }
104 bool isConstantRange() const { return Tag == constantrange; }
105 bool isOverdefined() const { return Tag == overdefined; }
107 Constant *getConstant() const {
108 assert(isConstant() && "Cannot get the constant of a non-constant!");
112 Constant *getNotConstant() const {
113 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
117 ConstantRange getConstantRange() const {
118 assert(isConstantRange() &&
119 "Cannot get the constant-range of a non-constant-range!");
123 /// markOverdefined - Return true if this is a change in status.
124 bool markOverdefined() {
131 /// markConstant - Return true if this is a change in status.
132 bool markConstant(Constant *V) {
133 assert(V && "Marking constant with NULL");
134 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
135 return markConstantRange(ConstantRange(CI->getValue()));
136 if (isa<UndefValue>(V))
139 assert((!isConstant() || getConstant() == V) &&
140 "Marking constant with different value");
141 assert(isUndefined());
147 /// markNotConstant - Return true if this is a change in status.
148 bool markNotConstant(Constant *V) {
149 assert(V && "Marking constant with NULL");
150 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
151 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
152 if (isa<UndefValue>(V))
155 assert((!isConstant() || getConstant() != V) &&
156 "Marking constant !constant with same value");
157 assert((!isNotConstant() || getNotConstant() == V) &&
158 "Marking !constant with different value");
159 assert(isUndefined() || isConstant());
165 /// markConstantRange - Return true if this is a change in status.
166 bool markConstantRange(const ConstantRange NewR) {
167 if (isConstantRange()) {
168 if (NewR.isEmptySet())
169 return markOverdefined();
171 bool changed = Range == NewR;
176 assert(isUndefined());
177 if (NewR.isEmptySet())
178 return markOverdefined();
185 /// mergeIn - Merge the specified lattice value into this one, updating this
186 /// one and returning true if anything changed.
187 bool mergeIn(const LVILatticeVal &RHS) {
188 if (RHS.isUndefined() || isOverdefined()) return false;
189 if (RHS.isOverdefined()) return markOverdefined();
199 if (RHS.isConstant()) {
202 return markOverdefined();
205 if (RHS.isNotConstant()) {
207 return markOverdefined();
209 // Unless we can prove that the two Constants are different, we must
210 // move to overdefined.
211 // FIXME: use TargetData for smarter constant folding.
212 if (ConstantInt *Res = dyn_cast<ConstantInt>(
213 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
215 RHS.getNotConstant())))
217 return markNotConstant(RHS.getNotConstant());
219 return markOverdefined();
222 // RHS is a ConstantRange, LHS is a non-integer Constant.
224 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
225 // a function. The correct result is to pick up RHS.
227 return markOverdefined();
230 if (isNotConstant()) {
231 if (RHS.isConstant()) {
233 return markOverdefined();
235 // Unless we can prove that the two Constants are different, we must
236 // move to overdefined.
237 // FIXME: use TargetData for smarter constant folding.
238 if (ConstantInt *Res = dyn_cast<ConstantInt>(
239 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
245 return markOverdefined();
248 if (RHS.isNotConstant()) {
251 return markOverdefined();
254 return markOverdefined();
257 assert(isConstantRange() && "New LVILattice type?");
258 if (!RHS.isConstantRange())
259 return markOverdefined();
261 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
262 if (NewR.isFullSet())
263 return markOverdefined();
264 return markConstantRange(NewR);
268 } // end anonymous namespace.
271 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
272 if (Val.isUndefined())
273 return OS << "undefined";
274 if (Val.isOverdefined())
275 return OS << "overdefined";
277 if (Val.isNotConstant())
278 return OS << "notconstant<" << *Val.getNotConstant() << '>';
279 else if (Val.isConstantRange())
280 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
281 << Val.getConstantRange().getUpper() << '>';
282 return OS << "constant<" << *Val.getConstant() << '>';
286 //===----------------------------------------------------------------------===//
287 // LazyValueInfoCache Decl
288 //===----------------------------------------------------------------------===//
291 /// LVIValueHandle - A callback value handle update the cache when
292 /// values are erased.
293 class LazyValueInfoCache;
294 struct LVIValueHandle : public CallbackVH {
295 LazyValueInfoCache *Parent;
297 LVIValueHandle(Value *V, LazyValueInfoCache *P)
298 : CallbackVH(V), Parent(P) { }
301 void allUsesReplacedWith(Value *V) {
309 struct DenseMapInfo<LVIValueHandle> {
310 typedef DenseMapInfo<Value*> PointerInfo;
311 static inline LVIValueHandle getEmptyKey() {
312 return LVIValueHandle(PointerInfo::getEmptyKey(),
313 static_cast<LazyValueInfoCache*>(0));
315 static inline LVIValueHandle getTombstoneKey() {
316 return LVIValueHandle(PointerInfo::getTombstoneKey(),
317 static_cast<LazyValueInfoCache*>(0));
319 static unsigned getHashValue(const LVIValueHandle &Val) {
320 return PointerInfo::getHashValue(Val);
322 static bool isEqual(const LVIValueHandle &LHS, const LVIValueHandle &RHS) {
328 struct DenseMapInfo<std::pair<AssertingVH<BasicBlock>, Value*> > {
329 typedef std::pair<AssertingVH<BasicBlock>, Value*> PairTy;
330 typedef DenseMapInfo<AssertingVH<BasicBlock> > APointerInfo;
331 typedef DenseMapInfo<Value*> BPointerInfo;
332 static inline PairTy getEmptyKey() {
333 return std::make_pair(APointerInfo::getEmptyKey(),
334 BPointerInfo::getEmptyKey());
336 static inline PairTy getTombstoneKey() {
337 return std::make_pair(APointerInfo::getTombstoneKey(),
338 BPointerInfo::getTombstoneKey());
340 static unsigned getHashValue( const PairTy &Val) {
341 return APointerInfo::getHashValue(Val.first) ^
342 BPointerInfo::getHashValue(Val.second);
344 static bool isEqual(const PairTy &LHS, const PairTy &RHS) {
345 return APointerInfo::isEqual(LHS.first, RHS.first) &&
346 BPointerInfo::isEqual(LHS.second, RHS.second);
352 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
353 /// maintains information about queries across the clients' queries.
354 class LazyValueInfoCache {
355 /// ValueCacheEntryTy - This is all of the cached block information for
356 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
357 /// entries, allowing us to do a lookup with a binary search.
358 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
360 /// ValueCache - This is all of the cached information for all values,
361 /// mapped from Value* to key information.
362 DenseMap<LVIValueHandle, ValueCacheEntryTy> ValueCache;
364 /// OverDefinedCache - This tracks, on a per-block basis, the set of
365 /// values that are over-defined at the end of that block. This is required
366 /// for cache updating.
367 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
368 DenseSet<OverDefinedPairTy> OverDefinedCache;
370 /// BlockValueStack - This stack holds the state of the value solver
371 /// during a query. It basically emulates the callstack of the naive
372 /// recursive value lookup process.
373 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
375 friend struct LVIValueHandle;
377 /// OverDefinedCacheUpdater - A helper object that ensures that the
378 /// OverDefinedCache is updated whenever solveBlockValue returns.
379 struct OverDefinedCacheUpdater {
380 LazyValueInfoCache *Parent;
385 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
386 LazyValueInfoCache *P)
387 : Parent(P), Val(V), BB(B), BBLV(LV) { }
389 bool markResult(bool changed) {
390 if (changed && BBLV.isOverdefined())
391 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
398 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
399 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
400 LVILatticeVal &Result);
401 bool hasBlockValue(Value *Val, BasicBlock *BB);
403 // These methods process one work item and may add more. A false value
404 // returned means that the work item was not completely processed and must
405 // be revisited after going through the new items.
406 bool solveBlockValue(Value *Val, BasicBlock *BB);
407 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
408 Value *Val, BasicBlock *BB);
409 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
410 PHINode *PN, BasicBlock *BB);
411 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
412 Instruction *BBI, BasicBlock *BB);
416 ValueCacheEntryTy &lookup(Value *V) {
417 return ValueCache[LVIValueHandle(V, this)];
421 /// getValueInBlock - This is the query interface to determine the lattice
422 /// value for the specified Value* at the end of the specified block.
423 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
425 /// getValueOnEdge - This is the query interface to determine the lattice
426 /// value for the specified Value* that is true on the specified edge.
427 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
429 /// threadEdge - This is the update interface to inform the cache that an
430 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
432 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
434 /// eraseBlock - This is part of the update interface to inform the cache
435 /// that a block has been deleted.
436 void eraseBlock(BasicBlock *BB);
438 /// clear - Empty the cache.
441 OverDefinedCache.clear();
444 } // end anonymous namespace
446 void LVIValueHandle::deleted() {
447 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
449 SmallVector<OverDefinedPairTy, 4> ToErase;
450 for (DenseSet<OverDefinedPairTy>::iterator
451 I = Parent->OverDefinedCache.begin(),
452 E = Parent->OverDefinedCache.end();
454 if (I->second == getValPtr())
455 ToErase.push_back(*I);
458 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
459 E = ToErase.end(); I != E; ++I)
460 Parent->OverDefinedCache.erase(*I);
462 // This erasure deallocates *this, so it MUST happen after we're done
463 // using any and all members of *this.
464 Parent->ValueCache.erase(*this);
467 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
468 SmallVector<OverDefinedPairTy, 4> ToErase;
469 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
470 E = OverDefinedCache.end(); I != E; ++I) {
472 ToErase.push_back(*I);
475 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
476 E = ToErase.end(); I != E; ++I)
477 OverDefinedCache.erase(*I);
479 for (DenseMap<LVIValueHandle, ValueCacheEntryTy>::iterator
480 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
484 void LazyValueInfoCache::solve() {
485 while (!BlockValueStack.empty()) {
486 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
487 if (solveBlockValue(e.second, e.first))
488 BlockValueStack.pop();
492 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
493 // If already a constant, there is nothing to compute.
494 if (isa<Constant>(Val))
497 LVIValueHandle ValHandle(Val, this);
498 if (!ValueCache.count(ValHandle)) return false;
499 return ValueCache[ValHandle].count(BB);
502 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
503 // If already a constant, there is nothing to compute.
504 if (Constant *VC = dyn_cast<Constant>(Val))
505 return LVILatticeVal::get(VC);
507 return lookup(Val)[BB];
510 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
511 if (isa<Constant>(Val))
514 ValueCacheEntryTy &Cache = lookup(Val);
515 LVILatticeVal &BBLV = Cache[BB];
517 // OverDefinedCacheUpdater is a helper object that will update
518 // the OverDefinedCache for us when this method exits. Make sure to
519 // call markResult on it as we exist, passing a bool to indicate if the
520 // cache needs updating, i.e. if we have solve a new value or not.
521 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
523 // If we've already computed this block's value, return it.
524 if (!BBLV.isUndefined()) {
525 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
527 // Since we're reusing a cached value here, we don't need to update the
528 // OverDefinedCahce. The cache will have been properly updated
529 // whenever the cached value was inserted.
530 ODCacheUpdater.markResult(false);
534 // Otherwise, this is the first time we're seeing this block. Reset the
535 // lattice value to overdefined, so that cycles will terminate and be
536 // conservatively correct.
537 BBLV.markOverdefined();
539 Instruction *BBI = dyn_cast<Instruction>(Val);
540 if (BBI == 0 || BBI->getParent() != BB) {
541 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
544 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
545 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
548 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
549 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
550 return ODCacheUpdater.markResult(true);
553 // We can only analyze the definitions of certain classes of instructions
554 // (integral binops and casts at the moment), so bail if this isn't one.
555 LVILatticeVal Result;
556 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
557 !BBI->getType()->isIntegerTy()) {
558 DEBUG(dbgs() << " compute BB '" << BB->getName()
559 << "' - overdefined because inst def found.\n");
560 BBLV.markOverdefined();
561 return ODCacheUpdater.markResult(true);
564 // FIXME: We're currently limited to binops with a constant RHS. This should
566 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
567 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
568 DEBUG(dbgs() << " compute BB '" << BB->getName()
569 << "' - overdefined because inst def found.\n");
571 BBLV.markOverdefined();
572 return ODCacheUpdater.markResult(true);
575 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
578 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
579 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
580 return L->getPointerAddressSpace() == 0 &&
581 GetUnderlyingObject(L->getPointerOperand()) ==
582 GetUnderlyingObject(Ptr);
584 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
585 return S->getPointerAddressSpace() == 0 &&
586 GetUnderlyingObject(S->getPointerOperand()) ==
587 GetUnderlyingObject(Ptr);
589 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
590 if (MI->isVolatile()) return false;
591 if (MI->getAddressSpace() != 0) return false;
593 // FIXME: check whether it has a valuerange that excludes zero?
594 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
595 if (!Len || Len->isZero()) return false;
597 if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
599 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
600 return MTI->getRawSource() == Ptr || MTI->getSource() == Ptr;
605 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
606 Value *Val, BasicBlock *BB) {
607 LVILatticeVal Result; // Start Undefined.
609 // If this is a pointer, and there's a load from that pointer in this BB,
610 // then we know that the pointer can't be NULL.
611 bool NotNull = false;
612 if (Val->getType()->isPointerTy()) {
613 if (isa<AllocaInst>(Val)) {
616 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
617 if (InstructionDereferencesPointer(BI, Val)) {
625 // If this is the entry block, we must be asking about an argument. The
626 // value is overdefined.
627 if (BB == &BB->getParent()->getEntryBlock()) {
628 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
630 const PointerType *PTy = cast<PointerType>(Val->getType());
631 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
633 Result.markOverdefined();
639 // Loop over all of our predecessors, merging what we know from them into
641 bool EdgesMissing = false;
642 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
643 LVILatticeVal EdgeResult;
644 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
648 Result.mergeIn(EdgeResult);
650 // If we hit overdefined, exit early. The BlockVals entry is already set
652 if (Result.isOverdefined()) {
653 DEBUG(dbgs() << " compute BB '" << BB->getName()
654 << "' - overdefined because of pred.\n");
655 // If we previously determined that this is a pointer that can't be null
656 // then return that rather than giving up entirely.
658 const PointerType *PTy = cast<PointerType>(Val->getType());
659 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
669 // Return the merged value, which is more precise than 'overdefined'.
670 assert(!Result.isOverdefined());
675 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
676 PHINode *PN, BasicBlock *BB) {
677 LVILatticeVal Result; // Start Undefined.
679 // Loop over all of our predecessors, merging what we know from them into
681 bool EdgesMissing = false;
682 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
683 BasicBlock *PhiBB = PN->getIncomingBlock(i);
684 Value *PhiVal = PN->getIncomingValue(i);
685 LVILatticeVal EdgeResult;
686 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
690 Result.mergeIn(EdgeResult);
692 // If we hit overdefined, exit early. The BlockVals entry is already set
694 if (Result.isOverdefined()) {
695 DEBUG(dbgs() << " compute BB '" << BB->getName()
696 << "' - overdefined because of pred.\n");
705 // Return the merged value, which is more precise than 'overdefined'.
706 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
711 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
714 // Figure out the range of the LHS. If that fails, bail.
715 if (!hasBlockValue(BBI->getOperand(0), BB)) {
716 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
720 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
721 if (!LHSVal.isConstantRange()) {
722 BBLV.markOverdefined();
726 ConstantRange LHSRange = LHSVal.getConstantRange();
727 ConstantRange RHSRange(1);
728 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
729 if (isa<BinaryOperator>(BBI)) {
730 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
731 RHSRange = ConstantRange(RHS->getValue());
733 BBLV.markOverdefined();
738 // NOTE: We're currently limited by the set of operations that ConstantRange
739 // can evaluate symbolically. Enhancing that set will allows us to analyze
741 LVILatticeVal Result;
742 switch (BBI->getOpcode()) {
743 case Instruction::Add:
744 Result.markConstantRange(LHSRange.add(RHSRange));
746 case Instruction::Sub:
747 Result.markConstantRange(LHSRange.sub(RHSRange));
749 case Instruction::Mul:
750 Result.markConstantRange(LHSRange.multiply(RHSRange));
752 case Instruction::UDiv:
753 Result.markConstantRange(LHSRange.udiv(RHSRange));
755 case Instruction::Shl:
756 Result.markConstantRange(LHSRange.shl(RHSRange));
758 case Instruction::LShr:
759 Result.markConstantRange(LHSRange.lshr(RHSRange));
761 case Instruction::Trunc:
762 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
764 case Instruction::SExt:
765 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
767 case Instruction::ZExt:
768 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
770 case Instruction::BitCast:
771 Result.markConstantRange(LHSRange);
773 case Instruction::And:
774 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
776 case Instruction::Or:
777 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
780 // Unhandled instructions are overdefined.
782 DEBUG(dbgs() << " compute BB '" << BB->getName()
783 << "' - overdefined because inst def found.\n");
784 Result.markOverdefined();
792 /// getEdgeValue - This method attempts to infer more complex
793 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
794 BasicBlock *BBTo, LVILatticeVal &Result) {
795 // If already a constant, there is nothing to compute.
796 if (Constant *VC = dyn_cast<Constant>(Val)) {
797 Result = LVILatticeVal::get(VC);
801 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
803 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
804 // If this is a conditional branch and only one successor goes to BBTo, then
805 // we maybe able to infer something from the condition.
806 if (BI->isConditional() &&
807 BI->getSuccessor(0) != BI->getSuccessor(1)) {
808 bool isTrueDest = BI->getSuccessor(0) == BBTo;
809 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
810 "BBTo isn't a successor of BBFrom");
812 // If V is the condition of the branch itself, then we know exactly what
814 if (BI->getCondition() == Val) {
815 Result = LVILatticeVal::get(ConstantInt::get(
816 Type::getInt1Ty(Val->getContext()), isTrueDest));
820 // If the condition of the branch is an equality comparison, we may be
821 // able to infer the value.
822 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
823 if (ICI && ICI->getOperand(0) == Val &&
824 isa<Constant>(ICI->getOperand(1))) {
825 if (ICI->isEquality()) {
826 // We know that V has the RHS constant if this is a true SETEQ or
828 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
829 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
831 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
835 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
836 // Calculate the range of values that would satisfy the comparison.
837 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
838 ConstantRange TrueValues =
839 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
841 // If we're interested in the false dest, invert the condition.
842 if (!isTrueDest) TrueValues = TrueValues.inverse();
844 // Figure out the possible values of the query BEFORE this branch.
845 if (!hasBlockValue(Val, BBFrom)) {
846 BlockValueStack.push(std::make_pair(BBFrom, Val));
850 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
851 if (!InBlock.isConstantRange()) {
852 Result = LVILatticeVal::getRange(TrueValues);
856 // Find all potential values that satisfy both the input and output
858 ConstantRange PossibleValues =
859 TrueValues.intersectWith(InBlock.getConstantRange());
861 Result = LVILatticeVal::getRange(PossibleValues);
868 // If the edge was formed by a switch on the value, then we may know exactly
870 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
871 if (SI->getCondition() == Val) {
872 // We don't know anything in the default case.
873 if (SI->getDefaultDest() == BBTo) {
874 Result.markOverdefined();
878 // We only know something if there is exactly one value that goes from
880 unsigned NumEdges = 0;
881 ConstantInt *EdgeVal = 0;
882 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
883 if (SI->getSuccessor(i) != BBTo) continue;
884 if (NumEdges++) break;
885 EdgeVal = SI->getCaseValue(i);
887 assert(EdgeVal && "Missing successor?");
889 Result = LVILatticeVal::get(EdgeVal);
895 // Otherwise see if the value is known in the block.
896 if (hasBlockValue(Val, BBFrom)) {
897 Result = getBlockValue(Val, BBFrom);
900 BlockValueStack.push(std::make_pair(BBFrom, Val));
904 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
905 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
906 << BB->getName() << "'\n");
908 BlockValueStack.push(std::make_pair(BB, V));
910 LVILatticeVal Result = getBlockValue(V, BB);
912 DEBUG(dbgs() << " Result = " << Result << "\n");
916 LVILatticeVal LazyValueInfoCache::
917 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
918 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
919 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
921 LVILatticeVal Result;
922 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
924 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
926 assert(WasFastQuery && "More work to do after problem solved?");
929 DEBUG(dbgs() << " Result = " << Result << "\n");
933 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
934 BasicBlock *NewSucc) {
935 // When an edge in the graph has been threaded, values that we could not
936 // determine a value for before (i.e. were marked overdefined) may be possible
937 // to solve now. We do NOT try to proactively update these values. Instead,
938 // we clear their entries from the cache, and allow lazy updating to recompute
941 // The updating process is fairly simple: we need to dropped cached info
942 // for all values that were marked overdefined in OldSucc, and for those same
943 // values in any successor of OldSucc (except NewSucc) in which they were
944 // also marked overdefined.
945 std::vector<BasicBlock*> worklist;
946 worklist.push_back(OldSucc);
948 DenseSet<Value*> ClearSet;
949 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
950 E = OverDefinedCache.end(); I != E; ++I) {
951 if (I->first == OldSucc)
952 ClearSet.insert(I->second);
955 // Use a worklist to perform a depth-first search of OldSucc's successors.
956 // NOTE: We do not need a visited list since any blocks we have already
957 // visited will have had their overdefined markers cleared already, and we
958 // thus won't loop to their successors.
959 while (!worklist.empty()) {
960 BasicBlock *ToUpdate = worklist.back();
963 // Skip blocks only accessible through NewSucc.
964 if (ToUpdate == NewSucc) continue;
966 bool changed = false;
967 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
969 // If a value was marked overdefined in OldSucc, and is here too...
970 DenseSet<OverDefinedPairTy>::iterator OI =
971 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
972 if (OI == OverDefinedCache.end()) continue;
974 // Remove it from the caches.
975 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
976 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
978 assert(CI != Entry.end() && "Couldn't find entry to update?");
980 OverDefinedCache.erase(OI);
982 // If we removed anything, then we potentially need to update
983 // blocks successors too.
987 if (!changed) continue;
989 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
993 //===----------------------------------------------------------------------===//
994 // LazyValueInfo Impl
995 //===----------------------------------------------------------------------===//
997 /// getCache - This lazily constructs the LazyValueInfoCache.
998 static LazyValueInfoCache &getCache(void *&PImpl) {
1000 PImpl = new LazyValueInfoCache();
1001 return *static_cast<LazyValueInfoCache*>(PImpl);
1004 bool LazyValueInfo::runOnFunction(Function &F) {
1006 getCache(PImpl).clear();
1008 TD = getAnalysisIfAvailable<TargetData>();
1013 void LazyValueInfo::releaseMemory() {
1014 // If the cache was allocated, free it.
1016 delete &getCache(PImpl);
1021 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1022 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1024 if (Result.isConstant())
1025 return Result.getConstant();
1026 if (Result.isConstantRange()) {
1027 ConstantRange CR = Result.getConstantRange();
1028 if (const APInt *SingleVal = CR.getSingleElement())
1029 return ConstantInt::get(V->getContext(), *SingleVal);
1034 /// getConstantOnEdge - Determine whether the specified value is known to be a
1035 /// constant on the specified edge. Return null if not.
1036 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1038 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1040 if (Result.isConstant())
1041 return Result.getConstant();
1042 if (Result.isConstantRange()) {
1043 ConstantRange CR = Result.getConstantRange();
1044 if (const APInt *SingleVal = CR.getSingleElement())
1045 return ConstantInt::get(V->getContext(), *SingleVal);
1050 /// getPredicateOnEdge - Determine whether the specified value comparison
1051 /// with a constant is known to be true or false on the specified CFG edge.
1052 /// Pred is a CmpInst predicate.
1053 LazyValueInfo::Tristate
1054 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1055 BasicBlock *FromBB, BasicBlock *ToBB) {
1056 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1058 // If we know the value is a constant, evaluate the conditional.
1060 if (Result.isConstant()) {
1061 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
1062 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1063 return ResCI->isZero() ? False : True;
1067 if (Result.isConstantRange()) {
1068 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1069 if (!CI) return Unknown;
1071 ConstantRange CR = Result.getConstantRange();
1072 if (Pred == ICmpInst::ICMP_EQ) {
1073 if (!CR.contains(CI->getValue()))
1076 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1078 } else if (Pred == ICmpInst::ICMP_NE) {
1079 if (!CR.contains(CI->getValue()))
1082 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1086 // Handle more complex predicates.
1087 ConstantRange TrueValues =
1088 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1089 if (TrueValues.contains(CR))
1091 if (TrueValues.inverse().contains(CR))
1096 if (Result.isNotConstant()) {
1097 // If this is an equality comparison, we can try to fold it knowing that
1099 if (Pred == ICmpInst::ICMP_EQ) {
1100 // !C1 == C -> false iff C1 == C.
1101 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1102 Result.getNotConstant(), C, TD);
1103 if (Res->isNullValue())
1105 } else if (Pred == ICmpInst::ICMP_NE) {
1106 // !C1 != C -> true iff C1 == C.
1107 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1108 Result.getNotConstant(), C, TD);
1109 if (Res->isNullValue())
1118 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1119 BasicBlock *NewSucc) {
1120 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1123 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1124 if (PImpl) getCache(PImpl).eraseBlock(BB);