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/Analysis/ConstantFolding.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/Support/ConstantRange.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/ValueHandle.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/DenseSet.h"
29 #include "llvm/ADT/STLExtras.h"
34 char LazyValueInfo::ID = 0;
35 INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
36 "Lazy Value Information Analysis", false, true)
39 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
43 //===----------------------------------------------------------------------===//
45 //===----------------------------------------------------------------------===//
47 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
50 /// FIXME: This is basically just for bringup, this can be made a lot more rich
56 /// undefined - This Value has no known value yet.
59 /// constant - This Value has a specific constant value.
61 /// notconstant - This Value is known to not have the specified value.
64 /// constantrange - The Value falls within this range.
67 /// overdefined - This value is not known to be constant, and we know that
72 /// Val: This stores the current lattice value along with the Constant* for
73 /// the constant if this is a 'constant' or 'notconstant' value.
79 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
81 static LVILatticeVal get(Constant *C) {
83 if (!isa<UndefValue>(C))
87 static LVILatticeVal getNot(Constant *C) {
89 if (!isa<UndefValue>(C))
90 Res.markNotConstant(C);
93 static LVILatticeVal getRange(ConstantRange CR) {
95 Res.markConstantRange(CR);
99 bool isUndefined() const { return Tag == undefined; }
100 bool isConstant() const { return Tag == constant; }
101 bool isNotConstant() const { return Tag == notconstant; }
102 bool isConstantRange() const { return Tag == constantrange; }
103 bool isOverdefined() const { return Tag == overdefined; }
105 Constant *getConstant() const {
106 assert(isConstant() && "Cannot get the constant of a non-constant!");
110 Constant *getNotConstant() const {
111 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
115 ConstantRange getConstantRange() const {
116 assert(isConstantRange() &&
117 "Cannot get the constant-range of a non-constant-range!");
121 /// markOverdefined - Return true if this is a change in status.
122 bool markOverdefined() {
129 /// markConstant - Return true if this is a change in status.
130 bool markConstant(Constant *V) {
131 assert(V && "Marking constant with NULL");
132 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
133 return markConstantRange(ConstantRange(CI->getValue()));
134 if (isa<UndefValue>(V))
137 assert((!isConstant() || getConstant() == V) &&
138 "Marking constant with different value");
139 assert(isUndefined());
145 /// markNotConstant - Return true if this is a change in status.
146 bool markNotConstant(Constant *V) {
147 assert(V && "Marking constant with NULL");
148 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
149 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
150 if (isa<UndefValue>(V))
153 assert((!isConstant() || getConstant() != V) &&
154 "Marking constant !constant with same value");
155 assert((!isNotConstant() || getNotConstant() == V) &&
156 "Marking !constant with different value");
157 assert(isUndefined() || isConstant());
163 /// markConstantRange - Return true if this is a change in status.
164 bool markConstantRange(const ConstantRange NewR) {
165 if (isConstantRange()) {
166 if (NewR.isEmptySet())
167 return markOverdefined();
169 bool changed = Range == NewR;
174 assert(isUndefined());
175 if (NewR.isEmptySet())
176 return markOverdefined();
183 /// mergeIn - Merge the specified lattice value into this one, updating this
184 /// one and returning true if anything changed.
185 bool mergeIn(const LVILatticeVal &RHS) {
186 if (RHS.isUndefined() || isOverdefined()) return false;
187 if (RHS.isOverdefined()) return markOverdefined();
197 if (RHS.isConstant()) {
200 return markOverdefined();
203 if (RHS.isNotConstant()) {
205 return markOverdefined();
207 // Unless we can prove that the two Constants are different, we must
208 // move to overdefined.
209 // FIXME: use TargetData for smarter constant folding.
210 if (ConstantInt *Res = dyn_cast<ConstantInt>(
211 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
213 RHS.getNotConstant())))
215 return markNotConstant(RHS.getNotConstant());
217 return markOverdefined();
220 // RHS is a ConstantRange, LHS is a non-integer Constant.
222 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
223 // a function. The correct result is to pick up RHS.
225 return markOverdefined();
228 if (isNotConstant()) {
229 if (RHS.isConstant()) {
231 return markOverdefined();
233 // Unless we can prove that the two Constants are different, we must
234 // move to overdefined.
235 // FIXME: use TargetData for smarter constant folding.
236 if (ConstantInt *Res = dyn_cast<ConstantInt>(
237 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
243 return markOverdefined();
246 if (RHS.isNotConstant()) {
249 return markOverdefined();
252 return markOverdefined();
255 assert(isConstantRange() && "New LVILattice type?");
256 if (!RHS.isConstantRange())
257 return markOverdefined();
259 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
260 if (NewR.isFullSet())
261 return markOverdefined();
262 return markConstantRange(NewR);
266 } // end anonymous namespace.
269 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
270 if (Val.isUndefined())
271 return OS << "undefined";
272 if (Val.isOverdefined())
273 return OS << "overdefined";
275 if (Val.isNotConstant())
276 return OS << "notconstant<" << *Val.getNotConstant() << '>';
277 else if (Val.isConstantRange())
278 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
279 << Val.getConstantRange().getUpper() << '>';
280 return OS << "constant<" << *Val.getConstant() << '>';
284 //===----------------------------------------------------------------------===//
285 // LazyValueInfoCache Decl
286 //===----------------------------------------------------------------------===//
289 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
290 /// maintains information about queries across the clients' queries.
291 class LazyValueInfoCache {
293 /// ValueCacheEntryTy - This is all of the cached block information for
294 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
295 /// entries, allowing us to do a lookup with a binary search.
296 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
299 /// LVIValueHandle - A callback value handle update the cache when
300 /// values are erased.
301 struct LVIValueHandle : public CallbackVH {
302 LazyValueInfoCache *Parent;
304 LVIValueHandle(Value *V, LazyValueInfoCache *P)
305 : CallbackVH(V), Parent(P) { }
308 void allUsesReplacedWith(Value *V) {
313 /// ValueCache - This is all of the cached information for all values,
314 /// mapped from Value* to key information.
315 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
317 /// OverDefinedCache - This tracks, on a per-block basis, the set of
318 /// values that are over-defined at the end of that block. This is required
319 /// for cache updating.
320 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
322 LVILatticeVal &getCachedEntryForBlock(Value *Val, BasicBlock *BB);
323 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
324 LVILatticeVal getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T);
326 ValueCacheEntryTy &lookup(Value *V) {
327 return ValueCache[LVIValueHandle(V, this)];
330 LVILatticeVal setBlockValue(Value *V, BasicBlock *BB, LVILatticeVal L,
331 ValueCacheEntryTy &Cache) {
332 if (L.isOverdefined()) OverDefinedCache.insert(std::make_pair(BB, V));
333 return Cache[BB] = L;
337 /// getValueInBlock - This is the query interface to determine the lattice
338 /// value for the specified Value* at the end of the specified block.
339 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
341 /// getValueOnEdge - This is the query interface to determine the lattice
342 /// value for the specified Value* that is true on the specified edge.
343 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
345 /// threadEdge - This is the update interface to inform the cache that an
346 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
348 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
350 /// eraseBlock - This is part of the update interface to inform the cache
351 /// that a block has been deleted.
352 void eraseBlock(BasicBlock *BB);
354 /// clear - Empty the cache.
357 OverDefinedCache.clear();
360 } // end anonymous namespace
362 void LazyValueInfoCache::LVIValueHandle::deleted() {
363 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
364 I = Parent->OverDefinedCache.begin(),
365 E = Parent->OverDefinedCache.end();
367 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
369 if (tmp->second == getValPtr())
370 Parent->OverDefinedCache.erase(tmp);
373 // This erasure deallocates *this, so it MUST happen after we're done
374 // using any and all members of *this.
375 Parent->ValueCache.erase(*this);
378 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
379 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
380 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
381 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
383 if (tmp->first == BB)
384 OverDefinedCache.erase(tmp);
387 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
388 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
392 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
393 ValueCacheEntryTy &Cache = lookup(Val);
394 LVILatticeVal &BBLV = Cache[BB];
396 // If we've already computed this block's value, return it.
397 if (!BBLV.isUndefined()) {
398 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
402 // Otherwise, this is the first time we're seeing this block. Reset the
403 // lattice value to overdefined, so that cycles will terminate and be
404 // conservatively correct.
405 BBLV.markOverdefined();
407 Instruction *BBI = dyn_cast<Instruction>(Val);
408 if (BBI == 0 || BBI->getParent() != BB) {
409 LVILatticeVal Result; // Start Undefined.
411 // If this is a pointer, and there's a load from that pointer in this BB,
412 // then we know that the pointer can't be NULL.
413 bool NotNull = false;
414 if (Val->getType()->isPointerTy()) {
415 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
416 LoadInst *L = dyn_cast<LoadInst>(BI);
417 if (L && L->getPointerAddressSpace() == 0 &&
418 GetUnderlyingObject(L->getPointerOperand()) ==
419 GetUnderlyingObject(Val)) {
426 unsigned NumPreds = 0;
427 // Loop over all of our predecessors, merging what we know from them into
429 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
430 Result.mergeIn(getEdgeValue(Val, *PI, BB));
432 // If we hit overdefined, exit early. The BlockVals entry is already set
434 if (Result.isOverdefined()) {
435 DEBUG(dbgs() << " compute BB '" << BB->getName()
436 << "' - overdefined because of pred.\n");
437 // If we previously determined that this is a pointer that can't be null
438 // then return that rather than giving up entirely.
440 const PointerType *PTy = cast<PointerType>(Val->getType());
441 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
444 return setBlockValue(Val, BB, Result, Cache);
450 // If this is the entry block, we must be asking about an argument. The
451 // value is overdefined.
452 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
453 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
454 Result.markOverdefined();
455 return setBlockValue(Val, BB, Result, Cache);
458 // Return the merged value, which is more precise than 'overdefined'.
459 assert(!Result.isOverdefined());
460 return setBlockValue(Val, BB, Result, Cache);
463 // If this value is defined by an instruction in this block, we have to
464 // process it here somehow or return overdefined.
465 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
466 LVILatticeVal Result; // Start Undefined.
468 // Loop over all of our predecessors, merging what we know from them into
470 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
471 Value *PhiVal = PN->getIncomingValueForBlock(*PI);
472 Result.mergeIn(getValueOnEdge(PhiVal, *PI, BB));
474 // If we hit overdefined, exit early. The BlockVals entry is already set
476 if (Result.isOverdefined()) {
477 DEBUG(dbgs() << " compute BB '" << BB->getName()
478 << "' - overdefined because of pred.\n");
479 return setBlockValue(Val, BB, Result, Cache);
483 // Return the merged value, which is more precise than 'overdefined'.
484 assert(!Result.isOverdefined());
485 return setBlockValue(Val, BB, Result, Cache);
488 assert(Cache[BB].isOverdefined() &&
489 "Recursive query changed our cache?");
491 // We can only analyze the definitions of certain classes of instructions
492 // (integral binops and casts at the moment), so bail if this isn't one.
493 LVILatticeVal Result;
494 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
495 !BBI->getType()->isIntegerTy()) {
496 DEBUG(dbgs() << " compute BB '" << BB->getName()
497 << "' - overdefined because inst def found.\n");
498 Result.markOverdefined();
499 return setBlockValue(Val, BB, Result, Cache);
502 // FIXME: We're currently limited to binops with a constant RHS. This should
504 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
505 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
506 DEBUG(dbgs() << " compute BB '" << BB->getName()
507 << "' - overdefined because inst def found.\n");
509 Result.markOverdefined();
510 return setBlockValue(Val, BB, Result, Cache);
513 // Figure out the range of the LHS. If that fails, bail.
514 LVILatticeVal LHSVal = getValueInBlock(BBI->getOperand(0), BB);
515 if (!LHSVal.isConstantRange()) {
516 Result.markOverdefined();
517 return setBlockValue(Val, BB, Result, Cache);
520 ConstantInt *RHS = 0;
521 ConstantRange LHSRange = LHSVal.getConstantRange();
522 ConstantRange RHSRange(1);
523 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
524 if (isa<BinaryOperator>(BBI)) {
525 RHS = dyn_cast<ConstantInt>(BBI->getOperand(1));
527 Result.markOverdefined();
528 return setBlockValue(Val, BB, Result, Cache);
531 RHSRange = ConstantRange(RHS->getValue(), RHS->getValue()+1);
534 // NOTE: We're currently limited by the set of operations that ConstantRange
535 // can evaluate symbolically. Enhancing that set will allows us to analyze
537 switch (BBI->getOpcode()) {
538 case Instruction::Add:
539 Result.markConstantRange(LHSRange.add(RHSRange));
541 case Instruction::Sub:
542 Result.markConstantRange(LHSRange.sub(RHSRange));
544 case Instruction::Mul:
545 Result.markConstantRange(LHSRange.multiply(RHSRange));
547 case Instruction::UDiv:
548 Result.markConstantRange(LHSRange.udiv(RHSRange));
550 case Instruction::Shl:
551 Result.markConstantRange(LHSRange.shl(RHSRange));
553 case Instruction::LShr:
554 Result.markConstantRange(LHSRange.lshr(RHSRange));
556 case Instruction::Trunc:
557 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
559 case Instruction::SExt:
560 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
562 case Instruction::ZExt:
563 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
565 case Instruction::BitCast:
566 Result.markConstantRange(LHSRange);
568 case Instruction::And:
569 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
571 case Instruction::Or:
572 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
575 // Unhandled instructions are overdefined.
577 DEBUG(dbgs() << " compute BB '" << BB->getName()
578 << "' - overdefined because inst def found.\n");
579 Result.markOverdefined();
583 return setBlockValue(Val, BB, Result, Cache);
587 /// getEdgeValue - This method attempts to infer more complex
588 LVILatticeVal LazyValueInfoCache::getEdgeValue(Value *Val,
591 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
593 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
594 // If this is a conditional branch and only one successor goes to BBTo, then
595 // we maybe able to infer something from the condition.
596 if (BI->isConditional() &&
597 BI->getSuccessor(0) != BI->getSuccessor(1)) {
598 bool isTrueDest = BI->getSuccessor(0) == BBTo;
599 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
600 "BBTo isn't a successor of BBFrom");
602 // If V is the condition of the branch itself, then we know exactly what
604 if (BI->getCondition() == Val)
605 return LVILatticeVal::get(ConstantInt::get(
606 Type::getInt1Ty(Val->getContext()), isTrueDest));
608 // If the condition of the branch is an equality comparison, we may be
609 // able to infer the value.
610 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
611 if (ICI && ICI->getOperand(0) == Val &&
612 isa<Constant>(ICI->getOperand(1))) {
613 if (ICI->isEquality()) {
614 // We know that V has the RHS constant if this is a true SETEQ or
616 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
617 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
618 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
621 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
622 // Calculate the range of values that would satisfy the comparison.
623 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
624 ConstantRange TrueValues =
625 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
627 // If we're interested in the false dest, invert the condition.
628 if (!isTrueDest) TrueValues = TrueValues.inverse();
630 // Figure out the possible values of the query BEFORE this branch.
631 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
632 if (!InBlock.isConstantRange())
633 return LVILatticeVal::getRange(TrueValues);
635 // Find all potential values that satisfy both the input and output
637 ConstantRange PossibleValues =
638 TrueValues.intersectWith(InBlock.getConstantRange());
640 return LVILatticeVal::getRange(PossibleValues);
646 // If the edge was formed by a switch on the value, then we may know exactly
648 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
649 if (SI->getCondition() == Val) {
650 // We don't know anything in the default case.
651 if (SI->getDefaultDest() == BBTo) {
652 LVILatticeVal Result;
653 Result.markOverdefined();
657 // We only know something if there is exactly one value that goes from
659 unsigned NumEdges = 0;
660 ConstantInt *EdgeVal = 0;
661 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
662 if (SI->getSuccessor(i) != BBTo) continue;
663 if (NumEdges++) break;
664 EdgeVal = SI->getCaseValue(i);
666 assert(EdgeVal && "Missing successor?");
668 return LVILatticeVal::get(EdgeVal);
672 // Otherwise see if the value is known in the block.
673 return getBlockValue(Val, BBFrom);
676 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
677 // If already a constant, there is nothing to compute.
678 if (Constant *VC = dyn_cast<Constant>(V))
679 return LVILatticeVal::get(VC);
681 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
682 << BB->getName() << "'\n");
684 LVILatticeVal Result = getBlockValue(V, BB);
686 DEBUG(dbgs() << " Result = " << Result << "\n");
690 LVILatticeVal LazyValueInfoCache::
691 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
692 // If already a constant, there is nothing to compute.
693 if (Constant *VC = dyn_cast<Constant>(V))
694 return LVILatticeVal::get(VC);
696 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
697 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
699 LVILatticeVal Result = getEdgeValue(V, FromBB, ToBB);
701 DEBUG(dbgs() << " Result = " << Result << "\n");
706 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
707 BasicBlock *NewSucc) {
708 // When an edge in the graph has been threaded, values that we could not
709 // determine a value for before (i.e. were marked overdefined) may be possible
710 // to solve now. We do NOT try to proactively update these values. Instead,
711 // we clear their entries from the cache, and allow lazy updating to recompute
714 // The updating process is fairly simple: we need to dropped cached info
715 // for all values that were marked overdefined in OldSucc, and for those same
716 // values in any successor of OldSucc (except NewSucc) in which they were
717 // also marked overdefined.
718 std::vector<BasicBlock*> worklist;
719 worklist.push_back(OldSucc);
721 DenseSet<Value*> ClearSet;
722 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
723 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
724 if (I->first == OldSucc)
725 ClearSet.insert(I->second);
728 // Use a worklist to perform a depth-first search of OldSucc's successors.
729 // NOTE: We do not need a visited list since any blocks we have already
730 // visited will have had their overdefined markers cleared already, and we
731 // thus won't loop to their successors.
732 while (!worklist.empty()) {
733 BasicBlock *ToUpdate = worklist.back();
736 // Skip blocks only accessible through NewSucc.
737 if (ToUpdate == NewSucc) continue;
739 bool changed = false;
740 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
742 // If a value was marked overdefined in OldSucc, and is here too...
743 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
744 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
745 if (OI == OverDefinedCache.end()) continue;
747 // Remove it from the caches.
748 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
749 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
751 assert(CI != Entry.end() && "Couldn't find entry to update?");
753 OverDefinedCache.erase(OI);
755 // If we removed anything, then we potentially need to update
756 // blocks successors too.
760 if (!changed) continue;
762 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
766 //===----------------------------------------------------------------------===//
767 // LazyValueInfo Impl
768 //===----------------------------------------------------------------------===//
770 /// getCache - This lazily constructs the LazyValueInfoCache.
771 static LazyValueInfoCache &getCache(void *&PImpl) {
773 PImpl = new LazyValueInfoCache();
774 return *static_cast<LazyValueInfoCache*>(PImpl);
777 bool LazyValueInfo::runOnFunction(Function &F) {
779 getCache(PImpl).clear();
781 TD = getAnalysisIfAvailable<TargetData>();
786 void LazyValueInfo::releaseMemory() {
787 // If the cache was allocated, free it.
789 delete &getCache(PImpl);
794 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
795 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
797 if (Result.isConstant())
798 return Result.getConstant();
799 if (Result.isConstantRange()) {
800 ConstantRange CR = Result.getConstantRange();
801 if (const APInt *SingleVal = CR.getSingleElement())
802 return ConstantInt::get(V->getContext(), *SingleVal);
807 /// getConstantOnEdge - Determine whether the specified value is known to be a
808 /// constant on the specified edge. Return null if not.
809 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
811 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
813 if (Result.isConstant())
814 return Result.getConstant();
815 if (Result.isConstantRange()) {
816 ConstantRange CR = Result.getConstantRange();
817 if (const APInt *SingleVal = CR.getSingleElement())
818 return ConstantInt::get(V->getContext(), *SingleVal);
823 /// getPredicateOnEdge - Determine whether the specified value comparison
824 /// with a constant is known to be true or false on the specified CFG edge.
825 /// Pred is a CmpInst predicate.
826 LazyValueInfo::Tristate
827 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
828 BasicBlock *FromBB, BasicBlock *ToBB) {
829 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
831 // If we know the value is a constant, evaluate the conditional.
833 if (Result.isConstant()) {
834 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
835 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
836 return ResCI->isZero() ? False : True;
840 if (Result.isConstantRange()) {
841 ConstantInt *CI = dyn_cast<ConstantInt>(C);
842 if (!CI) return Unknown;
844 ConstantRange CR = Result.getConstantRange();
845 if (Pred == ICmpInst::ICMP_EQ) {
846 if (!CR.contains(CI->getValue()))
849 if (CR.isSingleElement() && CR.contains(CI->getValue()))
851 } else if (Pred == ICmpInst::ICMP_NE) {
852 if (!CR.contains(CI->getValue()))
855 if (CR.isSingleElement() && CR.contains(CI->getValue()))
859 // Handle more complex predicates.
860 ConstantRange TrueValues =
861 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
862 if (TrueValues.contains(CR))
864 if (TrueValues.inverse().contains(CR))
869 if (Result.isNotConstant()) {
870 // If this is an equality comparison, we can try to fold it knowing that
872 if (Pred == ICmpInst::ICMP_EQ) {
873 // !C1 == C -> false iff C1 == C.
874 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
875 Result.getNotConstant(), C, TD);
876 if (Res->isNullValue())
878 } else if (Pred == ICmpInst::ICMP_NE) {
879 // !C1 != C -> true iff C1 == C.
880 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
881 Result.getNotConstant(), C, TD);
882 if (Res->isNullValue())
891 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
892 BasicBlock *NewSucc) {
893 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
896 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
897 if (PImpl) getCache(PImpl).eraseBlock(BB);