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(Value *Val, BasicBlock *BB);
333 bool solveBlockValuePHINode(PHINode *PN, BasicBlock *BB);
334 bool solveBlockValueConstantRange(Instruction *BBI, BasicBlock *BB);
338 ValueCacheEntryTy &lookup(Value *V) {
339 return ValueCache[LVIValueHandle(V, this)];
342 LVILatticeVal setBlockValue(Value *V, BasicBlock *BB, LVILatticeVal L,
343 ValueCacheEntryTy &Cache) {
344 if (L.isOverdefined()) OverDefinedCache.insert(std::make_pair(BB, V));
345 return Cache[BB] = L;
347 LVILatticeVal setBlockValue(Value *V, BasicBlock *BB, LVILatticeVal L) {
348 return setBlockValue(V, BB, L, lookup(V));
351 struct BlockStackEntry {
352 BlockStackEntry(Value *Val, BasicBlock *BB) : Val(Val), BB(BB) {}
356 std::stack<BlockStackEntry> block_value_stack;
359 /// getValueInBlock - This is the query interface to determine the lattice
360 /// value for the specified Value* at the end of the specified block.
361 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
363 /// getValueOnEdge - This is the query interface to determine the lattice
364 /// value for the specified Value* that is true on the specified edge.
365 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
367 /// threadEdge - This is the update interface to inform the cache that an
368 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
370 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
372 /// eraseBlock - This is part of the update interface to inform the cache
373 /// that a block has been deleted.
374 void eraseBlock(BasicBlock *BB);
376 /// clear - Empty the cache.
379 OverDefinedCache.clear();
382 } // end anonymous namespace
384 void LazyValueInfoCache::LVIValueHandle::deleted() {
385 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
386 I = Parent->OverDefinedCache.begin(),
387 E = Parent->OverDefinedCache.end();
389 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
391 if (tmp->second == getValPtr())
392 Parent->OverDefinedCache.erase(tmp);
395 // This erasure deallocates *this, so it MUST happen after we're done
396 // using any and all members of *this.
397 Parent->ValueCache.erase(*this);
400 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
401 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
402 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
403 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
405 if (tmp->first == BB)
406 OverDefinedCache.erase(tmp);
409 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
410 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
414 void LazyValueInfoCache::solve() {
415 while (!block_value_stack.empty()) {
416 BlockStackEntry &e = block_value_stack.top();
417 if (solveBlockValue(e.Val, e.BB))
418 block_value_stack.pop();
422 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
423 // If already a constant, there is nothing to compute.
424 if (isa<Constant>(Val))
427 return lookup(Val).count(BB);
430 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
431 // If already a constant, there is nothing to compute.
432 if (Constant *VC = dyn_cast<Constant>(Val))
433 return LVILatticeVal::get(VC);
435 return lookup(Val)[BB];
438 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
439 if (isa<Constant>(Val))
442 ValueCacheEntryTy &Cache = lookup(Val);
443 LVILatticeVal &BBLV = Cache[BB];
445 // If we've already computed this block's value, return it.
446 if (!BBLV.isUndefined()) {
447 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
451 // Otherwise, this is the first time we're seeing this block. Reset the
452 // lattice value to overdefined, so that cycles will terminate and be
453 // conservatively correct.
454 BBLV.markOverdefined();
456 Instruction *BBI = dyn_cast<Instruction>(Val);
457 if (BBI == 0 || BBI->getParent() != BB) {
458 return solveBlockValueNonLocal(Val, BB);
461 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
462 return solveBlockValuePHINode(PN, BB);
465 // We can only analyze the definitions of certain classes of instructions
466 // (integral binops and casts at the moment), so bail if this isn't one.
467 LVILatticeVal Result;
468 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
469 !BBI->getType()->isIntegerTy()) {
470 DEBUG(dbgs() << " compute BB '" << BB->getName()
471 << "' - overdefined because inst def found.\n");
472 Result.markOverdefined();
473 setBlockValue(Val, BB, Result, Cache);
477 // FIXME: We're currently limited to binops with a constant RHS. This should
479 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
480 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
481 DEBUG(dbgs() << " compute BB '" << BB->getName()
482 << "' - overdefined because inst def found.\n");
484 Result.markOverdefined();
485 setBlockValue(Val, BB, Result, Cache);
489 return solveBlockValueConstantRange(BBI, BB);
492 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
493 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
494 return L->getPointerAddressSpace() == 0 &&
495 GetUnderlyingObject(L->getPointerOperand()) ==
496 GetUnderlyingObject(Ptr);
498 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
499 return S->getPointerAddressSpace() == 0 &&
500 GetUnderlyingObject(S->getPointerOperand()) ==
501 GetUnderlyingObject(Ptr);
503 // FIXME: llvm.memset, etc.
507 bool LazyValueInfoCache::solveBlockValueNonLocal(Value *Val, BasicBlock *BB) {
508 LVILatticeVal Result; // Start Undefined.
510 // If this is a pointer, and there's a load from that pointer in this BB,
511 // then we know that the pointer can't be NULL.
512 bool NotNull = false;
513 if (Val->getType()->isPointerTy()) {
514 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
515 if (InstructionDereferencesPointer(BI, Val)) {
522 // If this is the entry block, we must be asking about an argument. The
523 // value is overdefined.
524 if (BB == &BB->getParent()->getEntryBlock()) {
525 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
527 const PointerType *PTy = cast<PointerType>(Val->getType());
528 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
530 Result.markOverdefined();
532 setBlockValue(Val, BB, Result);
536 // Loop over all of our predecessors, merging what we know from them into
538 bool EdgesMissing = false;
539 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
540 LVILatticeVal EdgeResult;
541 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
545 Result.mergeIn(EdgeResult);
547 // If we hit overdefined, exit early. The BlockVals entry is already set
549 if (Result.isOverdefined()) {
550 DEBUG(dbgs() << " compute BB '" << BB->getName()
551 << "' - overdefined because of pred.\n");
552 // If we previously determined that this is a pointer that can't be null
553 // then return that rather than giving up entirely.
555 const PointerType *PTy = cast<PointerType>(Val->getType());
556 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
558 setBlockValue(Val, BB, Result);
565 // Return the merged value, which is more precise than 'overdefined'.
566 assert(!Result.isOverdefined());
567 setBlockValue(Val, BB, Result);
571 bool LazyValueInfoCache::solveBlockValuePHINode(PHINode *PN, BasicBlock *BB) {
572 LVILatticeVal Result; // Start Undefined.
574 // Loop over all of our predecessors, merging what we know from them into
576 bool EdgesMissing = false;
577 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
578 BasicBlock *PhiBB = PN->getIncomingBlock(i);
579 Value *PhiVal = PN->getIncomingValue(i);
580 LVILatticeVal EdgeResult;
581 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
585 Result.mergeIn(EdgeResult);
587 // If we hit overdefined, exit early. The BlockVals entry is already set
589 if (Result.isOverdefined()) {
590 DEBUG(dbgs() << " compute BB '" << BB->getName()
591 << "' - overdefined because of pred.\n");
592 setBlockValue(PN, BB, Result);
599 // Return the merged value, which is more precise than 'overdefined'.
600 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
601 setBlockValue(PN, BB, Result);
605 bool LazyValueInfoCache::solveBlockValueConstantRange(Instruction *BBI,
607 // Figure out the range of the LHS. If that fails, bail.
608 if (!hasBlockValue(BBI->getOperand(0), BB)) {
609 block_value_stack.push(BlockStackEntry(BBI->getOperand(0), BB));
613 LVILatticeVal Result;
614 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
615 if (!LHSVal.isConstantRange()) {
616 Result.markOverdefined();
617 setBlockValue(BBI, BB, Result);
621 ConstantRange LHSRange = LHSVal.getConstantRange();
622 ConstantRange RHSRange(1);
623 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
624 if (isa<BinaryOperator>(BBI)) {
625 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
626 RHSRange = ConstantRange(RHS->getValue());
628 Result.markOverdefined();
629 setBlockValue(BBI, BB, Result);
634 // NOTE: We're currently limited by the set of operations that ConstantRange
635 // can evaluate symbolically. Enhancing that set will allows us to analyze
637 switch (BBI->getOpcode()) {
638 case Instruction::Add:
639 Result.markConstantRange(LHSRange.add(RHSRange));
641 case Instruction::Sub:
642 Result.markConstantRange(LHSRange.sub(RHSRange));
644 case Instruction::Mul:
645 Result.markConstantRange(LHSRange.multiply(RHSRange));
647 case Instruction::UDiv:
648 Result.markConstantRange(LHSRange.udiv(RHSRange));
650 case Instruction::Shl:
651 Result.markConstantRange(LHSRange.shl(RHSRange));
653 case Instruction::LShr:
654 Result.markConstantRange(LHSRange.lshr(RHSRange));
656 case Instruction::Trunc:
657 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
659 case Instruction::SExt:
660 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
662 case Instruction::ZExt:
663 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
665 case Instruction::BitCast:
666 Result.markConstantRange(LHSRange);
668 case Instruction::And:
669 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
671 case Instruction::Or:
672 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
675 // Unhandled instructions are overdefined.
677 DEBUG(dbgs() << " compute BB '" << BB->getName()
678 << "' - overdefined because inst def found.\n");
679 Result.markOverdefined();
683 setBlockValue(BBI, BB, Result);
687 /// getEdgeValue - This method attempts to infer more complex
688 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
689 BasicBlock *BBTo, LVILatticeVal &Result) {
690 // If already a constant, there is nothing to compute.
691 if (Constant *VC = dyn_cast<Constant>(Val)) {
692 Result = LVILatticeVal::get(VC);
696 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
698 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
699 // If this is a conditional branch and only one successor goes to BBTo, then
700 // we maybe able to infer something from the condition.
701 if (BI->isConditional() &&
702 BI->getSuccessor(0) != BI->getSuccessor(1)) {
703 bool isTrueDest = BI->getSuccessor(0) == BBTo;
704 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
705 "BBTo isn't a successor of BBFrom");
707 // If V is the condition of the branch itself, then we know exactly what
709 if (BI->getCondition() == Val) {
710 Result = LVILatticeVal::get(ConstantInt::get(
711 Type::getInt1Ty(Val->getContext()), isTrueDest));
715 // If the condition of the branch is an equality comparison, we may be
716 // able to infer the value.
717 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
718 if (ICI && ICI->getOperand(0) == Val &&
719 isa<Constant>(ICI->getOperand(1))) {
720 if (ICI->isEquality()) {
721 // We know that V has the RHS constant if this is a true SETEQ or
723 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
724 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
726 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
730 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
731 // Calculate the range of values that would satisfy the comparison.
732 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
733 ConstantRange TrueValues =
734 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
736 // If we're interested in the false dest, invert the condition.
737 if (!isTrueDest) TrueValues = TrueValues.inverse();
739 // Figure out the possible values of the query BEFORE this branch.
740 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
741 if (!InBlock.isConstantRange()) {
742 Result = LVILatticeVal::getRange(TrueValues);
746 // Find all potential values that satisfy both the input and output
748 ConstantRange PossibleValues =
749 TrueValues.intersectWith(InBlock.getConstantRange());
751 Result = LVILatticeVal::getRange(PossibleValues);
758 // If the edge was formed by a switch on the value, then we may know exactly
760 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
761 if (SI->getCondition() == Val) {
762 // We don't know anything in the default case.
763 if (SI->getDefaultDest() == BBTo) {
764 Result.markOverdefined();
768 // We only know something if there is exactly one value that goes from
770 unsigned NumEdges = 0;
771 ConstantInt *EdgeVal = 0;
772 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
773 if (SI->getSuccessor(i) != BBTo) continue;
774 if (NumEdges++) break;
775 EdgeVal = SI->getCaseValue(i);
777 assert(EdgeVal && "Missing successor?");
779 Result = LVILatticeVal::get(EdgeVal);
785 // Otherwise see if the value is known in the block.
786 if (hasBlockValue(Val, BBFrom)) {
787 Result = getBlockValue(Val, BBFrom);
790 block_value_stack.push(BlockStackEntry(Val, BBFrom));
794 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
795 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
796 << BB->getName() << "'\n");
798 block_value_stack.push(BlockStackEntry(V, BB));
800 LVILatticeVal Result = getBlockValue(V, BB);
802 DEBUG(dbgs() << " Result = " << Result << "\n");
806 LVILatticeVal LazyValueInfoCache::
807 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
808 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
809 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
811 LVILatticeVal Result;
812 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
814 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
816 assert(WasFastQuery && "More work to do after problem solved?");
819 DEBUG(dbgs() << " Result = " << Result << "\n");
823 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
824 BasicBlock *NewSucc) {
825 // When an edge in the graph has been threaded, values that we could not
826 // determine a value for before (i.e. were marked overdefined) may be possible
827 // to solve now. We do NOT try to proactively update these values. Instead,
828 // we clear their entries from the cache, and allow lazy updating to recompute
831 // The updating process is fairly simple: we need to dropped cached info
832 // for all values that were marked overdefined in OldSucc, and for those same
833 // values in any successor of OldSucc (except NewSucc) in which they were
834 // also marked overdefined.
835 std::vector<BasicBlock*> worklist;
836 worklist.push_back(OldSucc);
838 DenseSet<Value*> ClearSet;
839 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
840 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
841 if (I->first == OldSucc)
842 ClearSet.insert(I->second);
845 // Use a worklist to perform a depth-first search of OldSucc's successors.
846 // NOTE: We do not need a visited list since any blocks we have already
847 // visited will have had their overdefined markers cleared already, and we
848 // thus won't loop to their successors.
849 while (!worklist.empty()) {
850 BasicBlock *ToUpdate = worklist.back();
853 // Skip blocks only accessible through NewSucc.
854 if (ToUpdate == NewSucc) continue;
856 bool changed = false;
857 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
859 // If a value was marked overdefined in OldSucc, and is here too...
860 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
861 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
862 if (OI == OverDefinedCache.end()) continue;
864 // Remove it from the caches.
865 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
866 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
868 assert(CI != Entry.end() && "Couldn't find entry to update?");
870 OverDefinedCache.erase(OI);
872 // If we removed anything, then we potentially need to update
873 // blocks successors too.
877 if (!changed) continue;
879 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
883 //===----------------------------------------------------------------------===//
884 // LazyValueInfo Impl
885 //===----------------------------------------------------------------------===//
887 /// getCache - This lazily constructs the LazyValueInfoCache.
888 static LazyValueInfoCache &getCache(void *&PImpl) {
890 PImpl = new LazyValueInfoCache();
891 return *static_cast<LazyValueInfoCache*>(PImpl);
894 bool LazyValueInfo::runOnFunction(Function &F) {
896 getCache(PImpl).clear();
898 TD = getAnalysisIfAvailable<TargetData>();
903 void LazyValueInfo::releaseMemory() {
904 // If the cache was allocated, free it.
906 delete &getCache(PImpl);
911 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
912 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
914 if (Result.isConstant())
915 return Result.getConstant();
916 if (Result.isConstantRange()) {
917 ConstantRange CR = Result.getConstantRange();
918 if (const APInt *SingleVal = CR.getSingleElement())
919 return ConstantInt::get(V->getContext(), *SingleVal);
924 /// getConstantOnEdge - Determine whether the specified value is known to be a
925 /// constant on the specified edge. Return null if not.
926 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
928 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
930 if (Result.isConstant())
931 return Result.getConstant();
932 if (Result.isConstantRange()) {
933 ConstantRange CR = Result.getConstantRange();
934 if (const APInt *SingleVal = CR.getSingleElement())
935 return ConstantInt::get(V->getContext(), *SingleVal);
940 /// getPredicateOnEdge - Determine whether the specified value comparison
941 /// with a constant is known to be true or false on the specified CFG edge.
942 /// Pred is a CmpInst predicate.
943 LazyValueInfo::Tristate
944 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
945 BasicBlock *FromBB, BasicBlock *ToBB) {
946 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
948 // If we know the value is a constant, evaluate the conditional.
950 if (Result.isConstant()) {
951 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
952 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
953 return ResCI->isZero() ? False : True;
957 if (Result.isConstantRange()) {
958 ConstantInt *CI = dyn_cast<ConstantInt>(C);
959 if (!CI) return Unknown;
961 ConstantRange CR = Result.getConstantRange();
962 if (Pred == ICmpInst::ICMP_EQ) {
963 if (!CR.contains(CI->getValue()))
966 if (CR.isSingleElement() && CR.contains(CI->getValue()))
968 } else if (Pred == ICmpInst::ICMP_NE) {
969 if (!CR.contains(CI->getValue()))
972 if (CR.isSingleElement() && CR.contains(CI->getValue()))
976 // Handle more complex predicates.
977 ConstantRange TrueValues =
978 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
979 if (TrueValues.contains(CR))
981 if (TrueValues.inverse().contains(CR))
986 if (Result.isNotConstant()) {
987 // If this is an equality comparison, we can try to fold it knowing that
989 if (Pred == ICmpInst::ICMP_EQ) {
990 // !C1 == C -> false iff C1 == C.
991 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
992 Result.getNotConstant(), C, TD);
993 if (Res->isNullValue())
995 } else if (Pred == ICmpInst::ICMP_NE) {
996 // !C1 != C -> true iff C1 == C.
997 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
998 Result.getNotConstant(), C, TD);
999 if (Res->isNullValue())
1008 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1009 BasicBlock *NewSucc) {
1010 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1013 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1014 if (PImpl) getCache(PImpl).eraseBlock(BB);