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"
35 char LazyValueInfo::ID = 0;
36 INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
37 "Lazy Value Information Analysis", false, true)
40 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
48 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
51 /// FIXME: This is basically just for bringup, this can be made a lot more rich
57 /// undefined - This Value has no known value yet.
60 /// constant - This Value has a specific constant value.
62 /// notconstant - This Value is known to not have the specified value.
65 /// constantrange - The Value falls within this range.
68 /// overdefined - This value is not known to be constant, and we know that
73 /// Val: This stores the current lattice value along with the Constant* for
74 /// the constant if this is a 'constant' or 'notconstant' value.
80 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
82 static LVILatticeVal get(Constant *C) {
84 if (!isa<UndefValue>(C))
88 static LVILatticeVal getNot(Constant *C) {
90 if (!isa<UndefValue>(C))
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) {
132 assert(V && "Marking constant with NULL");
133 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
134 return markConstantRange(ConstantRange(CI->getValue()));
135 if (isa<UndefValue>(V))
138 assert((!isConstant() || getConstant() == V) &&
139 "Marking constant with different value");
140 assert(isUndefined());
146 /// markNotConstant - Return true if this is a change in status.
147 bool markNotConstant(Constant *V) {
148 assert(V && "Marking constant with NULL");
149 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
150 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
151 if (isa<UndefValue>(V))
154 assert((!isConstant() || getConstant() != V) &&
155 "Marking constant !constant with same value");
156 assert((!isNotConstant() || getNotConstant() == V) &&
157 "Marking !constant with different value");
158 assert(isUndefined() || isConstant());
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();
198 if (RHS.isConstant()) {
201 return markOverdefined();
204 if (RHS.isNotConstant()) {
206 return markOverdefined();
208 // Unless we can prove that the two Constants are different, we must
209 // move to overdefined.
210 // FIXME: use TargetData for smarter constant folding.
211 if (ConstantInt *Res = dyn_cast<ConstantInt>(
212 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
214 RHS.getNotConstant())))
216 return markNotConstant(RHS.getNotConstant());
218 return markOverdefined();
221 // RHS is a ConstantRange, LHS is a non-integer Constant.
223 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
224 // a function. The correct result is to pick up RHS.
226 return markOverdefined();
229 if (isNotConstant()) {
230 if (RHS.isConstant()) {
232 return markOverdefined();
234 // Unless we can prove that the two Constants are different, we must
235 // move to overdefined.
236 // FIXME: use TargetData for smarter constant folding.
237 if (ConstantInt *Res = dyn_cast<ConstantInt>(
238 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
244 return markOverdefined();
247 if (RHS.isNotConstant()) {
250 return markOverdefined();
253 return markOverdefined();
256 assert(isConstantRange() && "New LVILattice type?");
257 if (!RHS.isConstantRange())
258 return markOverdefined();
260 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
261 if (NewR.isFullSet())
262 return markOverdefined();
263 return markConstantRange(NewR);
267 } // end anonymous namespace.
270 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
271 if (Val.isUndefined())
272 return OS << "undefined";
273 if (Val.isOverdefined())
274 return OS << "overdefined";
276 if (Val.isNotConstant())
277 return OS << "notconstant<" << *Val.getNotConstant() << '>';
278 else if (Val.isConstantRange())
279 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
280 << Val.getConstantRange().getUpper() << '>';
281 return OS << "constant<" << *Val.getConstant() << '>';
285 //===----------------------------------------------------------------------===//
286 // LazyValueInfoCache Decl
287 //===----------------------------------------------------------------------===//
290 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
291 /// maintains information about queries across the clients' queries.
292 class LazyValueInfoCache {
294 /// ValueCacheEntryTy - This is all of the cached block information for
295 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
296 /// entries, allowing us to do a lookup with a binary search.
297 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
300 /// LVIValueHandle - A callback value handle update the cache when
301 /// values are erased.
302 struct LVIValueHandle : public CallbackVH {
303 LazyValueInfoCache *Parent;
305 LVIValueHandle(Value *V, LazyValueInfoCache *P)
306 : CallbackVH(V), Parent(P) { }
309 void allUsesReplacedWith(Value *V) {
314 /// ValueCache - This is all of the cached information for all values,
315 /// mapped from Value* to key information.
316 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
318 /// OverDefinedCache - This tracks, on a per-block basis, the set of
319 /// values that are over-defined at the end of that block. This is required
320 /// for cache updating.
321 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
323 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
324 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
325 LVILatticeVal &Result);
326 bool hasBlockValue(Value *Val, BasicBlock *BB);
328 // These methods process one work item and may add more. A false value
329 // returned means that the work item was not completely processed and must
330 // be revisited after going through the new items.
331 bool solveBlockValue(Value *Val, BasicBlock *BB);
332 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
333 Value *Val, BasicBlock *BB);
334 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
335 PHINode *PN, BasicBlock *BB);
336 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
337 Instruction *BBI, BasicBlock *BB);
341 ValueCacheEntryTy &lookup(Value *V) {
342 return ValueCache[LVIValueHandle(V, this)];
345 LVILatticeVal setBlockValue(Value *V, BasicBlock *BB, LVILatticeVal L,
346 ValueCacheEntryTy &Cache) {
347 if (L.isOverdefined()) OverDefinedCache.insert(std::make_pair(BB, V));
348 return Cache[BB] = L;
350 LVILatticeVal setBlockValue(Value *V, BasicBlock *BB, LVILatticeVal L) {
351 return setBlockValue(V, BB, L, lookup(V));
354 struct BlockStackEntry {
355 BlockStackEntry(Value *Val, BasicBlock *BB) : Val(Val), BB(BB) {}
359 std::stack<BlockStackEntry> block_value_stack;
362 /// getValueInBlock - This is the query interface to determine the lattice
363 /// value for the specified Value* at the end of the specified block.
364 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
366 /// getValueOnEdge - This is the query interface to determine the lattice
367 /// value for the specified Value* that is true on the specified edge.
368 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
370 /// threadEdge - This is the update interface to inform the cache that an
371 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
373 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
375 /// eraseBlock - This is part of the update interface to inform the cache
376 /// that a block has been deleted.
377 void eraseBlock(BasicBlock *BB);
379 /// clear - Empty the cache.
382 OverDefinedCache.clear();
385 } // end anonymous namespace
387 void LazyValueInfoCache::LVIValueHandle::deleted() {
388 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
389 I = Parent->OverDefinedCache.begin(),
390 E = Parent->OverDefinedCache.end();
392 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
394 if (tmp->second == getValPtr())
395 Parent->OverDefinedCache.erase(tmp);
398 // This erasure deallocates *this, so it MUST happen after we're done
399 // using any and all members of *this.
400 Parent->ValueCache.erase(*this);
403 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
404 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
405 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
406 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
408 if (tmp->first == BB)
409 OverDefinedCache.erase(tmp);
412 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
413 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
417 void LazyValueInfoCache::solve() {
418 while (!block_value_stack.empty()) {
419 BlockStackEntry &e = block_value_stack.top();
420 if (solveBlockValue(e.Val, e.BB))
421 block_value_stack.pop();
425 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
426 // If already a constant, there is nothing to compute.
427 if (isa<Constant>(Val))
430 return lookup(Val).count(BB);
433 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
434 // If already a constant, there is nothing to compute.
435 if (Constant *VC = dyn_cast<Constant>(Val))
436 return LVILatticeVal::get(VC);
438 return lookup(Val)[BB];
441 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
442 if (isa<Constant>(Val))
445 ValueCacheEntryTy &Cache = lookup(Val);
446 LVILatticeVal &BBLV = Cache[BB];
448 // If we've already computed this block's value, return it.
449 if (!BBLV.isUndefined()) {
450 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
454 // Otherwise, this is the first time we're seeing this block. Reset the
455 // lattice value to overdefined, so that cycles will terminate and be
456 // conservatively correct.
457 BBLV.markOverdefined();
459 Instruction *BBI = dyn_cast<Instruction>(Val);
460 if (BBI == 0 || BBI->getParent() != BB) {
461 return solveBlockValueNonLocal(BBLV, Val, BB);
464 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
465 return solveBlockValuePHINode(BBLV, PN, BB);
468 // We can only analyze the definitions of certain classes of instructions
469 // (integral binops and casts at the moment), so bail if this isn't one.
470 LVILatticeVal Result;
471 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
472 !BBI->getType()->isIntegerTy()) {
473 DEBUG(dbgs() << " compute BB '" << BB->getName()
474 << "' - overdefined because inst def found.\n");
475 BBLV.markOverdefined();
479 // FIXME: We're currently limited to binops with a constant RHS. This should
481 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
482 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
483 DEBUG(dbgs() << " compute BB '" << BB->getName()
484 << "' - overdefined because inst def found.\n");
486 BBLV.markOverdefined();
490 return solveBlockValueConstantRange(BBLV, BBI, BB);
493 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
494 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
495 return L->getPointerAddressSpace() == 0 &&
496 GetUnderlyingObject(L->getPointerOperand()) ==
497 GetUnderlyingObject(Ptr);
499 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
500 return S->getPointerAddressSpace() == 0 &&
501 GetUnderlyingObject(S->getPointerOperand()) ==
502 GetUnderlyingObject(Ptr);
504 // FIXME: llvm.memset, etc.
508 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
509 Value *Val, BasicBlock *BB) {
510 LVILatticeVal Result; // Start Undefined.
512 // If this is a pointer, and there's a load from that pointer in this BB,
513 // then we know that the pointer can't be NULL.
514 bool NotNull = false;
515 if (Val->getType()->isPointerTy()) {
516 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
517 if (InstructionDereferencesPointer(BI, Val)) {
524 // If this is the entry block, we must be asking about an argument. The
525 // value is overdefined.
526 if (BB == &BB->getParent()->getEntryBlock()) {
527 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
529 const PointerType *PTy = cast<PointerType>(Val->getType());
530 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
532 Result.markOverdefined();
538 // Loop over all of our predecessors, merging what we know from them into
540 bool EdgesMissing = false;
541 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
542 LVILatticeVal EdgeResult;
543 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
547 Result.mergeIn(EdgeResult);
549 // If we hit overdefined, exit early. The BlockVals entry is already set
551 if (Result.isOverdefined()) {
552 DEBUG(dbgs() << " compute BB '" << BB->getName()
553 << "' - overdefined because of pred.\n");
554 // If we previously determined that this is a pointer that can't be null
555 // then return that rather than giving up entirely.
557 const PointerType *PTy = cast<PointerType>(Val->getType());
558 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
568 // Return the merged value, which is more precise than 'overdefined'.
569 assert(!Result.isOverdefined());
574 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
575 PHINode *PN, BasicBlock *BB) {
576 LVILatticeVal Result; // Start Undefined.
578 // Loop over all of our predecessors, merging what we know from them into
580 bool EdgesMissing = false;
581 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
582 BasicBlock *PhiBB = PN->getIncomingBlock(i);
583 Value *PhiVal = PN->getIncomingValue(i);
584 LVILatticeVal EdgeResult;
585 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
589 Result.mergeIn(EdgeResult);
591 // If we hit overdefined, exit early. The BlockVals entry is already set
593 if (Result.isOverdefined()) {
594 DEBUG(dbgs() << " compute BB '" << BB->getName()
595 << "' - overdefined because of pred.\n");
604 // Return the merged value, which is more precise than 'overdefined'.
605 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
610 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
613 // Figure out the range of the LHS. If that fails, bail.
614 if (!hasBlockValue(BBI->getOperand(0), BB)) {
615 block_value_stack.push(BlockStackEntry(BBI->getOperand(0), BB));
619 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
620 if (!LHSVal.isConstantRange()) {
621 BBLV.markOverdefined();
625 ConstantRange LHSRange = LHSVal.getConstantRange();
626 ConstantRange RHSRange(1);
627 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
628 if (isa<BinaryOperator>(BBI)) {
629 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
630 RHSRange = ConstantRange(RHS->getValue());
632 BBLV.markOverdefined();
637 // NOTE: We're currently limited by the set of operations that ConstantRange
638 // can evaluate symbolically. Enhancing that set will allows us to analyze
640 LVILatticeVal Result;
641 switch (BBI->getOpcode()) {
642 case Instruction::Add:
643 Result.markConstantRange(LHSRange.add(RHSRange));
645 case Instruction::Sub:
646 Result.markConstantRange(LHSRange.sub(RHSRange));
648 case Instruction::Mul:
649 Result.markConstantRange(LHSRange.multiply(RHSRange));
651 case Instruction::UDiv:
652 Result.markConstantRange(LHSRange.udiv(RHSRange));
654 case Instruction::Shl:
655 Result.markConstantRange(LHSRange.shl(RHSRange));
657 case Instruction::LShr:
658 Result.markConstantRange(LHSRange.lshr(RHSRange));
660 case Instruction::Trunc:
661 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
663 case Instruction::SExt:
664 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
666 case Instruction::ZExt:
667 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
669 case Instruction::BitCast:
670 Result.markConstantRange(LHSRange);
672 case Instruction::And:
673 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
675 case Instruction::Or:
676 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
679 // Unhandled instructions are overdefined.
681 DEBUG(dbgs() << " compute BB '" << BB->getName()
682 << "' - overdefined because inst def found.\n");
683 Result.markOverdefined();
691 /// getEdgeValue - This method attempts to infer more complex
692 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
693 BasicBlock *BBTo, LVILatticeVal &Result) {
694 // If already a constant, there is nothing to compute.
695 if (Constant *VC = dyn_cast<Constant>(Val)) {
696 Result = LVILatticeVal::get(VC);
700 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
702 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
703 // If this is a conditional branch and only one successor goes to BBTo, then
704 // we maybe able to infer something from the condition.
705 if (BI->isConditional() &&
706 BI->getSuccessor(0) != BI->getSuccessor(1)) {
707 bool isTrueDest = BI->getSuccessor(0) == BBTo;
708 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
709 "BBTo isn't a successor of BBFrom");
711 // If V is the condition of the branch itself, then we know exactly what
713 if (BI->getCondition() == Val) {
714 Result = LVILatticeVal::get(ConstantInt::get(
715 Type::getInt1Ty(Val->getContext()), isTrueDest));
719 // If the condition of the branch is an equality comparison, we may be
720 // able to infer the value.
721 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
722 if (ICI && ICI->getOperand(0) == Val &&
723 isa<Constant>(ICI->getOperand(1))) {
724 if (ICI->isEquality()) {
725 // We know that V has the RHS constant if this is a true SETEQ or
727 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
728 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
730 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
734 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
735 // Calculate the range of values that would satisfy the comparison.
736 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
737 ConstantRange TrueValues =
738 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
740 // If we're interested in the false dest, invert the condition.
741 if (!isTrueDest) TrueValues = TrueValues.inverse();
743 // Figure out the possible values of the query BEFORE this branch.
744 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
745 if (!InBlock.isConstantRange()) {
746 Result = LVILatticeVal::getRange(TrueValues);
750 // Find all potential values that satisfy both the input and output
752 ConstantRange PossibleValues =
753 TrueValues.intersectWith(InBlock.getConstantRange());
755 Result = LVILatticeVal::getRange(PossibleValues);
762 // If the edge was formed by a switch on the value, then we may know exactly
764 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
765 if (SI->getCondition() == Val) {
766 // We don't know anything in the default case.
767 if (SI->getDefaultDest() == BBTo) {
768 Result.markOverdefined();
772 // We only know something if there is exactly one value that goes from
774 unsigned NumEdges = 0;
775 ConstantInt *EdgeVal = 0;
776 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
777 if (SI->getSuccessor(i) != BBTo) continue;
778 if (NumEdges++) break;
779 EdgeVal = SI->getCaseValue(i);
781 assert(EdgeVal && "Missing successor?");
783 Result = LVILatticeVal::get(EdgeVal);
789 // Otherwise see if the value is known in the block.
790 if (hasBlockValue(Val, BBFrom)) {
791 Result = getBlockValue(Val, BBFrom);
794 block_value_stack.push(BlockStackEntry(Val, BBFrom));
798 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
799 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
800 << BB->getName() << "'\n");
802 block_value_stack.push(BlockStackEntry(V, BB));
804 LVILatticeVal Result = getBlockValue(V, BB);
806 DEBUG(dbgs() << " Result = " << Result << "\n");
810 LVILatticeVal LazyValueInfoCache::
811 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
812 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
813 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
815 LVILatticeVal Result;
816 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
818 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
820 assert(WasFastQuery && "More work to do after problem solved?");
823 DEBUG(dbgs() << " Result = " << Result << "\n");
827 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
828 BasicBlock *NewSucc) {
829 // When an edge in the graph has been threaded, values that we could not
830 // determine a value for before (i.e. were marked overdefined) may be possible
831 // to solve now. We do NOT try to proactively update these values. Instead,
832 // we clear their entries from the cache, and allow lazy updating to recompute
835 // The updating process is fairly simple: we need to dropped cached info
836 // for all values that were marked overdefined in OldSucc, and for those same
837 // values in any successor of OldSucc (except NewSucc) in which they were
838 // also marked overdefined.
839 std::vector<BasicBlock*> worklist;
840 worklist.push_back(OldSucc);
842 DenseSet<Value*> ClearSet;
843 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
844 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
845 if (I->first == OldSucc)
846 ClearSet.insert(I->second);
849 // Use a worklist to perform a depth-first search of OldSucc's successors.
850 // NOTE: We do not need a visited list since any blocks we have already
851 // visited will have had their overdefined markers cleared already, and we
852 // thus won't loop to their successors.
853 while (!worklist.empty()) {
854 BasicBlock *ToUpdate = worklist.back();
857 // Skip blocks only accessible through NewSucc.
858 if (ToUpdate == NewSucc) continue;
860 bool changed = false;
861 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
863 // If a value was marked overdefined in OldSucc, and is here too...
864 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
865 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
866 if (OI == OverDefinedCache.end()) continue;
868 // Remove it from the caches.
869 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
870 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
872 assert(CI != Entry.end() && "Couldn't find entry to update?");
874 OverDefinedCache.erase(OI);
876 // If we removed anything, then we potentially need to update
877 // blocks successors too.
881 if (!changed) continue;
883 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
887 //===----------------------------------------------------------------------===//
888 // LazyValueInfo Impl
889 //===----------------------------------------------------------------------===//
891 /// getCache - This lazily constructs the LazyValueInfoCache.
892 static LazyValueInfoCache &getCache(void *&PImpl) {
894 PImpl = new LazyValueInfoCache();
895 return *static_cast<LazyValueInfoCache*>(PImpl);
898 bool LazyValueInfo::runOnFunction(Function &F) {
900 getCache(PImpl).clear();
902 TD = getAnalysisIfAvailable<TargetData>();
907 void LazyValueInfo::releaseMemory() {
908 // If the cache was allocated, free it.
910 delete &getCache(PImpl);
915 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
916 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
918 if (Result.isConstant())
919 return Result.getConstant();
920 if (Result.isConstantRange()) {
921 ConstantRange CR = Result.getConstantRange();
922 if (const APInt *SingleVal = CR.getSingleElement())
923 return ConstantInt::get(V->getContext(), *SingleVal);
928 /// getConstantOnEdge - Determine whether the specified value is known to be a
929 /// constant on the specified edge. Return null if not.
930 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
932 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
934 if (Result.isConstant())
935 return Result.getConstant();
936 if (Result.isConstantRange()) {
937 ConstantRange CR = Result.getConstantRange();
938 if (const APInt *SingleVal = CR.getSingleElement())
939 return ConstantInt::get(V->getContext(), *SingleVal);
944 /// getPredicateOnEdge - Determine whether the specified value comparison
945 /// with a constant is known to be true or false on the specified CFG edge.
946 /// Pred is a CmpInst predicate.
947 LazyValueInfo::Tristate
948 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
949 BasicBlock *FromBB, BasicBlock *ToBB) {
950 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
952 // If we know the value is a constant, evaluate the conditional.
954 if (Result.isConstant()) {
955 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
956 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
957 return ResCI->isZero() ? False : True;
961 if (Result.isConstantRange()) {
962 ConstantInt *CI = dyn_cast<ConstantInt>(C);
963 if (!CI) return Unknown;
965 ConstantRange CR = Result.getConstantRange();
966 if (Pred == ICmpInst::ICMP_EQ) {
967 if (!CR.contains(CI->getValue()))
970 if (CR.isSingleElement() && CR.contains(CI->getValue()))
972 } else if (Pred == ICmpInst::ICMP_NE) {
973 if (!CR.contains(CI->getValue()))
976 if (CR.isSingleElement() && CR.contains(CI->getValue()))
980 // Handle more complex predicates.
981 ConstantRange TrueValues =
982 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
983 if (TrueValues.contains(CR))
985 if (TrueValues.inverse().contains(CR))
990 if (Result.isNotConstant()) {
991 // If this is an equality comparison, we can try to fold it knowing that
993 if (Pred == ICmpInst::ICMP_EQ) {
994 // !C1 == C -> false iff C1 == C.
995 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
996 Result.getNotConstant(), C, TD);
997 if (Res->isNullValue())
999 } else if (Pred == ICmpInst::ICMP_NE) {
1000 // !C1 != C -> true iff C1 == C.
1001 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1002 Result.getNotConstant(), C, TD);
1003 if (Res->isNullValue())
1012 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1013 BasicBlock *NewSucc) {
1014 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1017 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1018 if (PImpl) getCache(PImpl).eraseBlock(BB);