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/IntrinsicInst.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetLibraryInfo.h"
24 #include "llvm/Support/CFG.h"
25 #include "llvm/Support/ConstantRange.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/ValueHandle.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/STLExtras.h"
35 char LazyValueInfo::ID = 0;
36 INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
37 "Lazy Value Information Analysis", false, true)
38 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
39 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
40 "Lazy Value Information Analysis", false, true)
43 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each
54 /// FIXME: This is basically just for bringup, this can be made a lot more rich
60 /// undefined - This Value has no known value yet.
63 /// constant - This Value has a specific constant value.
65 /// notconstant - This Value is known to not have the specified value.
68 /// constantrange - The Value falls within this range.
71 /// overdefined - This value is not known to be constant, and we know that
76 /// Val: This stores the current lattice value along with the Constant* for
77 /// the constant if this is a 'constant' or 'notconstant' value.
83 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
85 static LVILatticeVal get(Constant *C) {
87 if (!isa<UndefValue>(C))
91 static LVILatticeVal getNot(Constant *C) {
93 if (!isa<UndefValue>(C))
94 Res.markNotConstant(C);
97 static LVILatticeVal getRange(ConstantRange CR) {
99 Res.markConstantRange(CR);
103 bool isUndefined() const { return Tag == undefined; }
104 bool isConstant() const { return Tag == constant; }
105 bool isNotConstant() const { return Tag == notconstant; }
106 bool isConstantRange() const { return Tag == constantrange; }
107 bool isOverdefined() const { return Tag == overdefined; }
109 Constant *getConstant() const {
110 assert(isConstant() && "Cannot get the constant of a non-constant!");
114 Constant *getNotConstant() const {
115 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
119 ConstantRange getConstantRange() const {
120 assert(isConstantRange() &&
121 "Cannot get the constant-range of a non-constant-range!");
125 /// markOverdefined - Return true if this is a change in status.
126 bool markOverdefined() {
133 /// markConstant - Return true if this is a change in status.
134 bool markConstant(Constant *V) {
135 assert(V && "Marking constant with NULL");
136 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
137 return markConstantRange(ConstantRange(CI->getValue()));
138 if (isa<UndefValue>(V))
141 assert((!isConstant() || getConstant() == V) &&
142 "Marking constant with different value");
143 assert(isUndefined());
149 /// markNotConstant - Return true if this is a change in status.
150 bool markNotConstant(Constant *V) {
151 assert(V && "Marking constant with NULL");
152 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
153 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
154 if (isa<UndefValue>(V))
157 assert((!isConstant() || getConstant() != V) &&
158 "Marking constant !constant with same value");
159 assert((!isNotConstant() || getNotConstant() == V) &&
160 "Marking !constant with different value");
161 assert(isUndefined() || isConstant());
167 /// markConstantRange - Return true if this is a change in status.
168 bool markConstantRange(const ConstantRange NewR) {
169 if (isConstantRange()) {
170 if (NewR.isEmptySet())
171 return markOverdefined();
173 bool changed = Range == NewR;
178 assert(isUndefined());
179 if (NewR.isEmptySet())
180 return markOverdefined();
187 /// mergeIn - Merge the specified lattice value into this one, updating this
188 /// one and returning true if anything changed.
189 bool mergeIn(const LVILatticeVal &RHS) {
190 if (RHS.isUndefined() || isOverdefined()) return false;
191 if (RHS.isOverdefined()) return markOverdefined();
201 if (RHS.isConstant()) {
204 return markOverdefined();
207 if (RHS.isNotConstant()) {
209 return markOverdefined();
211 // Unless we can prove that the two Constants are different, we must
212 // move to overdefined.
213 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
214 if (ConstantInt *Res = dyn_cast<ConstantInt>(
215 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
217 RHS.getNotConstant())))
219 return markNotConstant(RHS.getNotConstant());
221 return markOverdefined();
224 // RHS is a ConstantRange, LHS is a non-integer Constant.
226 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
227 // a function. The correct result is to pick up RHS.
229 return markOverdefined();
232 if (isNotConstant()) {
233 if (RHS.isConstant()) {
235 return markOverdefined();
237 // Unless we can prove that the two Constants are different, we must
238 // move to overdefined.
239 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
240 if (ConstantInt *Res = dyn_cast<ConstantInt>(
241 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
247 return markOverdefined();
250 if (RHS.isNotConstant()) {
253 return markOverdefined();
256 return markOverdefined();
259 assert(isConstantRange() && "New LVILattice type?");
260 if (!RHS.isConstantRange())
261 return markOverdefined();
263 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
264 if (NewR.isFullSet())
265 return markOverdefined();
266 return markConstantRange(NewR);
270 } // end anonymous namespace.
273 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
275 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
276 if (Val.isUndefined())
277 return OS << "undefined";
278 if (Val.isOverdefined())
279 return OS << "overdefined";
281 if (Val.isNotConstant())
282 return OS << "notconstant<" << *Val.getNotConstant() << '>';
283 else if (Val.isConstantRange())
284 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
285 << Val.getConstantRange().getUpper() << '>';
286 return OS << "constant<" << *Val.getConstant() << '>';
290 //===----------------------------------------------------------------------===//
291 // LazyValueInfoCache Decl
292 //===----------------------------------------------------------------------===//
295 /// LVIValueHandle - A callback value handle update the cache when
296 /// values are erased.
297 class LazyValueInfoCache;
298 struct LVIValueHandle : public CallbackVH {
299 LazyValueInfoCache *Parent;
301 LVIValueHandle(Value *V, LazyValueInfoCache *P)
302 : CallbackVH(V), Parent(P) { }
305 void allUsesReplacedWith(Value *V) {
312 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
313 /// maintains information about queries across the clients' queries.
314 class LazyValueInfoCache {
315 /// ValueCacheEntryTy - This is all of the cached block information for
316 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
317 /// entries, allowing us to do a lookup with a binary search.
318 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
320 /// ValueCache - This is all of the cached information for all values,
321 /// mapped from Value* to key information.
322 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
324 /// OverDefinedCache - This tracks, on a per-block basis, the set of
325 /// values that are over-defined at the end of that block. This is required
326 /// for cache updating.
327 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
328 DenseSet<OverDefinedPairTy> OverDefinedCache;
330 /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
331 /// don't spend time removing unused blocks from our caches.
332 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
334 /// BlockValueStack - This stack holds the state of the value solver
335 /// during a query. It basically emulates the callstack of the naive
336 /// recursive value lookup process.
337 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
339 friend struct LVIValueHandle;
341 /// OverDefinedCacheUpdater - A helper object that ensures that the
342 /// OverDefinedCache is updated whenever solveBlockValue returns.
343 struct OverDefinedCacheUpdater {
344 LazyValueInfoCache *Parent;
349 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
350 LazyValueInfoCache *P)
351 : Parent(P), Val(V), BB(B), BBLV(LV) { }
353 bool markResult(bool changed) {
354 if (changed && BBLV.isOverdefined())
355 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
362 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
363 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
364 LVILatticeVal &Result);
365 bool hasBlockValue(Value *Val, BasicBlock *BB);
367 // These methods process one work item and may add more. A false value
368 // returned means that the work item was not completely processed and must
369 // be revisited after going through the new items.
370 bool solveBlockValue(Value *Val, BasicBlock *BB);
371 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
372 Value *Val, BasicBlock *BB);
373 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
374 PHINode *PN, BasicBlock *BB);
375 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
376 Instruction *BBI, BasicBlock *BB);
380 ValueCacheEntryTy &lookup(Value *V) {
381 return ValueCache[LVIValueHandle(V, this)];
385 /// getValueInBlock - This is the query interface to determine the lattice
386 /// value for the specified Value* at the end of the specified block.
387 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
389 /// getValueOnEdge - This is the query interface to determine the lattice
390 /// value for the specified Value* that is true on the specified edge.
391 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
393 /// threadEdge - This is the update interface to inform the cache that an
394 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
396 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
398 /// eraseBlock - This is part of the update interface to inform the cache
399 /// that a block has been deleted.
400 void eraseBlock(BasicBlock *BB);
402 /// clear - Empty the cache.
406 OverDefinedCache.clear();
409 } // end anonymous namespace
411 void LVIValueHandle::deleted() {
412 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
414 SmallVector<OverDefinedPairTy, 4> ToErase;
415 for (DenseSet<OverDefinedPairTy>::iterator
416 I = Parent->OverDefinedCache.begin(),
417 E = Parent->OverDefinedCache.end();
419 if (I->second == getValPtr())
420 ToErase.push_back(*I);
423 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
424 E = ToErase.end(); I != E; ++I)
425 Parent->OverDefinedCache.erase(*I);
427 // This erasure deallocates *this, so it MUST happen after we're done
428 // using any and all members of *this.
429 Parent->ValueCache.erase(*this);
432 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
433 // Shortcut if we have never seen this block.
434 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
435 if (I == SeenBlocks.end())
439 SmallVector<OverDefinedPairTy, 4> ToErase;
440 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
441 E = OverDefinedCache.end(); I != E; ++I) {
443 ToErase.push_back(*I);
446 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
447 E = ToErase.end(); I != E; ++I)
448 OverDefinedCache.erase(*I);
450 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
451 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
455 void LazyValueInfoCache::solve() {
456 while (!BlockValueStack.empty()) {
457 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
458 if (solveBlockValue(e.second, e.first))
459 BlockValueStack.pop();
463 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
464 // If already a constant, there is nothing to compute.
465 if (isa<Constant>(Val))
468 LVIValueHandle ValHandle(Val, this);
469 if (!ValueCache.count(ValHandle)) return false;
470 return ValueCache[ValHandle].count(BB);
473 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
474 // If already a constant, there is nothing to compute.
475 if (Constant *VC = dyn_cast<Constant>(Val))
476 return LVILatticeVal::get(VC);
478 SeenBlocks.insert(BB);
479 return lookup(Val)[BB];
482 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
483 if (isa<Constant>(Val))
486 ValueCacheEntryTy &Cache = lookup(Val);
487 SeenBlocks.insert(BB);
488 LVILatticeVal &BBLV = Cache[BB];
490 // OverDefinedCacheUpdater is a helper object that will update
491 // the OverDefinedCache for us when this method exits. Make sure to
492 // call markResult on it as we exist, passing a bool to indicate if the
493 // cache needs updating, i.e. if we have solve a new value or not.
494 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
496 // If we've already computed this block's value, return it.
497 if (!BBLV.isUndefined()) {
498 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
500 // Since we're reusing a cached value here, we don't need to update the
501 // OverDefinedCahce. The cache will have been properly updated
502 // whenever the cached value was inserted.
503 ODCacheUpdater.markResult(false);
507 // Otherwise, this is the first time we're seeing this block. Reset the
508 // lattice value to overdefined, so that cycles will terminate and be
509 // conservatively correct.
510 BBLV.markOverdefined();
512 Instruction *BBI = dyn_cast<Instruction>(Val);
513 if (BBI == 0 || BBI->getParent() != BB) {
514 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
517 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
518 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
521 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
522 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
523 return ODCacheUpdater.markResult(true);
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 BBLV.markOverdefined();
534 return ODCacheUpdater.markResult(true);
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 BBLV.markOverdefined();
545 return ODCacheUpdater.markResult(true);
548 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
551 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
552 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
553 return L->getPointerAddressSpace() == 0 &&
554 GetUnderlyingObject(L->getPointerOperand()) ==
555 GetUnderlyingObject(Ptr);
557 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
558 return S->getPointerAddressSpace() == 0 &&
559 GetUnderlyingObject(S->getPointerOperand()) ==
560 GetUnderlyingObject(Ptr);
562 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
563 if (MI->isVolatile()) return false;
565 // FIXME: check whether it has a valuerange that excludes zero?
566 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
567 if (!Len || Len->isZero()) return false;
569 if (MI->getDestAddressSpace() == 0)
570 if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
572 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
573 if (MTI->getSourceAddressSpace() == 0)
574 if (MTI->getRawSource() == Ptr || MTI->getSource() == Ptr)
580 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
581 Value *Val, BasicBlock *BB) {
582 LVILatticeVal Result; // Start Undefined.
584 // If this is a pointer, and there's a load from that pointer in this BB,
585 // then we know that the pointer can't be NULL.
586 bool NotNull = false;
587 if (Val->getType()->isPointerTy()) {
588 if (isa<AllocaInst>(Val)) {
591 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
592 if (InstructionDereferencesPointer(BI, Val)) {
600 // If this is the entry block, we must be asking about an argument. The
601 // value is overdefined.
602 if (BB == &BB->getParent()->getEntryBlock()) {
603 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
605 PointerType *PTy = cast<PointerType>(Val->getType());
606 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
608 Result.markOverdefined();
614 // Loop over all of our predecessors, merging what we know from them into
616 bool EdgesMissing = false;
617 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
618 LVILatticeVal EdgeResult;
619 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
623 Result.mergeIn(EdgeResult);
625 // If we hit overdefined, exit early. The BlockVals entry is already set
627 if (Result.isOverdefined()) {
628 DEBUG(dbgs() << " compute BB '" << BB->getName()
629 << "' - overdefined because of pred.\n");
630 // If we previously determined that this is a pointer that can't be null
631 // then return that rather than giving up entirely.
633 PointerType *PTy = cast<PointerType>(Val->getType());
634 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
644 // Return the merged value, which is more precise than 'overdefined'.
645 assert(!Result.isOverdefined());
650 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
651 PHINode *PN, BasicBlock *BB) {
652 LVILatticeVal Result; // Start Undefined.
654 // Loop over all of our predecessors, merging what we know from them into
656 bool EdgesMissing = false;
657 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
658 BasicBlock *PhiBB = PN->getIncomingBlock(i);
659 Value *PhiVal = PN->getIncomingValue(i);
660 LVILatticeVal EdgeResult;
661 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
665 Result.mergeIn(EdgeResult);
667 // If we hit overdefined, exit early. The BlockVals entry is already set
669 if (Result.isOverdefined()) {
670 DEBUG(dbgs() << " compute BB '" << BB->getName()
671 << "' - overdefined because of pred.\n");
680 // Return the merged value, which is more precise than 'overdefined'.
681 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
686 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
689 // Figure out the range of the LHS. If that fails, bail.
690 if (!hasBlockValue(BBI->getOperand(0), BB)) {
691 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
695 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
696 if (!LHSVal.isConstantRange()) {
697 BBLV.markOverdefined();
701 ConstantRange LHSRange = LHSVal.getConstantRange();
702 ConstantRange RHSRange(1);
703 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
704 if (isa<BinaryOperator>(BBI)) {
705 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
706 RHSRange = ConstantRange(RHS->getValue());
708 BBLV.markOverdefined();
713 // NOTE: We're currently limited by the set of operations that ConstantRange
714 // can evaluate symbolically. Enhancing that set will allows us to analyze
716 LVILatticeVal Result;
717 switch (BBI->getOpcode()) {
718 case Instruction::Add:
719 Result.markConstantRange(LHSRange.add(RHSRange));
721 case Instruction::Sub:
722 Result.markConstantRange(LHSRange.sub(RHSRange));
724 case Instruction::Mul:
725 Result.markConstantRange(LHSRange.multiply(RHSRange));
727 case Instruction::UDiv:
728 Result.markConstantRange(LHSRange.udiv(RHSRange));
730 case Instruction::Shl:
731 Result.markConstantRange(LHSRange.shl(RHSRange));
733 case Instruction::LShr:
734 Result.markConstantRange(LHSRange.lshr(RHSRange));
736 case Instruction::Trunc:
737 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
739 case Instruction::SExt:
740 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
742 case Instruction::ZExt:
743 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
745 case Instruction::BitCast:
746 Result.markConstantRange(LHSRange);
748 case Instruction::And:
749 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
751 case Instruction::Or:
752 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
755 // Unhandled instructions are overdefined.
757 DEBUG(dbgs() << " compute BB '" << BB->getName()
758 << "' - overdefined because inst def found.\n");
759 Result.markOverdefined();
767 /// getEdgeValue - This method attempts to infer more complex
768 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
769 BasicBlock *BBTo, LVILatticeVal &Result) {
770 // If already a constant, there is nothing to compute.
771 if (Constant *VC = dyn_cast<Constant>(Val)) {
772 Result = LVILatticeVal::get(VC);
776 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
778 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
779 // If this is a conditional branch and only one successor goes to BBTo, then
780 // we maybe able to infer something from the condition.
781 if (BI->isConditional() &&
782 BI->getSuccessor(0) != BI->getSuccessor(1)) {
783 bool isTrueDest = BI->getSuccessor(0) == BBTo;
784 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
785 "BBTo isn't a successor of BBFrom");
787 // If V is the condition of the branch itself, then we know exactly what
789 if (BI->getCondition() == Val) {
790 Result = LVILatticeVal::get(ConstantInt::get(
791 Type::getInt1Ty(Val->getContext()), isTrueDest));
795 // If the condition of the branch is an equality comparison, we may be
796 // able to infer the value.
797 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
798 if (ICI && ICI->getOperand(0) == Val &&
799 isa<Constant>(ICI->getOperand(1))) {
800 if (ICI->isEquality()) {
801 // We know that V has the RHS constant if this is a true SETEQ or
803 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
804 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
806 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
810 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
811 // Calculate the range of values that would satisfy the comparison.
812 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
813 ConstantRange TrueValues =
814 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
816 // If we're interested in the false dest, invert the condition.
817 if (!isTrueDest) TrueValues = TrueValues.inverse();
819 // Figure out the possible values of the query BEFORE this branch.
820 if (!hasBlockValue(Val, BBFrom)) {
821 BlockValueStack.push(std::make_pair(BBFrom, Val));
825 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
826 if (!InBlock.isConstantRange()) {
827 Result = LVILatticeVal::getRange(TrueValues);
831 // Find all potential values that satisfy both the input and output
833 ConstantRange PossibleValues =
834 TrueValues.intersectWith(InBlock.getConstantRange());
836 Result = LVILatticeVal::getRange(PossibleValues);
843 // If the edge was formed by a switch on the value, then we may know exactly
845 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
846 if (SI->getCondition() == Val) {
847 // We don't know anything in the default case.
848 if (SI->getDefaultDest() == BBTo) {
849 Result.markOverdefined();
853 // We only know something if there is exactly one value that goes from
855 unsigned NumEdges = 0;
856 ConstantInt *EdgeVal = 0;
857 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
858 if (SI->getSuccessor(i) != BBTo) continue;
859 if (NumEdges++) break;
860 EdgeVal = SI->getCaseValue(i);
862 assert(EdgeVal && "Missing successor?");
864 Result = LVILatticeVal::get(EdgeVal);
870 // Otherwise see if the value is known in the block.
871 if (hasBlockValue(Val, BBFrom)) {
872 Result = getBlockValue(Val, BBFrom);
875 BlockValueStack.push(std::make_pair(BBFrom, Val));
879 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
880 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
881 << BB->getName() << "'\n");
883 BlockValueStack.push(std::make_pair(BB, V));
885 LVILatticeVal Result = getBlockValue(V, BB);
887 DEBUG(dbgs() << " Result = " << Result << "\n");
891 LVILatticeVal LazyValueInfoCache::
892 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
893 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
894 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
896 LVILatticeVal Result;
897 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
899 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
901 assert(WasFastQuery && "More work to do after problem solved?");
904 DEBUG(dbgs() << " Result = " << Result << "\n");
908 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
909 BasicBlock *NewSucc) {
910 // When an edge in the graph has been threaded, values that we could not
911 // determine a value for before (i.e. were marked overdefined) may be possible
912 // to solve now. We do NOT try to proactively update these values. Instead,
913 // we clear their entries from the cache, and allow lazy updating to recompute
916 // The updating process is fairly simple: we need to dropped cached info
917 // for all values that were marked overdefined in OldSucc, and for those same
918 // values in any successor of OldSucc (except NewSucc) in which they were
919 // also marked overdefined.
920 std::vector<BasicBlock*> worklist;
921 worklist.push_back(OldSucc);
923 DenseSet<Value*> ClearSet;
924 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
925 E = OverDefinedCache.end(); I != E; ++I) {
926 if (I->first == OldSucc)
927 ClearSet.insert(I->second);
930 // Use a worklist to perform a depth-first search of OldSucc's successors.
931 // NOTE: We do not need a visited list since any blocks we have already
932 // visited will have had their overdefined markers cleared already, and we
933 // thus won't loop to their successors.
934 while (!worklist.empty()) {
935 BasicBlock *ToUpdate = worklist.back();
938 // Skip blocks only accessible through NewSucc.
939 if (ToUpdate == NewSucc) continue;
941 bool changed = false;
942 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
944 // If a value was marked overdefined in OldSucc, and is here too...
945 DenseSet<OverDefinedPairTy>::iterator OI =
946 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
947 if (OI == OverDefinedCache.end()) continue;
949 // Remove it from the caches.
950 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
951 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
953 assert(CI != Entry.end() && "Couldn't find entry to update?");
955 OverDefinedCache.erase(OI);
957 // If we removed anything, then we potentially need to update
958 // blocks successors too.
962 if (!changed) continue;
964 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
968 //===----------------------------------------------------------------------===//
969 // LazyValueInfo Impl
970 //===----------------------------------------------------------------------===//
972 /// getCache - This lazily constructs the LazyValueInfoCache.
973 static LazyValueInfoCache &getCache(void *&PImpl) {
975 PImpl = new LazyValueInfoCache();
976 return *static_cast<LazyValueInfoCache*>(PImpl);
979 bool LazyValueInfo::runOnFunction(Function &F) {
981 getCache(PImpl).clear();
983 TD = getAnalysisIfAvailable<TargetData>();
984 TLI = &getAnalysis<TargetLibraryInfo>();
990 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
991 AU.setPreservesAll();
992 AU.addRequired<TargetLibraryInfo>();
995 void LazyValueInfo::releaseMemory() {
996 // If the cache was allocated, free it.
998 delete &getCache(PImpl);
1003 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1004 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1006 if (Result.isConstant())
1007 return Result.getConstant();
1008 if (Result.isConstantRange()) {
1009 ConstantRange CR = Result.getConstantRange();
1010 if (const APInt *SingleVal = CR.getSingleElement())
1011 return ConstantInt::get(V->getContext(), *SingleVal);
1016 /// getConstantOnEdge - Determine whether the specified value is known to be a
1017 /// constant on the specified edge. Return null if not.
1018 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1020 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1022 if (Result.isConstant())
1023 return Result.getConstant();
1024 if (Result.isConstantRange()) {
1025 ConstantRange CR = Result.getConstantRange();
1026 if (const APInt *SingleVal = CR.getSingleElement())
1027 return ConstantInt::get(V->getContext(), *SingleVal);
1032 /// getPredicateOnEdge - Determine whether the specified value comparison
1033 /// with a constant is known to be true or false on the specified CFG edge.
1034 /// Pred is a CmpInst predicate.
1035 LazyValueInfo::Tristate
1036 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1037 BasicBlock *FromBB, BasicBlock *ToBB) {
1038 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
1040 // If we know the value is a constant, evaluate the conditional.
1042 if (Result.isConstant()) {
1043 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD,
1045 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1046 return ResCI->isZero() ? False : True;
1050 if (Result.isConstantRange()) {
1051 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1052 if (!CI) return Unknown;
1054 ConstantRange CR = Result.getConstantRange();
1055 if (Pred == ICmpInst::ICMP_EQ) {
1056 if (!CR.contains(CI->getValue()))
1059 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1061 } else if (Pred == ICmpInst::ICMP_NE) {
1062 if (!CR.contains(CI->getValue()))
1065 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1069 // Handle more complex predicates.
1070 ConstantRange TrueValues =
1071 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1072 if (TrueValues.contains(CR))
1074 if (TrueValues.inverse().contains(CR))
1079 if (Result.isNotConstant()) {
1080 // If this is an equality comparison, we can try to fold it knowing that
1082 if (Pred == ICmpInst::ICMP_EQ) {
1083 // !C1 == C -> false iff C1 == C.
1084 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1085 Result.getNotConstant(), C, TD,
1087 if (Res->isNullValue())
1089 } else if (Pred == ICmpInst::ICMP_NE) {
1090 // !C1 != C -> true iff C1 == C.
1091 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1092 Result.getNotConstant(), C, TD,
1094 if (Res->isNullValue())
1103 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1104 BasicBlock *NewSucc) {
1105 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1108 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1109 if (PImpl) getCache(PImpl).eraseBlock(BB);