blob: 48778232002e991bf66f1002011b87fae90c9623 [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"
Owen Anderson5be2e782010-08-05 22:59:19 +000022#include "llvm/Support/ConstantRange.h"
Chris Lattnerb8c124c2009-11-12 01:22:16 +000023#include "llvm/Support/Debug.h"
Chris Lattner16976522009-11-11 22:48:44 +000024#include "llvm/Support/raw_ostream.h"
Owen Anderson7f9cb742010-07-30 23:59:40 +000025#include "llvm/Support/ValueHandle.h"
Chris Lattner16976522009-11-11 22:48:44 +000026#include "llvm/ADT/DenseMap.h"
Owen Anderson9a65dc92010-07-27 23:58:11 +000027#include "llvm/ADT/DenseSet.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,
Owen Anderson5be2e782010-08-05 22:59:19 +000055
Chris Lattnercc4d3b22009-11-11 02:08:33 +000056 /// constant - This LLVM Value has a specific constant value.
57 constant,
Chris Lattnerb52675b2009-11-12 04:36:58 +000058 /// notconstant - This LLVM value is known to not have the specified value.
59 notconstant,
60
Owen Anderson5be2e782010-08-05 22:59:19 +000061 /// constantrange
62 constantrange,
63
Chris Lattnercc4d3b22009-11-11 02:08:33 +000064 /// overdefined - This instruction is not known to be constant, and we know
65 /// it has a value.
66 overdefined
67 };
68
69 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattnerb52675b2009-11-12 04:36:58 +000070 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersondb78d732010-08-05 22:10:46 +000071 LatticeValueTy Tag;
72 Constant *Val;
Owen Anderson5be2e782010-08-05 22:59:19 +000073 ConstantRange Range;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000074
75public:
Owen Anderson5be2e782010-08-05 22:59:19 +000076 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
Chris Lattnercc4d3b22009-11-11 02:08:33 +000077
Chris Lattner16976522009-11-11 22:48:44 +000078 static LVILatticeVal get(Constant *C) {
79 LVILatticeVal Res;
Owen Anderson9f014062010-08-10 20:03:09 +000080 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
81 Res.markConstantRange(ConstantRange(CI->getValue(), CI->getValue()+1));
82 else if (!isa<UndefValue>(C))
83 Res.markConstant(C);
Chris Lattner16976522009-11-11 22:48:44 +000084 return Res;
85 }
Chris Lattnerb52675b2009-11-12 04:36:58 +000086 static LVILatticeVal getNot(Constant *C) {
87 LVILatticeVal Res;
Owen Anderson9f014062010-08-10 20:03:09 +000088 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
89 Res.markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
90 else
91 Res.markNotConstant(C);
Chris Lattnerb52675b2009-11-12 04:36:58 +000092 return Res;
93 }
Owen Anderson625051b2010-08-10 23:20:01 +000094 static LVILatticeVal getRange(ConstantRange CR) {
95 LVILatticeVal Res;
96 Res.markConstantRange(CR);
97 return Res;
98 }
Chris Lattner16976522009-11-11 22:48:44 +000099
Owen Anderson5be2e782010-08-05 22:59:19 +0000100 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; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000105
106 Constant *getConstant() const {
107 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000108 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000109 }
110
Chris Lattnerb52675b2009-11-12 04:36:58 +0000111 Constant *getNotConstant() const {
112 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000113 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000114 }
115
Owen Anderson5be2e782010-08-05 22:59:19 +0000116 ConstantRange getConstantRange() const {
117 assert(isConstantRange() &&
118 "Cannot get the constant-range of a non-constant-range!");
119 return Range;
120 }
121
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000122 /// markOverdefined - Return true if this is a change in status.
123 bool markOverdefined() {
124 if (isOverdefined())
125 return false;
Owen Andersondb78d732010-08-05 22:10:46 +0000126 Tag = overdefined;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000127 return true;
128 }
129
130 /// markConstant - Return true if this is a change in status.
131 bool markConstant(Constant *V) {
132 if (isConstant()) {
133 assert(getConstant() == V && "Marking constant with different value");
134 return false;
135 }
136
137 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000138 Tag = constant;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000139 assert(V && "Marking constant with NULL");
Owen Andersondb78d732010-08-05 22:10:46 +0000140 Val = V;
Chris Lattner16976522009-11-11 22:48:44 +0000141 return true;
142 }
143
Chris Lattnerb52675b2009-11-12 04:36:58 +0000144 /// 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");
148 return false;
149 }
150
151 if (isConstant())
152 assert(getConstant() != V && "Marking not constant with different value");
153 else
154 assert(isUndefined());
155
Owen Andersondb78d732010-08-05 22:10:46 +0000156 Tag = notconstant;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000157 assert(V && "Marking constant with NULL");
Owen Andersondb78d732010-08-05 22:10:46 +0000158 Val = V;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000159 return true;
160 }
161
Owen Anderson5be2e782010-08-05 22:59:19 +0000162 /// 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();
167
Owen Anderson5be2e782010-08-05 22:59:19 +0000168 bool changed = Range == NewR;
169 Range = NewR;
170 return changed;
171 }
172
173 assert(isUndefined());
174 if (NewR.isEmptySet())
175 return markOverdefined();
176 else if (NewR.isFullSet()) {
177 Tag = undefined;
178 return true;
179 }
180
181 Tag = constantrange;
182 Range = NewR;
183 return true;
184 }
185
Chris Lattner16976522009-11-11 22:48:44 +0000186 /// mergeIn - Merge the specified lattice value into this one, updating this
187 /// one and returning true if anything changed.
188 bool mergeIn(const LVILatticeVal &RHS) {
189 if (RHS.isUndefined() || isOverdefined()) return false;
190 if (RHS.isOverdefined()) return markOverdefined();
191
Chris Lattnerb52675b2009-11-12 04:36:58 +0000192 if (RHS.isNotConstant()) {
193 if (isNotConstant()) {
Chris Lattnerf496e792009-11-12 04:57:13 +0000194 if (getNotConstant() != RHS.getNotConstant() ||
195 isa<ConstantExpr>(getNotConstant()) ||
196 isa<ConstantExpr>(RHS.getNotConstant()))
Chris Lattnerb52675b2009-11-12 04:36:58 +0000197 return markOverdefined();
198 return false;
199 }
Chris Lattnerf496e792009-11-12 04:57:13 +0000200 if (isConstant()) {
201 if (getConstant() == RHS.getNotConstant() ||
202 isa<ConstantExpr>(RHS.getNotConstant()) ||
203 isa<ConstantExpr>(getConstant()))
204 return markOverdefined();
205 return markNotConstant(RHS.getNotConstant());
206 }
207
208 assert(isUndefined() && "Unexpected lattice");
Chris Lattnerb52675b2009-11-12 04:36:58 +0000209 return markNotConstant(RHS.getNotConstant());
210 }
211
Owen Anderson5be2e782010-08-05 22:59:19 +0000212 if (RHS.isConstantRange()) {
213 if (isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +0000214 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
215 if (NewR.isFullSet())
Owen Anderson5be2e782010-08-05 22:59:19 +0000216 return markOverdefined();
217 else
218 return markConstantRange(NewR);
219 }
220
221 assert(isUndefined() && "Unexpected lattice");
222 return markConstantRange(RHS.getConstantRange());
223 }
224
Chris Lattnerf496e792009-11-12 04:57:13 +0000225 // RHS must be a constant, we must be undef, constant, or notconstant.
Owen Anderson5be2e782010-08-05 22:59:19 +0000226 assert(!isConstantRange() &&
227 "Constant and ConstantRange cannot be merged.");
228
Chris Lattnerf496e792009-11-12 04:57:13 +0000229 if (isUndefined())
230 return markConstant(RHS.getConstant());
231
232 if (isConstant()) {
233 if (getConstant() != RHS.getConstant())
234 return markOverdefined();
235 return false;
236 }
237
238 // If we are known "!=4" and RHS is "==5", stay at "!=4".
239 if (getNotConstant() == RHS.getConstant() ||
240 isa<ConstantExpr>(getNotConstant()) ||
241 isa<ConstantExpr>(RHS.getConstant()))
Chris Lattner16976522009-11-11 22:48:44 +0000242 return markOverdefined();
Chris Lattnerf496e792009-11-12 04:57:13 +0000243 return false;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000244 }
245
246};
247
248} // end anonymous namespace.
249
Chris Lattner16976522009-11-11 22:48:44 +0000250namespace llvm {
251raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
252 if (Val.isUndefined())
253 return OS << "undefined";
254 if (Val.isOverdefined())
255 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000256
257 if (Val.isNotConstant())
258 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000259 else if (Val.isConstantRange())
260 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
261 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000262 return OS << "constant<" << *Val.getConstant() << '>';
263}
264}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000265
266//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000267// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000268//===----------------------------------------------------------------------===//
269
Chris Lattner2c5adf82009-11-15 19:59:49 +0000270namespace {
271 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
272 /// maintains information about queries across the clients' queries.
273 class LazyValueInfoCache {
Owen Anderson81881bc2010-07-30 20:56:07 +0000274 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000275 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
276 /// specified basic block for a Value* that depends on context.
277 typedef std::pair<BasicBlock*, LVILatticeVal> BlockCacheEntryTy;
278
279 /// ValueCacheEntryTy - This is all of the cached block information for
280 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
281 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000282 typedef std::map<BasicBlock*, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000283
Owen Anderson81881bc2010-07-30 20:56:07 +0000284 private:
Owen Anderson7f9cb742010-07-30 23:59:40 +0000285 /// LVIValueHandle - A callback value handle update the cache when
286 /// values are erased.
287 struct LVIValueHandle : public CallbackVH {
288 LazyValueInfoCache *Parent;
289
290 LVIValueHandle(Value *V, LazyValueInfoCache *P)
291 : CallbackVH(V), Parent(P) { }
292
293 void deleted();
294 void allUsesReplacedWith(Value* V) {
295 deleted();
296 }
297
298 LVIValueHandle &operator=(Value *V) {
299 return *this = LVIValueHandle(V, Parent);
300 }
301 };
302
Chris Lattner2c5adf82009-11-15 19:59:49 +0000303 /// ValueCache - This is all of the cached information for all values,
304 /// mapped from Value* to key information.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000305 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000306
307 /// OverDefinedCache - This tracks, on a per-block basis, the set of
308 /// values that are over-defined at the end of that block. This is required
309 /// for cache updating.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000310 std::set<std::pair<BasicBlock*, Value*> > OverDefinedCache;
311
Chris Lattner2c5adf82009-11-15 19:59:49 +0000312 public:
313
314 /// getValueInBlock - This is the query interface to determine the lattice
315 /// value for the specified Value* at the end of the specified block.
316 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
317
318 /// getValueOnEdge - This is the query interface to determine the lattice
319 /// value for the specified Value* that is true on the specified edge.
320 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000321
322 /// threadEdge - This is the update interface to inform the cache that an
323 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
324 /// NewSucc.
325 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000326 };
327} // end anonymous namespace
328
Owen Anderson81881bc2010-07-30 20:56:07 +0000329//===----------------------------------------------------------------------===//
330// LVIQuery Impl
331//===----------------------------------------------------------------------===//
332
333namespace {
334 /// LVIQuery - This is a transient object that exists while a query is
335 /// being performed.
336 ///
337 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
338 /// reallocation of the densemap on every query.
339 class LVIQuery {
340 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
341 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
342
343 /// This is the current value being queried for.
344 Value *Val;
345
Owen Anderson7f9cb742010-07-30 23:59:40 +0000346 /// This is a pointer to the owning cache, for recursive queries.
347 LazyValueInfoCache &Parent;
348
Owen Anderson81881bc2010-07-30 20:56:07 +0000349 /// This is all of the cached information about this value.
350 ValueCacheEntryTy &Cache;
351
352 /// This tracks, for each block, what values are overdefined.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000353 std::set<std::pair<BasicBlock*, Value*> > &OverDefinedCache;
Owen Anderson81881bc2010-07-30 20:56:07 +0000354
355 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
356 /// added to cache but that are not in sorted order.
357 DenseSet<BasicBlock*> NewBlockInfo;
358 public:
359
Owen Anderson7f9cb742010-07-30 23:59:40 +0000360 LVIQuery(Value *V, LazyValueInfoCache &P,
361 ValueCacheEntryTy &VC,
362 std::set<std::pair<BasicBlock*, Value*> > &ODC)
363 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000364 }
365
366 ~LVIQuery() {
367 // When the query is done, insert the newly discovered facts into the
368 // cache in sorted order.
369 if (NewBlockInfo.empty()) return;
370
371 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
372 E = NewBlockInfo.end(); I != E; ++I) {
373 if (Cache[*I].isOverdefined())
374 OverDefinedCache.insert(std::make_pair(*I, Val));
375 }
376 }
377
378 LVILatticeVal getBlockValue(BasicBlock *BB);
379 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
380
381 private:
382 LVILatticeVal &getCachedEntryForBlock(BasicBlock *BB);
383 };
384} // end anonymous namespace
Chris Lattner2c5adf82009-11-15 19:59:49 +0000385
Owen Anderson7f9cb742010-07-30 23:59:40 +0000386void LazyValueInfoCache::LVIValueHandle::deleted() {
387 Parent->ValueCache.erase(*this);
388 for (std::set<std::pair<BasicBlock*, Value*> >::iterator
389 I = Parent->OverDefinedCache.begin(),
390 E = Parent->OverDefinedCache.end();
391 I != E; ) {
392 std::set<std::pair<BasicBlock*, Value*> >::iterator tmp = I;
393 ++I;
394 if (tmp->second == getValPtr())
395 Parent->OverDefinedCache.erase(tmp);
396 }
397}
398
399
Chris Lattnere5642812009-11-15 20:00:52 +0000400/// getCachedEntryForBlock - See if we already have a value for this block. If
Owen Anderson9a65dc92010-07-27 23:58:11 +0000401/// so, return it, otherwise create a new entry in the Cache map to use.
Owen Anderson81881bc2010-07-30 20:56:07 +0000402LVILatticeVal &LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
403 NewBlockInfo.insert(BB);
Owen Anderson9a65dc92010-07-27 23:58:11 +0000404 return Cache[BB];
Chris Lattnere5642812009-11-15 20:00:52 +0000405}
Chris Lattner2c5adf82009-11-15 19:59:49 +0000406
Owen Anderson81881bc2010-07-30 20:56:07 +0000407LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000408 // See if we already have a value for this block.
Owen Anderson81881bc2010-07-30 20:56:07 +0000409 LVILatticeVal &BBLV = getCachedEntryForBlock(BB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000410
411 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000412 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000413 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Chris Lattner2c5adf82009-11-15 19:59:49 +0000414 return BBLV;
Chris Lattnere5642812009-11-15 20:00:52 +0000415 }
416
Chris Lattner2c5adf82009-11-15 19:59:49 +0000417 // Otherwise, this is the first time we're seeing this block. Reset the
418 // lattice value to overdefined, so that cycles will terminate and be
419 // conservatively correct.
420 BBLV.markOverdefined();
421
422 // If V is live into BB, see if our predecessors know anything about it.
423 Instruction *BBI = dyn_cast<Instruction>(Val);
424 if (BBI == 0 || BBI->getParent() != BB) {
425 LVILatticeVal Result; // Start Undefined.
426 unsigned NumPreds = 0;
427
428 // Loop over all of our predecessors, merging what we know from them into
429 // result.
430 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000431 Result.mergeIn(getEdgeValue(*PI, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000432
433 // If we hit overdefined, exit early. The BlockVals entry is already set
434 // to overdefined.
Chris Lattnere5642812009-11-15 20:00:52 +0000435 if (Result.isOverdefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000436 DEBUG(dbgs() << " compute BB '" << BB->getName()
Chris Lattnere5642812009-11-15 20:00:52 +0000437 << "' - overdefined because of pred.\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000438 return Result;
Chris Lattnere5642812009-11-15 20:00:52 +0000439 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000440 ++NumPreds;
441 }
442
443 // If this is the entry block, we must be asking about an argument. The
444 // value is overdefined.
445 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
446 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
447 Result.markOverdefined();
448 return Result;
449 }
450
451 // Return the merged value, which is more precise than 'overdefined'.
452 assert(!Result.isOverdefined());
Owen Anderson81881bc2010-07-30 20:56:07 +0000453 return getCachedEntryForBlock(BB) = Result;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000454 }
455
456 // If this value is defined by an instruction in this block, we have to
457 // process it here somehow or return overdefined.
458 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson7f9cb742010-07-30 23:59:40 +0000459 LVILatticeVal Result; // Start Undefined.
460
461 // Loop over all of our predecessors, merging what we know from them into
462 // result.
463 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
464 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
465 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
466
467 // If we hit overdefined, exit early. The BlockVals entry is already set
468 // to overdefined.
469 if (Result.isOverdefined()) {
470 DEBUG(dbgs() << " compute BB '" << BB->getName()
471 << "' - overdefined because of pred.\n");
472 return Result;
473 }
474 }
475
476 // Return the merged value, which is more precise than 'overdefined'.
477 assert(!Result.isOverdefined());
478 return getCachedEntryForBlock(BB) = Result;
479
Chris Lattner2c5adf82009-11-15 19:59:49 +0000480 } else {
481
482 }
483
David Greene5d93a1f2009-12-23 20:43:58 +0000484 DEBUG(dbgs() << " compute BB '" << BB->getName()
Chris Lattnere5642812009-11-15 20:00:52 +0000485 << "' - overdefined because inst def found.\n");
486
Chris Lattner2c5adf82009-11-15 19:59:49 +0000487 LVILatticeVal Result;
488 Result.markOverdefined();
Owen Anderson81881bc2010-07-30 20:56:07 +0000489 return getCachedEntryForBlock(BB) = Result;
Chris Lattner10f2d132009-11-11 00:22:30 +0000490}
491
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000492
Chris Lattner800c47e2009-11-15 20:02:12 +0000493/// getEdgeValue - This method attempts to infer more complex
Owen Anderson81881bc2010-07-30 20:56:07 +0000494LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
Chris Lattner800c47e2009-11-15 20:02:12 +0000495 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
496 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000497 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
498 // If this is a conditional branch and only one successor goes to BBTo, then
499 // we maybe able to infer something from the condition.
500 if (BI->isConditional() &&
501 BI->getSuccessor(0) != BI->getSuccessor(1)) {
502 bool isTrueDest = BI->getSuccessor(0) == BBTo;
503 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
504 "BBTo isn't a successor of BBFrom");
505
506 // If V is the condition of the branch itself, then we know exactly what
507 // it is.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000508 if (BI->getCondition() == Val)
Chris Lattner16976522009-11-11 22:48:44 +0000509 return LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000510 Type::getInt1Ty(Val->getContext()), isTrueDest));
Chris Lattner16976522009-11-11 22:48:44 +0000511
512 // If the condition of the branch is an equality comparison, we may be
513 // able to infer the value.
514 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
Owen Anderson625051b2010-08-10 23:20:01 +0000515 if (ICI->getOperand(0) == Val && isa<Constant>(ICI->getOperand(1))) {
516 if (ICI->isEquality()) {
517 // We know that V has the RHS constant if this is a true SETEQ or
518 // false SETNE.
519 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
520 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
521 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
522 } else if (ConstantInt *CI =
523 dyn_cast<ConstantInt>(ICI->getOperand(1))) {
524
525 // Calculate the range of values that would satisfy the comparison.
526 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
527 ConstantRange TrueValues =
528 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
529
530 // If we're interested in the false dest, invert the condition.
531 if (!isTrueDest) TrueValues = TrueValues.inverse();
532
533 // Figure out the possible values of the query BEFORE this branch.
534 LVILatticeVal InBlock = getBlockValue(BBFrom);
535 if (!InBlock.isConstantRange()) return InBlock;
536
537 // Find all potential values that satisfy both the input and output
538 // conditions.
539 ConstantRange PossibleValues =
540 TrueValues.intersectWith(InBlock.getConstantRange());
541
542 return LVILatticeVal::getRange(PossibleValues);
543 }
Chris Lattner16976522009-11-11 22:48:44 +0000544 }
545 }
546 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000547
548 // If the edge was formed by a switch on the value, then we may know exactly
549 // what it is.
550 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
551 // If BBTo is the default destination of the switch, we don't know anything.
552 // Given a more powerful range analysis we could know stuff.
553 if (SI->getCondition() == Val && SI->getDefaultDest() != BBTo) {
554 // We only know something if there is exactly one value that goes from
555 // BBFrom to BBTo.
556 unsigned NumEdges = 0;
557 ConstantInt *EdgeVal = 0;
558 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
559 if (SI->getSuccessor(i) != BBTo) continue;
560 if (NumEdges++) break;
561 EdgeVal = SI->getCaseValue(i);
562 }
563 assert(EdgeVal && "Missing successor?");
564 if (NumEdges == 1)
565 return LVILatticeVal::get(EdgeVal);
566 }
567 }
Chris Lattner16976522009-11-11 22:48:44 +0000568
569 // Otherwise see if the value is known in the block.
Owen Anderson81881bc2010-07-30 20:56:07 +0000570 return getBlockValue(BBFrom);
Chris Lattner16976522009-11-11 22:48:44 +0000571}
572
Owen Anderson81881bc2010-07-30 20:56:07 +0000573
574//===----------------------------------------------------------------------===//
575// LazyValueInfoCache Impl
576//===----------------------------------------------------------------------===//
577
Chris Lattner2c5adf82009-11-15 19:59:49 +0000578LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
579 // If already a constant, there is nothing to compute.
Chris Lattner16976522009-11-11 22:48:44 +0000580 if (Constant *VC = dyn_cast<Constant>(V))
Chris Lattner2c5adf82009-11-15 19:59:49 +0000581 return LVILatticeVal::get(VC);
Chris Lattner16976522009-11-11 22:48:44 +0000582
David Greene5d93a1f2009-12-23 20:43:58 +0000583 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000584 << BB->getName() << "'\n");
585
Owen Anderson7f9cb742010-07-30 23:59:40 +0000586 LVILatticeVal Result = LVIQuery(V, *this,
587 ValueCache[LVIValueHandle(V, this)],
Owen Anderson81881bc2010-07-30 20:56:07 +0000588 OverDefinedCache).getBlockValue(BB);
Chris Lattner16976522009-11-11 22:48:44 +0000589
David Greene5d93a1f2009-12-23 20:43:58 +0000590 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000591 return Result;
592}
Chris Lattner16976522009-11-11 22:48:44 +0000593
Chris Lattner2c5adf82009-11-15 19:59:49 +0000594LVILatticeVal LazyValueInfoCache::
595getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
596 // If already a constant, there is nothing to compute.
597 if (Constant *VC = dyn_cast<Constant>(V))
598 return LVILatticeVal::get(VC);
599
David Greene5d93a1f2009-12-23 20:43:58 +0000600 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000601 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000602
Owen Anderson81881bc2010-07-30 20:56:07 +0000603 LVILatticeVal Result =
Owen Anderson7f9cb742010-07-30 23:59:40 +0000604 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
Owen Anderson81881bc2010-07-30 20:56:07 +0000605 OverDefinedCache).getEdgeValue(FromBB, ToBB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000606
David Greene5d93a1f2009-12-23 20:43:58 +0000607 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000608
609 return Result;
610}
611
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000612void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
613 BasicBlock *NewSucc) {
614 // When an edge in the graph has been threaded, values that we could not
615 // determine a value for before (i.e. were marked overdefined) may be possible
616 // to solve now. We do NOT try to proactively update these values. Instead,
617 // we clear their entries from the cache, and allow lazy updating to recompute
618 // them when needed.
619
620 // The updating process is fairly simple: we need to dropped cached info
621 // for all values that were marked overdefined in OldSucc, and for those same
622 // values in any successor of OldSucc (except NewSucc) in which they were
623 // also marked overdefined.
624 std::vector<BasicBlock*> worklist;
625 worklist.push_back(OldSucc);
626
Owen Anderson9a65dc92010-07-27 23:58:11 +0000627 DenseSet<Value*> ClearSet;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000628 for (std::set<std::pair<BasicBlock*, Value*> >::iterator
Owen Anderson9a65dc92010-07-27 23:58:11 +0000629 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
630 if (I->first == OldSucc)
631 ClearSet.insert(I->second);
632 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000633
634 // Use a worklist to perform a depth-first search of OldSucc's successors.
635 // NOTE: We do not need a visited list since any blocks we have already
636 // visited will have had their overdefined markers cleared already, and we
637 // thus won't loop to their successors.
638 while (!worklist.empty()) {
639 BasicBlock *ToUpdate = worklist.back();
640 worklist.pop_back();
641
642 // Skip blocks only accessible through NewSucc.
643 if (ToUpdate == NewSucc) continue;
644
645 bool changed = false;
Owen Anderson9a65dc92010-07-27 23:58:11 +0000646 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000647 I != E; ++I) {
648 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson7f9cb742010-07-30 23:59:40 +0000649 std::set<std::pair<BasicBlock*, Value*> >::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000650 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
651 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000652
Owen Anderson9a65dc92010-07-27 23:58:11 +0000653 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000654 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000655 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
656
657 assert(CI != Entry.end() && "Couldn't find entry to update?");
658 Entry.erase(CI);
659 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000660
Owen Anderson9a65dc92010-07-27 23:58:11 +0000661 // If we removed anything, then we potentially need to update
662 // blocks successors too.
663 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000664 }
665
666 if (!changed) continue;
667
668 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
669 }
670}
671
Chris Lattner2c5adf82009-11-15 19:59:49 +0000672//===----------------------------------------------------------------------===//
673// LazyValueInfo Impl
674//===----------------------------------------------------------------------===//
675
676bool LazyValueInfo::runOnFunction(Function &F) {
677 TD = getAnalysisIfAvailable<TargetData>();
678 // Fully lazy.
679 return false;
680}
681
682/// getCache - This lazily constructs the LazyValueInfoCache.
683static LazyValueInfoCache &getCache(void *&PImpl) {
684 if (!PImpl)
685 PImpl = new LazyValueInfoCache();
686 return *static_cast<LazyValueInfoCache*>(PImpl);
687}
688
689void LazyValueInfo::releaseMemory() {
690 // If the cache was allocated, free it.
691 if (PImpl) {
692 delete &getCache(PImpl);
693 PImpl = 0;
694 }
695}
696
697Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
698 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
699
Chris Lattner16976522009-11-11 22:48:44 +0000700 if (Result.isConstant())
701 return Result.getConstant();
702 return 0;
703}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000704
Chris Lattner38392bb2009-11-12 01:29:10 +0000705/// getConstantOnEdge - Determine whether the specified value is known to be a
706/// constant on the specified edge. Return null if not.
707Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
708 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000709 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +0000710
711 if (Result.isConstant())
712 return Result.getConstant();
Owen Anderson9f014062010-08-10 20:03:09 +0000713 else if (Result.isConstantRange()) {
714 ConstantRange CR = Result.getConstantRange();
715 if (const APInt *SingleVal = CR.getSingleElement())
716 return ConstantInt::get(V->getContext(), *SingleVal);
717 }
Chris Lattner38392bb2009-11-12 01:29:10 +0000718 return 0;
719}
720
Chris Lattnerb52675b2009-11-12 04:36:58 +0000721/// getPredicateOnEdge - Determine whether the specified value comparison
722/// with a constant is known to be true or false on the specified CFG edge.
723/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000724LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +0000725LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
726 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000727 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000728
Chris Lattnerb52675b2009-11-12 04:36:58 +0000729 // If we know the value is a constant, evaluate the conditional.
730 Constant *Res = 0;
731 if (Result.isConstant()) {
732 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
733 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
734 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000735 return Unknown;
736 }
737
Owen Anderson9f014062010-08-10 20:03:09 +0000738 if (Result.isConstantRange()) {
739 ConstantInt *CI = cast<ConstantInt>(C);
740 ConstantRange CR = Result.getConstantRange();
741 if (Pred == ICmpInst::ICMP_EQ) {
742 if (!CR.contains(CI->getValue()))
743 return False;
744
745 if (CR.isSingleElement() && CR.contains(CI->getValue()))
746 return True;
747 } else if (Pred == ICmpInst::ICMP_NE) {
748 if (!CR.contains(CI->getValue()))
749 return True;
750
751 if (CR.isSingleElement() && CR.contains(CI->getValue()))
752 return False;
753 }
754
755 // Handle more complex predicates.
756 ConstantRange RHS(CI->getValue(), CI->getValue()+1);
757 ConstantRange TrueValues = ConstantRange::makeICmpRegion(Pred, RHS);
758 if (CR.intersectWith(TrueValues).isEmptySet())
759 return False;
Owen Anderson625051b2010-08-10 23:20:01 +0000760 else if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +0000761 return True;
762
763 return Unknown;
764 }
765
Chris Lattner2c5adf82009-11-15 19:59:49 +0000766 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000767 // If this is an equality comparison, we can try to fold it knowing that
768 // "V != C1".
769 if (Pred == ICmpInst::ICMP_EQ) {
770 // !C1 == C -> false iff C1 == C.
771 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
772 Result.getNotConstant(), C, TD);
773 if (Res->isNullValue())
774 return False;
775 } else if (Pred == ICmpInst::ICMP_NE) {
776 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +0000777 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chris Lattnerb52675b2009-11-12 04:36:58 +0000778 Result.getNotConstant(), C, TD);
779 if (Res->isNullValue())
780 return True;
781 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000782 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000783 }
784
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000785 return Unknown;
786}
787
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000788void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
789 BasicBlock* NewSucc) {
790 getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
791}