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"
31 char LazyValueInfo::ID = 0;
32 INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
33 "Lazy Value Information Analysis", false, true);
36 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
40 //===----------------------------------------------------------------------===//
42 //===----------------------------------------------------------------------===//
44 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
47 /// FIXME: This is basically just for bringup, this can be made a lot more rich
53 /// undefined - This LLVM Value has no known value yet.
56 /// constant - This LLVM Value has a specific constant value.
58 /// notconstant - This LLVM value is known to not have the specified value.
64 /// overdefined - This instruction is not known to be constant, and we know
69 /// Val: This stores the current lattice value along with the Constant* for
70 /// the constant if this is a 'constant' or 'notconstant' value.
76 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
78 static LVILatticeVal get(Constant *C) {
80 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
81 Res.markConstantRange(ConstantRange(CI->getValue(), CI->getValue()+1));
82 else if (!isa<UndefValue>(C))
86 static LVILatticeVal getNot(Constant *C) {
88 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
89 Res.markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
91 Res.markNotConstant(C);
94 static LVILatticeVal getRange(ConstantRange CR) {
96 Res.markConstantRange(CR);
100 bool isUndefined() const { return Tag == undefined; }
101 bool isConstant() const { return Tag == constant; }
102 bool isNotConstant() const { return Tag == notconstant; }
103 bool isConstantRange() const { return Tag == constantrange; }
104 bool isOverdefined() const { return Tag == overdefined; }
106 Constant *getConstant() const {
107 assert(isConstant() && "Cannot get the constant of a non-constant!");
111 Constant *getNotConstant() const {
112 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
116 ConstantRange getConstantRange() const {
117 assert(isConstantRange() &&
118 "Cannot get the constant-range of a non-constant-range!");
122 /// markOverdefined - Return true if this is a change in status.
123 bool markOverdefined() {
130 /// markConstant - Return true if this is a change in status.
131 bool markConstant(Constant *V) {
133 assert(getConstant() == V && "Marking constant with different value");
137 assert(isUndefined());
139 assert(V && "Marking constant with NULL");
144 /// markNotConstant - Return true if this is a change in status.
145 bool markNotConstant(Constant *V) {
146 if (isNotConstant()) {
147 assert(getNotConstant() == V && "Marking !constant with different value");
152 assert(getConstant() != V && "Marking not constant with different value");
154 assert(isUndefined());
157 assert(V && "Marking constant with NULL");
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();
176 else if (NewR.isFullSet()) {
186 /// mergeIn - Merge the specified lattice value into this one, updating this
187 /// one and returning true if anything changed.
188 bool mergeIn(const LVILatticeVal &RHS) {
189 if (RHS.isUndefined() || isOverdefined()) return false;
190 if (RHS.isOverdefined()) return markOverdefined();
192 if (RHS.isNotConstant()) {
193 if (isNotConstant()) {
194 if (getNotConstant() != RHS.getNotConstant() ||
195 isa<ConstantExpr>(getNotConstant()) ||
196 isa<ConstantExpr>(RHS.getNotConstant()))
197 return markOverdefined();
201 if (getConstant() == RHS.getNotConstant() ||
202 isa<ConstantExpr>(RHS.getNotConstant()) ||
203 isa<ConstantExpr>(getConstant()))
204 return markOverdefined();
205 return markNotConstant(RHS.getNotConstant());
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 undef, constant, or notconstant.
228 assert(!isConstantRange() &&
229 "Constant and ConstantRange cannot be merged.");
232 return markConstant(RHS.getConstant());
235 if (getConstant() != RHS.getConstant())
236 return markOverdefined();
240 // If we are known "!=4" and RHS is "==5", stay at "!=4".
241 if (getNotConstant() == RHS.getConstant() ||
242 isa<ConstantExpr>(getNotConstant()) ||
243 isa<ConstantExpr>(RHS.getConstant()))
244 return markOverdefined();
250 } // end anonymous namespace.
253 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
254 if (Val.isUndefined())
255 return OS << "undefined";
256 if (Val.isOverdefined())
257 return OS << "overdefined";
259 if (Val.isNotConstant())
260 return OS << "notconstant<" << *Val.getNotConstant() << '>';
261 else if (Val.isConstantRange())
262 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
263 << Val.getConstantRange().getUpper() << '>';
264 return OS << "constant<" << *Val.getConstant() << '>';
268 //===----------------------------------------------------------------------===//
269 // LazyValueInfoCache Decl
270 //===----------------------------------------------------------------------===//
273 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
274 /// maintains information about queries across the clients' queries.
275 class LazyValueInfoCache {
277 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
278 /// specified basic block for a Value* that depends on context.
279 typedef std::pair<AssertingVH<BasicBlock>, LVILatticeVal> BlockCacheEntryTy;
281 /// ValueCacheEntryTy - This is all of the cached block information for
282 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
283 /// entries, allowing us to do a lookup with a binary search.
284 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
287 /// LVIValueHandle - A callback value handle update the cache when
288 /// values are erased.
289 struct LVIValueHandle : public CallbackVH {
290 LazyValueInfoCache *Parent;
292 LVIValueHandle(Value *V, LazyValueInfoCache *P)
293 : CallbackVH(V), Parent(P) { }
296 void allUsesReplacedWith(Value* V) {
300 LVIValueHandle &operator=(Value *V) {
301 return *this = LVIValueHandle(V, Parent);
305 /// ValueCache - This is all of the cached information for all values,
306 /// mapped from Value* to key information.
307 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
309 /// OverDefinedCache - This tracks, on a per-block basis, the set of
310 /// values that are over-defined at the end of that block. This is required
311 /// for cache updating.
312 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
316 /// getValueInBlock - This is the query interface to determine the lattice
317 /// value for the specified Value* at the end of the specified block.
318 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
320 /// getValueOnEdge - This is the query interface to determine the lattice
321 /// value for the specified Value* that is true on the specified edge.
322 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
324 /// threadEdge - This is the update interface to inform the cache that an
325 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
327 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
329 /// eraseBlock - This is part of the update interface to inform the cache
330 /// that a block has been deleted.
331 void eraseBlock(BasicBlock *BB);
333 /// clear - Empty the cache.
336 OverDefinedCache.clear();
339 } // end anonymous namespace
341 //===----------------------------------------------------------------------===//
343 //===----------------------------------------------------------------------===//
346 /// LVIQuery - This is a transient object that exists while a query is
349 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
350 /// reallocation of the densemap on every query.
352 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
353 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
355 /// This is the current value being queried for.
358 /// This is a pointer to the owning cache, for recursive queries.
359 LazyValueInfoCache &Parent;
361 /// This is all of the cached information about this value.
362 ValueCacheEntryTy &Cache;
364 /// This tracks, for each block, what values are overdefined.
365 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &OverDefinedCache;
367 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
368 /// added to cache but that are not in sorted order.
369 DenseSet<BasicBlock*> NewBlockInfo;
373 LVIQuery(Value *V, LazyValueInfoCache &P,
374 ValueCacheEntryTy &VC,
375 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &ODC)
376 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
380 // When the query is done, insert the newly discovered facts into the
381 // cache in sorted order.
382 if (NewBlockInfo.empty()) return;
384 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
385 E = NewBlockInfo.end(); I != E; ++I) {
386 if (Cache[*I].isOverdefined())
387 OverDefinedCache.insert(std::make_pair(*I, Val));
391 LVILatticeVal getBlockValue(BasicBlock *BB);
392 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
395 LVILatticeVal getCachedEntryForBlock(BasicBlock *BB);
397 } // end anonymous namespace
399 void LazyValueInfoCache::LVIValueHandle::deleted() {
400 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
401 I = Parent->OverDefinedCache.begin(),
402 E = Parent->OverDefinedCache.end();
404 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
406 if (tmp->second == getValPtr())
407 Parent->OverDefinedCache.erase(tmp);
410 // This erasure deallocates *this, so it MUST happen after we're done
411 // using any and all members of *this.
412 Parent->ValueCache.erase(*this);
415 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
416 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
417 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
418 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
420 if (tmp->first == BB)
421 OverDefinedCache.erase(tmp);
424 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
425 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
429 /// getCachedEntryForBlock - See if we already have a value for this block. If
430 /// so, return it, otherwise create a new entry in the Cache map to use.
431 LVILatticeVal LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
432 NewBlockInfo.insert(BB);
436 LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
437 // See if we already have a value for this block.
438 LVILatticeVal BBLV = getCachedEntryForBlock(BB);
440 // If we've already computed this block's value, return it.
441 if (!BBLV.isUndefined()) {
442 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
446 // Otherwise, this is the first time we're seeing this block. Reset the
447 // lattice value to overdefined, so that cycles will terminate and be
448 // conservatively correct.
449 BBLV.markOverdefined();
452 Instruction *BBI = dyn_cast<Instruction>(Val);
453 if (BBI == 0 || BBI->getParent() != BB) {
454 LVILatticeVal Result; // Start Undefined.
456 // If this is a pointer, and there's a load from that pointer in this BB,
457 // then we know that the pointer can't be NULL.
458 if (Val->getType()->isPointerTy()) {
459 const PointerType *PTy = cast<PointerType>(Val->getType());
460 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
461 LoadInst *L = dyn_cast<LoadInst>(BI);
462 if (L && L->getPointerAddressSpace() == 0 &&
463 L->getPointerOperand()->getUnderlyingObject() ==
464 Val->getUnderlyingObject()) {
465 return LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
470 unsigned NumPreds = 0;
471 // Loop over all of our predecessors, merging what we know from them into
473 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
474 Result.mergeIn(getEdgeValue(*PI, BB));
476 // If we hit overdefined, exit early. The BlockVals entry is already set
478 if (Result.isOverdefined()) {
479 DEBUG(dbgs() << " compute BB '" << BB->getName()
480 << "' - overdefined because of pred.\n");
486 // If this is the entry block, we must be asking about an argument. The
487 // value is overdefined.
488 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
489 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
490 Result.markOverdefined();
494 // Return the merged value, which is more precise than 'overdefined'.
495 assert(!Result.isOverdefined());
496 return Cache[BB] = Result;
499 // If this value is defined by an instruction in this block, we have to
500 // process it here somehow or return overdefined.
501 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
502 LVILatticeVal Result; // Start Undefined.
504 // Loop over all of our predecessors, merging what we know from them into
506 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
507 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
508 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
510 // If we hit overdefined, exit early. The BlockVals entry is already set
512 if (Result.isOverdefined()) {
513 DEBUG(dbgs() << " compute BB '" << BB->getName()
514 << "' - overdefined because of pred.\n");
519 // Return the merged value, which is more precise than 'overdefined'.
520 assert(!Result.isOverdefined());
521 return Cache[BB] = Result;
524 assert(Cache[BB].isOverdefined() && "Recursive query changed our cache?");
526 // We can only analyze the definitions of certain classes of instructions
527 // (integral binops and casts at the moment), so bail if this isn't one.
528 LVILatticeVal Result;
529 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
530 !BBI->getType()->isIntegerTy()) {
531 DEBUG(dbgs() << " compute BB '" << BB->getName()
532 << "' - overdefined because inst def found.\n");
533 Result.markOverdefined();
537 // FIXME: We're currently limited to binops with a constant RHS. This should
539 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
540 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
541 DEBUG(dbgs() << " compute BB '" << BB->getName()
542 << "' - overdefined because inst def found.\n");
544 Result.markOverdefined();
548 // Figure out the range of the LHS. If that fails, bail.
549 LVILatticeVal LHSVal = Parent.getValueInBlock(BBI->getOperand(0), BB);
550 if (!LHSVal.isConstantRange()) {
551 Result.markOverdefined();
555 ConstantInt *RHS = 0;
556 ConstantRange LHSRange = LHSVal.getConstantRange();
557 ConstantRange RHSRange(1);
558 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
559 if (isa<BinaryOperator>(BBI)) {
560 RHS = dyn_cast<ConstantInt>(BBI->getOperand(1));
562 Result.markOverdefined();
566 RHSRange = ConstantRange(RHS->getValue(), RHS->getValue()+1);
569 // NOTE: We're currently limited by the set of operations that ConstantRange
570 // can evaluate symbolically. Enhancing that set will allows us to analyze
572 switch (BBI->getOpcode()) {
573 case Instruction::Add:
574 Result.markConstantRange(LHSRange.add(RHSRange));
576 case Instruction::Sub:
577 Result.markConstantRange(LHSRange.sub(RHSRange));
579 case Instruction::Mul:
580 Result.markConstantRange(LHSRange.multiply(RHSRange));
582 case Instruction::UDiv:
583 Result.markConstantRange(LHSRange.udiv(RHSRange));
585 case Instruction::Shl:
586 Result.markConstantRange(LHSRange.shl(RHSRange));
588 case Instruction::LShr:
589 Result.markConstantRange(LHSRange.lshr(RHSRange));
591 case Instruction::Trunc:
592 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
594 case Instruction::SExt:
595 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
597 case Instruction::ZExt:
598 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
600 case Instruction::BitCast:
601 Result.markConstantRange(LHSRange);
604 // Unhandled instructions are overdefined.
606 DEBUG(dbgs() << " compute BB '" << BB->getName()
607 << "' - overdefined because inst def found.\n");
608 Result.markOverdefined();
612 return Cache[BB] = Result;
616 /// getEdgeValue - This method attempts to infer more complex
617 LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
618 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
620 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
621 // If this is a conditional branch and only one successor goes to BBTo, then
622 // we maybe able to infer something from the condition.
623 if (BI->isConditional() &&
624 BI->getSuccessor(0) != BI->getSuccessor(1)) {
625 bool isTrueDest = BI->getSuccessor(0) == BBTo;
626 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
627 "BBTo isn't a successor of BBFrom");
629 // If V is the condition of the branch itself, then we know exactly what
631 if (BI->getCondition() == Val)
632 return LVILatticeVal::get(ConstantInt::get(
633 Type::getInt1Ty(Val->getContext()), isTrueDest));
635 // If the condition of the branch is an equality comparison, we may be
636 // able to infer the value.
637 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
638 if (ICI && ICI->getOperand(0) == Val &&
639 isa<Constant>(ICI->getOperand(1))) {
640 if (ICI->isEquality()) {
641 // We know that V has the RHS constant if this is a true SETEQ or
643 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
644 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
645 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
648 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
649 // Calculate the range of values that would satisfy the comparison.
650 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
651 ConstantRange TrueValues =
652 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
654 // If we're interested in the false dest, invert the condition.
655 if (!isTrueDest) TrueValues = TrueValues.inverse();
657 // Figure out the possible values of the query BEFORE this branch.
658 LVILatticeVal InBlock = getBlockValue(BBFrom);
659 if (!InBlock.isConstantRange())
660 return LVILatticeVal::getRange(TrueValues);
662 // Find all potential values that satisfy both the input and output
664 ConstantRange PossibleValues =
665 TrueValues.intersectWith(InBlock.getConstantRange());
667 return LVILatticeVal::getRange(PossibleValues);
673 // If the edge was formed by a switch on the value, then we may know exactly
675 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
676 // If BBTo is the default destination of the switch, we know that it
677 // doesn't have the same value as any of the cases.
678 if (SI->getCondition() == Val) {
679 if (SI->getDefaultDest() == BBTo) {
680 const IntegerType *IT = cast<IntegerType>(Val->getType());
681 ConstantRange CR(IT->getBitWidth());
683 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
684 const APInt CaseVal = SI->getCaseValue(i)->getValue();
685 ConstantRange CaseRange(CaseVal, CaseVal+1);
686 CaseRange = CaseRange.inverse();
687 CR = CR.intersectWith(CaseRange);
690 LVILatticeVal Result;
691 if (CR.isFullSet() || CR.isEmptySet())
692 Result.markOverdefined();
694 Result.markConstantRange(CR);
698 // We only know something if there is exactly one value that goes from
700 unsigned NumEdges = 0;
701 ConstantInt *EdgeVal = 0;
702 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
703 if (SI->getSuccessor(i) != BBTo) continue;
704 if (NumEdges++) break;
705 EdgeVal = SI->getCaseValue(i);
707 assert(EdgeVal && "Missing successor?");
709 return LVILatticeVal::get(EdgeVal);
713 // Otherwise see if the value is known in the block.
714 return getBlockValue(BBFrom);
718 //===----------------------------------------------------------------------===//
719 // LazyValueInfoCache Impl
720 //===----------------------------------------------------------------------===//
722 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
723 // If already a constant, there is nothing to compute.
724 if (Constant *VC = dyn_cast<Constant>(V))
725 return LVILatticeVal::get(VC);
727 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
728 << BB->getName() << "'\n");
730 LVILatticeVal Result = LVIQuery(V, *this,
731 ValueCache[LVIValueHandle(V, this)],
732 OverDefinedCache).getBlockValue(BB);
734 DEBUG(dbgs() << " Result = " << Result << "\n");
738 LVILatticeVal LazyValueInfoCache::
739 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
740 // If already a constant, there is nothing to compute.
741 if (Constant *VC = dyn_cast<Constant>(V))
742 return LVILatticeVal::get(VC);
744 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
745 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
747 LVILatticeVal Result =
748 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
749 OverDefinedCache).getEdgeValue(FromBB, ToBB);
751 DEBUG(dbgs() << " Result = " << Result << "\n");
756 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
757 BasicBlock *NewSucc) {
758 // When an edge in the graph has been threaded, values that we could not
759 // determine a value for before (i.e. were marked overdefined) may be possible
760 // to solve now. We do NOT try to proactively update these values. Instead,
761 // we clear their entries from the cache, and allow lazy updating to recompute
764 // The updating process is fairly simple: we need to dropped cached info
765 // for all values that were marked overdefined in OldSucc, and for those same
766 // values in any successor of OldSucc (except NewSucc) in which they were
767 // also marked overdefined.
768 std::vector<BasicBlock*> worklist;
769 worklist.push_back(OldSucc);
771 DenseSet<Value*> ClearSet;
772 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
773 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
774 if (I->first == OldSucc)
775 ClearSet.insert(I->second);
778 // Use a worklist to perform a depth-first search of OldSucc's successors.
779 // NOTE: We do not need a visited list since any blocks we have already
780 // visited will have had their overdefined markers cleared already, and we
781 // thus won't loop to their successors.
782 while (!worklist.empty()) {
783 BasicBlock *ToUpdate = worklist.back();
786 // Skip blocks only accessible through NewSucc.
787 if (ToUpdate == NewSucc) continue;
789 bool changed = false;
790 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
792 // If a value was marked overdefined in OldSucc, and is here too...
793 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
794 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
795 if (OI == OverDefinedCache.end()) continue;
797 // Remove it from the caches.
798 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
799 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
801 assert(CI != Entry.end() && "Couldn't find entry to update?");
803 OverDefinedCache.erase(OI);
805 // If we removed anything, then we potentially need to update
806 // blocks successors too.
810 if (!changed) continue;
812 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
816 //===----------------------------------------------------------------------===//
817 // LazyValueInfo Impl
818 //===----------------------------------------------------------------------===//
820 /// getCache - This lazily constructs the LazyValueInfoCache.
821 static LazyValueInfoCache &getCache(void *&PImpl) {
823 PImpl = new LazyValueInfoCache();
824 return *static_cast<LazyValueInfoCache*>(PImpl);
827 bool LazyValueInfo::runOnFunction(Function &F) {
829 getCache(PImpl).clear();
831 TD = getAnalysisIfAvailable<TargetData>();
836 void LazyValueInfo::releaseMemory() {
837 // If the cache was allocated, free it.
839 delete &getCache(PImpl);
844 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
845 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
847 if (Result.isConstant())
848 return Result.getConstant();
849 else if (Result.isConstantRange()) {
850 ConstantRange CR = Result.getConstantRange();
851 if (const APInt *SingleVal = CR.getSingleElement())
852 return ConstantInt::get(V->getContext(), *SingleVal);
857 /// getConstantOnEdge - Determine whether the specified value is known to be a
858 /// constant on the specified edge. Return null if not.
859 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
861 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
863 if (Result.isConstant())
864 return Result.getConstant();
865 else if (Result.isConstantRange()) {
866 ConstantRange CR = Result.getConstantRange();
867 if (const APInt *SingleVal = CR.getSingleElement())
868 return ConstantInt::get(V->getContext(), *SingleVal);
873 /// getPredicateOnEdge - Determine whether the specified value comparison
874 /// with a constant is known to be true or false on the specified CFG edge.
875 /// Pred is a CmpInst predicate.
876 LazyValueInfo::Tristate
877 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
878 BasicBlock *FromBB, BasicBlock *ToBB) {
879 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
881 // If we know the value is a constant, evaluate the conditional.
883 if (Result.isConstant()) {
884 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
885 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
886 return ResCI->isZero() ? False : True;
890 if (Result.isConstantRange()) {
891 ConstantInt *CI = dyn_cast<ConstantInt>(C);
892 if (!CI) return Unknown;
894 ConstantRange CR = Result.getConstantRange();
895 if (Pred == ICmpInst::ICMP_EQ) {
896 if (!CR.contains(CI->getValue()))
899 if (CR.isSingleElement() && CR.contains(CI->getValue()))
901 } else if (Pred == ICmpInst::ICMP_NE) {
902 if (!CR.contains(CI->getValue()))
905 if (CR.isSingleElement() && CR.contains(CI->getValue()))
909 // Handle more complex predicates.
910 ConstantRange RHS(CI->getValue(), CI->getValue()+1);
911 ConstantRange TrueValues = ConstantRange::makeICmpRegion(Pred, RHS);
912 if (CR.intersectWith(TrueValues).isEmptySet())
914 else if (TrueValues.contains(CR))
920 if (Result.isNotConstant()) {
921 // If this is an equality comparison, we can try to fold it knowing that
923 if (Pred == ICmpInst::ICMP_EQ) {
924 // !C1 == C -> false iff C1 == C.
925 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
926 Result.getNotConstant(), C, TD);
927 if (Res->isNullValue())
929 } else if (Pred == ICmpInst::ICMP_NE) {
930 // !C1 != C -> true iff C1 == C.
931 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
932 Result.getNotConstant(), C, TD);
933 if (Res->isNullValue())
942 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
943 BasicBlock* NewSucc) {
944 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
947 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
948 if (PImpl) getCache(PImpl).eraseBlock(BB);