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/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Support/CFG.h"
22 #include "llvm/Support/ConstantRange.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Support/ValueHandle.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/STLExtras.h"
33 char LazyValueInfo::ID = 0;
34 INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
35 "Lazy Value Information Analysis", false, true)
38 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
42 //===----------------------------------------------------------------------===//
44 //===----------------------------------------------------------------------===//
46 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
49 /// FIXME: This is basically just for bringup, this can be made a lot more rich
55 /// undefined - This Value has no known value yet.
58 /// constant - This Value has a specific constant value.
60 /// notconstant - This Value is known to not have the specified value.
63 /// constantrange - The Value falls within this range.
66 /// overdefined - This value is not known to be constant, and we know that
71 /// Val: This stores the current lattice value along with the Constant* for
72 /// the constant if this is a 'constant' or 'notconstant' value.
78 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
80 static LVILatticeVal get(Constant *C) {
82 if (!isa<UndefValue>(C))
86 static LVILatticeVal getNot(Constant *C) {
88 if (!isa<UndefValue>(C))
89 Res.markNotConstant(C);
92 static LVILatticeVal getRange(ConstantRange CR) {
94 Res.markConstantRange(CR);
98 bool isUndefined() const { return Tag == undefined; }
99 bool isConstant() const { return Tag == constant; }
100 bool isNotConstant() const { return Tag == notconstant; }
101 bool isConstantRange() const { return Tag == constantrange; }
102 bool isOverdefined() const { return Tag == overdefined; }
104 Constant *getConstant() const {
105 assert(isConstant() && "Cannot get the constant of a non-constant!");
109 Constant *getNotConstant() const {
110 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
114 ConstantRange getConstantRange() const {
115 assert(isConstantRange() &&
116 "Cannot get the constant-range of a non-constant-range!");
120 /// markOverdefined - Return true if this is a change in status.
121 bool markOverdefined() {
128 /// markConstant - Return true if this is a change in status.
129 bool markConstant(Constant *V) {
130 assert(V && "Marking constant with NULL");
131 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
132 return markConstantRange(ConstantRange(CI->getValue()));
133 if (isa<UndefValue>(V))
136 assert((!isConstant() || getConstant() == V) &&
137 "Marking constant with different value");
138 assert(isUndefined());
144 /// markNotConstant - Return true if this is a change in status.
145 bool markNotConstant(Constant *V) {
146 assert(V && "Marking constant with NULL");
147 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
148 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
149 if (isa<UndefValue>(V))
152 assert((!isConstant() || getConstant() != V) &&
153 "Marking constant !constant with same value");
154 assert((!isNotConstant() || getNotConstant() == V) &&
155 "Marking !constant with different value");
156 assert(isUndefined() || isConstant());
162 /// markConstantRange - Return true if this is a change in status.
163 bool markConstantRange(const ConstantRange NewR) {
164 if (isConstantRange()) {
165 if (NewR.isEmptySet())
166 return markOverdefined();
168 bool changed = Range == NewR;
173 assert(isUndefined());
174 if (NewR.isEmptySet())
175 return markOverdefined();
182 /// mergeIn - Merge the specified lattice value into this one, updating this
183 /// one and returning true if anything changed.
184 bool mergeIn(const LVILatticeVal &RHS) {
185 if (RHS.isUndefined() || isOverdefined()) return false;
186 if (RHS.isOverdefined()) return markOverdefined();
196 if (RHS.isConstant()) {
199 return markOverdefined();
202 if (RHS.isNotConstant()) {
204 return markOverdefined();
206 // Unless we can prove that the two Constants are different, we must
207 // move to overdefined.
208 // FIXME: use TargetData for smarter constant folding.
209 if (ConstantInt *Res = dyn_cast<ConstantInt>(
210 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
212 RHS.getNotConstant())))
214 return markNotConstant(RHS.getNotConstant());
216 return markOverdefined();
219 // RHS is a ConstantRange, LHS is a non-integer Constant.
221 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
222 // a function. The correct result is to pick up RHS.
224 return markOverdefined();
227 if (isNotConstant()) {
228 if (RHS.isConstant()) {
230 return markOverdefined();
232 // Unless we can prove that the two Constants are different, we must
233 // move to overdefined.
234 // FIXME: use TargetData for smarter constant folding.
235 if (ConstantInt *Res = dyn_cast<ConstantInt>(
236 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
242 return markOverdefined();
245 if (RHS.isNotConstant()) {
248 return markOverdefined();
251 return markOverdefined();
254 assert(isConstantRange() && "New LVILattice type?");
255 if (!RHS.isConstantRange())
256 return markOverdefined();
258 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
259 if (NewR.isFullSet())
260 return markOverdefined();
261 return markConstantRange(NewR);
265 } // end anonymous namespace.
268 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
269 if (Val.isUndefined())
270 return OS << "undefined";
271 if (Val.isOverdefined())
272 return OS << "overdefined";
274 if (Val.isNotConstant())
275 return OS << "notconstant<" << *Val.getNotConstant() << '>';
276 else if (Val.isConstantRange())
277 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
278 << Val.getConstantRange().getUpper() << '>';
279 return OS << "constant<" << *Val.getConstant() << '>';
283 //===----------------------------------------------------------------------===//
284 // LazyValueInfoCache Decl
285 //===----------------------------------------------------------------------===//
288 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
289 /// maintains information about queries across the clients' queries.
290 class LazyValueInfoCache {
292 /// ValueCacheEntryTy - This is all of the cached block information for
293 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
294 /// entries, allowing us to do a lookup with a binary search.
295 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
298 /// LVIValueHandle - A callback value handle update the cache when
299 /// values are erased.
300 struct LVIValueHandle : public CallbackVH {
301 LazyValueInfoCache *Parent;
303 LVIValueHandle(Value *V, LazyValueInfoCache *P)
304 : CallbackVH(V), Parent(P) { }
307 void allUsesReplacedWith(Value *V) {
312 /// ValueCache - This is all of the cached information for all values,
313 /// mapped from Value* to key information.
314 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
316 /// OverDefinedCache - This tracks, on a per-block basis, the set of
317 /// values that are over-defined at the end of that block. This is required
318 /// for cache updating.
319 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
321 LVILatticeVal &getCachedEntryForBlock(Value *Val, BasicBlock *BB);
322 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
323 LVILatticeVal getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T);
325 ValueCacheEntryTy &lookup(Value *V) {
326 return ValueCache[LVIValueHandle(V, this)];
329 LVILatticeVal setBlockValue(Value *V, BasicBlock *BB, LVILatticeVal L,
330 ValueCacheEntryTy &Cache) {
331 if (L.isOverdefined()) OverDefinedCache.insert(std::make_pair(BB, V));
332 return Cache[BB] = L;
336 /// getValueInBlock - This is the query interface to determine the lattice
337 /// value for the specified Value* at the end of the specified block.
338 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
340 /// getValueOnEdge - This is the query interface to determine the lattice
341 /// value for the specified Value* that is true on the specified edge.
342 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
344 /// threadEdge - This is the update interface to inform the cache that an
345 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
347 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
349 /// eraseBlock - This is part of the update interface to inform the cache
350 /// that a block has been deleted.
351 void eraseBlock(BasicBlock *BB);
353 /// clear - Empty the cache.
356 OverDefinedCache.clear();
359 } // end anonymous namespace
361 void LazyValueInfoCache::LVIValueHandle::deleted() {
362 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
363 I = Parent->OverDefinedCache.begin(),
364 E = Parent->OverDefinedCache.end();
366 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
368 if (tmp->second == getValPtr())
369 Parent->OverDefinedCache.erase(tmp);
372 // This erasure deallocates *this, so it MUST happen after we're done
373 // using any and all members of *this.
374 Parent->ValueCache.erase(*this);
377 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
378 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
379 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
380 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
382 if (tmp->first == BB)
383 OverDefinedCache.erase(tmp);
386 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
387 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
391 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
392 ValueCacheEntryTy &Cache = lookup(Val);
393 LVILatticeVal &BBLV = Cache[BB];
395 // If we've already computed this block's value, return it.
396 if (!BBLV.isUndefined()) {
397 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
401 // Otherwise, this is the first time we're seeing this block. Reset the
402 // lattice value to overdefined, so that cycles will terminate and be
403 // conservatively correct.
404 BBLV.markOverdefined();
406 Instruction *BBI = dyn_cast<Instruction>(Val);
407 if (BBI == 0 || BBI->getParent() != BB) {
408 LVILatticeVal Result; // Start Undefined.
410 // If this is a pointer, and there's a load from that pointer in this BB,
411 // then we know that the pointer can't be NULL.
412 bool NotNull = false;
413 if (Val->getType()->isPointerTy()) {
414 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
415 LoadInst *L = dyn_cast<LoadInst>(BI);
416 if (L && L->getPointerAddressSpace() == 0 &&
417 L->getPointerOperand()->getUnderlyingObject() ==
418 Val->getUnderlyingObject()) {
425 unsigned NumPreds = 0;
426 // Loop over all of our predecessors, merging what we know from them into
428 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
429 Result.mergeIn(getEdgeValue(Val, *PI, BB));
431 // If we hit overdefined, exit early. The BlockVals entry is already set
433 if (Result.isOverdefined()) {
434 DEBUG(dbgs() << " compute BB '" << BB->getName()
435 << "' - overdefined because of pred.\n");
436 // If we previously determined that this is a pointer that can't be null
437 // then return that rather than giving up entirely.
439 const PointerType *PTy = cast<PointerType>(Val->getType());
440 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
443 return setBlockValue(Val, BB, Result, Cache);
449 // If this is the entry block, we must be asking about an argument. The
450 // value is overdefined.
451 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
452 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
453 Result.markOverdefined();
454 return setBlockValue(Val, BB, Result, Cache);
457 // Return the merged value, which is more precise than 'overdefined'.
458 assert(!Result.isOverdefined());
459 return setBlockValue(Val, BB, Result, Cache);
462 // If this value is defined by an instruction in this block, we have to
463 // process it here somehow or return overdefined.
464 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
465 LVILatticeVal Result; // Start Undefined.
467 // Loop over all of our predecessors, merging what we know from them into
469 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
470 Value *PhiVal = PN->getIncomingValueForBlock(*PI);
471 Result.mergeIn(getValueOnEdge(PhiVal, *PI, BB));
473 // If we hit overdefined, exit early. The BlockVals entry is already set
475 if (Result.isOverdefined()) {
476 DEBUG(dbgs() << " compute BB '" << BB->getName()
477 << "' - overdefined because of pred.\n");
478 return setBlockValue(Val, BB, Result, Cache);
482 // Return the merged value, which is more precise than 'overdefined'.
483 assert(!Result.isOverdefined());
484 return setBlockValue(Val, BB, Result, Cache);
487 assert(Cache[BB].isOverdefined() &&
488 "Recursive query changed our cache?");
490 // We can only analyze the definitions of certain classes of instructions
491 // (integral binops and casts at the moment), so bail if this isn't one.
492 LVILatticeVal Result;
493 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
494 !BBI->getType()->isIntegerTy()) {
495 DEBUG(dbgs() << " compute BB '" << BB->getName()
496 << "' - overdefined because inst def found.\n");
497 Result.markOverdefined();
498 return setBlockValue(Val, BB, Result, Cache);
501 // FIXME: We're currently limited to binops with a constant RHS. This should
503 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
504 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
505 DEBUG(dbgs() << " compute BB '" << BB->getName()
506 << "' - overdefined because inst def found.\n");
508 Result.markOverdefined();
509 return setBlockValue(Val, BB, Result, Cache);
512 // Figure out the range of the LHS. If that fails, bail.
513 LVILatticeVal LHSVal = getValueInBlock(BBI->getOperand(0), BB);
514 if (!LHSVal.isConstantRange()) {
515 Result.markOverdefined();
516 return setBlockValue(Val, BB, Result, Cache);
519 ConstantInt *RHS = 0;
520 ConstantRange LHSRange = LHSVal.getConstantRange();
521 ConstantRange RHSRange(1);
522 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
523 if (isa<BinaryOperator>(BBI)) {
524 RHS = dyn_cast<ConstantInt>(BBI->getOperand(1));
526 Result.markOverdefined();
527 return setBlockValue(Val, BB, Result, Cache);
530 RHSRange = ConstantRange(RHS->getValue(), RHS->getValue()+1);
533 // NOTE: We're currently limited by the set of operations that ConstantRange
534 // can evaluate symbolically. Enhancing that set will allows us to analyze
536 switch (BBI->getOpcode()) {
537 case Instruction::Add:
538 Result.markConstantRange(LHSRange.add(RHSRange));
540 case Instruction::Sub:
541 Result.markConstantRange(LHSRange.sub(RHSRange));
543 case Instruction::Mul:
544 Result.markConstantRange(LHSRange.multiply(RHSRange));
546 case Instruction::UDiv:
547 Result.markConstantRange(LHSRange.udiv(RHSRange));
549 case Instruction::Shl:
550 Result.markConstantRange(LHSRange.shl(RHSRange));
552 case Instruction::LShr:
553 Result.markConstantRange(LHSRange.lshr(RHSRange));
555 case Instruction::Trunc:
556 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
558 case Instruction::SExt:
559 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
561 case Instruction::ZExt:
562 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
564 case Instruction::BitCast:
565 Result.markConstantRange(LHSRange);
567 case Instruction::And:
568 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
570 case Instruction::Or:
571 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
574 // Unhandled instructions are overdefined.
576 DEBUG(dbgs() << " compute BB '" << BB->getName()
577 << "' - overdefined because inst def found.\n");
578 Result.markOverdefined();
582 return setBlockValue(Val, BB, Result, Cache);
586 /// getEdgeValue - This method attempts to infer more complex
587 LVILatticeVal LazyValueInfoCache::getEdgeValue(Value *Val,
590 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
592 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
593 // If this is a conditional branch and only one successor goes to BBTo, then
594 // we maybe able to infer something from the condition.
595 if (BI->isConditional() &&
596 BI->getSuccessor(0) != BI->getSuccessor(1)) {
597 bool isTrueDest = BI->getSuccessor(0) == BBTo;
598 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
599 "BBTo isn't a successor of BBFrom");
601 // If V is the condition of the branch itself, then we know exactly what
603 if (BI->getCondition() == Val)
604 return LVILatticeVal::get(ConstantInt::get(
605 Type::getInt1Ty(Val->getContext()), isTrueDest));
607 // If the condition of the branch is an equality comparison, we may be
608 // able to infer the value.
609 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
610 if (ICI && ICI->getOperand(0) == Val &&
611 isa<Constant>(ICI->getOperand(1))) {
612 if (ICI->isEquality()) {
613 // We know that V has the RHS constant if this is a true SETEQ or
615 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
616 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
617 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
620 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
621 // Calculate the range of values that would satisfy the comparison.
622 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
623 ConstantRange TrueValues =
624 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
626 // If we're interested in the false dest, invert the condition.
627 if (!isTrueDest) TrueValues = TrueValues.inverse();
629 // Figure out the possible values of the query BEFORE this branch.
630 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
631 if (!InBlock.isConstantRange())
632 return LVILatticeVal::getRange(TrueValues);
634 // Find all potential values that satisfy both the input and output
636 ConstantRange PossibleValues =
637 TrueValues.intersectWith(InBlock.getConstantRange());
639 return LVILatticeVal::getRange(PossibleValues);
645 // If the edge was formed by a switch on the value, then we may know exactly
647 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
648 if (SI->getCondition() == Val) {
649 // We don't know anything in the default case.
650 if (SI->getDefaultDest() == BBTo) {
651 LVILatticeVal Result;
652 Result.markOverdefined();
656 // We only know something if there is exactly one value that goes from
658 unsigned NumEdges = 0;
659 ConstantInt *EdgeVal = 0;
660 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
661 if (SI->getSuccessor(i) != BBTo) continue;
662 if (NumEdges++) break;
663 EdgeVal = SI->getCaseValue(i);
665 assert(EdgeVal && "Missing successor?");
667 return LVILatticeVal::get(EdgeVal);
671 // Otherwise see if the value is known in the block.
672 return getBlockValue(Val, BBFrom);
675 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
676 // If already a constant, there is nothing to compute.
677 if (Constant *VC = dyn_cast<Constant>(V))
678 return LVILatticeVal::get(VC);
680 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
681 << BB->getName() << "'\n");
683 LVILatticeVal Result = getBlockValue(V, BB);
685 DEBUG(dbgs() << " Result = " << Result << "\n");
689 LVILatticeVal LazyValueInfoCache::
690 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
691 // If already a constant, there is nothing to compute.
692 if (Constant *VC = dyn_cast<Constant>(V))
693 return LVILatticeVal::get(VC);
695 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
696 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
698 LVILatticeVal Result = getEdgeValue(V, FromBB, ToBB);
700 DEBUG(dbgs() << " Result = " << Result << "\n");
705 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
706 BasicBlock *NewSucc) {
707 // When an edge in the graph has been threaded, values that we could not
708 // determine a value for before (i.e. were marked overdefined) may be possible
709 // to solve now. We do NOT try to proactively update these values. Instead,
710 // we clear their entries from the cache, and allow lazy updating to recompute
713 // The updating process is fairly simple: we need to dropped cached info
714 // for all values that were marked overdefined in OldSucc, and for those same
715 // values in any successor of OldSucc (except NewSucc) in which they were
716 // also marked overdefined.
717 std::vector<BasicBlock*> worklist;
718 worklist.push_back(OldSucc);
720 DenseSet<Value*> ClearSet;
721 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
722 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
723 if (I->first == OldSucc)
724 ClearSet.insert(I->second);
727 // Use a worklist to perform a depth-first search of OldSucc's successors.
728 // NOTE: We do not need a visited list since any blocks we have already
729 // visited will have had their overdefined markers cleared already, and we
730 // thus won't loop to their successors.
731 while (!worklist.empty()) {
732 BasicBlock *ToUpdate = worklist.back();
735 // Skip blocks only accessible through NewSucc.
736 if (ToUpdate == NewSucc) continue;
738 bool changed = false;
739 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
741 // If a value was marked overdefined in OldSucc, and is here too...
742 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
743 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
744 if (OI == OverDefinedCache.end()) continue;
746 // Remove it from the caches.
747 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
748 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
750 assert(CI != Entry.end() && "Couldn't find entry to update?");
752 OverDefinedCache.erase(OI);
754 // If we removed anything, then we potentially need to update
755 // blocks successors too.
759 if (!changed) continue;
761 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
765 //===----------------------------------------------------------------------===//
766 // LazyValueInfo Impl
767 //===----------------------------------------------------------------------===//
769 /// getCache - This lazily constructs the LazyValueInfoCache.
770 static LazyValueInfoCache &getCache(void *&PImpl) {
772 PImpl = new LazyValueInfoCache();
773 return *static_cast<LazyValueInfoCache*>(PImpl);
776 bool LazyValueInfo::runOnFunction(Function &F) {
778 getCache(PImpl).clear();
780 TD = getAnalysisIfAvailable<TargetData>();
785 void LazyValueInfo::releaseMemory() {
786 // If the cache was allocated, free it.
788 delete &getCache(PImpl);
793 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
794 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
796 if (Result.isConstant())
797 return Result.getConstant();
798 if (Result.isConstantRange()) {
799 ConstantRange CR = Result.getConstantRange();
800 if (const APInt *SingleVal = CR.getSingleElement())
801 return ConstantInt::get(V->getContext(), *SingleVal);
806 /// getConstantOnEdge - Determine whether the specified value is known to be a
807 /// constant on the specified edge. Return null if not.
808 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
810 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
812 if (Result.isConstant())
813 return Result.getConstant();
814 if (Result.isConstantRange()) {
815 ConstantRange CR = Result.getConstantRange();
816 if (const APInt *SingleVal = CR.getSingleElement())
817 return ConstantInt::get(V->getContext(), *SingleVal);
822 /// getPredicateOnEdge - Determine whether the specified value comparison
823 /// with a constant is known to be true or false on the specified CFG edge.
824 /// Pred is a CmpInst predicate.
825 LazyValueInfo::Tristate
826 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
827 BasicBlock *FromBB, BasicBlock *ToBB) {
828 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
830 // If we know the value is a constant, evaluate the conditional.
832 if (Result.isConstant()) {
833 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
834 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
835 return ResCI->isZero() ? False : True;
839 if (Result.isConstantRange()) {
840 ConstantInt *CI = dyn_cast<ConstantInt>(C);
841 if (!CI) return Unknown;
843 ConstantRange CR = Result.getConstantRange();
844 if (Pred == ICmpInst::ICMP_EQ) {
845 if (!CR.contains(CI->getValue()))
848 if (CR.isSingleElement() && CR.contains(CI->getValue()))
850 } else if (Pred == ICmpInst::ICMP_NE) {
851 if (!CR.contains(CI->getValue()))
854 if (CR.isSingleElement() && CR.contains(CI->getValue()))
858 // Handle more complex predicates.
859 ConstantRange TrueValues =
860 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
861 if (TrueValues.contains(CR))
863 if (TrueValues.inverse().contains(CR))
868 if (Result.isNotConstant()) {
869 // If this is an equality comparison, we can try to fold it knowing that
871 if (Pred == ICmpInst::ICMP_EQ) {
872 // !C1 == C -> false iff C1 == C.
873 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
874 Result.getNotConstant(), C, TD);
875 if (Res->isNullValue())
877 } else if (Pred == ICmpInst::ICMP_NE) {
878 // !C1 != C -> true iff C1 == C.
879 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
880 Result.getNotConstant(), C, TD);
881 if (Res->isNullValue())
890 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
891 BasicBlock *NewSucc) {
892 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
895 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
896 if (PImpl) getCache(PImpl).eraseBlock(BB);