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 LLVM Value has no known value yet.
58 /// constant - This LLVM Value has a specific constant value.
60 /// notconstant - This LLVM value is known to not have the specified value.
66 /// overdefined - This instruction is not known to be constant, and we know
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 (ConstantInt *CI = dyn_cast<ConstantInt>(C))
83 Res.markConstantRange(ConstantRange(CI->getValue(), CI->getValue()+1));
84 else if (!isa<UndefValue>(C))
88 static LVILatticeVal getNot(Constant *C) {
90 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
91 Res.markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
93 Res.markNotConstant(C);
96 static LVILatticeVal getRange(ConstantRange CR) {
98 Res.markConstantRange(CR);
102 bool isUndefined() const { return Tag == undefined; }
103 bool isConstant() const { return Tag == constant; }
104 bool isNotConstant() const { return Tag == notconstant; }
105 bool isConstantRange() const { return Tag == constantrange; }
106 bool isOverdefined() const { return Tag == overdefined; }
108 Constant *getConstant() const {
109 assert(isConstant() && "Cannot get the constant of a non-constant!");
113 Constant *getNotConstant() const {
114 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
118 ConstantRange getConstantRange() const {
119 assert(isConstantRange() &&
120 "Cannot get the constant-range of a non-constant-range!");
124 /// markOverdefined - Return true if this is a change in status.
125 bool markOverdefined() {
132 /// markConstant - Return true if this is a change in status.
133 bool markConstant(Constant *V) {
135 assert(getConstant() == V && "Marking constant with different value");
139 assert(isUndefined());
141 assert(V && "Marking constant with NULL");
146 /// markNotConstant - Return true if this is a change in status.
147 bool markNotConstant(Constant *V) {
148 if (isNotConstant()) {
149 assert(getNotConstant() == V && "Marking !constant with different value");
154 assert(getConstant() != V && "Marking not constant with different value");
156 assert(isUndefined());
159 assert(V && "Marking constant with NULL");
164 /// markConstantRange - Return true if this is a change in status.
165 bool markConstantRange(const ConstantRange NewR) {
166 if (isConstantRange()) {
167 if (NewR.isEmptySet())
168 return markOverdefined();
170 bool changed = Range == NewR;
175 assert(isUndefined());
176 if (NewR.isEmptySet())
177 return markOverdefined();
184 /// mergeIn - Merge the specified lattice value into this one, updating this
185 /// one and returning true if anything changed.
186 bool mergeIn(const LVILatticeVal &RHS) {
187 if (RHS.isUndefined() || isOverdefined()) return false;
188 if (RHS.isOverdefined()) return markOverdefined();
190 if (RHS.isNotConstant()) {
191 if (isNotConstant()) {
192 if (getNotConstant() != RHS.getNotConstant() ||
193 isa<ConstantExpr>(getNotConstant()) ||
194 isa<ConstantExpr>(RHS.getNotConstant()))
195 return markOverdefined();
197 } else if (isConstant()) {
198 if (getConstant() == RHS.getNotConstant() ||
199 isa<ConstantExpr>(RHS.getNotConstant()) ||
200 isa<ConstantExpr>(getConstant()))
201 return markOverdefined();
202 return markNotConstant(RHS.getNotConstant());
203 } else if (isConstantRange()) {
204 // FIXME: This could be made more precise.
205 return markOverdefined();
208 assert(isUndefined() && "Unexpected lattice");
209 return markNotConstant(RHS.getNotConstant());
212 if (RHS.isConstantRange()) {
213 if (isConstantRange()) {
214 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
215 if (NewR.isFullSet())
216 return markOverdefined();
218 return markConstantRange(NewR);
219 } else if (!isUndefined()) {
220 return markOverdefined();
223 assert(isUndefined() && "Unexpected lattice");
224 return markConstantRange(RHS.getConstantRange());
227 // RHS must be a constant, we must be constantrange,
228 // undef, constant, or notconstant.
229 if (isConstantRange()) {
230 // FIXME: This could be made more precise.
231 return markOverdefined();
235 return markConstant(RHS.getConstant());
238 if (getConstant() != RHS.getConstant())
239 return markOverdefined();
243 // If we are known "!=4" and RHS is "==5", stay at "!=4".
244 if (getNotConstant() == RHS.getConstant() ||
245 isa<ConstantExpr>(getNotConstant()) ||
246 isa<ConstantExpr>(RHS.getConstant()))
247 return markOverdefined();
253 } // end anonymous namespace.
256 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
257 if (Val.isUndefined())
258 return OS << "undefined";
259 if (Val.isOverdefined())
260 return OS << "overdefined";
262 if (Val.isNotConstant())
263 return OS << "notconstant<" << *Val.getNotConstant() << '>';
264 else if (Val.isConstantRange())
265 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
266 << Val.getConstantRange().getUpper() << '>';
267 return OS << "constant<" << *Val.getConstant() << '>';
271 //===----------------------------------------------------------------------===//
272 // LazyValueInfoCache Decl
273 //===----------------------------------------------------------------------===//
276 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
277 /// maintains information about queries across the clients' queries.
278 class LazyValueInfoCache {
280 /// ValueCacheEntryTy - This is all of the cached block information for
281 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
282 /// entries, allowing us to do a lookup with a binary search.
283 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
286 /// LVIValueHandle - A callback value handle update the cache when
287 /// values are erased.
288 struct LVIValueHandle : public CallbackVH {
289 LazyValueInfoCache *Parent;
291 LVIValueHandle(Value *V, LazyValueInfoCache *P)
292 : CallbackVH(V), Parent(P) { }
295 void allUsesReplacedWith(Value* V) {
300 /// ValueCache - This is all of the cached information for all values,
301 /// mapped from Value* to key information.
302 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
304 /// OverDefinedCache - This tracks, on a per-block basis, the set of
305 /// values that are over-defined at the end of that block. This is required
306 /// for cache updating.
307 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
309 LVILatticeVal &getCachedEntryForBlock(Value *Val, BasicBlock *BB);
310 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
311 LVILatticeVal getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T);
313 ValueCacheEntryTy &lookup(Value *V) {
314 return ValueCache[LVIValueHandle(V, this)];
317 LVILatticeVal setBlockValue(Value *V, BasicBlock *BB, LVILatticeVal L,
318 ValueCacheEntryTy &Cache) {
319 if (L.isOverdefined()) OverDefinedCache.insert(std::make_pair(BB, V));
320 return Cache[BB] = L;
325 /// getValueInBlock - This is the query interface to determine the lattice
326 /// value for the specified Value* at the end of the specified block.
327 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
329 /// getValueOnEdge - This is the query interface to determine the lattice
330 /// value for the specified Value* that is true on the specified edge.
331 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
333 /// threadEdge - This is the update interface to inform the cache that an
334 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
336 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
338 /// eraseBlock - This is part of the update interface to inform the cache
339 /// that a block has been deleted.
340 void eraseBlock(BasicBlock *BB);
342 /// clear - Empty the cache.
345 OverDefinedCache.clear();
348 } // end anonymous namespace
350 void LazyValueInfoCache::LVIValueHandle::deleted() {
351 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
352 I = Parent->OverDefinedCache.begin(),
353 E = Parent->OverDefinedCache.end();
355 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
357 if (tmp->second == getValPtr())
358 Parent->OverDefinedCache.erase(tmp);
361 // This erasure deallocates *this, so it MUST happen after we're done
362 // using any and all members of *this.
363 Parent->ValueCache.erase(*this);
366 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
367 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
368 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
369 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
371 if (tmp->first == BB)
372 OverDefinedCache.erase(tmp);
375 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
376 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
380 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
381 ValueCacheEntryTy &Cache = lookup(Val);
382 LVILatticeVal &BBLV = Cache[BB];
384 // If we've already computed this block's value, return it.
385 if (!BBLV.isUndefined()) {
386 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
390 // Otherwise, this is the first time we're seeing this block. Reset the
391 // lattice value to overdefined, so that cycles will terminate and be
392 // conservatively correct.
393 BBLV.markOverdefined();
395 Instruction *BBI = dyn_cast<Instruction>(Val);
396 if (BBI == 0 || BBI->getParent() != BB) {
397 LVILatticeVal Result; // Start Undefined.
399 // If this is a pointer, and there's a load from that pointer in this BB,
400 // then we know that the pointer can't be NULL.
401 bool NotNull = false;
402 if (Val->getType()->isPointerTy()) {
403 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
404 LoadInst *L = dyn_cast<LoadInst>(BI);
405 if (L && L->getPointerAddressSpace() == 0 &&
406 L->getPointerOperand()->getUnderlyingObject() ==
407 Val->getUnderlyingObject()) {
414 unsigned NumPreds = 0;
415 // Loop over all of our predecessors, merging what we know from them into
417 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
418 Result.mergeIn(getEdgeValue(Val, *PI, BB));
420 // If we hit overdefined, exit early. The BlockVals entry is already set
422 if (Result.isOverdefined()) {
423 DEBUG(dbgs() << " compute BB '" << BB->getName()
424 << "' - overdefined because of pred.\n");
425 // If we previously determined that this is a pointer that can't be null
426 // then return that rather than giving up entirely.
428 const PointerType *PTy = cast<PointerType>(Val->getType());
429 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
432 return setBlockValue(Val, BB, Result, Cache);
438 // If this is the entry block, we must be asking about an argument. The
439 // value is overdefined.
440 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
441 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
442 Result.markOverdefined();
443 return setBlockValue(Val, BB, Result, Cache);
446 // Return the merged value, which is more precise than 'overdefined'.
447 assert(!Result.isOverdefined());
448 return setBlockValue(Val, BB, Result, Cache);
451 // If this value is defined by an instruction in this block, we have to
452 // process it here somehow or return overdefined.
453 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
454 LVILatticeVal Result; // Start Undefined.
456 // Loop over all of our predecessors, merging what we know from them into
458 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
459 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
460 Result.mergeIn(getValueOnEdge(PhiVal, *PI, BB));
462 // If we hit overdefined, exit early. The BlockVals entry is already set
464 if (Result.isOverdefined()) {
465 DEBUG(dbgs() << " compute BB '" << BB->getName()
466 << "' - overdefined because of pred.\n");
467 return setBlockValue(Val, BB, Result, Cache);
471 // Return the merged value, which is more precise than 'overdefined'.
472 assert(!Result.isOverdefined());
473 return setBlockValue(Val, BB, Result, Cache);
476 assert(Cache[BB].isOverdefined() &&
477 "Recursive query changed our cache?");
479 // We can only analyze the definitions of certain classes of instructions
480 // (integral binops and casts at the moment), so bail if this isn't one.
481 LVILatticeVal Result;
482 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
483 !BBI->getType()->isIntegerTy()) {
484 DEBUG(dbgs() << " compute BB '" << BB->getName()
485 << "' - overdefined because inst def found.\n");
486 Result.markOverdefined();
487 return setBlockValue(Val, BB, Result, Cache);
490 // FIXME: We're currently limited to binops with a constant RHS. This should
492 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
493 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
494 DEBUG(dbgs() << " compute BB '" << BB->getName()
495 << "' - overdefined because inst def found.\n");
497 Result.markOverdefined();
498 return setBlockValue(Val, BB, Result, Cache);
501 // Figure out the range of the LHS. If that fails, bail.
502 LVILatticeVal LHSVal = getValueInBlock(BBI->getOperand(0), BB);
503 if (!LHSVal.isConstantRange()) {
504 Result.markOverdefined();
505 return setBlockValue(Val, BB, Result, Cache);
508 ConstantInt *RHS = 0;
509 ConstantRange LHSRange = LHSVal.getConstantRange();
510 ConstantRange RHSRange(1);
511 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
512 if (isa<BinaryOperator>(BBI)) {
513 RHS = dyn_cast<ConstantInt>(BBI->getOperand(1));
515 Result.markOverdefined();
516 return setBlockValue(Val, BB, Result, Cache);
519 RHSRange = ConstantRange(RHS->getValue(), RHS->getValue()+1);
522 // NOTE: We're currently limited by the set of operations that ConstantRange
523 // can evaluate symbolically. Enhancing that set will allows us to analyze
525 switch (BBI->getOpcode()) {
526 case Instruction::Add:
527 Result.markConstantRange(LHSRange.add(RHSRange));
529 case Instruction::Sub:
530 Result.markConstantRange(LHSRange.sub(RHSRange));
532 case Instruction::Mul:
533 Result.markConstantRange(LHSRange.multiply(RHSRange));
535 case Instruction::UDiv:
536 Result.markConstantRange(LHSRange.udiv(RHSRange));
538 case Instruction::Shl:
539 Result.markConstantRange(LHSRange.shl(RHSRange));
541 case Instruction::LShr:
542 Result.markConstantRange(LHSRange.lshr(RHSRange));
544 case Instruction::Trunc:
545 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
547 case Instruction::SExt:
548 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
550 case Instruction::ZExt:
551 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
553 case Instruction::BitCast:
554 Result.markConstantRange(LHSRange);
556 case Instruction::And:
557 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
559 case Instruction::Or:
560 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
563 // Unhandled instructions are overdefined.
565 DEBUG(dbgs() << " compute BB '" << BB->getName()
566 << "' - overdefined because inst def found.\n");
567 Result.markOverdefined();
571 return setBlockValue(Val, BB, Result, Cache);
575 /// getEdgeValue - This method attempts to infer more complex
576 LVILatticeVal LazyValueInfoCache::getEdgeValue(Value *Val,
579 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
581 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
582 // If this is a conditional branch and only one successor goes to BBTo, then
583 // we maybe able to infer something from the condition.
584 if (BI->isConditional() &&
585 BI->getSuccessor(0) != BI->getSuccessor(1)) {
586 bool isTrueDest = BI->getSuccessor(0) == BBTo;
587 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
588 "BBTo isn't a successor of BBFrom");
590 // If V is the condition of the branch itself, then we know exactly what
592 if (BI->getCondition() == Val)
593 return LVILatticeVal::get(ConstantInt::get(
594 Type::getInt1Ty(Val->getContext()), isTrueDest));
596 // If the condition of the branch is an equality comparison, we may be
597 // able to infer the value.
598 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
599 if (ICI && ICI->getOperand(0) == Val &&
600 isa<Constant>(ICI->getOperand(1))) {
601 if (ICI->isEquality()) {
602 // We know that V has the RHS constant if this is a true SETEQ or
604 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
605 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
606 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
609 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
610 // Calculate the range of values that would satisfy the comparison.
611 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
612 ConstantRange TrueValues =
613 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
615 // If we're interested in the false dest, invert the condition.
616 if (!isTrueDest) TrueValues = TrueValues.inverse();
618 // Figure out the possible values of the query BEFORE this branch.
619 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
620 if (!InBlock.isConstantRange())
621 return LVILatticeVal::getRange(TrueValues);
623 // Find all potential values that satisfy both the input and output
625 ConstantRange PossibleValues =
626 TrueValues.intersectWith(InBlock.getConstantRange());
628 return LVILatticeVal::getRange(PossibleValues);
634 // If the edge was formed by a switch on the value, then we may know exactly
636 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
637 if (SI->getCondition() == Val) {
638 // We don't know anything in the default case.
639 if (SI->getDefaultDest() == BBTo) {
640 LVILatticeVal Result;
641 Result.markOverdefined();
645 // We only know something if there is exactly one value that goes from
647 unsigned NumEdges = 0;
648 ConstantInt *EdgeVal = 0;
649 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
650 if (SI->getSuccessor(i) != BBTo) continue;
651 if (NumEdges++) break;
652 EdgeVal = SI->getCaseValue(i);
654 assert(EdgeVal && "Missing successor?");
656 return LVILatticeVal::get(EdgeVal);
660 // Otherwise see if the value is known in the block.
661 return getBlockValue(Val, BBFrom);
664 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
665 // If already a constant, there is nothing to compute.
666 if (Constant *VC = dyn_cast<Constant>(V))
667 return LVILatticeVal::get(VC);
669 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
670 << BB->getName() << "'\n");
672 LVILatticeVal Result = getBlockValue(V, BB);
674 DEBUG(dbgs() << " Result = " << Result << "\n");
678 LVILatticeVal LazyValueInfoCache::
679 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
680 // If already a constant, there is nothing to compute.
681 if (Constant *VC = dyn_cast<Constant>(V))
682 return LVILatticeVal::get(VC);
684 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
685 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
687 LVILatticeVal Result = getEdgeValue(V, FromBB, ToBB);
689 DEBUG(dbgs() << " Result = " << Result << "\n");
694 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
695 BasicBlock *NewSucc) {
696 // When an edge in the graph has been threaded, values that we could not
697 // determine a value for before (i.e. were marked overdefined) may be possible
698 // to solve now. We do NOT try to proactively update these values. Instead,
699 // we clear their entries from the cache, and allow lazy updating to recompute
702 // The updating process is fairly simple: we need to dropped cached info
703 // for all values that were marked overdefined in OldSucc, and for those same
704 // values in any successor of OldSucc (except NewSucc) in which they were
705 // also marked overdefined.
706 std::vector<BasicBlock*> worklist;
707 worklist.push_back(OldSucc);
709 DenseSet<Value*> ClearSet;
710 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
711 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
712 if (I->first == OldSucc)
713 ClearSet.insert(I->second);
716 // Use a worklist to perform a depth-first search of OldSucc's successors.
717 // NOTE: We do not need a visited list since any blocks we have already
718 // visited will have had their overdefined markers cleared already, and we
719 // thus won't loop to their successors.
720 while (!worklist.empty()) {
721 BasicBlock *ToUpdate = worklist.back();
724 // Skip blocks only accessible through NewSucc.
725 if (ToUpdate == NewSucc) continue;
727 bool changed = false;
728 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
730 // If a value was marked overdefined in OldSucc, and is here too...
731 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
732 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
733 if (OI == OverDefinedCache.end()) continue;
735 // Remove it from the caches.
736 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
737 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
739 assert(CI != Entry.end() && "Couldn't find entry to update?");
741 OverDefinedCache.erase(OI);
743 // If we removed anything, then we potentially need to update
744 // blocks successors too.
748 if (!changed) continue;
750 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
754 //===----------------------------------------------------------------------===//
755 // LazyValueInfo Impl
756 //===----------------------------------------------------------------------===//
758 /// getCache - This lazily constructs the LazyValueInfoCache.
759 static LazyValueInfoCache &getCache(void *&PImpl) {
761 PImpl = new LazyValueInfoCache();
762 return *static_cast<LazyValueInfoCache*>(PImpl);
765 bool LazyValueInfo::runOnFunction(Function &F) {
767 getCache(PImpl).clear();
769 TD = getAnalysisIfAvailable<TargetData>();
774 void LazyValueInfo::releaseMemory() {
775 // If the cache was allocated, free it.
777 delete &getCache(PImpl);
782 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
783 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
785 if (Result.isConstant())
786 return Result.getConstant();
787 else if (Result.isConstantRange()) {
788 ConstantRange CR = Result.getConstantRange();
789 if (const APInt *SingleVal = CR.getSingleElement())
790 return ConstantInt::get(V->getContext(), *SingleVal);
795 /// getConstantOnEdge - Determine whether the specified value is known to be a
796 /// constant on the specified edge. Return null if not.
797 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
799 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
801 if (Result.isConstant())
802 return Result.getConstant();
803 else if (Result.isConstantRange()) {
804 ConstantRange CR = Result.getConstantRange();
805 if (const APInt *SingleVal = CR.getSingleElement())
806 return ConstantInt::get(V->getContext(), *SingleVal);
811 /// getPredicateOnEdge - Determine whether the specified value comparison
812 /// with a constant is known to be true or false on the specified CFG edge.
813 /// Pred is a CmpInst predicate.
814 LazyValueInfo::Tristate
815 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
816 BasicBlock *FromBB, BasicBlock *ToBB) {
817 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
819 // If we know the value is a constant, evaluate the conditional.
821 if (Result.isConstant()) {
822 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
823 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
824 return ResCI->isZero() ? False : True;
828 if (Result.isConstantRange()) {
829 ConstantInt *CI = dyn_cast<ConstantInt>(C);
830 if (!CI) return Unknown;
832 ConstantRange CR = Result.getConstantRange();
833 if (Pred == ICmpInst::ICMP_EQ) {
834 if (!CR.contains(CI->getValue()))
837 if (CR.isSingleElement() && CR.contains(CI->getValue()))
839 } else if (Pred == ICmpInst::ICMP_NE) {
840 if (!CR.contains(CI->getValue()))
843 if (CR.isSingleElement() && CR.contains(CI->getValue()))
847 // Handle more complex predicates.
848 ConstantRange RHS(CI->getValue(), CI->getValue()+1);
849 ConstantRange TrueValues = ConstantRange::makeICmpRegion(Pred, RHS);
850 if (CR.intersectWith(TrueValues).isEmptySet())
852 else if (TrueValues.contains(CR))
858 if (Result.isNotConstant()) {
859 // If this is an equality comparison, we can try to fold it knowing that
861 if (Pred == ICmpInst::ICMP_EQ) {
862 // !C1 == C -> false iff C1 == C.
863 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
864 Result.getNotConstant(), C, TD);
865 if (Res->isNullValue())
867 } else if (Pred == ICmpInst::ICMP_NE) {
868 // !C1 != C -> true iff C1 == C.
869 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
870 Result.getNotConstant(), C, TD);
871 if (Res->isNullValue())
880 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
881 BasicBlock* NewSucc) {
882 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
885 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
886 if (PImpl) getCache(PImpl).eraseBlock(BB);