blob: ecc1831dbe5b06ce14849361d8b2081d1ddd8e50 [file] [log] [blame]
Chris Lattner10f2d132009-11-11 00:22:30 +00001//===- LazyValueInfo.cpp - Value constraint analysis ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interface for lazy computation of value constraint
11// information.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnerb8c124c2009-11-12 01:22:16 +000015#define DEBUG_TYPE "lazy-value-info"
Chris Lattner10f2d132009-11-11 00:22:30 +000016#include "llvm/Analysis/LazyValueInfo.h"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000017#include "llvm/Constants.h"
18#include "llvm/Instructions.h"
19#include "llvm/Analysis/ConstantFolding.h"
20#include "llvm/Target/TargetData.h"
Chris Lattner16976522009-11-11 22:48:44 +000021#include "llvm/Support/CFG.h"
Chris Lattnerb8c124c2009-11-12 01:22:16 +000022#include "llvm/Support/Debug.h"
Chris Lattner16976522009-11-11 22:48:44 +000023#include "llvm/Support/raw_ostream.h"
Owen Anderson7f9cb742010-07-30 23:59:40 +000024#include "llvm/Support/ValueHandle.h"
Chris Lattner16976522009-11-11 22:48:44 +000025#include "llvm/ADT/DenseMap.h"
Owen Anderson9a65dc92010-07-27 23:58:11 +000026#include "llvm/ADT/DenseSet.h"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000027#include "llvm/ADT/PointerIntPair.h"
Chris Lattnere5642812009-11-15 20:00:52 +000028#include "llvm/ADT/STLExtras.h"
Chris Lattner10f2d132009-11-11 00:22:30 +000029using namespace llvm;
30
31char LazyValueInfo::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000032INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
33 "Lazy Value Information Analysis", false, true);
Chris Lattner10f2d132009-11-11 00:22:30 +000034
35namespace llvm {
36 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
37}
38
Chris Lattnercc4d3b22009-11-11 02:08:33 +000039
40//===----------------------------------------------------------------------===//
41// LVILatticeVal
42//===----------------------------------------------------------------------===//
43
44/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
45/// value.
46///
47/// FIXME: This is basically just for bringup, this can be made a lot more rich
48/// in the future.
49///
50namespace {
51class LVILatticeVal {
52 enum LatticeValueTy {
53 /// undefined - This LLVM Value has no known value yet.
54 undefined,
55 /// constant - This LLVM Value has a specific constant value.
56 constant,
Chris Lattnerb52675b2009-11-12 04:36:58 +000057
58 /// notconstant - This LLVM value is known to not have the specified value.
59 notconstant,
60
Chris Lattnercc4d3b22009-11-11 02:08:33 +000061 /// overdefined - This instruction is not known to be constant, and we know
62 /// it has a value.
63 overdefined
64 };
65
66 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattnerb52675b2009-11-12 04:36:58 +000067 /// the constant if this is a 'constant' or 'notconstant' value.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000068 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
69
70public:
71 LVILatticeVal() : Val(0, undefined) {}
72
Chris Lattner16976522009-11-11 22:48:44 +000073 static LVILatticeVal get(Constant *C) {
74 LVILatticeVal Res;
75 Res.markConstant(C);
76 return Res;
77 }
Chris Lattnerb52675b2009-11-12 04:36:58 +000078 static LVILatticeVal getNot(Constant *C) {
79 LVILatticeVal Res;
80 Res.markNotConstant(C);
81 return Res;
82 }
Chris Lattner16976522009-11-11 22:48:44 +000083
Chris Lattnercc4d3b22009-11-11 02:08:33 +000084 bool isUndefined() const { return Val.getInt() == undefined; }
85 bool isConstant() const { return Val.getInt() == constant; }
Chris Lattnerb52675b2009-11-12 04:36:58 +000086 bool isNotConstant() const { return Val.getInt() == notconstant; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +000087 bool isOverdefined() const { return Val.getInt() == overdefined; }
88
89 Constant *getConstant() const {
90 assert(isConstant() && "Cannot get the constant of a non-constant!");
91 return Val.getPointer();
92 }
93
Chris Lattnerb52675b2009-11-12 04:36:58 +000094 Constant *getNotConstant() const {
95 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
96 return Val.getPointer();
Chris Lattnercc4d3b22009-11-11 02:08:33 +000097 }
98
99 /// markOverdefined - Return true if this is a change in status.
100 bool markOverdefined() {
101 if (isOverdefined())
102 return false;
103 Val.setInt(overdefined);
104 return true;
105 }
106
107 /// markConstant - Return true if this is a change in status.
108 bool markConstant(Constant *V) {
109 if (isConstant()) {
110 assert(getConstant() == V && "Marking constant with different value");
111 return false;
112 }
113
114 assert(isUndefined());
115 Val.setInt(constant);
116 assert(V && "Marking constant with NULL");
117 Val.setPointer(V);
Chris Lattner16976522009-11-11 22:48:44 +0000118 return true;
119 }
120
Chris Lattnerb52675b2009-11-12 04:36:58 +0000121 /// markNotConstant - Return true if this is a change in status.
122 bool markNotConstant(Constant *V) {
123 if (isNotConstant()) {
124 assert(getNotConstant() == V && "Marking !constant with different value");
125 return false;
126 }
127
128 if (isConstant())
129 assert(getConstant() != V && "Marking not constant with different value");
130 else
131 assert(isUndefined());
132
133 Val.setInt(notconstant);
134 assert(V && "Marking constant with NULL");
135 Val.setPointer(V);
136 return true;
137 }
138
Chris Lattner16976522009-11-11 22:48:44 +0000139 /// mergeIn - Merge the specified lattice value into this one, updating this
140 /// one and returning true if anything changed.
141 bool mergeIn(const LVILatticeVal &RHS) {
142 if (RHS.isUndefined() || isOverdefined()) return false;
143 if (RHS.isOverdefined()) return markOverdefined();
144
Chris Lattnerb52675b2009-11-12 04:36:58 +0000145 if (RHS.isNotConstant()) {
146 if (isNotConstant()) {
Chris Lattnerf496e792009-11-12 04:57:13 +0000147 if (getNotConstant() != RHS.getNotConstant() ||
148 isa<ConstantExpr>(getNotConstant()) ||
149 isa<ConstantExpr>(RHS.getNotConstant()))
Chris Lattnerb52675b2009-11-12 04:36:58 +0000150 return markOverdefined();
151 return false;
152 }
Chris Lattnerf496e792009-11-12 04:57:13 +0000153 if (isConstant()) {
154 if (getConstant() == RHS.getNotConstant() ||
155 isa<ConstantExpr>(RHS.getNotConstant()) ||
156 isa<ConstantExpr>(getConstant()))
157 return markOverdefined();
158 return markNotConstant(RHS.getNotConstant());
159 }
160
161 assert(isUndefined() && "Unexpected lattice");
Chris Lattnerb52675b2009-11-12 04:36:58 +0000162 return markNotConstant(RHS.getNotConstant());
163 }
164
Chris Lattnerf496e792009-11-12 04:57:13 +0000165 // RHS must be a constant, we must be undef, constant, or notconstant.
166 if (isUndefined())
167 return markConstant(RHS.getConstant());
168
169 if (isConstant()) {
170 if (getConstant() != RHS.getConstant())
171 return markOverdefined();
172 return false;
173 }
174
175 // If we are known "!=4" and RHS is "==5", stay at "!=4".
176 if (getNotConstant() == RHS.getConstant() ||
177 isa<ConstantExpr>(getNotConstant()) ||
178 isa<ConstantExpr>(RHS.getConstant()))
Chris Lattner16976522009-11-11 22:48:44 +0000179 return markOverdefined();
Chris Lattnerf496e792009-11-12 04:57:13 +0000180 return false;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000181 }
182
183};
184
185} // end anonymous namespace.
186
Chris Lattner16976522009-11-11 22:48:44 +0000187namespace llvm {
188raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
189 if (Val.isUndefined())
190 return OS << "undefined";
191 if (Val.isOverdefined())
192 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000193
194 if (Val.isNotConstant())
195 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000196 return OS << "constant<" << *Val.getConstant() << '>';
197}
198}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000199
200//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000201// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000202//===----------------------------------------------------------------------===//
203
Chris Lattner2c5adf82009-11-15 19:59:49 +0000204namespace {
205 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
206 /// maintains information about queries across the clients' queries.
207 class LazyValueInfoCache {
Owen Anderson81881bc2010-07-30 20:56:07 +0000208 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000209 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
210 /// specified basic block for a Value* that depends on context.
211 typedef std::pair<BasicBlock*, LVILatticeVal> BlockCacheEntryTy;
212
213 /// ValueCacheEntryTy - This is all of the cached block information for
214 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
215 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000216 typedef std::map<BasicBlock*, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000217
Owen Anderson81881bc2010-07-30 20:56:07 +0000218 private:
Owen Anderson7f9cb742010-07-30 23:59:40 +0000219 /// LVIValueHandle - A callback value handle update the cache when
220 /// values are erased.
221 struct LVIValueHandle : public CallbackVH {
222 LazyValueInfoCache *Parent;
223
224 LVIValueHandle(Value *V, LazyValueInfoCache *P)
225 : CallbackVH(V), Parent(P) { }
226
227 void deleted();
228 void allUsesReplacedWith(Value* V) {
229 deleted();
230 }
231
232 LVIValueHandle &operator=(Value *V) {
233 return *this = LVIValueHandle(V, Parent);
234 }
235 };
236
Chris Lattner2c5adf82009-11-15 19:59:49 +0000237 /// ValueCache - This is all of the cached information for all values,
238 /// mapped from Value* to key information.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000239 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000240
241 /// OverDefinedCache - This tracks, on a per-block basis, the set of
242 /// values that are over-defined at the end of that block. This is required
243 /// for cache updating.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000244 std::set<std::pair<BasicBlock*, Value*> > OverDefinedCache;
245
Chris Lattner2c5adf82009-11-15 19:59:49 +0000246 public:
247
248 /// getValueInBlock - This is the query interface to determine the lattice
249 /// value for the specified Value* at the end of the specified block.
250 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
251
252 /// getValueOnEdge - This is the query interface to determine the lattice
253 /// value for the specified Value* that is true on the specified edge.
254 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000255
256 /// threadEdge - This is the update interface to inform the cache that an
257 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
258 /// NewSucc.
259 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000260 };
261} // end anonymous namespace
262
Owen Anderson81881bc2010-07-30 20:56:07 +0000263//===----------------------------------------------------------------------===//
264// LVIQuery Impl
265//===----------------------------------------------------------------------===//
266
267namespace {
268 /// LVIQuery - This is a transient object that exists while a query is
269 /// being performed.
270 ///
271 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
272 /// reallocation of the densemap on every query.
273 class LVIQuery {
274 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
275 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
276
277 /// This is the current value being queried for.
278 Value *Val;
279
Owen Anderson7f9cb742010-07-30 23:59:40 +0000280 /// This is a pointer to the owning cache, for recursive queries.
281 LazyValueInfoCache &Parent;
282
Owen Anderson81881bc2010-07-30 20:56:07 +0000283 /// This is all of the cached information about this value.
284 ValueCacheEntryTy &Cache;
285
286 /// This tracks, for each block, what values are overdefined.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000287 std::set<std::pair<BasicBlock*, Value*> > &OverDefinedCache;
Owen Anderson81881bc2010-07-30 20:56:07 +0000288
289 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
290 /// added to cache but that are not in sorted order.
291 DenseSet<BasicBlock*> NewBlockInfo;
292 public:
293
Owen Anderson7f9cb742010-07-30 23:59:40 +0000294 LVIQuery(Value *V, LazyValueInfoCache &P,
295 ValueCacheEntryTy &VC,
296 std::set<std::pair<BasicBlock*, Value*> > &ODC)
297 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000298 }
299
300 ~LVIQuery() {
301 // When the query is done, insert the newly discovered facts into the
302 // cache in sorted order.
303 if (NewBlockInfo.empty()) return;
304
305 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
306 E = NewBlockInfo.end(); I != E; ++I) {
307 if (Cache[*I].isOverdefined())
308 OverDefinedCache.insert(std::make_pair(*I, Val));
309 }
310 }
311
312 LVILatticeVal getBlockValue(BasicBlock *BB);
313 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
314
315 private:
316 LVILatticeVal &getCachedEntryForBlock(BasicBlock *BB);
317 };
318} // end anonymous namespace
Chris Lattner2c5adf82009-11-15 19:59:49 +0000319
Owen Anderson7f9cb742010-07-30 23:59:40 +0000320void LazyValueInfoCache::LVIValueHandle::deleted() {
321 Parent->ValueCache.erase(*this);
322 for (std::set<std::pair<BasicBlock*, Value*> >::iterator
323 I = Parent->OverDefinedCache.begin(),
324 E = Parent->OverDefinedCache.end();
325 I != E; ) {
326 std::set<std::pair<BasicBlock*, Value*> >::iterator tmp = I;
327 ++I;
328 if (tmp->second == getValPtr())
329 Parent->OverDefinedCache.erase(tmp);
330 }
331}
332
333
Chris Lattnere5642812009-11-15 20:00:52 +0000334/// getCachedEntryForBlock - See if we already have a value for this block. If
Owen Anderson9a65dc92010-07-27 23:58:11 +0000335/// so, return it, otherwise create a new entry in the Cache map to use.
Owen Anderson81881bc2010-07-30 20:56:07 +0000336LVILatticeVal &LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
337 NewBlockInfo.insert(BB);
Owen Anderson9a65dc92010-07-27 23:58:11 +0000338 return Cache[BB];
Chris Lattnere5642812009-11-15 20:00:52 +0000339}
Chris Lattner2c5adf82009-11-15 19:59:49 +0000340
Owen Anderson81881bc2010-07-30 20:56:07 +0000341LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000342 // See if we already have a value for this block.
Owen Anderson81881bc2010-07-30 20:56:07 +0000343 LVILatticeVal &BBLV = getCachedEntryForBlock(BB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000344
345 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000346 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000347 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Chris Lattner2c5adf82009-11-15 19:59:49 +0000348 return BBLV;
Chris Lattnere5642812009-11-15 20:00:52 +0000349 }
350
Chris Lattner2c5adf82009-11-15 19:59:49 +0000351 // Otherwise, this is the first time we're seeing this block. Reset the
352 // lattice value to overdefined, so that cycles will terminate and be
353 // conservatively correct.
354 BBLV.markOverdefined();
355
356 // If V is live into BB, see if our predecessors know anything about it.
357 Instruction *BBI = dyn_cast<Instruction>(Val);
358 if (BBI == 0 || BBI->getParent() != BB) {
359 LVILatticeVal Result; // Start Undefined.
360 unsigned NumPreds = 0;
361
362 // Loop over all of our predecessors, merging what we know from them into
363 // result.
364 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000365 Result.mergeIn(getEdgeValue(*PI, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000366
367 // If we hit overdefined, exit early. The BlockVals entry is already set
368 // to overdefined.
Chris Lattnere5642812009-11-15 20:00:52 +0000369 if (Result.isOverdefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000370 DEBUG(dbgs() << " compute BB '" << BB->getName()
Chris Lattnere5642812009-11-15 20:00:52 +0000371 << "' - overdefined because of pred.\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000372 return Result;
Chris Lattnere5642812009-11-15 20:00:52 +0000373 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000374 ++NumPreds;
375 }
376
377 // If this is the entry block, we must be asking about an argument. The
378 // value is overdefined.
379 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
380 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
381 Result.markOverdefined();
382 return Result;
383 }
384
385 // Return the merged value, which is more precise than 'overdefined'.
386 assert(!Result.isOverdefined());
Owen Anderson81881bc2010-07-30 20:56:07 +0000387 return getCachedEntryForBlock(BB) = Result;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000388 }
389
390 // If this value is defined by an instruction in this block, we have to
391 // process it here somehow or return overdefined.
392 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson7f9cb742010-07-30 23:59:40 +0000393 LVILatticeVal Result; // Start Undefined.
394
395 // Loop over all of our predecessors, merging what we know from them into
396 // result.
397 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
398 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
399 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
400
401 // If we hit overdefined, exit early. The BlockVals entry is already set
402 // to overdefined.
403 if (Result.isOverdefined()) {
404 DEBUG(dbgs() << " compute BB '" << BB->getName()
405 << "' - overdefined because of pred.\n");
406 return Result;
407 }
408 }
409
410 // Return the merged value, which is more precise than 'overdefined'.
411 assert(!Result.isOverdefined());
412 return getCachedEntryForBlock(BB) = Result;
413
Chris Lattner2c5adf82009-11-15 19:59:49 +0000414 } else {
415
416 }
417
David Greene5d93a1f2009-12-23 20:43:58 +0000418 DEBUG(dbgs() << " compute BB '" << BB->getName()
Chris Lattnere5642812009-11-15 20:00:52 +0000419 << "' - overdefined because inst def found.\n");
420
Chris Lattner2c5adf82009-11-15 19:59:49 +0000421 LVILatticeVal Result;
422 Result.markOverdefined();
Owen Anderson81881bc2010-07-30 20:56:07 +0000423 return getCachedEntryForBlock(BB) = Result;
Chris Lattner10f2d132009-11-11 00:22:30 +0000424}
425
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000426
Chris Lattner800c47e2009-11-15 20:02:12 +0000427/// getEdgeValue - This method attempts to infer more complex
Owen Anderson81881bc2010-07-30 20:56:07 +0000428LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
Chris Lattner800c47e2009-11-15 20:02:12 +0000429 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
430 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000431 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
432 // If this is a conditional branch and only one successor goes to BBTo, then
433 // we maybe able to infer something from the condition.
434 if (BI->isConditional() &&
435 BI->getSuccessor(0) != BI->getSuccessor(1)) {
436 bool isTrueDest = BI->getSuccessor(0) == BBTo;
437 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
438 "BBTo isn't a successor of BBFrom");
439
440 // If V is the condition of the branch itself, then we know exactly what
441 // it is.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000442 if (BI->getCondition() == Val)
Chris Lattner16976522009-11-11 22:48:44 +0000443 return LVILatticeVal::get(ConstantInt::get(
Chris Lattner2c5adf82009-11-15 19:59:49 +0000444 Type::getInt1Ty(Val->getContext()), isTrueDest));
Chris Lattner16976522009-11-11 22:48:44 +0000445
446 // If the condition of the branch is an equality comparison, we may be
447 // able to infer the value.
448 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
Chris Lattner2c5adf82009-11-15 19:59:49 +0000449 if (ICI->isEquality() && ICI->getOperand(0) == Val &&
Chris Lattner16976522009-11-11 22:48:44 +0000450 isa<Constant>(ICI->getOperand(1))) {
451 // We know that V has the RHS constant if this is a true SETEQ or
452 // false SETNE.
453 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
454 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
Chris Lattnerb52675b2009-11-12 04:36:58 +0000455 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
Chris Lattner16976522009-11-11 22:48:44 +0000456 }
457 }
458 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000459
460 // If the edge was formed by a switch on the value, then we may know exactly
461 // what it is.
462 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
463 // If BBTo is the default destination of the switch, we don't know anything.
464 // Given a more powerful range analysis we could know stuff.
465 if (SI->getCondition() == Val && SI->getDefaultDest() != BBTo) {
466 // We only know something if there is exactly one value that goes from
467 // BBFrom to BBTo.
468 unsigned NumEdges = 0;
469 ConstantInt *EdgeVal = 0;
470 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
471 if (SI->getSuccessor(i) != BBTo) continue;
472 if (NumEdges++) break;
473 EdgeVal = SI->getCaseValue(i);
474 }
475 assert(EdgeVal && "Missing successor?");
476 if (NumEdges == 1)
477 return LVILatticeVal::get(EdgeVal);
478 }
479 }
Chris Lattner16976522009-11-11 22:48:44 +0000480
481 // Otherwise see if the value is known in the block.
Owen Anderson81881bc2010-07-30 20:56:07 +0000482 return getBlockValue(BBFrom);
Chris Lattner16976522009-11-11 22:48:44 +0000483}
484
Owen Anderson81881bc2010-07-30 20:56:07 +0000485
486//===----------------------------------------------------------------------===//
487// LazyValueInfoCache Impl
488//===----------------------------------------------------------------------===//
489
Chris Lattner2c5adf82009-11-15 19:59:49 +0000490LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
491 // If already a constant, there is nothing to compute.
Chris Lattner16976522009-11-11 22:48:44 +0000492 if (Constant *VC = dyn_cast<Constant>(V))
Chris Lattner2c5adf82009-11-15 19:59:49 +0000493 return LVILatticeVal::get(VC);
Chris Lattner16976522009-11-11 22:48:44 +0000494
David Greene5d93a1f2009-12-23 20:43:58 +0000495 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000496 << BB->getName() << "'\n");
497
Owen Anderson7f9cb742010-07-30 23:59:40 +0000498 LVILatticeVal Result = LVIQuery(V, *this,
499 ValueCache[LVIValueHandle(V, this)],
Owen Anderson81881bc2010-07-30 20:56:07 +0000500 OverDefinedCache).getBlockValue(BB);
Chris Lattner16976522009-11-11 22:48:44 +0000501
David Greene5d93a1f2009-12-23 20:43:58 +0000502 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000503 return Result;
504}
Chris Lattner16976522009-11-11 22:48:44 +0000505
Chris Lattner2c5adf82009-11-15 19:59:49 +0000506LVILatticeVal LazyValueInfoCache::
507getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
508 // If already a constant, there is nothing to compute.
509 if (Constant *VC = dyn_cast<Constant>(V))
510 return LVILatticeVal::get(VC);
511
David Greene5d93a1f2009-12-23 20:43:58 +0000512 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000513 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000514
Owen Anderson81881bc2010-07-30 20:56:07 +0000515 LVILatticeVal Result =
Owen Anderson7f9cb742010-07-30 23:59:40 +0000516 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
Owen Anderson81881bc2010-07-30 20:56:07 +0000517 OverDefinedCache).getEdgeValue(FromBB, ToBB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000518
David Greene5d93a1f2009-12-23 20:43:58 +0000519 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000520
521 return Result;
522}
523
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000524void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
525 BasicBlock *NewSucc) {
526 // When an edge in the graph has been threaded, values that we could not
527 // determine a value for before (i.e. were marked overdefined) may be possible
528 // to solve now. We do NOT try to proactively update these values. Instead,
529 // we clear their entries from the cache, and allow lazy updating to recompute
530 // them when needed.
531
532 // The updating process is fairly simple: we need to dropped cached info
533 // for all values that were marked overdefined in OldSucc, and for those same
534 // values in any successor of OldSucc (except NewSucc) in which they were
535 // also marked overdefined.
536 std::vector<BasicBlock*> worklist;
537 worklist.push_back(OldSucc);
538
Owen Anderson9a65dc92010-07-27 23:58:11 +0000539 DenseSet<Value*> ClearSet;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000540 for (std::set<std::pair<BasicBlock*, Value*> >::iterator
Owen Anderson9a65dc92010-07-27 23:58:11 +0000541 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
542 if (I->first == OldSucc)
543 ClearSet.insert(I->second);
544 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000545
546 // Use a worklist to perform a depth-first search of OldSucc's successors.
547 // NOTE: We do not need a visited list since any blocks we have already
548 // visited will have had their overdefined markers cleared already, and we
549 // thus won't loop to their successors.
550 while (!worklist.empty()) {
551 BasicBlock *ToUpdate = worklist.back();
552 worklist.pop_back();
553
554 // Skip blocks only accessible through NewSucc.
555 if (ToUpdate == NewSucc) continue;
556
557 bool changed = false;
Owen Anderson9a65dc92010-07-27 23:58:11 +0000558 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000559 I != E; ++I) {
560 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson7f9cb742010-07-30 23:59:40 +0000561 std::set<std::pair<BasicBlock*, Value*> >::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000562 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
563 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000564
Owen Anderson9a65dc92010-07-27 23:58:11 +0000565 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000566 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000567 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
568
569 assert(CI != Entry.end() && "Couldn't find entry to update?");
570 Entry.erase(CI);
571 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000572
Owen Anderson9a65dc92010-07-27 23:58:11 +0000573 // If we removed anything, then we potentially need to update
574 // blocks successors too.
575 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000576 }
577
578 if (!changed) continue;
579
580 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
581 }
582}
583
Chris Lattner2c5adf82009-11-15 19:59:49 +0000584//===----------------------------------------------------------------------===//
585// LazyValueInfo Impl
586//===----------------------------------------------------------------------===//
587
588bool LazyValueInfo::runOnFunction(Function &F) {
589 TD = getAnalysisIfAvailable<TargetData>();
590 // Fully lazy.
591 return false;
592}
593
594/// getCache - This lazily constructs the LazyValueInfoCache.
595static LazyValueInfoCache &getCache(void *&PImpl) {
596 if (!PImpl)
597 PImpl = new LazyValueInfoCache();
598 return *static_cast<LazyValueInfoCache*>(PImpl);
599}
600
601void LazyValueInfo::releaseMemory() {
602 // If the cache was allocated, free it.
603 if (PImpl) {
604 delete &getCache(PImpl);
605 PImpl = 0;
606 }
607}
608
609Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
610 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
611
Chris Lattner16976522009-11-11 22:48:44 +0000612 if (Result.isConstant())
613 return Result.getConstant();
614 return 0;
615}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000616
Chris Lattner38392bb2009-11-12 01:29:10 +0000617/// getConstantOnEdge - Determine whether the specified value is known to be a
618/// constant on the specified edge. Return null if not.
619Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
620 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000621 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +0000622
623 if (Result.isConstant())
624 return Result.getConstant();
625 return 0;
626}
627
Chris Lattnerb52675b2009-11-12 04:36:58 +0000628/// getPredicateOnEdge - Determine whether the specified value comparison
629/// with a constant is known to be true or false on the specified CFG edge.
630/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000631LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +0000632LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
633 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000634 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000635
Chris Lattnerb52675b2009-11-12 04:36:58 +0000636 // If we know the value is a constant, evaluate the conditional.
637 Constant *Res = 0;
638 if (Result.isConstant()) {
639 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
640 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
641 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000642 return Unknown;
643 }
644
645 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000646 // If this is an equality comparison, we can try to fold it knowing that
647 // "V != C1".
648 if (Pred == ICmpInst::ICMP_EQ) {
649 // !C1 == C -> false iff C1 == C.
650 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
651 Result.getNotConstant(), C, TD);
652 if (Res->isNullValue())
653 return False;
654 } else if (Pred == ICmpInst::ICMP_NE) {
655 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +0000656 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chris Lattnerb52675b2009-11-12 04:36:58 +0000657 Result.getNotConstant(), C, TD);
658 if (Res->isNullValue())
659 return True;
660 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000661 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000662 }
663
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000664 return Unknown;
665}
666
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000667void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
668 BasicBlock* NewSucc) {
669 getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
670}