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 return OS << "constant<" << *Val.getConstant() << '>';
254 //===----------------------------------------------------------------------===//
255 // LazyValueInfoCache Decl
256 //===----------------------------------------------------------------------===//
259 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
260 /// maintains information about queries across the clients' queries.
261 class LazyValueInfoCache {
263 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
264 /// specified basic block for a Value* that depends on context.
265 typedef std::pair<BasicBlock*, LVILatticeVal> BlockCacheEntryTy;
267 /// ValueCacheEntryTy - This is all of the cached block information for
268 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
269 /// entries, allowing us to do a lookup with a binary search.
270 typedef std::map<BasicBlock*, LVILatticeVal> ValueCacheEntryTy;
273 /// LVIValueHandle - A callback value handle update the cache when
274 /// values are erased.
275 struct LVIValueHandle : public CallbackVH {
276 LazyValueInfoCache *Parent;
278 LVIValueHandle(Value *V, LazyValueInfoCache *P)
279 : CallbackVH(V), Parent(P) { }
282 void allUsesReplacedWith(Value* V) {
286 LVIValueHandle &operator=(Value *V) {
287 return *this = LVIValueHandle(V, Parent);
291 /// ValueCache - This is all of the cached information for all values,
292 /// mapped from Value* to key information.
293 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
295 /// OverDefinedCache - This tracks, on a per-block basis, the set of
296 /// values that are over-defined at the end of that block. This is required
297 /// for cache updating.
298 std::set<std::pair<BasicBlock*, Value*> > OverDefinedCache;
302 /// getValueInBlock - This is the query interface to determine the lattice
303 /// value for the specified Value* at the end of the specified block.
304 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
306 /// getValueOnEdge - This is the query interface to determine the lattice
307 /// value for the specified Value* that is true on the specified edge.
308 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
310 /// threadEdge - This is the update interface to inform the cache that an
311 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
313 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
315 } // end anonymous namespace
317 //===----------------------------------------------------------------------===//
319 //===----------------------------------------------------------------------===//
322 /// LVIQuery - This is a transient object that exists while a query is
325 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
326 /// reallocation of the densemap on every query.
328 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
329 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
331 /// This is the current value being queried for.
334 /// This is a pointer to the owning cache, for recursive queries.
335 LazyValueInfoCache &Parent;
337 /// This is all of the cached information about this value.
338 ValueCacheEntryTy &Cache;
340 /// This tracks, for each block, what values are overdefined.
341 std::set<std::pair<BasicBlock*, Value*> > &OverDefinedCache;
343 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
344 /// added to cache but that are not in sorted order.
345 DenseSet<BasicBlock*> NewBlockInfo;
348 LVIQuery(Value *V, LazyValueInfoCache &P,
349 ValueCacheEntryTy &VC,
350 std::set<std::pair<BasicBlock*, Value*> > &ODC)
351 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
355 // When the query is done, insert the newly discovered facts into the
356 // cache in sorted order.
357 if (NewBlockInfo.empty()) return;
359 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
360 E = NewBlockInfo.end(); I != E; ++I) {
361 if (Cache[*I].isOverdefined())
362 OverDefinedCache.insert(std::make_pair(*I, Val));
366 LVILatticeVal getBlockValue(BasicBlock *BB);
367 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
370 LVILatticeVal &getCachedEntryForBlock(BasicBlock *BB);
372 } // end anonymous namespace
374 void LazyValueInfoCache::LVIValueHandle::deleted() {
375 Parent->ValueCache.erase(*this);
376 for (std::set<std::pair<BasicBlock*, Value*> >::iterator
377 I = Parent->OverDefinedCache.begin(),
378 E = Parent->OverDefinedCache.end();
380 std::set<std::pair<BasicBlock*, Value*> >::iterator tmp = I;
382 if (tmp->second == getValPtr())
383 Parent->OverDefinedCache.erase(tmp);
388 /// getCachedEntryForBlock - See if we already have a value for this block. If
389 /// so, return it, otherwise create a new entry in the Cache map to use.
390 LVILatticeVal &LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
391 NewBlockInfo.insert(BB);
395 LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
396 // See if we already have a value for this block.
397 LVILatticeVal &BBLV = getCachedEntryForBlock(BB);
399 // If we've already computed this block's value, return it.
400 if (!BBLV.isUndefined()) {
401 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
405 // Otherwise, this is the first time we're seeing this block. Reset the
406 // lattice value to overdefined, so that cycles will terminate and be
407 // conservatively correct.
408 BBLV.markOverdefined();
410 // If V is live into BB, see if our predecessors know anything about it.
411 Instruction *BBI = dyn_cast<Instruction>(Val);
412 if (BBI == 0 || BBI->getParent() != BB) {
413 LVILatticeVal Result; // Start Undefined.
414 unsigned NumPreds = 0;
416 // Loop over all of our predecessors, merging what we know from them into
418 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
419 Result.mergeIn(getEdgeValue(*PI, BB));
421 // If we hit overdefined, exit early. The BlockVals entry is already set
423 if (Result.isOverdefined()) {
424 DEBUG(dbgs() << " compute BB '" << BB->getName()
425 << "' - overdefined because of pred.\n");
431 // If this is the entry block, we must be asking about an argument. The
432 // value is overdefined.
433 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
434 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
435 Result.markOverdefined();
439 // Return the merged value, which is more precise than 'overdefined'.
440 assert(!Result.isOverdefined());
441 return getCachedEntryForBlock(BB) = Result;
444 // If this value is defined by an instruction in this block, we have to
445 // process it here somehow or return overdefined.
446 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
447 LVILatticeVal Result; // Start Undefined.
449 // Loop over all of our predecessors, merging what we know from them into
451 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
452 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
453 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
455 // If we hit overdefined, exit early. The BlockVals entry is already set
457 if (Result.isOverdefined()) {
458 DEBUG(dbgs() << " compute BB '" << BB->getName()
459 << "' - overdefined because of pred.\n");
464 // Return the merged value, which is more precise than 'overdefined'.
465 assert(!Result.isOverdefined());
466 return getCachedEntryForBlock(BB) = Result;
472 DEBUG(dbgs() << " compute BB '" << BB->getName()
473 << "' - overdefined because inst def found.\n");
475 LVILatticeVal Result;
476 Result.markOverdefined();
477 return getCachedEntryForBlock(BB) = Result;
481 /// getEdgeValue - This method attempts to infer more complex
482 LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
483 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
485 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
486 // If this is a conditional branch and only one successor goes to BBTo, then
487 // we maybe able to infer something from the condition.
488 if (BI->isConditional() &&
489 BI->getSuccessor(0) != BI->getSuccessor(1)) {
490 bool isTrueDest = BI->getSuccessor(0) == BBTo;
491 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
492 "BBTo isn't a successor of BBFrom");
494 // If V is the condition of the branch itself, then we know exactly what
496 if (BI->getCondition() == Val)
497 return LVILatticeVal::get(ConstantInt::get(
498 Type::getInt1Ty(Val->getContext()), isTrueDest));
500 // If the condition of the branch is an equality comparison, we may be
501 // able to infer the value.
502 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
503 if (ICI->isEquality() && ICI->getOperand(0) == Val &&
504 isa<Constant>(ICI->getOperand(1))) {
505 // We know that V has the RHS constant if this is a true SETEQ or
507 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
508 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
509 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
514 // If the edge was formed by a switch on the value, then we may know exactly
516 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
517 // If BBTo is the default destination of the switch, we don't know anything.
518 // Given a more powerful range analysis we could know stuff.
519 if (SI->getCondition() == Val && SI->getDefaultDest() != BBTo) {
520 // We only know something if there is exactly one value that goes from
522 unsigned NumEdges = 0;
523 ConstantInt *EdgeVal = 0;
524 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
525 if (SI->getSuccessor(i) != BBTo) continue;
526 if (NumEdges++) break;
527 EdgeVal = SI->getCaseValue(i);
529 assert(EdgeVal && "Missing successor?");
531 return LVILatticeVal::get(EdgeVal);
535 // Otherwise see if the value is known in the block.
536 return getBlockValue(BBFrom);
540 //===----------------------------------------------------------------------===//
541 // LazyValueInfoCache Impl
542 //===----------------------------------------------------------------------===//
544 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
545 // If already a constant, there is nothing to compute.
546 if (Constant *VC = dyn_cast<Constant>(V))
547 return LVILatticeVal::get(VC);
549 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
550 << BB->getName() << "'\n");
552 LVILatticeVal Result = LVIQuery(V, *this,
553 ValueCache[LVIValueHandle(V, this)],
554 OverDefinedCache).getBlockValue(BB);
556 DEBUG(dbgs() << " Result = " << Result << "\n");
560 LVILatticeVal LazyValueInfoCache::
561 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
562 // If already a constant, there is nothing to compute.
563 if (Constant *VC = dyn_cast<Constant>(V))
564 return LVILatticeVal::get(VC);
566 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
567 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
569 LVILatticeVal Result =
570 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
571 OverDefinedCache).getEdgeValue(FromBB, ToBB);
573 DEBUG(dbgs() << " Result = " << Result << "\n");
578 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
579 BasicBlock *NewSucc) {
580 // When an edge in the graph has been threaded, values that we could not
581 // determine a value for before (i.e. were marked overdefined) may be possible
582 // to solve now. We do NOT try to proactively update these values. Instead,
583 // we clear their entries from the cache, and allow lazy updating to recompute
586 // The updating process is fairly simple: we need to dropped cached info
587 // for all values that were marked overdefined in OldSucc, and for those same
588 // values in any successor of OldSucc (except NewSucc) in which they were
589 // also marked overdefined.
590 std::vector<BasicBlock*> worklist;
591 worklist.push_back(OldSucc);
593 DenseSet<Value*> ClearSet;
594 for (std::set<std::pair<BasicBlock*, Value*> >::iterator
595 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
596 if (I->first == OldSucc)
597 ClearSet.insert(I->second);
600 // Use a worklist to perform a depth-first search of OldSucc's successors.
601 // NOTE: We do not need a visited list since any blocks we have already
602 // visited will have had their overdefined markers cleared already, and we
603 // thus won't loop to their successors.
604 while (!worklist.empty()) {
605 BasicBlock *ToUpdate = worklist.back();
608 // Skip blocks only accessible through NewSucc.
609 if (ToUpdate == NewSucc) continue;
611 bool changed = false;
612 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
614 // If a value was marked overdefined in OldSucc, and is here too...
615 std::set<std::pair<BasicBlock*, Value*> >::iterator OI =
616 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
617 if (OI == OverDefinedCache.end()) continue;
619 // Remove it from the caches.
620 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
621 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
623 assert(CI != Entry.end() && "Couldn't find entry to update?");
625 OverDefinedCache.erase(OI);
627 // If we removed anything, then we potentially need to update
628 // blocks successors too.
632 if (!changed) continue;
634 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
638 //===----------------------------------------------------------------------===//
639 // LazyValueInfo Impl
640 //===----------------------------------------------------------------------===//
642 bool LazyValueInfo::runOnFunction(Function &F) {
643 TD = getAnalysisIfAvailable<TargetData>();
648 /// getCache - This lazily constructs the LazyValueInfoCache.
649 static LazyValueInfoCache &getCache(void *&PImpl) {
651 PImpl = new LazyValueInfoCache();
652 return *static_cast<LazyValueInfoCache*>(PImpl);
655 void LazyValueInfo::releaseMemory() {
656 // If the cache was allocated, free it.
658 delete &getCache(PImpl);
663 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
664 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
666 if (Result.isConstant())
667 return Result.getConstant();
671 /// getConstantOnEdge - Determine whether the specified value is known to be a
672 /// constant on the specified edge. Return null if not.
673 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
675 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
677 if (Result.isConstant())
678 return Result.getConstant();
682 /// getPredicateOnEdge - Determine whether the specified value comparison
683 /// with a constant is known to be true or false on the specified CFG edge.
684 /// Pred is a CmpInst predicate.
685 LazyValueInfo::Tristate
686 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
687 BasicBlock *FromBB, BasicBlock *ToBB) {
688 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
690 // If we know the value is a constant, evaluate the conditional.
692 if (Result.isConstant()) {
693 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
694 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
695 return ResCI->isZero() ? False : True;
699 if (Result.isNotConstant()) {
700 // If this is an equality comparison, we can try to fold it knowing that
702 if (Pred == ICmpInst::ICMP_EQ) {
703 // !C1 == C -> false iff C1 == C.
704 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
705 Result.getNotConstant(), C, TD);
706 if (Res->isNullValue())
708 } else if (Pred == ICmpInst::ICMP_NE) {
709 // !C1 != C -> true iff C1 == C.
710 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
711 Result.getNotConstant(), C, TD);
712 if (Res->isNullValue())
721 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
722 BasicBlock* NewSucc) {
723 getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);