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) {
83 static LVILatticeVal getNot(Constant *C) {
85 Res.markNotConstant(C);
89 bool isUndefined() const { return Tag == undefined; }
90 bool isConstant() const { return Tag == constant; }
91 bool isNotConstant() const { return Tag == notconstant; }
92 bool isConstantRange() const { return Tag == constantrange; }
93 bool isOverdefined() const { return Tag == overdefined; }
95 Constant *getConstant() const {
96 assert(isConstant() && "Cannot get the constant of a non-constant!");
100 Constant *getNotConstant() const {
101 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
105 ConstantRange getConstantRange() const {
106 assert(isConstantRange() &&
107 "Cannot get the constant-range of a non-constant-range!");
111 /// markOverdefined - Return true if this is a change in status.
112 bool markOverdefined() {
119 /// markConstant - Return true if this is a change in status.
120 bool markConstant(Constant *V) {
122 assert(getConstant() == V && "Marking constant with different value");
126 assert(isUndefined());
128 assert(V && "Marking constant with NULL");
133 /// markNotConstant - Return true if this is a change in status.
134 bool markNotConstant(Constant *V) {
135 if (isNotConstant()) {
136 assert(getNotConstant() == V && "Marking !constant with different value");
141 assert(getConstant() != V && "Marking not constant with different value");
143 assert(isUndefined());
146 assert(V && "Marking constant with NULL");
151 /// markConstantRange - Return true if this is a change in status.
152 bool markConstantRange(const ConstantRange NewR) {
153 if (isConstantRange()) {
154 if (NewR.isEmptySet())
155 return markOverdefined();
157 assert(Range.contains(NewR) &&
158 "Marking constant range with non-subset range!");
159 bool changed = Range == NewR;
164 assert(isUndefined());
165 if (NewR.isEmptySet())
166 return markOverdefined();
167 else if (NewR.isFullSet()) {
177 /// mergeIn - Merge the specified lattice value into this one, updating this
178 /// one and returning true if anything changed.
179 bool mergeIn(const LVILatticeVal &RHS) {
180 if (RHS.isUndefined() || isOverdefined()) return false;
181 if (RHS.isOverdefined()) return markOverdefined();
183 if (RHS.isNotConstant()) {
184 if (isNotConstant()) {
185 if (getNotConstant() != RHS.getNotConstant() ||
186 isa<ConstantExpr>(getNotConstant()) ||
187 isa<ConstantExpr>(RHS.getNotConstant()))
188 return markOverdefined();
192 if (getConstant() == RHS.getNotConstant() ||
193 isa<ConstantExpr>(RHS.getNotConstant()) ||
194 isa<ConstantExpr>(getConstant()))
195 return markOverdefined();
196 return markNotConstant(RHS.getNotConstant());
199 assert(isUndefined() && "Unexpected lattice");
200 return markNotConstant(RHS.getNotConstant());
203 if (RHS.isConstantRange()) {
204 if (isConstantRange()) {
205 ConstantRange NewR = Range.intersectWith(RHS.getConstantRange());
206 if (NewR.isEmptySet())
207 return markOverdefined();
209 return markConstantRange(NewR);
212 assert(isUndefined() && "Unexpected lattice");
213 return markConstantRange(RHS.getConstantRange());
216 // RHS must be a constant, we must be undef, constant, or notconstant.
217 assert(!isConstantRange() &&
218 "Constant and ConstantRange cannot be merged.");
221 return markConstant(RHS.getConstant());
224 if (getConstant() != RHS.getConstant())
225 return markOverdefined();
229 // If we are known "!=4" and RHS is "==5", stay at "!=4".
230 if (getNotConstant() == RHS.getConstant() ||
231 isa<ConstantExpr>(getNotConstant()) ||
232 isa<ConstantExpr>(RHS.getConstant()))
233 return markOverdefined();
239 } // end anonymous namespace.
242 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
243 if (Val.isUndefined())
244 return OS << "undefined";
245 if (Val.isOverdefined())
246 return OS << "overdefined";
248 if (Val.isNotConstant())
249 return OS << "notconstant<" << *Val.getNotConstant() << '>';
250 else if (Val.isConstantRange())
251 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
252 << Val.getConstantRange().getUpper() << '>';
253 return OS << "constant<" << *Val.getConstant() << '>';
257 //===----------------------------------------------------------------------===//
258 // LazyValueInfoCache Decl
259 //===----------------------------------------------------------------------===//
262 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
263 /// maintains information about queries across the clients' queries.
264 class LazyValueInfoCache {
266 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
267 /// specified basic block for a Value* that depends on context.
268 typedef std::pair<BasicBlock*, LVILatticeVal> BlockCacheEntryTy;
270 /// ValueCacheEntryTy - This is all of the cached block information for
271 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
272 /// entries, allowing us to do a lookup with a binary search.
273 typedef std::map<BasicBlock*, LVILatticeVal> ValueCacheEntryTy;
276 /// LVIValueHandle - A callback value handle update the cache when
277 /// values are erased.
278 struct LVIValueHandle : public CallbackVH {
279 LazyValueInfoCache *Parent;
281 LVIValueHandle(Value *V, LazyValueInfoCache *P)
282 : CallbackVH(V), Parent(P) { }
285 void allUsesReplacedWith(Value* V) {
289 LVIValueHandle &operator=(Value *V) {
290 return *this = LVIValueHandle(V, Parent);
294 /// ValueCache - This is all of the cached information for all values,
295 /// mapped from Value* to key information.
296 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
298 /// OverDefinedCache - This tracks, on a per-block basis, the set of
299 /// values that are over-defined at the end of that block. This is required
300 /// for cache updating.
301 std::set<std::pair<BasicBlock*, Value*> > OverDefinedCache;
305 /// getValueInBlock - This is the query interface to determine the lattice
306 /// value for the specified Value* at the end of the specified block.
307 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
309 /// getValueOnEdge - This is the query interface to determine the lattice
310 /// value for the specified Value* that is true on the specified edge.
311 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
313 /// threadEdge - This is the update interface to inform the cache that an
314 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
316 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
318 } // end anonymous namespace
320 //===----------------------------------------------------------------------===//
322 //===----------------------------------------------------------------------===//
325 /// LVIQuery - This is a transient object that exists while a query is
328 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
329 /// reallocation of the densemap on every query.
331 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
332 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
334 /// This is the current value being queried for.
337 /// This is a pointer to the owning cache, for recursive queries.
338 LazyValueInfoCache &Parent;
340 /// This is all of the cached information about this value.
341 ValueCacheEntryTy &Cache;
343 /// This tracks, for each block, what values are overdefined.
344 std::set<std::pair<BasicBlock*, Value*> > &OverDefinedCache;
346 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
347 /// added to cache but that are not in sorted order.
348 DenseSet<BasicBlock*> NewBlockInfo;
351 LVIQuery(Value *V, LazyValueInfoCache &P,
352 ValueCacheEntryTy &VC,
353 std::set<std::pair<BasicBlock*, Value*> > &ODC)
354 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
358 // When the query is done, insert the newly discovered facts into the
359 // cache in sorted order.
360 if (NewBlockInfo.empty()) return;
362 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
363 E = NewBlockInfo.end(); I != E; ++I) {
364 if (Cache[*I].isOverdefined())
365 OverDefinedCache.insert(std::make_pair(*I, Val));
369 LVILatticeVal getBlockValue(BasicBlock *BB);
370 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
373 LVILatticeVal &getCachedEntryForBlock(BasicBlock *BB);
375 } // end anonymous namespace
377 void LazyValueInfoCache::LVIValueHandle::deleted() {
378 Parent->ValueCache.erase(*this);
379 for (std::set<std::pair<BasicBlock*, Value*> >::iterator
380 I = Parent->OverDefinedCache.begin(),
381 E = Parent->OverDefinedCache.end();
383 std::set<std::pair<BasicBlock*, Value*> >::iterator tmp = I;
385 if (tmp->second == getValPtr())
386 Parent->OverDefinedCache.erase(tmp);
391 /// getCachedEntryForBlock - See if we already have a value for this block. If
392 /// so, return it, otherwise create a new entry in the Cache map to use.
393 LVILatticeVal &LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
394 NewBlockInfo.insert(BB);
398 LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
399 // See if we already have a value for this block.
400 LVILatticeVal &BBLV = getCachedEntryForBlock(BB);
402 // If we've already computed this block's value, return it.
403 if (!BBLV.isUndefined()) {
404 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
408 // Otherwise, this is the first time we're seeing this block. Reset the
409 // lattice value to overdefined, so that cycles will terminate and be
410 // conservatively correct.
411 BBLV.markOverdefined();
413 // If V is live into BB, see if our predecessors know anything about it.
414 Instruction *BBI = dyn_cast<Instruction>(Val);
415 if (BBI == 0 || BBI->getParent() != BB) {
416 LVILatticeVal Result; // Start Undefined.
417 unsigned NumPreds = 0;
419 // Loop over all of our predecessors, merging what we know from them into
421 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
422 Result.mergeIn(getEdgeValue(*PI, BB));
424 // If we hit overdefined, exit early. The BlockVals entry is already set
426 if (Result.isOverdefined()) {
427 DEBUG(dbgs() << " compute BB '" << BB->getName()
428 << "' - overdefined because of pred.\n");
434 // If this is the entry block, we must be asking about an argument. The
435 // value is overdefined.
436 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
437 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
438 Result.markOverdefined();
442 // Return the merged value, which is more precise than 'overdefined'.
443 assert(!Result.isOverdefined());
444 return getCachedEntryForBlock(BB) = Result;
447 // If this value is defined by an instruction in this block, we have to
448 // process it here somehow or return overdefined.
449 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
450 LVILatticeVal Result; // Start Undefined.
452 // Loop over all of our predecessors, merging what we know from them into
454 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
455 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
456 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
458 // If we hit overdefined, exit early. The BlockVals entry is already set
460 if (Result.isOverdefined()) {
461 DEBUG(dbgs() << " compute BB '" << BB->getName()
462 << "' - overdefined because of pred.\n");
467 // Return the merged value, which is more precise than 'overdefined'.
468 assert(!Result.isOverdefined());
469 return getCachedEntryForBlock(BB) = Result;
475 DEBUG(dbgs() << " compute BB '" << BB->getName()
476 << "' - overdefined because inst def found.\n");
478 LVILatticeVal Result;
479 Result.markOverdefined();
480 return getCachedEntryForBlock(BB) = Result;
484 /// getEdgeValue - This method attempts to infer more complex
485 LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
486 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
488 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
489 // If this is a conditional branch and only one successor goes to BBTo, then
490 // we maybe able to infer something from the condition.
491 if (BI->isConditional() &&
492 BI->getSuccessor(0) != BI->getSuccessor(1)) {
493 bool isTrueDest = BI->getSuccessor(0) == BBTo;
494 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
495 "BBTo isn't a successor of BBFrom");
497 // If V is the condition of the branch itself, then we know exactly what
499 if (BI->getCondition() == Val)
500 return LVILatticeVal::get(ConstantInt::get(
501 Type::getInt1Ty(Val->getContext()), isTrueDest));
503 // If the condition of the branch is an equality comparison, we may be
504 // able to infer the value.
505 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
506 if (ICI->isEquality() && ICI->getOperand(0) == Val &&
507 isa<Constant>(ICI->getOperand(1))) {
508 // We know that V has the RHS constant if this is a true SETEQ or
510 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
511 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
512 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
517 // If the edge was formed by a switch on the value, then we may know exactly
519 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
520 // If BBTo is the default destination of the switch, we don't know anything.
521 // Given a more powerful range analysis we could know stuff.
522 if (SI->getCondition() == Val && SI->getDefaultDest() != BBTo) {
523 // We only know something if there is exactly one value that goes from
525 unsigned NumEdges = 0;
526 ConstantInt *EdgeVal = 0;
527 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
528 if (SI->getSuccessor(i) != BBTo) continue;
529 if (NumEdges++) break;
530 EdgeVal = SI->getCaseValue(i);
532 assert(EdgeVal && "Missing successor?");
534 return LVILatticeVal::get(EdgeVal);
538 // Otherwise see if the value is known in the block.
539 return getBlockValue(BBFrom);
543 //===----------------------------------------------------------------------===//
544 // LazyValueInfoCache Impl
545 //===----------------------------------------------------------------------===//
547 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
548 // If already a constant, there is nothing to compute.
549 if (Constant *VC = dyn_cast<Constant>(V))
550 return LVILatticeVal::get(VC);
552 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
553 << BB->getName() << "'\n");
555 LVILatticeVal Result = LVIQuery(V, *this,
556 ValueCache[LVIValueHandle(V, this)],
557 OverDefinedCache).getBlockValue(BB);
559 DEBUG(dbgs() << " Result = " << Result << "\n");
563 LVILatticeVal LazyValueInfoCache::
564 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
565 // If already a constant, there is nothing to compute.
566 if (Constant *VC = dyn_cast<Constant>(V))
567 return LVILatticeVal::get(VC);
569 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
570 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
572 LVILatticeVal Result =
573 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
574 OverDefinedCache).getEdgeValue(FromBB, ToBB);
576 DEBUG(dbgs() << " Result = " << Result << "\n");
581 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
582 BasicBlock *NewSucc) {
583 // When an edge in the graph has been threaded, values that we could not
584 // determine a value for before (i.e. were marked overdefined) may be possible
585 // to solve now. We do NOT try to proactively update these values. Instead,
586 // we clear their entries from the cache, and allow lazy updating to recompute
589 // The updating process is fairly simple: we need to dropped cached info
590 // for all values that were marked overdefined in OldSucc, and for those same
591 // values in any successor of OldSucc (except NewSucc) in which they were
592 // also marked overdefined.
593 std::vector<BasicBlock*> worklist;
594 worklist.push_back(OldSucc);
596 DenseSet<Value*> ClearSet;
597 for (std::set<std::pair<BasicBlock*, Value*> >::iterator
598 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
599 if (I->first == OldSucc)
600 ClearSet.insert(I->second);
603 // Use a worklist to perform a depth-first search of OldSucc's successors.
604 // NOTE: We do not need a visited list since any blocks we have already
605 // visited will have had their overdefined markers cleared already, and we
606 // thus won't loop to their successors.
607 while (!worklist.empty()) {
608 BasicBlock *ToUpdate = worklist.back();
611 // Skip blocks only accessible through NewSucc.
612 if (ToUpdate == NewSucc) continue;
614 bool changed = false;
615 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
617 // If a value was marked overdefined in OldSucc, and is here too...
618 std::set<std::pair<BasicBlock*, Value*> >::iterator OI =
619 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
620 if (OI == OverDefinedCache.end()) continue;
622 // Remove it from the caches.
623 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
624 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
626 assert(CI != Entry.end() && "Couldn't find entry to update?");
628 OverDefinedCache.erase(OI);
630 // If we removed anything, then we potentially need to update
631 // blocks successors too.
635 if (!changed) continue;
637 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
641 //===----------------------------------------------------------------------===//
642 // LazyValueInfo Impl
643 //===----------------------------------------------------------------------===//
645 bool LazyValueInfo::runOnFunction(Function &F) {
646 TD = getAnalysisIfAvailable<TargetData>();
651 /// getCache - This lazily constructs the LazyValueInfoCache.
652 static LazyValueInfoCache &getCache(void *&PImpl) {
654 PImpl = new LazyValueInfoCache();
655 return *static_cast<LazyValueInfoCache*>(PImpl);
658 void LazyValueInfo::releaseMemory() {
659 // If the cache was allocated, free it.
661 delete &getCache(PImpl);
666 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
667 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
669 if (Result.isConstant())
670 return Result.getConstant();
674 /// getConstantOnEdge - Determine whether the specified value is known to be a
675 /// constant on the specified edge. Return null if not.
676 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
678 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
680 if (Result.isConstant())
681 return Result.getConstant();
685 /// getPredicateOnEdge - Determine whether the specified value comparison
686 /// with a constant is known to be true or false on the specified CFG edge.
687 /// Pred is a CmpInst predicate.
688 LazyValueInfo::Tristate
689 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
690 BasicBlock *FromBB, BasicBlock *ToBB) {
691 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
693 // If we know the value is a constant, evaluate the conditional.
695 if (Result.isConstant()) {
696 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
697 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
698 return ResCI->isZero() ? False : True;
702 if (Result.isNotConstant()) {
703 // If this is an equality comparison, we can try to fold it knowing that
705 if (Pred == ICmpInst::ICMP_EQ) {
706 // !C1 == C -> false iff C1 == C.
707 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
708 Result.getNotConstant(), C, TD);
709 if (Res->isNullValue())
711 } else if (Pred == ICmpInst::ICMP_NE) {
712 // !C1 != C -> true iff C1 == C.
713 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
714 Result.getNotConstant(), C, TD);
715 if (Res->isNullValue())
724 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
725 BasicBlock* NewSucc) {
726 getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);