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();
182 /// mergeIn - Merge the specified lattice value into this one, updating this
183 /// one and returning true if anything changed.
184 bool mergeIn(const LVILatticeVal &RHS) {
185 if (RHS.isUndefined() || isOverdefined()) return false;
186 if (RHS.isOverdefined()) return markOverdefined();
188 if (RHS.isNotConstant()) {
189 if (isNotConstant()) {
190 if (getNotConstant() != RHS.getNotConstant() ||
191 isa<ConstantExpr>(getNotConstant()) ||
192 isa<ConstantExpr>(RHS.getNotConstant()))
193 return markOverdefined();
195 } else if (isConstant()) {
196 if (getConstant() == RHS.getNotConstant() ||
197 isa<ConstantExpr>(RHS.getNotConstant()) ||
198 isa<ConstantExpr>(getConstant()))
199 return markOverdefined();
200 return markNotConstant(RHS.getNotConstant());
201 } else if (isConstantRange()) {
202 return markOverdefined();
205 assert(isUndefined() && "Unexpected lattice");
206 return markNotConstant(RHS.getNotConstant());
209 if (RHS.isConstantRange()) {
210 if (isConstantRange()) {
211 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
212 if (NewR.isFullSet())
213 return markOverdefined();
215 return markConstantRange(NewR);
216 } else if (!isUndefined()) {
217 return markOverdefined();
220 assert(isUndefined() && "Unexpected lattice");
221 return markConstantRange(RHS.getConstantRange());
224 // RHS must be a constant, we must be undef, constant, or notconstant.
225 assert(!isConstantRange() &&
226 "Constant and ConstantRange cannot be merged.");
229 return markConstant(RHS.getConstant());
232 if (getConstant() != RHS.getConstant())
233 return markOverdefined();
237 // If we are known "!=4" and RHS is "==5", stay at "!=4".
238 if (getNotConstant() == RHS.getConstant() ||
239 isa<ConstantExpr>(getNotConstant()) ||
240 isa<ConstantExpr>(RHS.getConstant()))
241 return markOverdefined();
247 } // end anonymous namespace.
250 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
251 if (Val.isUndefined())
252 return OS << "undefined";
253 if (Val.isOverdefined())
254 return OS << "overdefined";
256 if (Val.isNotConstant())
257 return OS << "notconstant<" << *Val.getNotConstant() << '>';
258 else if (Val.isConstantRange())
259 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
260 << Val.getConstantRange().getUpper() << '>';
261 return OS << "constant<" << *Val.getConstant() << '>';
265 //===----------------------------------------------------------------------===//
266 // LazyValueInfoCache Decl
267 //===----------------------------------------------------------------------===//
270 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
271 /// maintains information about queries across the clients' queries.
272 class LazyValueInfoCache {
274 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
275 /// specified basic block for a Value* that depends on context.
276 typedef std::pair<AssertingVH<BasicBlock>, LVILatticeVal> BlockCacheEntryTy;
278 /// ValueCacheEntryTy - This is all of the cached block information for
279 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
280 /// entries, allowing us to do a lookup with a binary search.
281 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
284 /// LVIValueHandle - A callback value handle update the cache when
285 /// values are erased.
286 struct LVIValueHandle : public CallbackVH {
287 LazyValueInfoCache *Parent;
289 LVIValueHandle(Value *V, LazyValueInfoCache *P)
290 : CallbackVH(V), Parent(P) { }
293 void allUsesReplacedWith(Value* V) {
297 LVIValueHandle &operator=(Value *V) {
298 return *this = LVIValueHandle(V, Parent);
302 /// ValueCache - This is all of the cached information for all values,
303 /// mapped from Value* to key information.
304 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
306 /// OverDefinedCache - This tracks, on a per-block basis, the set of
307 /// values that are over-defined at the end of that block. This is required
308 /// for cache updating.
309 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
313 /// getValueInBlock - This is the query interface to determine the lattice
314 /// value for the specified Value* at the end of the specified block.
315 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
317 /// getValueOnEdge - This is the query interface to determine the lattice
318 /// value for the specified Value* that is true on the specified edge.
319 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
321 /// threadEdge - This is the update interface to inform the cache that an
322 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
324 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
326 /// eraseBlock - This is part of the update interface to inform the cache
327 /// that a block has been deleted.
328 void eraseBlock(BasicBlock *BB);
330 /// clear - Empty the cache.
333 OverDefinedCache.clear();
336 } // end anonymous namespace
338 //===----------------------------------------------------------------------===//
340 //===----------------------------------------------------------------------===//
343 /// LVIQuery - This is a transient object that exists while a query is
346 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
347 /// reallocation of the densemap on every query.
349 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
350 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
352 /// This is the current value being queried for.
355 /// This is a pointer to the owning cache, for recursive queries.
356 LazyValueInfoCache &Parent;
358 /// This is all of the cached information about this value.
359 ValueCacheEntryTy &Cache;
361 /// This tracks, for each block, what values are overdefined.
362 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &OverDefinedCache;
364 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
365 /// added to cache but that are not in sorted order.
366 DenseSet<BasicBlock*> NewBlockInfo;
370 LVIQuery(Value *V, LazyValueInfoCache &P,
371 ValueCacheEntryTy &VC,
372 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &ODC)
373 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
377 // When the query is done, insert the newly discovered facts into the
378 // cache in sorted order.
379 if (NewBlockInfo.empty()) return;
381 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
382 E = NewBlockInfo.end(); I != E; ++I) {
383 if (Cache[*I].isOverdefined())
384 OverDefinedCache.insert(std::make_pair(*I, Val));
388 LVILatticeVal getBlockValue(BasicBlock *BB);
389 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
392 LVILatticeVal getCachedEntryForBlock(BasicBlock *BB);
394 } // end anonymous namespace
396 void LazyValueInfoCache::LVIValueHandle::deleted() {
397 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
398 I = Parent->OverDefinedCache.begin(),
399 E = Parent->OverDefinedCache.end();
401 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
403 if (tmp->second == getValPtr())
404 Parent->OverDefinedCache.erase(tmp);
407 // This erasure deallocates *this, so it MUST happen after we're done
408 // using any and all members of *this.
409 Parent->ValueCache.erase(*this);
412 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
413 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
414 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
415 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
417 if (tmp->first == BB)
418 OverDefinedCache.erase(tmp);
421 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
422 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
426 /// getCachedEntryForBlock - See if we already have a value for this block. If
427 /// so, return it, otherwise create a new entry in the Cache map to use.
428 LVILatticeVal LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
429 NewBlockInfo.insert(BB);
433 LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
434 // See if we already have a value for this block.
435 LVILatticeVal BBLV = getCachedEntryForBlock(BB);
437 // If we've already computed this block's value, return it.
438 if (!BBLV.isUndefined()) {
439 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
443 // Otherwise, this is the first time we're seeing this block. Reset the
444 // lattice value to overdefined, so that cycles will terminate and be
445 // conservatively correct.
446 BBLV.markOverdefined();
449 Instruction *BBI = dyn_cast<Instruction>(Val);
450 if (BBI == 0 || BBI->getParent() != BB) {
451 LVILatticeVal Result; // Start Undefined.
453 // If this is a pointer, and there's a load from that pointer in this BB,
454 // then we know that the pointer can't be NULL.
455 bool NotNull = false;
456 if (Val->getType()->isPointerTy()) {
457 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
458 LoadInst *L = dyn_cast<LoadInst>(BI);
459 if (L && L->getPointerAddressSpace() == 0 &&
460 L->getPointerOperand()->getUnderlyingObject() ==
461 Val->getUnderlyingObject()) {
468 unsigned NumPreds = 0;
469 // Loop over all of our predecessors, merging what we know from them into
471 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
472 Result.mergeIn(getEdgeValue(*PI, BB));
474 // If we hit overdefined, exit early. The BlockVals entry is already set
476 if (Result.isOverdefined()) {
477 DEBUG(dbgs() << " compute BB '" << BB->getName()
478 << "' - overdefined because of pred.\n");
479 // If we previously determined that this is a pointer that can't be null
480 // then return that rather than giving up entirely.
482 const PointerType *PTy = cast<PointerType>(Val->getType());
483 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
492 // If this is the entry block, we must be asking about an argument. The
493 // value is overdefined.
494 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
495 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
496 Result.markOverdefined();
500 // Return the merged value, which is more precise than 'overdefined'.
501 assert(!Result.isOverdefined());
502 return Cache[BB] = Result;
505 // If this value is defined by an instruction in this block, we have to
506 // process it here somehow or return overdefined.
507 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
508 LVILatticeVal Result; // Start Undefined.
510 // Loop over all of our predecessors, merging what we know from them into
512 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
513 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
514 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
516 // If we hit overdefined, exit early. The BlockVals entry is already set
518 if (Result.isOverdefined()) {
519 DEBUG(dbgs() << " compute BB '" << BB->getName()
520 << "' - overdefined because of pred.\n");
525 // Return the merged value, which is more precise than 'overdefined'.
526 assert(!Result.isOverdefined());
527 return Cache[BB] = Result;
530 assert(Cache[BB].isOverdefined() && "Recursive query changed our cache?");
532 // We can only analyze the definitions of certain classes of instructions
533 // (integral binops and casts at the moment), so bail if this isn't one.
534 LVILatticeVal Result;
535 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
536 !BBI->getType()->isIntegerTy()) {
537 DEBUG(dbgs() << " compute BB '" << BB->getName()
538 << "' - overdefined because inst def found.\n");
539 Result.markOverdefined();
543 // FIXME: We're currently limited to binops with a constant RHS. This should
545 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
546 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
547 DEBUG(dbgs() << " compute BB '" << BB->getName()
548 << "' - overdefined because inst def found.\n");
550 Result.markOverdefined();
554 // Figure out the range of the LHS. If that fails, bail.
555 LVILatticeVal LHSVal = Parent.getValueInBlock(BBI->getOperand(0), BB);
556 if (!LHSVal.isConstantRange()) {
557 Result.markOverdefined();
561 ConstantInt *RHS = 0;
562 ConstantRange LHSRange = LHSVal.getConstantRange();
563 ConstantRange RHSRange(1);
564 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
565 if (isa<BinaryOperator>(BBI)) {
566 RHS = dyn_cast<ConstantInt>(BBI->getOperand(1));
568 Result.markOverdefined();
572 RHSRange = ConstantRange(RHS->getValue(), RHS->getValue()+1);
575 // NOTE: We're currently limited by the set of operations that ConstantRange
576 // can evaluate symbolically. Enhancing that set will allows us to analyze
578 switch (BBI->getOpcode()) {
579 case Instruction::Add:
580 Result.markConstantRange(LHSRange.add(RHSRange));
582 case Instruction::Sub:
583 Result.markConstantRange(LHSRange.sub(RHSRange));
585 case Instruction::Mul:
586 Result.markConstantRange(LHSRange.multiply(RHSRange));
588 case Instruction::UDiv:
589 Result.markConstantRange(LHSRange.udiv(RHSRange));
591 case Instruction::Shl:
592 Result.markConstantRange(LHSRange.shl(RHSRange));
594 case Instruction::LShr:
595 Result.markConstantRange(LHSRange.lshr(RHSRange));
597 case Instruction::Trunc:
598 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
600 case Instruction::SExt:
601 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
603 case Instruction::ZExt:
604 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
606 case Instruction::BitCast:
607 Result.markConstantRange(LHSRange);
610 // Unhandled instructions are overdefined.
612 DEBUG(dbgs() << " compute BB '" << BB->getName()
613 << "' - overdefined because inst def found.\n");
614 Result.markOverdefined();
618 return Cache[BB] = Result;
622 /// getEdgeValue - This method attempts to infer more complex
623 LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
624 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
626 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
627 // If this is a conditional branch and only one successor goes to BBTo, then
628 // we maybe able to infer something from the condition.
629 if (BI->isConditional() &&
630 BI->getSuccessor(0) != BI->getSuccessor(1)) {
631 bool isTrueDest = BI->getSuccessor(0) == BBTo;
632 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
633 "BBTo isn't a successor of BBFrom");
635 // If V is the condition of the branch itself, then we know exactly what
637 if (BI->getCondition() == Val)
638 return LVILatticeVal::get(ConstantInt::get(
639 Type::getInt1Ty(Val->getContext()), isTrueDest));
641 // If the condition of the branch is an equality comparison, we may be
642 // able to infer the value.
643 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
644 if (ICI && ICI->getOperand(0) == Val &&
645 isa<Constant>(ICI->getOperand(1))) {
646 if (ICI->isEquality()) {
647 // We know that V has the RHS constant if this is a true SETEQ or
649 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
650 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
651 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
654 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
655 // Calculate the range of values that would satisfy the comparison.
656 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
657 ConstantRange TrueValues =
658 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
660 // If we're interested in the false dest, invert the condition.
661 if (!isTrueDest) TrueValues = TrueValues.inverse();
663 // Figure out the possible values of the query BEFORE this branch.
664 LVILatticeVal InBlock = getBlockValue(BBFrom);
665 if (!InBlock.isConstantRange())
666 return LVILatticeVal::getRange(TrueValues);
668 // Find all potential values that satisfy both the input and output
670 ConstantRange PossibleValues =
671 TrueValues.intersectWith(InBlock.getConstantRange());
673 return LVILatticeVal::getRange(PossibleValues);
679 // If the edge was formed by a switch on the value, then we may know exactly
681 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
682 if (SI->getCondition() == Val) {
683 // We don't know anything in the default case.
684 if (SI->getDefaultDest() == BBTo) {
685 LVILatticeVal Result;
686 Result.markOverdefined();
690 // We only know something if there is exactly one value that goes from
692 unsigned NumEdges = 0;
693 ConstantInt *EdgeVal = 0;
694 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
695 if (SI->getSuccessor(i) != BBTo) continue;
696 if (NumEdges++) break;
697 EdgeVal = SI->getCaseValue(i);
699 assert(EdgeVal && "Missing successor?");
701 return LVILatticeVal::get(EdgeVal);
705 // Otherwise see if the value is known in the block.
706 return getBlockValue(BBFrom);
710 //===----------------------------------------------------------------------===//
711 // LazyValueInfoCache Impl
712 //===----------------------------------------------------------------------===//
714 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
715 // If already a constant, there is nothing to compute.
716 if (Constant *VC = dyn_cast<Constant>(V))
717 return LVILatticeVal::get(VC);
719 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
720 << BB->getName() << "'\n");
722 LVILatticeVal Result = LVIQuery(V, *this,
723 ValueCache[LVIValueHandle(V, this)],
724 OverDefinedCache).getBlockValue(BB);
726 DEBUG(dbgs() << " Result = " << Result << "\n");
730 LVILatticeVal LazyValueInfoCache::
731 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
732 // If already a constant, there is nothing to compute.
733 if (Constant *VC = dyn_cast<Constant>(V))
734 return LVILatticeVal::get(VC);
736 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
737 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
739 LVILatticeVal Result =
740 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
741 OverDefinedCache).getEdgeValue(FromBB, ToBB);
743 DEBUG(dbgs() << " Result = " << Result << "\n");
748 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
749 BasicBlock *NewSucc) {
750 // When an edge in the graph has been threaded, values that we could not
751 // determine a value for before (i.e. were marked overdefined) may be possible
752 // to solve now. We do NOT try to proactively update these values. Instead,
753 // we clear their entries from the cache, and allow lazy updating to recompute
756 // The updating process is fairly simple: we need to dropped cached info
757 // for all values that were marked overdefined in OldSucc, and for those same
758 // values in any successor of OldSucc (except NewSucc) in which they were
759 // also marked overdefined.
760 std::vector<BasicBlock*> worklist;
761 worklist.push_back(OldSucc);
763 DenseSet<Value*> ClearSet;
764 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
765 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
766 if (I->first == OldSucc)
767 ClearSet.insert(I->second);
770 // Use a worklist to perform a depth-first search of OldSucc's successors.
771 // NOTE: We do not need a visited list since any blocks we have already
772 // visited will have had their overdefined markers cleared already, and we
773 // thus won't loop to their successors.
774 while (!worklist.empty()) {
775 BasicBlock *ToUpdate = worklist.back();
778 // Skip blocks only accessible through NewSucc.
779 if (ToUpdate == NewSucc) continue;
781 bool changed = false;
782 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
784 // If a value was marked overdefined in OldSucc, and is here too...
785 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
786 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
787 if (OI == OverDefinedCache.end()) continue;
789 // Remove it from the caches.
790 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
791 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
793 assert(CI != Entry.end() && "Couldn't find entry to update?");
795 OverDefinedCache.erase(OI);
797 // If we removed anything, then we potentially need to update
798 // blocks successors too.
802 if (!changed) continue;
804 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
808 //===----------------------------------------------------------------------===//
809 // LazyValueInfo Impl
810 //===----------------------------------------------------------------------===//
812 /// getCache - This lazily constructs the LazyValueInfoCache.
813 static LazyValueInfoCache &getCache(void *&PImpl) {
815 PImpl = new LazyValueInfoCache();
816 return *static_cast<LazyValueInfoCache*>(PImpl);
819 bool LazyValueInfo::runOnFunction(Function &F) {
821 getCache(PImpl).clear();
823 TD = getAnalysisIfAvailable<TargetData>();
828 void LazyValueInfo::releaseMemory() {
829 // If the cache was allocated, free it.
831 delete &getCache(PImpl);
836 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
837 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
839 if (Result.isConstant())
840 return Result.getConstant();
841 else if (Result.isConstantRange()) {
842 ConstantRange CR = Result.getConstantRange();
843 if (const APInt *SingleVal = CR.getSingleElement())
844 return ConstantInt::get(V->getContext(), *SingleVal);
849 /// getConstantOnEdge - Determine whether the specified value is known to be a
850 /// constant on the specified edge. Return null if not.
851 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
853 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
855 if (Result.isConstant())
856 return Result.getConstant();
857 else if (Result.isConstantRange()) {
858 ConstantRange CR = Result.getConstantRange();
859 if (const APInt *SingleVal = CR.getSingleElement())
860 return ConstantInt::get(V->getContext(), *SingleVal);
865 /// getPredicateOnEdge - Determine whether the specified value comparison
866 /// with a constant is known to be true or false on the specified CFG edge.
867 /// Pred is a CmpInst predicate.
868 LazyValueInfo::Tristate
869 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
870 BasicBlock *FromBB, BasicBlock *ToBB) {
871 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
873 // If we know the value is a constant, evaluate the conditional.
875 if (Result.isConstant()) {
876 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
877 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
878 return ResCI->isZero() ? False : True;
882 if (Result.isConstantRange()) {
883 ConstantInt *CI = dyn_cast<ConstantInt>(C);
884 if (!CI) return Unknown;
886 ConstantRange CR = Result.getConstantRange();
887 if (Pred == ICmpInst::ICMP_EQ) {
888 if (!CR.contains(CI->getValue()))
891 if (CR.isSingleElement() && CR.contains(CI->getValue()))
893 } else if (Pred == ICmpInst::ICMP_NE) {
894 if (!CR.contains(CI->getValue()))
897 if (CR.isSingleElement() && CR.contains(CI->getValue()))
901 // Handle more complex predicates.
902 ConstantRange RHS(CI->getValue(), CI->getValue()+1);
903 ConstantRange TrueValues = ConstantRange::makeICmpRegion(Pred, RHS);
904 if (CR.intersectWith(TrueValues).isEmptySet())
906 else if (TrueValues.contains(CR))
912 if (Result.isNotConstant()) {
913 // If this is an equality comparison, we can try to fold it knowing that
915 if (Pred == ICmpInst::ICMP_EQ) {
916 // !C1 == C -> false iff C1 == C.
917 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
918 Result.getNotConstant(), C, TD);
919 if (Res->isNullValue())
921 } else if (Pred == ICmpInst::ICMP_NE) {
922 // !C1 != C -> true iff C1 == C.
923 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
924 Result.getNotConstant(), C, TD);
925 if (Res->isNullValue())
934 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
935 BasicBlock* NewSucc) {
936 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
939 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
940 if (PImpl) getCache(PImpl).eraseBlock(BB);