blob: f0664bfa9dd5650df2b8de919668bb5d883d48d9 [file] [log] [blame]
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001//===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
Chris Lattner741c94c2009-11-11 00:22:30 +00002//
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
15#include "llvm/Analysis/LazyValueInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
Hal Finkel7e184492014-09-07 20:29:59 +000018#include "llvm/Analysis/AssumptionTracker.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000020#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000021#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000022#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
Hal Finkel7e184492014-09-07 20:29:59 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Instructions.h"
27#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000028#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000029#include "llvm/IR/ValueHandle.h"
Chris Lattnerb584d1e2009-11-12 01:22:16 +000030#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Support/raw_ostream.h"
32#include "llvm/Target/TargetLibraryInfo.h"
Bill Wendling4ec081a2012-01-11 23:43:34 +000033#include <map>
Nick Lewycky55a700b2010-12-18 01:00:40 +000034#include <stack>
Chris Lattner741c94c2009-11-11 00:22:30 +000035using namespace llvm;
Benjamin Kramerd9d80b12012-03-02 15:34:43 +000036using namespace PatternMatch;
Chris Lattner741c94c2009-11-11 00:22:30 +000037
Chandler Carruthf1221bd2014-04-22 02:48:03 +000038#define DEBUG_TYPE "lazy-value-info"
39
Chris Lattner741c94c2009-11-11 00:22:30 +000040char LazyValueInfo::ID = 0;
Chad Rosier43a33062011-12-02 01:26:24 +000041INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
42 "Lazy Value Information Analysis", false, true)
Hal Finkel7e184492014-09-07 20:29:59 +000043INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
Chad Rosier43a33062011-12-02 01:26:24 +000044INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
45INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
Owen Andersondf7a4f22010-10-07 22:25:06 +000046 "Lazy Value Information Analysis", false, true)
Chris Lattner741c94c2009-11-11 00:22:30 +000047
48namespace llvm {
49 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
50}
51
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000052
53//===----------------------------------------------------------------------===//
54// LVILatticeVal
55//===----------------------------------------------------------------------===//
56
57/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
58/// value.
59///
60/// FIXME: This is basically just for bringup, this can be made a lot more rich
61/// in the future.
62///
63namespace {
64class LVILatticeVal {
65 enum LatticeValueTy {
Nick Lewycky11678bd2010-12-15 18:57:18 +000066 /// undefined - This Value has no known value yet.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000067 undefined,
Owen Anderson0f306a42010-08-05 22:59:19 +000068
Nick Lewycky11678bd2010-12-15 18:57:18 +000069 /// constant - This Value has a specific constant value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000070 constant,
Nick Lewycky11678bd2010-12-15 18:57:18 +000071 /// notconstant - This Value is known to not have the specified value.
Chris Lattner565ee2f2009-11-12 04:36:58 +000072 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000073
Nick Lewycky11678bd2010-12-15 18:57:18 +000074 /// constantrange - The Value falls within this range.
Owen Anderson0f306a42010-08-05 22:59:19 +000075 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000076
Nick Lewycky11678bd2010-12-15 18:57:18 +000077 /// overdefined - This value is not known to be constant, and we know that
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000078 /// it has a value.
79 overdefined
80 };
81
82 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000083 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000084 LatticeValueTy Tag;
85 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +000086 ConstantRange Range;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000087
88public:
Craig Topper9f008862014-04-15 04:59:12 +000089 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000090
Chris Lattner19019ea2009-11-11 22:48:44 +000091 static LVILatticeVal get(Constant *C) {
92 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +000093 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +000094 Res.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +000095 return Res;
96 }
Chris Lattner565ee2f2009-11-12 04:36:58 +000097 static LVILatticeVal getNot(Constant *C) {
98 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +000099 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000100 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000101 return Res;
102 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000103 static LVILatticeVal getRange(ConstantRange CR) {
104 LVILatticeVal Res;
105 Res.markConstantRange(CR);
106 return Res;
107 }
Chris Lattner19019ea2009-11-11 22:48:44 +0000108
Owen Anderson0f306a42010-08-05 22:59:19 +0000109 bool isUndefined() const { return Tag == undefined; }
110 bool isConstant() const { return Tag == constant; }
111 bool isNotConstant() const { return Tag == notconstant; }
112 bool isConstantRange() const { return Tag == constantrange; }
113 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000114
115 Constant *getConstant() const {
116 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000117 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000118 }
119
Chris Lattner565ee2f2009-11-12 04:36:58 +0000120 Constant *getNotConstant() const {
121 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000122 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000123 }
124
Owen Anderson0f306a42010-08-05 22:59:19 +0000125 ConstantRange getConstantRange() const {
126 assert(isConstantRange() &&
127 "Cannot get the constant-range of a non-constant-range!");
128 return Range;
129 }
130
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000131 /// markOverdefined - Return true if this is a change in status.
132 bool markOverdefined() {
133 if (isOverdefined())
134 return false;
Owen Andersonc3a14132010-08-05 22:10:46 +0000135 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000136 return true;
137 }
138
139 /// markConstant - Return true if this is a change in status.
140 bool markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000141 assert(V && "Marking constant with NULL");
142 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
143 return markConstantRange(ConstantRange(CI->getValue()));
144 if (isa<UndefValue>(V))
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000145 return false;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000146
147 assert((!isConstant() || getConstant() == V) &&
148 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000149 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000150 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000151 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000152 return true;
153 }
154
Chris Lattner565ee2f2009-11-12 04:36:58 +0000155 /// markNotConstant - Return true if this is a change in status.
156 bool markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000157 assert(V && "Marking constant with NULL");
Nick Lewycky11678bd2010-12-15 18:57:18 +0000158 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
159 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
160 if (isa<UndefValue>(V))
161 return false;
162
163 assert((!isConstant() || getConstant() != V) &&
164 "Marking constant !constant with same value");
165 assert((!isNotConstant() || getNotConstant() == V) &&
166 "Marking !constant with different value");
167 assert(isUndefined() || isConstant());
168 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000169 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000170 return true;
171 }
172
Owen Anderson0f306a42010-08-05 22:59:19 +0000173 /// markConstantRange - Return true if this is a change in status.
174 bool markConstantRange(const ConstantRange NewR) {
175 if (isConstantRange()) {
176 if (NewR.isEmptySet())
177 return markOverdefined();
178
Nuno Lopese6e04902012-06-28 01:16:18 +0000179 bool changed = Range != NewR;
Owen Anderson0f306a42010-08-05 22:59:19 +0000180 Range = NewR;
181 return changed;
182 }
183
184 assert(isUndefined());
185 if (NewR.isEmptySet())
186 return markOverdefined();
Owen Anderson0f306a42010-08-05 22:59:19 +0000187
188 Tag = constantrange;
189 Range = NewR;
190 return true;
191 }
192
Chris Lattner19019ea2009-11-11 22:48:44 +0000193 /// mergeIn - Merge the specified lattice value into this one, updating this
194 /// one and returning true if anything changed.
195 bool mergeIn(const LVILatticeVal &RHS) {
196 if (RHS.isUndefined() || isOverdefined()) return false;
197 if (RHS.isOverdefined()) return markOverdefined();
198
Nick Lewycky11678bd2010-12-15 18:57:18 +0000199 if (isUndefined()) {
200 Tag = RHS.Tag;
201 Val = RHS.Val;
202 Range = RHS.Range;
203 return true;
Chris Lattner22db4b52009-11-12 04:57:13 +0000204 }
205
Nick Lewycky11678bd2010-12-15 18:57:18 +0000206 if (isConstant()) {
207 if (RHS.isConstant()) {
208 if (Val == RHS.Val)
209 return false;
210 return markOverdefined();
211 }
212
213 if (RHS.isNotConstant()) {
214 if (Val == RHS.Val)
215 return markOverdefined();
216
217 // Unless we can prove that the two Constants are different, we must
218 // move to overdefined.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000219 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
Nick Lewycky11678bd2010-12-15 18:57:18 +0000220 if (ConstantInt *Res = dyn_cast<ConstantInt>(
221 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
222 getConstant(),
223 RHS.getNotConstant())))
224 if (Res->isOne())
225 return markNotConstant(RHS.getNotConstant());
226
227 return markOverdefined();
228 }
229
230 // RHS is a ConstantRange, LHS is a non-integer Constant.
231
232 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
233 // a function. The correct result is to pick up RHS.
234
Chris Lattner19019ea2009-11-11 22:48:44 +0000235 return markOverdefined();
Nick Lewycky11678bd2010-12-15 18:57:18 +0000236 }
237
238 if (isNotConstant()) {
239 if (RHS.isConstant()) {
240 if (Val == RHS.Val)
241 return markOverdefined();
242
243 // Unless we can prove that the two Constants are different, we must
244 // move to overdefined.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000245 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
Nick Lewycky11678bd2010-12-15 18:57:18 +0000246 if (ConstantInt *Res = dyn_cast<ConstantInt>(
247 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
248 getNotConstant(),
249 RHS.getConstant())))
250 if (Res->isOne())
251 return false;
252
253 return markOverdefined();
254 }
255
256 if (RHS.isNotConstant()) {
257 if (Val == RHS.Val)
258 return false;
259 return markOverdefined();
260 }
261
262 return markOverdefined();
263 }
264
265 assert(isConstantRange() && "New LVILattice type?");
266 if (!RHS.isConstantRange())
267 return markOverdefined();
268
269 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
270 if (NewR.isFullSet())
271 return markOverdefined();
272 return markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000273 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000274};
275
276} // end anonymous namespace.
277
Chris Lattner19019ea2009-11-11 22:48:44 +0000278namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000279raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
280 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000281raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
282 if (Val.isUndefined())
283 return OS << "undefined";
284 if (Val.isOverdefined())
285 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000286
287 if (Val.isNotConstant())
288 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson8afac042010-08-09 20:50:46 +0000289 else if (Val.isConstantRange())
290 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
291 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000292 return OS << "constant<" << *Val.getConstant() << '>';
293}
294}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000295
296//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000297// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000298//===----------------------------------------------------------------------===//
299
Chris Lattneraf025d32009-11-15 19:59:49 +0000300namespace {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000301 /// LVIValueHandle - A callback value handle updates the cache when
Owen Anderson118ac802011-01-05 21:15:29 +0000302 /// values are erased.
303 class LazyValueInfoCache;
304 struct LVIValueHandle : public CallbackVH {
305 LazyValueInfoCache *Parent;
306
307 LVIValueHandle(Value *V, LazyValueInfoCache *P)
308 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000309
310 void deleted() override;
311 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000312 deleted();
313 }
314 };
315}
316
Owen Anderson118ac802011-01-05 21:15:29 +0000317namespace {
Chris Lattneraf025d32009-11-15 19:59:49 +0000318 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
319 /// maintains information about queries across the clients' queries.
320 class LazyValueInfoCache {
Chris Lattneraf025d32009-11-15 19:59:49 +0000321 /// ValueCacheEntryTy - This is all of the cached block information for
322 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
323 /// entries, allowing us to do a lookup with a binary search.
Bill Wendling4ec081a2012-01-11 23:43:34 +0000324 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattneraf025d32009-11-15 19:59:49 +0000325
Owen Anderson6f060af2011-01-05 23:26:22 +0000326 /// ValueCache - This is all of the cached information for all values,
327 /// mapped from Value* to key information.
Bill Wendling58c75692012-01-12 01:41:03 +0000328 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Anderson6f060af2011-01-05 23:26:22 +0000329
330 /// OverDefinedCache - This tracks, on a per-block basis, the set of
331 /// values that are over-defined at the end of that block. This is required
332 /// for cache updating.
333 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
334 DenseSet<OverDefinedPairTy> OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000335
336 /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
337 /// don't spend time removing unused blocks from our caches.
338 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
339
Owen Anderson6f060af2011-01-05 23:26:22 +0000340 /// BlockValueStack - This stack holds the state of the value solver
341 /// during a query. It basically emulates the callstack of the naive
342 /// recursive value lookup process.
343 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
Hal Finkel7e184492014-09-07 20:29:59 +0000344
345 /// A pointer to the cache of @llvm.assume calls.
346 AssumptionTracker *AT;
347 /// An optional DL pointer.
348 const DataLayout *DL;
349 /// An optional DT pointer.
350 DominatorTree *DT;
Owen Anderson6f060af2011-01-05 23:26:22 +0000351
Owen Anderson118ac802011-01-05 21:15:29 +0000352 friend struct LVIValueHandle;
Owen Andersond83f98a2010-12-20 19:33:41 +0000353
354 /// OverDefinedCacheUpdater - A helper object that ensures that the
355 /// OverDefinedCache is updated whenever solveBlockValue returns.
356 struct OverDefinedCacheUpdater {
357 LazyValueInfoCache *Parent;
358 Value *Val;
359 BasicBlock *BB;
360 LVILatticeVal &BBLV;
361
362 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
363 LazyValueInfoCache *P)
364 : Parent(P), Val(V), BB(B), BBLV(LV) { }
365
366 bool markResult(bool changed) {
367 if (changed && BBLV.isOverdefined())
368 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
369 return changed;
370 }
371 };
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000372
Owen Anderson6f060af2011-01-05 23:26:22 +0000373
Owen Andersonc1561b82010-07-30 23:59:40 +0000374
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000375 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000376 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
Hal Finkel7e184492014-09-07 20:29:59 +0000377 LVILatticeVal &Result,
378 Instruction *CxtI = nullptr);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000379 bool hasBlockValue(Value *Val, BasicBlock *BB);
380
381 // These methods process one work item and may add more. A false value
382 // returned means that the work item was not completely processed and must
383 // be revisited after going through the new items.
384 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson64c2c572010-12-20 18:18:16 +0000385 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
386 Value *Val, BasicBlock *BB);
387 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
388 PHINode *PN, BasicBlock *BB);
389 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
390 Instruction *BBI, BasicBlock *BB);
Hal Finkel7e184492014-09-07 20:29:59 +0000391 void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
392 Instruction *BBI);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000393
394 void solve();
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000395
Nick Lewycky11678bd2010-12-15 18:57:18 +0000396 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000397 return ValueCache[LVIValueHandle(V, this)];
398 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000399
Chris Lattneraf025d32009-11-15 19:59:49 +0000400 public:
Chris Lattneraf025d32009-11-15 19:59:49 +0000401 /// getValueInBlock - This is the query interface to determine the lattice
402 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000403 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
404 Instruction *CxtI = nullptr);
405
406 /// getValueAt - This is the query interface to determine the lattice
407 /// value for the specified Value* at the specified instruction (generally
408 /// from an assume intrinsic).
409 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000410
411 /// getValueOnEdge - This is the query interface to determine the lattice
412 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000413 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
414 Instruction *CxtI = nullptr);
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000415
416 /// threadEdge - This is the update interface to inform the cache that an
417 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
418 /// NewSucc.
419 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson208636f2010-08-18 18:39:01 +0000420
421 /// eraseBlock - This is part of the update interface to inform the cache
422 /// that a block has been deleted.
423 void eraseBlock(BasicBlock *BB);
424
425 /// clear - Empty the cache.
426 void clear() {
Benjamin Kramerbbf3c602011-12-03 15:19:55 +0000427 SeenBlocks.clear();
Owen Anderson208636f2010-08-18 18:39:01 +0000428 ValueCache.clear();
429 OverDefinedCache.clear();
430 }
Hal Finkel7e184492014-09-07 20:29:59 +0000431
432 LazyValueInfoCache(AssumptionTracker *AT,
433 const DataLayout *DL = nullptr,
434 DominatorTree *DT = nullptr) : AT(AT), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000435 };
436} // end anonymous namespace
437
Owen Anderson118ac802011-01-05 21:15:29 +0000438void LVIValueHandle::deleted() {
439 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
440
441 SmallVector<OverDefinedPairTy, 4> ToErase;
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000442 for (const OverDefinedPairTy &P : Parent->OverDefinedCache)
443 if (P.second == getValPtr())
444 ToErase.push_back(P);
445 for (const OverDefinedPairTy &P : ToErase)
446 Parent->OverDefinedCache.erase(P);
Owen Anderson118ac802011-01-05 21:15:29 +0000447
Owen Anderson7b974a42010-08-11 22:36:04 +0000448 // This erasure deallocates *this, so it MUST happen after we're done
449 // using any and all members of *this.
450 Parent->ValueCache.erase(*this);
Owen Andersonc1561b82010-07-30 23:59:40 +0000451}
452
Owen Anderson208636f2010-08-18 18:39:01 +0000453void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramer36647082011-12-03 15:16:45 +0000454 // Shortcut if we have never seen this block.
455 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
456 if (I == SeenBlocks.end())
457 return;
458 SeenBlocks.erase(I);
459
Owen Anderson118ac802011-01-05 21:15:29 +0000460 SmallVector<OverDefinedPairTy, 4> ToErase;
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000461 for (const OverDefinedPairTy& P : OverDefinedCache)
462 if (P.first == BB)
463 ToErase.push_back(P);
464 for (const OverDefinedPairTy &P : ToErase)
465 OverDefinedCache.erase(P);
Owen Anderson208636f2010-08-18 18:39:01 +0000466
Bill Wendling58c75692012-01-12 01:41:03 +0000467 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
Owen Anderson208636f2010-08-18 18:39:01 +0000468 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
469 I->second.erase(BB);
470}
Owen Andersonc1561b82010-07-30 23:59:40 +0000471
Nick Lewycky55a700b2010-12-18 01:00:40 +0000472void LazyValueInfoCache::solve() {
Owen Anderson6f060af2011-01-05 23:26:22 +0000473 while (!BlockValueStack.empty()) {
474 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Nuno Lopese6e04902012-06-28 01:16:18 +0000475 if (solveBlockValue(e.second, e.first)) {
476 assert(BlockValueStack.top() == e);
Owen Anderson6f060af2011-01-05 23:26:22 +0000477 BlockValueStack.pop();
Nuno Lopese6e04902012-06-28 01:16:18 +0000478 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000479 }
480}
481
482bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
483 // If already a constant, there is nothing to compute.
484 if (isa<Constant>(Val))
485 return true;
486
Owen Anderson118ac802011-01-05 21:15:29 +0000487 LVIValueHandle ValHandle(Val, this);
Benjamin Kramerf29db272012-08-22 15:37:57 +0000488 std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
489 ValueCache.find(ValHandle);
490 if (I == ValueCache.end()) return false;
491 return I->second.count(BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000492}
493
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000494LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000495 // If already a constant, there is nothing to compute.
496 if (Constant *VC = dyn_cast<Constant>(Val))
497 return LVILatticeVal::get(VC);
498
Benjamin Kramer36647082011-12-03 15:16:45 +0000499 SeenBlocks.insert(BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000500 return lookup(Val)[BB];
501}
502
503bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
504 if (isa<Constant>(Val))
505 return true;
506
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000507 ValueCacheEntryTy &Cache = lookup(Val);
Benjamin Kramer36647082011-12-03 15:16:45 +0000508 SeenBlocks.insert(BB);
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000509 LVILatticeVal &BBLV = Cache[BB];
Owen Andersond83f98a2010-12-20 19:33:41 +0000510
511 // OverDefinedCacheUpdater is a helper object that will update
512 // the OverDefinedCache for us when this method exits. Make sure to
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000513 // call markResult on it as we exit, passing a bool to indicate if the
514 // cache needs updating, i.e. if we have solved a new value or not.
Owen Andersond83f98a2010-12-20 19:33:41 +0000515 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000516
James Molloycb7449d2014-10-03 09:29:24 +0000517 if (!BBLV.isUndefined()) {
David Greene37e98092009-12-23 20:43:58 +0000518 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Owen Andersond83f98a2010-12-20 19:33:41 +0000519
520 // Since we're reusing a cached value here, we don't need to update the
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000521 // OverDefinedCache. The cache will have been properly updated
Owen Andersond83f98a2010-12-20 19:33:41 +0000522 // whenever the cached value was inserted.
523 ODCacheUpdater.markResult(false);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000524 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000525 }
526
Chris Lattneraf025d32009-11-15 19:59:49 +0000527 // Otherwise, this is the first time we're seeing this block. Reset the
528 // lattice value to overdefined, so that cycles will terminate and be
529 // conservatively correct.
530 BBLV.markOverdefined();
531
Chris Lattneraf025d32009-11-15 19:59:49 +0000532 Instruction *BBI = dyn_cast<Instruction>(Val);
Craig Topper9f008862014-04-15 04:59:12 +0000533 if (!BBI || BBI->getParent() != BB) {
Owen Andersond83f98a2010-12-20 19:33:41 +0000534 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
Chris Lattneraf025d32009-11-15 19:59:49 +0000535 }
Chris Lattner2c708562009-11-15 20:00:52 +0000536
Nick Lewycky55a700b2010-12-18 01:00:40 +0000537 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Andersond83f98a2010-12-20 19:33:41 +0000538 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
Nick Lewycky55a700b2010-12-18 01:00:40 +0000539 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000540
Nick Lewycky367f98f2011-01-15 09:16:12 +0000541 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
542 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
543 return ODCacheUpdater.markResult(true);
544 }
545
Owen Anderson80d19f02010-08-18 21:11:37 +0000546 // We can only analyze the definitions of certain classes of instructions
547 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattneraf025d32009-11-15 19:59:49 +0000548 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000549 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
550 !BBI->getType()->isIntegerTy()) {
551 DEBUG(dbgs() << " compute BB '" << BB->getName()
552 << "' - overdefined because inst def found.\n");
Owen Anderson64c2c572010-12-20 18:18:16 +0000553 BBLV.markOverdefined();
Owen Andersond83f98a2010-12-20 19:33:41 +0000554 return ODCacheUpdater.markResult(true);
Owen Anderson80d19f02010-08-18 21:11:37 +0000555 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000556
Owen Anderson80d19f02010-08-18 21:11:37 +0000557 // FIXME: We're currently limited to binops with a constant RHS. This should
558 // be improved.
559 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
560 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
561 DEBUG(dbgs() << " compute BB '" << BB->getName()
562 << "' - overdefined because inst def found.\n");
563
Owen Anderson64c2c572010-12-20 18:18:16 +0000564 BBLV.markOverdefined();
Owen Andersond83f98a2010-12-20 19:33:41 +0000565 return ODCacheUpdater.markResult(true);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000566 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000567
Owen Andersond83f98a2010-12-20 19:33:41 +0000568 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
Nick Lewycky55a700b2010-12-18 01:00:40 +0000569}
570
571static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
572 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
573 return L->getPointerAddressSpace() == 0 &&
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000574 GetUnderlyingObject(L->getPointerOperand()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000575 }
576 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
577 return S->getPointerAddressSpace() == 0 &&
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000578 GetUnderlyingObject(S->getPointerOperand()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000579 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000580 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
581 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000582
583 // FIXME: check whether it has a valuerange that excludes zero?
584 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
585 if (!Len || Len->isZero()) return false;
586
Eli Friedman7a5fc692011-05-31 20:40:16 +0000587 if (MI->getDestAddressSpace() == 0)
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000588 if (GetUnderlyingObject(MI->getRawDest()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000589 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000590 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000591 if (MTI->getSourceAddressSpace() == 0)
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000592 if (GetUnderlyingObject(MTI->getRawSource()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000593 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000594 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000595 return false;
596}
597
Owen Anderson64c2c572010-12-20 18:18:16 +0000598bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
599 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000600 LVILatticeVal Result; // Start Undefined.
601
602 // If this is a pointer, and there's a load from that pointer in this BB,
603 // then we know that the pointer can't be NULL.
604 bool NotNull = false;
605 if (Val->getType()->isPointerTy()) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000606 if (isKnownNonNull(Val)) {
Nick Lewycky367f98f2011-01-15 09:16:12 +0000607 NotNull = true;
608 } else {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000609 Value *UnderlyingVal = GetUnderlyingObject(Val);
610 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
611 // inside InstructionDereferencesPointer either.
Craig Topper9f008862014-04-15 04:59:12 +0000612 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, nullptr, 1)) {
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000613 for (Instruction &I : *BB) {
614 if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000615 NotNull = true;
616 break;
617 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000618 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000619 }
620 }
621 }
622
623 // If this is the entry block, we must be asking about an argument. The
624 // value is overdefined.
625 if (BB == &BB->getParent()->getEntryBlock()) {
626 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
627 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000628 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000629 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
630 } else {
631 Result.markOverdefined();
632 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000633 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000634 return true;
635 }
636
637 // Loop over all of our predecessors, merging what we know from them into
638 // result.
639 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000640 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000641 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000642 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000643 if (EdgesMissing)
644 continue;
645
646 Result.mergeIn(EdgeResult);
647
648 // If we hit overdefined, exit early. The BlockVals entry is already set
649 // to overdefined.
650 if (Result.isOverdefined()) {
651 DEBUG(dbgs() << " compute BB '" << BB->getName()
652 << "' - overdefined because of pred.\n");
653 // If we previously determined that this is a pointer that can't be null
654 // then return that rather than giving up entirely.
655 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000656 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000657 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
658 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000659
660 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000661 return true;
662 }
663 }
664 if (EdgesMissing)
665 return false;
666
667 // Return the merged value, which is more precise than 'overdefined'.
668 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000669 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000670 return true;
671}
672
Owen Anderson64c2c572010-12-20 18:18:16 +0000673bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
674 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000675 LVILatticeVal Result; // Start Undefined.
676
677 // Loop over all of our predecessors, merging what we know from them into
678 // result.
679 bool EdgesMissing = false;
680 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
681 BasicBlock *PhiBB = PN->getIncomingBlock(i);
682 Value *PhiVal = PN->getIncomingValue(i);
683 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000684 // Note that we can provide PN as the context value to getEdgeValue, even
685 // though the results will be cached, because PN is the value being used as
686 // the cache key in the caller.
Hal Finkel7e184492014-09-07 20:29:59 +0000687 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000688 if (EdgesMissing)
689 continue;
690
691 Result.mergeIn(EdgeResult);
692
693 // If we hit overdefined, exit early. The BlockVals entry is already set
694 // to overdefined.
695 if (Result.isOverdefined()) {
696 DEBUG(dbgs() << " compute BB '" << BB->getName()
697 << "' - overdefined because of pred.\n");
Owen Anderson64c2c572010-12-20 18:18:16 +0000698
699 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000700 return true;
701 }
702 }
703 if (EdgesMissing)
704 return false;
705
706 // Return the merged value, which is more precise than 'overdefined'.
707 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000708 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000709 return true;
710}
711
Hal Finkel7e184492014-09-07 20:29:59 +0000712static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
713 LVILatticeVal &Result,
714 bool isTrueDest = true);
715
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000716// If we can determine a constant range for the value Val in the context
Hal Finkel7e184492014-09-07 20:29:59 +0000717// provided by the instruction BBI, then merge it into BBLV. If we did find a
718// constant range, return true.
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000719void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(Value *Val,
720 LVILatticeVal &BBLV,
721 Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000722 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
723 if (!BBI)
724 return;
725
726 for (auto &I : AT->assumptions(BBI->getParent()->getParent())) {
727 if (!isValidAssumeForContext(I, BBI, DL, DT))
728 continue;
729
730 Value *C = I->getArgOperand(0);
731 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
732 LVILatticeVal Result;
733 if (getValueFromFromCondition(Val, ICI, Result)) {
734 if (BBLV.isOverdefined())
735 BBLV = Result;
736 else
737 BBLV.mergeIn(Result);
738 }
739 }
740 }
741}
742
Owen Anderson64c2c572010-12-20 18:18:16 +0000743bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
744 Instruction *BBI,
Nick Lewycky55a700b2010-12-18 01:00:40 +0000745 BasicBlock *BB) {
Owen Anderson80d19f02010-08-18 21:11:37 +0000746 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000747 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Owen Anderson6f060af2011-01-05 23:26:22 +0000748 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
Nick Lewycky55a700b2010-12-18 01:00:40 +0000749 return false;
750 }
751
Nick Lewycky55a700b2010-12-18 01:00:40 +0000752 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Hal Finkel7e184492014-09-07 20:29:59 +0000753 mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
Owen Anderson80d19f02010-08-18 21:11:37 +0000754 if (!LHSVal.isConstantRange()) {
Owen Anderson64c2c572010-12-20 18:18:16 +0000755 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000756 return true;
Owen Anderson80d19f02010-08-18 21:11:37 +0000757 }
758
Owen Anderson80d19f02010-08-18 21:11:37 +0000759 ConstantRange LHSRange = LHSVal.getConstantRange();
760 ConstantRange RHSRange(1);
Chris Lattner229907c2011-07-18 04:54:35 +0000761 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
Owen Anderson80d19f02010-08-18 21:11:37 +0000762 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000763 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
764 RHSRange = ConstantRange(RHS->getValue());
765 } else {
Owen Anderson64c2c572010-12-20 18:18:16 +0000766 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000767 return true;
Owen Andersonc62f7042010-08-24 07:55:44 +0000768 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000769 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000770
Owen Anderson80d19f02010-08-18 21:11:37 +0000771 // NOTE: We're currently limited by the set of operations that ConstantRange
772 // can evaluate symbolically. Enhancing that set will allows us to analyze
773 // more definitions.
Owen Anderson64c2c572010-12-20 18:18:16 +0000774 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000775 switch (BBI->getOpcode()) {
776 case Instruction::Add:
777 Result.markConstantRange(LHSRange.add(RHSRange));
778 break;
779 case Instruction::Sub:
780 Result.markConstantRange(LHSRange.sub(RHSRange));
781 break;
782 case Instruction::Mul:
783 Result.markConstantRange(LHSRange.multiply(RHSRange));
784 break;
785 case Instruction::UDiv:
786 Result.markConstantRange(LHSRange.udiv(RHSRange));
787 break;
788 case Instruction::Shl:
789 Result.markConstantRange(LHSRange.shl(RHSRange));
790 break;
791 case Instruction::LShr:
792 Result.markConstantRange(LHSRange.lshr(RHSRange));
793 break;
794 case Instruction::Trunc:
795 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
796 break;
797 case Instruction::SExt:
798 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
799 break;
800 case Instruction::ZExt:
801 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
802 break;
803 case Instruction::BitCast:
804 Result.markConstantRange(LHSRange);
805 break;
Nick Lewyckyad48e012010-09-07 05:39:02 +0000806 case Instruction::And:
807 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
808 break;
809 case Instruction::Or:
810 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
811 break;
Owen Anderson80d19f02010-08-18 21:11:37 +0000812
813 // Unhandled instructions are overdefined.
814 default:
815 DEBUG(dbgs() << " compute BB '" << BB->getName()
816 << "' - overdefined because inst def found.\n");
817 Result.markOverdefined();
818 break;
819 }
820
Owen Anderson64c2c572010-12-20 18:18:16 +0000821 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000822 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +0000823}
824
Hal Finkel7e184492014-09-07 20:29:59 +0000825bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
826 LVILatticeVal &Result, bool isTrueDest) {
827 if (ICI && isa<Constant>(ICI->getOperand(1))) {
828 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
829 // We know that V has the RHS constant if this is a true SETEQ or
830 // false SETNE.
831 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
832 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
833 else
834 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
835 return true;
836 }
837
838 // Recognize the range checking idiom that InstCombine produces.
839 // (X-C1) u< C2 --> [C1, C1+C2)
840 ConstantInt *NegOffset = nullptr;
841 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
842 match(ICI->getOperand(0), m_Add(m_Specific(Val),
843 m_ConstantInt(NegOffset)));
844
845 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
846 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
847 // Calculate the range of values that would satisfy the comparison.
848 ConstantRange CmpRange(CI->getValue());
849 ConstantRange TrueValues =
850 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
851
852 if (NegOffset) // Apply the offset from above.
853 TrueValues = TrueValues.subtract(NegOffset->getValue());
854
855 // If we're interested in the false dest, invert the condition.
856 if (!isTrueDest) TrueValues = TrueValues.inverse();
857
858 Result = LVILatticeVal::getRange(TrueValues);
859 return true;
860 }
861 }
862
863 return false;
864}
865
Nuno Lopese6e04902012-06-28 01:16:18 +0000866/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
867/// Val is not constrained on the edge.
868static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
869 BasicBlock *BBTo, LVILatticeVal &Result) {
Chris Lattner77358782009-11-15 20:02:12 +0000870 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
871 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +0000872 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
873 // If this is a conditional branch and only one successor goes to BBTo, then
874 // we maybe able to infer something from the condition.
875 if (BI->isConditional() &&
876 BI->getSuccessor(0) != BI->getSuccessor(1)) {
877 bool isTrueDest = BI->getSuccessor(0) == BBTo;
878 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
879 "BBTo isn't a successor of BBFrom");
880
881 // If V is the condition of the branch itself, then we know exactly what
882 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000883 if (BI->getCondition() == Val) {
884 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +0000885 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +0000886 return true;
887 }
Chris Lattner19019ea2009-11-11 22:48:44 +0000888
889 // If the condition of the branch is an equality comparison, we may be
890 // able to infer the value.
Owen Anderson0bd61242010-08-11 04:24:25 +0000891 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
Hal Finkel7e184492014-09-07 20:29:59 +0000892 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
893 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +0000894 }
895 }
Chris Lattner77358782009-11-15 20:02:12 +0000896
897 // If the edge was formed by a switch on the value, then we may know exactly
898 // what it is.
899 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +0000900 if (SI->getCondition() != Val)
901 return false;
902
903 bool DefaultCase = SI->getDefaultDest() == BBTo;
904 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
905 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
906
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000907 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +0000908 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +0000909 if (DefaultCase) {
910 // It is possible that the default destination is the destination of
911 // some cases. There is no need to perform difference for those cases.
912 if (i.getCaseSuccessor() != BBTo)
913 EdgesVals = EdgesVals.difference(EdgeVal);
914 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +0000915 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +0000916 }
Nuno Lopes8650fb82012-06-28 16:13:37 +0000917 Result = LVILatticeVal::getRange(EdgesVals);
918 return true;
Chris Lattner77358782009-11-15 20:02:12 +0000919 }
Nuno Lopese6e04902012-06-28 01:16:18 +0000920 return false;
921}
922
923/// \brief Compute the value of Val on the edge BBFrom -> BBTo, or the value at
924/// the basic block if the edge does not constraint Val.
925bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +0000926 BasicBlock *BBTo, LVILatticeVal &Result,
927 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +0000928 // If already a constant, there is nothing to compute.
929 if (Constant *VC = dyn_cast<Constant>(Val)) {
930 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000931 return true;
932 }
Nuno Lopese6e04902012-06-28 01:16:18 +0000933
934 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
935 if (!Result.isConstantRange() ||
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000936 Result.getConstantRange().getSingleElement())
Nuno Lopese6e04902012-06-28 01:16:18 +0000937 return true;
938
939 // FIXME: this check should be moved to the beginning of the function when
940 // LVI better supports recursive values. Even for the single value case, we
941 // can intersect to detect dead code (an empty range).
942 if (!hasBlockValue(Val, BBFrom)) {
943 BlockValueStack.push(std::make_pair(BBFrom, Val));
944 return false;
945 }
946
947 // Try to intersect ranges of the BB and the constraint on the edge.
948 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Hal Finkela3f23e32014-10-14 16:04:49 +0000949 mergeAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +0000950 // See note on the use of the CxtI with mergeAssumeBlockValueConstantRange,
951 // and caching, below.
Hal Finkel7e184492014-09-07 20:29:59 +0000952 mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
Nuno Lopese6e04902012-06-28 01:16:18 +0000953 if (!InBlock.isConstantRange())
954 return true;
955
956 ConstantRange Range =
957 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
958 Result = LVILatticeVal::getRange(Range);
959 return true;
960 }
961
962 if (!hasBlockValue(Val, BBFrom)) {
963 BlockValueStack.push(std::make_pair(BBFrom, Val));
964 return false;
965 }
966
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000967 // If we couldn't compute the value on the edge, use the value from the BB.
Nuno Lopese6e04902012-06-28 01:16:18 +0000968 Result = getBlockValue(Val, BBFrom);
Hal Finkela3f23e32014-10-14 16:04:49 +0000969 mergeAssumeBlockValueConstantRange(Val, Result, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +0000970 // We can use the context instruction (generically the ultimate instruction
971 // the calling pass is trying to simplify) here, even though the result of
972 // this function is generally cached when called from the solve* functions
973 // (and that cached result might be used with queries using a different
974 // context instruction), because when this function is called from the solve*
975 // functions, the context instruction is not provided. When called from
976 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
977 // but then the result is not cached.
Hal Finkel7e184492014-09-07 20:29:59 +0000978 mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
Nuno Lopese6e04902012-06-28 01:16:18 +0000979 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +0000980}
981
Hal Finkel7e184492014-09-07 20:29:59 +0000982LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
983 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +0000984 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +0000985 << BB->getName() << "'\n");
986
Owen Anderson6f060af2011-01-05 23:26:22 +0000987 BlockValueStack.push(std::make_pair(BB, V));
Nick Lewycky55a700b2010-12-18 01:00:40 +0000988 solve();
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000989 LVILatticeVal Result = getBlockValue(V, BB);
Hal Finkel7e184492014-09-07 20:29:59 +0000990 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
991
992 DEBUG(dbgs() << " Result = " << Result << "\n");
993 return Result;
994}
995
996LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
997 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
998 << CxtI->getName() << "'\n");
999
1000 LVILatticeVal Result;
1001 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001002
David Greene37e98092009-12-23 20:43:58 +00001003 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001004 return Result;
1005}
Chris Lattner19019ea2009-11-11 22:48:44 +00001006
Chris Lattneraf025d32009-11-15 19:59:49 +00001007LVILatticeVal LazyValueInfoCache::
Hal Finkel7e184492014-09-07 20:29:59 +00001008getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1009 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001010 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001011 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001012
Nick Lewycky55a700b2010-12-18 01:00:40 +00001013 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001014 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001015 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001016 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001017 (void)WasFastQuery;
1018 assert(WasFastQuery && "More work to do after problem solved?");
1019 }
1020
David Greene37e98092009-12-23 20:43:58 +00001021 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001022 return Result;
1023}
1024
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001025void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1026 BasicBlock *NewSucc) {
1027 // When an edge in the graph has been threaded, values that we could not
1028 // determine a value for before (i.e. were marked overdefined) may be possible
1029 // to solve now. We do NOT try to proactively update these values. Instead,
1030 // we clear their entries from the cache, and allow lazy updating to recompute
1031 // them when needed.
1032
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001033 // The updating process is fairly simple: we need to drop cached info
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001034 // for all values that were marked overdefined in OldSucc, and for those same
1035 // values in any successor of OldSucc (except NewSucc) in which they were
1036 // also marked overdefined.
1037 std::vector<BasicBlock*> worklist;
1038 worklist.push_back(OldSucc);
1039
Owen Andersonaac5a722010-07-27 23:58:11 +00001040 DenseSet<Value*> ClearSet;
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001041 for (OverDefinedPairTy &P : OverDefinedCache)
1042 if (P.first == OldSucc)
1043 ClearSet.insert(P.second);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001044
1045 // Use a worklist to perform a depth-first search of OldSucc's successors.
1046 // NOTE: We do not need a visited list since any blocks we have already
1047 // visited will have had their overdefined markers cleared already, and we
1048 // thus won't loop to their successors.
1049 while (!worklist.empty()) {
1050 BasicBlock *ToUpdate = worklist.back();
1051 worklist.pop_back();
1052
1053 // Skip blocks only accessible through NewSucc.
1054 if (ToUpdate == NewSucc) continue;
1055
1056 bool changed = false;
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001057 for (Value *V : ClearSet) {
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001058 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson118ac802011-01-05 21:15:29 +00001059 DenseSet<OverDefinedPairTy>::iterator OI =
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001060 OverDefinedCache.find(std::make_pair(ToUpdate, V));
Owen Andersonaac5a722010-07-27 23:58:11 +00001061 if (OI == OverDefinedCache.end()) continue;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001062
Owen Andersonaac5a722010-07-27 23:58:11 +00001063 // Remove it from the caches.
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001064 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(V, this)];
Owen Andersonaac5a722010-07-27 23:58:11 +00001065 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001066
Owen Andersonaac5a722010-07-27 23:58:11 +00001067 assert(CI != Entry.end() && "Couldn't find entry to update?");
1068 Entry.erase(CI);
1069 OverDefinedCache.erase(OI);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001070
Owen Andersonaac5a722010-07-27 23:58:11 +00001071 // If we removed anything, then we potentially need to update
1072 // blocks successors too.
1073 changed = true;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001074 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001075
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001076 if (!changed) continue;
1077
1078 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1079 }
1080}
1081
Chris Lattneraf025d32009-11-15 19:59:49 +00001082//===----------------------------------------------------------------------===//
1083// LazyValueInfo Impl
1084//===----------------------------------------------------------------------===//
1085
Chris Lattneraf025d32009-11-15 19:59:49 +00001086/// getCache - This lazily constructs the LazyValueInfoCache.
Hal Finkel7e184492014-09-07 20:29:59 +00001087static LazyValueInfoCache &getCache(void *&PImpl,
1088 AssumptionTracker *AT,
1089 const DataLayout *DL = nullptr,
1090 DominatorTree *DT = nullptr) {
Chris Lattneraf025d32009-11-15 19:59:49 +00001091 if (!PImpl)
Hal Finkel7e184492014-09-07 20:29:59 +00001092 PImpl = new LazyValueInfoCache(AT, DL, DT);
Chris Lattneraf025d32009-11-15 19:59:49 +00001093 return *static_cast<LazyValueInfoCache*>(PImpl);
1094}
1095
Owen Anderson208636f2010-08-18 18:39:01 +00001096bool LazyValueInfo::runOnFunction(Function &F) {
Hal Finkel7e184492014-09-07 20:29:59 +00001097 AT = &getAnalysis<AssumptionTracker>();
1098
1099 DominatorTreeWrapperPass *DTWP =
1100 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1101 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chad Rosier43a33062011-12-02 01:26:24 +00001102
Rafael Espindola93512512014-02-25 17:30:31 +00001103 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topper9f008862014-04-15 04:59:12 +00001104 DL = DLP ? &DLP->getDataLayout() : nullptr;
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001105
Chad Rosier43a33062011-12-02 01:26:24 +00001106 TLI = &getAnalysis<TargetLibraryInfo>();
1107
Hal Finkel7e184492014-09-07 20:29:59 +00001108 if (PImpl)
1109 getCache(PImpl, AT, DL, DT).clear();
1110
Owen Anderson208636f2010-08-18 18:39:01 +00001111 // Fully lazy.
1112 return false;
1113}
1114
Chad Rosier43a33062011-12-02 01:26:24 +00001115void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1116 AU.setPreservesAll();
Hal Finkel7e184492014-09-07 20:29:59 +00001117 AU.addRequired<AssumptionTracker>();
Chad Rosier43a33062011-12-02 01:26:24 +00001118 AU.addRequired<TargetLibraryInfo>();
1119}
1120
Chris Lattneraf025d32009-11-15 19:59:49 +00001121void LazyValueInfo::releaseMemory() {
1122 // If the cache was allocated, free it.
1123 if (PImpl) {
Hal Finkel7e184492014-09-07 20:29:59 +00001124 delete &getCache(PImpl, AT);
Craig Topper9f008862014-04-15 04:59:12 +00001125 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001126 }
1127}
1128
Hal Finkel7e184492014-09-07 20:29:59 +00001129Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1130 Instruction *CxtI) {
1131 LVILatticeVal Result =
1132 getCache(PImpl, AT, DL, DT).getValueInBlock(V, BB, CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +00001133
Chris Lattner19019ea2009-11-11 22:48:44 +00001134 if (Result.isConstant())
1135 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001136 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001137 ConstantRange CR = Result.getConstantRange();
1138 if (const APInt *SingleVal = CR.getSingleElement())
1139 return ConstantInt::get(V->getContext(), *SingleVal);
1140 }
Craig Topper9f008862014-04-15 04:59:12 +00001141 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001142}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001143
Chris Lattnerd5e25432009-11-12 01:29:10 +00001144/// getConstantOnEdge - Determine whether the specified value is known to be a
1145/// constant on the specified edge. Return null if not.
1146Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001147 BasicBlock *ToBB,
1148 Instruction *CxtI) {
1149 LVILatticeVal Result =
1150 getCache(PImpl, AT, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chris Lattnerd5e25432009-11-12 01:29:10 +00001151
1152 if (Result.isConstant())
1153 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001154 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001155 ConstantRange CR = Result.getConstantRange();
1156 if (const APInt *SingleVal = CR.getSingleElement())
1157 return ConstantInt::get(V->getContext(), *SingleVal);
1158 }
Craig Topper9f008862014-04-15 04:59:12 +00001159 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001160}
1161
Hal Finkel7e184492014-09-07 20:29:59 +00001162static LazyValueInfo::Tristate
1163getPredicateResult(unsigned Pred, Constant *C, LVILatticeVal &Result,
1164 const DataLayout *DL, TargetLibraryInfo *TLI) {
1165
Chris Lattner565ee2f2009-11-12 04:36:58 +00001166 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001167 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001168 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001169 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001170 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001171 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001172 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1173 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001174 }
1175
Owen Anderson185fe002010-08-10 20:03:09 +00001176 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001177 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001178 if (!CI) return LazyValueInfo::Unknown;
Owen Andersonc62f7042010-08-24 07:55:44 +00001179
Owen Anderson185fe002010-08-10 20:03:09 +00001180 ConstantRange CR = Result.getConstantRange();
1181 if (Pred == ICmpInst::ICMP_EQ) {
1182 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001183 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001184
1185 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001186 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001187 } else if (Pred == ICmpInst::ICMP_NE) {
1188 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001189 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001190
1191 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001192 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001193 }
1194
1195 // Handle more complex predicates.
Nick Lewycky11678bd2010-12-15 18:57:18 +00001196 ConstantRange TrueValues =
1197 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1198 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001199 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001200 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001201 return LazyValueInfo::False;
1202 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001203 }
1204
Chris Lattneraf025d32009-11-15 19:59:49 +00001205 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001206 // If this is an equality comparison, we can try to fold it knowing that
1207 // "V != C1".
1208 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001209 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001210 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001211 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001212 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001213 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001214 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001215 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001216 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001217 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001218 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001219 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001220 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001221 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001222 }
Hal Finkel7e184492014-09-07 20:29:59 +00001223 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001224 }
1225
Hal Finkel7e184492014-09-07 20:29:59 +00001226 return LazyValueInfo::Unknown;
1227}
1228
1229/// getPredicateOnEdge - Determine whether the specified value comparison
1230/// with a constant is known to be true or false on the specified CFG edge.
1231/// Pred is a CmpInst predicate.
1232LazyValueInfo::Tristate
1233LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1234 BasicBlock *FromBB, BasicBlock *ToBB,
1235 Instruction *CxtI) {
1236 LVILatticeVal Result =
1237 getCache(PImpl, AT, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1238
1239 return getPredicateResult(Pred, C, Result, DL, TLI);
1240}
1241
1242LazyValueInfo::Tristate
1243LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1244 Instruction *CxtI) {
1245 LVILatticeVal Result =
1246 getCache(PImpl, AT, DL, DT).getValueAt(V, CxtI);
1247
1248 return getPredicateResult(Pred, C, Result, DL, TLI);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001249}
1250
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001251void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001252 BasicBlock *NewSucc) {
Hal Finkel7e184492014-09-07 20:29:59 +00001253 if (PImpl) getCache(PImpl, AT, DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
Owen Anderson208636f2010-08-18 18:39:01 +00001254}
1255
1256void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Hal Finkel7e184492014-09-07 20:29:59 +00001257 if (PImpl) getCache(PImpl, AT, DL, DT).eraseBlock(BB);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001258}