blob: c5c90271a088d548174032dbcbd30bb875aacf61 [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"
Chandler Carruth66b31302015-01-04 12:03:27 +000018#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000020#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000022#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
Hal Finkel7e184492014-09-07 20:29:59 +000026#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Instructions.h"
28#include "llvm/IR/IntrinsicInst.h"
Philip Reameseb3e9da2015-10-29 03:57:17 +000029#include "llvm/IR/LLVMContext.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000030#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000031#include "llvm/IR/ValueHandle.h"
Chris Lattnerb584d1e2009-11-12 01:22:16 +000032#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/raw_ostream.h"
Bill Wendling4ec081a2012-01-11 23:43:34 +000034#include <map>
Nick Lewycky55a700b2010-12-18 01:00:40 +000035#include <stack>
Chris Lattner741c94c2009-11-11 00:22:30 +000036using namespace llvm;
Benjamin Kramerd9d80b12012-03-02 15:34:43 +000037using namespace PatternMatch;
Chris Lattner741c94c2009-11-11 00:22:30 +000038
Chandler Carruthf1221bd2014-04-22 02:48:03 +000039#define DEBUG_TYPE "lazy-value-info"
40
Sean Silva687019f2016-06-13 22:01:25 +000041char LazyValueInfoWrapperPass::ID = 0;
42INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
Chad Rosier43a33062011-12-02 01:26:24 +000043 "Lazy Value Information Analysis", false, true)
Chandler Carruth66b31302015-01-04 12:03:27 +000044INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000045INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Sean Silva687019f2016-06-13 22:01:25 +000046INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
Owen Andersondf7a4f22010-10-07 22:25:06 +000047 "Lazy Value Information Analysis", false, true)
Chris Lattner741c94c2009-11-11 00:22:30 +000048
49namespace llvm {
Sean Silva687019f2016-06-13 22:01:25 +000050 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
Chris Lattner741c94c2009-11-11 00:22:30 +000051}
52
Sean Silva687019f2016-06-13 22:01:25 +000053char LazyValueAnalysis::PassID;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000054
55//===----------------------------------------------------------------------===//
56// LVILatticeVal
57//===----------------------------------------------------------------------===//
58
Sanjay Patel2a385e22015-01-09 16:47:20 +000059/// This is the information tracked by LazyValueInfo for each value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000060///
61/// FIXME: This is basically just for bringup, this can be made a lot more rich
62/// in the future.
63///
64namespace {
65class LVILatticeVal {
66 enum LatticeValueTy {
Philip Reames3bb28322016-04-25 18:48:43 +000067 /// This Value has no known value yet. As a result, this implies the
68 /// producing instruction is dead. Caution: We use this as the starting
69 /// state in our local meet rules. In this usage, it's taken to mean
NAKAMURA Takumif2529512016-07-04 01:26:27 +000070 /// "nothing known yet".
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000071 undefined,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000072
Philip Reames3bb28322016-04-25 18:48:43 +000073 /// This Value has a specific constant value. (For integers, constantrange
74 /// is used instead.)
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000075 constant,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000076
Philip Reames3bb28322016-04-25 18:48:43 +000077 /// This Value is known to not have the specified value. (For integers,
78 /// constantrange is used instead.)
Chris Lattner565ee2f2009-11-12 04:36:58 +000079 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000080
Philip Reames3bb28322016-04-25 18:48:43 +000081 /// The Value falls within this range. (Used only for integer typed values.)
Owen Anderson0f306a42010-08-05 22:59:19 +000082 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000083
Philip Reames3bb28322016-04-25 18:48:43 +000084 /// We can not precisely model the dynamic values this value might take.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000085 overdefined
86 };
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000087
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000088 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000089 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000090 LatticeValueTy Tag;
91 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +000092 ConstantRange Range;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000093
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000094public:
Craig Topper9f008862014-04-15 04:59:12 +000095 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000096
Chris Lattner19019ea2009-11-11 22:48:44 +000097 static LVILatticeVal get(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.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +0000101 return Res;
102 }
Chris Lattner565ee2f2009-11-12 04:36:58 +0000103 static LVILatticeVal getNot(Constant *C) {
104 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000105 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000106 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000107 return Res;
108 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000109 static LVILatticeVal getRange(ConstantRange CR) {
110 LVILatticeVal Res;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000111 Res.markConstantRange(std::move(CR));
Owen Anderson5f1dd092010-08-10 23:20:01 +0000112 return Res;
113 }
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000114 static LVILatticeVal getOverdefined() {
115 LVILatticeVal Res;
116 Res.markOverdefined();
117 return Res;
118 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000119
Owen Anderson0f306a42010-08-05 22:59:19 +0000120 bool isUndefined() const { return Tag == undefined; }
121 bool isConstant() const { return Tag == constant; }
122 bool isNotConstant() const { return Tag == notconstant; }
123 bool isConstantRange() const { return Tag == constantrange; }
124 bool isOverdefined() const { return Tag == overdefined; }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000125
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000126 Constant *getConstant() const {
127 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000128 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000129 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000130
Chris Lattner565ee2f2009-11-12 04:36:58 +0000131 Constant *getNotConstant() const {
132 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000133 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000134 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000135
Owen Anderson0f306a42010-08-05 22:59:19 +0000136 ConstantRange getConstantRange() const {
137 assert(isConstantRange() &&
138 "Cannot get the constant-range of a non-constant-range!");
139 return Range;
140 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000141
Sanjay Patel2a385e22015-01-09 16:47:20 +0000142 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000143 bool markOverdefined() {
144 if (isOverdefined())
145 return false;
Owen Andersonc3a14132010-08-05 22:10:46 +0000146 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000147 return true;
148 }
149
Sanjay Patel2a385e22015-01-09 16:47:20 +0000150 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000151 bool markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000152 assert(V && "Marking constant with NULL");
153 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
154 return markConstantRange(ConstantRange(CI->getValue()));
155 if (isa<UndefValue>(V))
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000156 return false;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000157
158 assert((!isConstant() || getConstant() == V) &&
159 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000160 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000161 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000162 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000163 return true;
164 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000165
Sanjay Patel2a385e22015-01-09 16:47:20 +0000166 /// Return true if this is a change in status.
Chris Lattner565ee2f2009-11-12 04:36:58 +0000167 bool markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000168 assert(V && "Marking constant with NULL");
Nick Lewycky11678bd2010-12-15 18:57:18 +0000169 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
170 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
171 if (isa<UndefValue>(V))
172 return false;
173
174 assert((!isConstant() || getConstant() != V) &&
175 "Marking constant !constant with same value");
176 assert((!isNotConstant() || getNotConstant() == V) &&
177 "Marking !constant with different value");
178 assert(isUndefined() || isConstant());
179 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000180 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000181 return true;
182 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000183
Sanjay Patel2a385e22015-01-09 16:47:20 +0000184 /// Return true if this is a change in status.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000185 bool markConstantRange(ConstantRange NewR) {
Owen Anderson0f306a42010-08-05 22:59:19 +0000186 if (isConstantRange()) {
187 if (NewR.isEmptySet())
188 return markOverdefined();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000189
Nuno Lopese6e04902012-06-28 01:16:18 +0000190 bool changed = Range != NewR;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000191 Range = std::move(NewR);
Owen Anderson0f306a42010-08-05 22:59:19 +0000192 return changed;
193 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000194
Owen Anderson0f306a42010-08-05 22:59:19 +0000195 assert(isUndefined());
196 if (NewR.isEmptySet())
197 return markOverdefined();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000198
Owen Anderson0f306a42010-08-05 22:59:19 +0000199 Tag = constantrange;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000200 Range = std::move(NewR);
Owen Anderson0f306a42010-08-05 22:59:19 +0000201 return true;
202 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000203
Sanjay Patel2a385e22015-01-09 16:47:20 +0000204 /// Merge the specified lattice value into this one, updating this
Chris Lattner19019ea2009-11-11 22:48:44 +0000205 /// one and returning true if anything changed.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000206 bool mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
Chris Lattner19019ea2009-11-11 22:48:44 +0000207 if (RHS.isUndefined() || isOverdefined()) return false;
208 if (RHS.isOverdefined()) return markOverdefined();
209
Nick Lewycky11678bd2010-12-15 18:57:18 +0000210 if (isUndefined()) {
211 Tag = RHS.Tag;
212 Val = RHS.Val;
213 Range = RHS.Range;
214 return true;
Chris Lattner22db4b52009-11-12 04:57:13 +0000215 }
216
Nick Lewycky11678bd2010-12-15 18:57:18 +0000217 if (isConstant()) {
218 if (RHS.isConstant()) {
219 if (Val == RHS.Val)
220 return false;
221 return markOverdefined();
222 }
223
224 if (RHS.isNotConstant()) {
225 if (Val == RHS.Val)
226 return markOverdefined();
227
228 // Unless we can prove that the two Constants are different, we must
229 // move to overdefined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000230 if (ConstantInt *Res =
231 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
232 CmpInst::ICMP_NE, getConstant(), RHS.getNotConstant(), DL)))
Nick Lewycky11678bd2010-12-15 18:57:18 +0000233 if (Res->isOne())
234 return markNotConstant(RHS.getNotConstant());
235
236 return markOverdefined();
237 }
238
Chris Lattner19019ea2009-11-11 22:48:44 +0000239 return markOverdefined();
Nick Lewycky11678bd2010-12-15 18:57:18 +0000240 }
241
242 if (isNotConstant()) {
243 if (RHS.isConstant()) {
244 if (Val == RHS.Val)
245 return markOverdefined();
246
247 // Unless we can prove that the two Constants are different, we must
248 // move to overdefined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000249 if (ConstantInt *Res =
250 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
251 CmpInst::ICMP_NE, getNotConstant(), RHS.getConstant(), DL)))
Nick Lewycky11678bd2010-12-15 18:57:18 +0000252 if (Res->isOne())
253 return false;
254
255 return markOverdefined();
256 }
257
258 if (RHS.isNotConstant()) {
259 if (Val == RHS.Val)
260 return false;
261 return markOverdefined();
262 }
263
264 return markOverdefined();
265 }
266
267 assert(isConstantRange() && "New LVILattice type?");
268 if (!RHS.isConstantRange())
269 return markOverdefined();
270
271 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
272 if (NewR.isFullSet())
273 return markOverdefined();
274 return markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000275 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000276};
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000277
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000278} // end anonymous namespace.
279
Chris Lattner19019ea2009-11-11 22:48:44 +0000280namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000281raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
282 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000283raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
284 if (Val.isUndefined())
285 return OS << "undefined";
286 if (Val.isOverdefined())
287 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000288
289 if (Val.isNotConstant())
290 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Davide Italianobd543d02016-05-25 22:29:34 +0000291 if (Val.isConstantRange())
Owen Anderson8afac042010-08-09 20:50:46 +0000292 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
293 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000294 return OS << "constant<" << *Val.getConstant() << '>';
295}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000296}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000297
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000298/// Returns true if this lattice value represents at most one possible value.
299/// This is as precise as any lattice value can get while still representing
300/// reachable code.
Benjamin Kramerc321e532016-06-08 19:09:22 +0000301static bool hasSingleValue(const LVILatticeVal &Val) {
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000302 if (Val.isConstantRange() &&
303 Val.getConstantRange().isSingleElement())
304 // Integer constants are single element ranges
305 return true;
306 if (Val.isConstant())
307 // Non integer constants
308 return true;
309 return false;
310}
311
312/// Combine two sets of facts about the same value into a single set of
313/// facts. Note that this method is not suitable for merging facts along
314/// different paths in a CFG; that's what the mergeIn function is for. This
315/// is for merging facts gathered about the same value at the same location
316/// through two independent means.
317/// Notes:
318/// * This method does not promise to return the most precise possible lattice
319/// value implied by A and B. It is allowed to return any lattice element
320/// which is at least as strong as *either* A or B (unless our facts
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000321/// conflict, see below).
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000322/// * Due to unreachable code, the intersection of two lattice values could be
323/// contradictory. If this happens, we return some valid lattice value so as
324/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
325/// we do not make this guarantee. TODO: This would be a useful enhancement.
326static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
327 // Undefined is the strongest state. It means the value is known to be along
328 // an unreachable path.
329 if (A.isUndefined())
330 return A;
331 if (B.isUndefined())
332 return B;
333
334 // If we gave up for one, but got a useable fact from the other, use it.
335 if (A.isOverdefined())
336 return B;
337 if (B.isOverdefined())
338 return A;
339
340 // Can't get any more precise than constants.
341 if (hasSingleValue(A))
342 return A;
343 if (hasSingleValue(B))
344 return B;
345
346 // Could be either constant range or not constant here.
347 if (!A.isConstantRange() || !B.isConstantRange()) {
348 // TODO: Arbitrary choice, could be improved
349 return A;
350 }
351
352 // Intersect two constant ranges
353 ConstantRange Range =
354 A.getConstantRange().intersectWith(B.getConstantRange());
355 // Note: An empty range is implicitly converted to overdefined internally.
356 // TODO: We could instead use Undefined here since we've proven a conflict
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000357 // and thus know this path must be unreachable.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000358 return LVILatticeVal::getRange(std::move(Range));
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000359}
Philip Reamesd1f829d2016-02-02 21:57:37 +0000360
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000361//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000362// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000363//===----------------------------------------------------------------------===//
364
Chris Lattneraf025d32009-11-15 19:59:49 +0000365namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000366 /// A callback value handle updates the cache when values are erased.
Owen Anderson118ac802011-01-05 21:15:29 +0000367 class LazyValueInfoCache;
David Blaikie774b5842015-08-03 22:30:24 +0000368 struct LVIValueHandle final : public CallbackVH {
Justin Lebar58b377e2016-07-27 22:33:36 +0000369 // Needs to access getValPtr(), which is protected.
370 friend struct DenseMapInfo<LVIValueHandle>;
371
Owen Anderson118ac802011-01-05 21:15:29 +0000372 LazyValueInfoCache *Parent;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000373
Owen Anderson118ac802011-01-05 21:15:29 +0000374 LVIValueHandle(Value *V, LazyValueInfoCache *P)
375 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000376
377 void deleted() override;
378 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000379 deleted();
380 }
381 };
Justin Lebar58b377e2016-07-27 22:33:36 +0000382} // end anonymous namespace
Owen Anderson118ac802011-01-05 21:15:29 +0000383
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000384namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000385 /// This is the cache kept by LazyValueInfo which
Chris Lattneraf025d32009-11-15 19:59:49 +0000386 /// maintains information about queries across the clients' queries.
387 class LazyValueInfoCache {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000388 /// This is all of the cached block information for exactly one Value*.
389 /// The entries are sorted by the BasicBlock* of the
Chris Lattneraf025d32009-11-15 19:59:49 +0000390 /// entries, allowing us to do a lookup with a binary search.
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000391 /// Over-defined lattice values are recorded in OverDefinedCache to reduce
392 /// memory overhead.
Justin Lebar58b377e2016-07-27 22:33:36 +0000393 struct ValueCacheEntryTy {
394 ValueCacheEntryTy(Value *V, LazyValueInfoCache *P) : Handle(V, P) {}
395 LVIValueHandle Handle;
396 SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4> BlockVals;
397 };
Chris Lattneraf025d32009-11-15 19:59:49 +0000398
Sanjay Patel2a385e22015-01-09 16:47:20 +0000399 /// This is all of the cached information for all values,
Owen Anderson6f060af2011-01-05 23:26:22 +0000400 /// mapped from Value* to key information.
Justin Lebar58b377e2016-07-27 22:33:36 +0000401 DenseMap<Value *, std::unique_ptr<ValueCacheEntryTy>> ValueCache;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000402
Sanjay Patel2a385e22015-01-09 16:47:20 +0000403 /// This tracks, on a per-block basis, the set of values that are
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000404 /// over-defined at the end of that block.
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000405 typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
406 OverDefinedCacheTy;
407 OverDefinedCacheTy OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000408
Sanjay Patel2a385e22015-01-09 16:47:20 +0000409 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000410 /// don't spend time removing unused blocks from our caches.
411 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
412
Sanjay Patel2a385e22015-01-09 16:47:20 +0000413 /// This stack holds the state of the value solver during a query.
414 /// It basically emulates the callstack of the naive
Owen Anderson6f060af2011-01-05 23:26:22 +0000415 /// recursive value lookup process.
416 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
Hal Finkel7e184492014-09-07 20:29:59 +0000417
Sanjay Patel2a385e22015-01-09 16:47:20 +0000418 /// Keeps track of which block-value pairs are in BlockValueStack.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000419 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
420
Sanjay Patel2a385e22015-01-09 16:47:20 +0000421 /// Push BV onto BlockValueStack unless it's already in there.
422 /// Returns true on success.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000423 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
Benjamin Kramer4e3b9032015-02-27 21:43:14 +0000424 if (!BlockValueSet.insert(BV).second)
Hans Wennborg45172ac2014-11-25 17:23:05 +0000425 return false; // It's already in the stack.
426
Philip Reames44456b82016-02-02 03:15:40 +0000427 DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
428 << "\n");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000429 BlockValueStack.push(BV);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000430 return true;
431 }
432
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000433 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
434 const DataLayout &DL; ///< A mandatory DataLayout
435 DominatorTree *DT; ///< An optional DT pointer.
436
Owen Anderson118ac802011-01-05 21:15:29 +0000437 friend struct LVIValueHandle;
Owen Anderson6f060af2011-01-05 23:26:22 +0000438
Hans Wennborg45172ac2014-11-25 17:23:05 +0000439 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
440 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000441
442 // Insert over-defined values into their own cache to reduce memory
443 // overhead.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000444 if (Result.isOverdefined())
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000445 OverDefinedCache[BB].insert(Val);
Justin Lebar58b377e2016-07-27 22:33:36 +0000446 else {
447 auto It = ValueCache.find_as(Val);
448 if (It == ValueCache.end()) {
449 ValueCache[Val] = make_unique<ValueCacheEntryTy>(Val, this);
450 It = ValueCache.find_as(Val);
451 assert(It != ValueCache.end() && "Val was just added to the map!");
452 }
453 It->second->BlockVals[BB] = Result;
454 }
Hans Wennborg45172ac2014-11-25 17:23:05 +0000455 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000456
NAKAMURA Takumif4c64412016-07-04 01:26:14 +0000457 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
458 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
459 LVILatticeVal &Result, Instruction *CxtI = nullptr);
460 bool hasBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000461
NAKAMURA Takumif4c64412016-07-04 01:26:14 +0000462 // These methods process one work item and may add more. A false value
463 // returned means that the work item was not completely processed and must
464 // be revisited after going through the new items.
465 bool solveBlockValue(Value *Val, BasicBlock *BB);
466 bool solveBlockValueNonLocal(LVILatticeVal &BBLV, Value *Val, BasicBlock *BB);
467 bool solveBlockValuePHINode(LVILatticeVal &BBLV, PHINode *PN, BasicBlock *BB);
468 bool solveBlockValueSelect(LVILatticeVal &BBLV, SelectInst *S,
469 BasicBlock *BB);
470 bool solveBlockValueBinaryOp(LVILatticeVal &BBLV, Instruction *BBI,
471 BasicBlock *BB);
472 bool solveBlockValueCast(LVILatticeVal &BBLV, Instruction *BBI,
473 BasicBlock *BB);
474 void intersectAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
475 Instruction *BBI);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000476
NAKAMURA Takumif4c64412016-07-04 01:26:14 +0000477 void solve();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000478
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000479 bool isOverdefined(Value *V, BasicBlock *BB) const {
480 auto ODI = OverDefinedCache.find(BB);
481
482 if (ODI == OverDefinedCache.end())
483 return false;
484
485 return ODI->second.count(V);
486 }
487
488 bool hasCachedValueInfo(Value *V, BasicBlock *BB) {
489 if (isOverdefined(V, BB))
490 return true;
491
Justin Lebar58b377e2016-07-27 22:33:36 +0000492 auto I = ValueCache.find_as(V);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000493 if (I == ValueCache.end())
494 return false;
495
Justin Lebar58b377e2016-07-27 22:33:36 +0000496 return I->second->BlockVals.count(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000497 }
498
499 LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) {
500 if (isOverdefined(V, BB))
501 return LVILatticeVal::getOverdefined();
502
Justin Lebar58b377e2016-07-27 22:33:36 +0000503 auto I = ValueCache.find_as(V);
504 if (I == ValueCache.end())
505 return LVILatticeVal();
506 auto BBI = I->second->BlockVals.find(BB);
507 if (BBI == I->second->BlockVals.end())
508 return LVILatticeVal();
509 return BBI->second;
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000510 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000511
Chris Lattneraf025d32009-11-15 19:59:49 +0000512 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000513 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000514 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000515 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
516 Instruction *CxtI = nullptr);
517
Sanjay Patel2a385e22015-01-09 16:47:20 +0000518 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000519 /// value for the specified Value* at the specified instruction (generally
520 /// from an assume intrinsic).
521 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000522
Sanjay Patel2a385e22015-01-09 16:47:20 +0000523 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000524 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000525 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
526 Instruction *CxtI = nullptr);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000527
Sanjay Patel2a385e22015-01-09 16:47:20 +0000528 /// This is the update interface to inform the cache that an edge from
529 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000530 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000531
Sanjay Patel2a385e22015-01-09 16:47:20 +0000532 /// This is part of the update interface to inform the cache
Owen Anderson208636f2010-08-18 18:39:01 +0000533 /// that a block has been deleted.
534 void eraseBlock(BasicBlock *BB);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000535
Owen Anderson208636f2010-08-18 18:39:01 +0000536 /// clear - Empty the cache.
537 void clear() {
Benjamin Kramerbbf3c602011-12-03 15:19:55 +0000538 SeenBlocks.clear();
Owen Anderson208636f2010-08-18 18:39:01 +0000539 ValueCache.clear();
540 OverDefinedCache.clear();
541 }
Hal Finkel7e184492014-09-07 20:29:59 +0000542
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000543 LazyValueInfoCache(AssumptionCache *AC, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000544 DominatorTree *DT = nullptr)
545 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000546 };
547} // end anonymous namespace
548
Owen Anderson118ac802011-01-05 21:15:29 +0000549void LVIValueHandle::deleted() {
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000550 SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
551 for (auto &I : Parent->OverDefinedCache) {
552 SmallPtrSetImpl<Value *> &ValueSet = I.second;
553 if (ValueSet.count(getValPtr()))
554 ValueSet.erase(getValPtr());
555 if (ValueSet.empty())
556 ToErase.push_back(I.first);
557 }
558 for (auto &BB : ToErase)
559 Parent->OverDefinedCache.erase(BB);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000560
Owen Anderson7b974a42010-08-11 22:36:04 +0000561 // This erasure deallocates *this, so it MUST happen after we're done
562 // using any and all members of *this.
563 Parent->ValueCache.erase(*this);
Owen Andersonc1561b82010-07-30 23:59:40 +0000564}
565
Owen Anderson208636f2010-08-18 18:39:01 +0000566void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramer36647082011-12-03 15:16:45 +0000567 // Shortcut if we have never seen this block.
568 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
569 if (I == SeenBlocks.end())
570 return;
571 SeenBlocks.erase(I);
572
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000573 auto ODI = OverDefinedCache.find(BB);
574 if (ODI != OverDefinedCache.end())
575 OverDefinedCache.erase(ODI);
Owen Anderson208636f2010-08-18 18:39:01 +0000576
Benjamin Krameraa209152016-06-26 17:27:42 +0000577 for (auto &I : ValueCache)
Justin Lebar58b377e2016-07-27 22:33:36 +0000578 I.second->BlockVals.erase(BB);
Owen Anderson208636f2010-08-18 18:39:01 +0000579}
Owen Andersonc1561b82010-07-30 23:59:40 +0000580
Nick Lewycky55a700b2010-12-18 01:00:40 +0000581void LazyValueInfoCache::solve() {
Owen Anderson6f060af2011-01-05 23:26:22 +0000582 while (!BlockValueStack.empty()) {
583 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000584 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
585
Nuno Lopese6e04902012-06-28 01:16:18 +0000586 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000587 // The work item was completely processed.
588 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000589 assert(hasCachedValueInfo(e.second, e.first) &&
590 "Result should be in cache!");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000591
Philip Reames44456b82016-02-02 03:15:40 +0000592 DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000593 << " = " << getCachedValueInfo(e.second, e.first) << "\n");
Philip Reames44456b82016-02-02 03:15:40 +0000594
Owen Anderson6f060af2011-01-05 23:26:22 +0000595 BlockValueStack.pop();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000596 BlockValueSet.erase(e);
597 } else {
598 // More work needs to be done before revisiting.
599 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000600 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000601 }
602}
603
604bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
605 // If already a constant, there is nothing to compute.
606 if (isa<Constant>(Val))
607 return true;
608
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000609 return hasCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000610}
611
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000612LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000613 // If already a constant, there is nothing to compute.
614 if (Constant *VC = dyn_cast<Constant>(Val))
615 return LVILatticeVal::get(VC);
616
Benjamin Kramer36647082011-12-03 15:16:45 +0000617 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000618 return getCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000619}
620
Philip Reameseb3e9da2015-10-29 03:57:17 +0000621static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
622 switch (BBI->getOpcode()) {
623 default: break;
624 case Instruction::Load:
625 case Instruction::Call:
626 case Instruction::Invoke:
NAKAMURA Takumibd072a92016-07-25 00:59:46 +0000627 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
Philip Reames70efccd2015-10-29 04:21:49 +0000628 if (isa<IntegerType>(BBI->getType())) {
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000629 return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
Philip Reameseb3e9da2015-10-29 03:57:17 +0000630 }
631 break;
632 };
Philip Reamesd1f829d2016-02-02 21:57:37 +0000633 // Nothing known - will be intersected with other facts
634 return LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +0000635}
636
Nick Lewycky55a700b2010-12-18 01:00:40 +0000637bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
638 if (isa<Constant>(Val))
639 return true;
640
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000641 if (hasCachedValueInfo(Val, BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000642 // If we have a cached value, use that.
643 DEBUG(dbgs() << " reuse BB '" << BB->getName()
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000644 << "' val=" << getCachedValueInfo(Val, BB) << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000645
Hans Wennborg45172ac2014-11-25 17:23:05 +0000646 // Since we're reusing a cached value, we don't need to update the
647 // OverDefinedCache. The cache will have been properly updated whenever the
648 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000649 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000650 }
651
Hans Wennborg45172ac2014-11-25 17:23:05 +0000652 // Hold off inserting this value into the Cache in case we have to return
653 // false and come back later.
654 LVILatticeVal Res;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000655
Chris Lattneraf025d32009-11-15 19:59:49 +0000656 Instruction *BBI = dyn_cast<Instruction>(Val);
Craig Topper9f008862014-04-15 04:59:12 +0000657 if (!BBI || BBI->getParent() != BB) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000658 if (!solveBlockValueNonLocal(Res, Val, BB))
659 return false;
660 insertResult(Val, BB, Res);
661 return true;
Chris Lattneraf025d32009-11-15 19:59:49 +0000662 }
Chris Lattner2c708562009-11-15 20:00:52 +0000663
Nick Lewycky55a700b2010-12-18 01:00:40 +0000664 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000665 if (!solveBlockValuePHINode(Res, PN, BB))
666 return false;
667 insertResult(Val, BB, Res);
668 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000669 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000670
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000671 if (auto *SI = dyn_cast<SelectInst>(BBI)) {
672 if (!solveBlockValueSelect(Res, SI, BB))
673 return false;
674 insertResult(Val, BB, Res);
675 return true;
676 }
677
Philip Reames2ab964e2016-04-27 01:02:25 +0000678 // If this value is a nonnull pointer, record it's range and bailout. Note
679 // that for all other pointer typed values, we terminate the search at the
680 // definition. We could easily extend this to look through geps, bitcasts,
681 // and the like to prove non-nullness, but it's not clear that's worth it
682 // compile time wise. The context-insensative value walk done inside
683 // isKnownNonNull gets most of the profitable cases at much less expense.
684 // This does mean that we have a sensativity to where the defining
685 // instruction is placed, even if it could legally be hoisted much higher.
686 // That is unfortunate.
Igor Laevsky0fa48192015-09-18 13:01:48 +0000687 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
688 if (PT && isKnownNonNull(BBI)) {
689 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
Hans Wennborg45172ac2014-11-25 17:23:05 +0000690 insertResult(Val, BB, Res);
691 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000692 }
Davide Italianobd543d02016-05-25 22:29:34 +0000693 if (BBI->getType()->isIntegerTy()) {
Philip Reames2ab964e2016-04-27 01:02:25 +0000694 if (isa<CastInst>(BBI)) {
695 if (!solveBlockValueCast(Res, BBI, BB))
696 return false;
697 insertResult(Val, BB, Res);
698 return true;
699 }
700 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
NAKAMURA Takumibd072a92016-07-25 00:59:46 +0000701 if (BO && isa<ConstantInt>(BO->getOperand(1))) {
Philip Reames2ab964e2016-04-27 01:02:25 +0000702 if (!solveBlockValueBinaryOp(Res, BBI, BB))
703 return false;
704 insertResult(Val, BB, Res);
705 return true;
706 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000707 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000708
Philip Reamesa0c9f6e2016-03-04 22:27:39 +0000709 DEBUG(dbgs() << " compute BB '" << BB->getName()
710 << "' - unknown inst def found.\n");
711 Res = getFromRangeMetadata(BBI);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000712 insertResult(Val, BB, Res);
713 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000714}
715
716static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
717 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
718 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000719 GetUnderlyingObject(L->getPointerOperand(),
720 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000721 }
722 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
723 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000724 GetUnderlyingObject(S->getPointerOperand(),
725 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000726 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000727 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
728 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000729
730 // FIXME: check whether it has a valuerange that excludes zero?
731 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
732 if (!Len || Len->isZero()) return false;
733
Eli Friedman7a5fc692011-05-31 20:40:16 +0000734 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000735 if (GetUnderlyingObject(MI->getRawDest(),
736 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000737 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000738 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000739 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000740 if (GetUnderlyingObject(MTI->getRawSource(),
741 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000742 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000743 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000744 return false;
745}
746
Philip Reames3f83dbe2016-04-27 00:30:55 +0000747/// Return true if the allocation associated with Val is ever dereferenced
748/// within the given basic block. This establishes the fact Val is not null,
749/// but does not imply that the memory at Val is dereferenceable. (Val may
750/// point off the end of the dereferenceable part of the object.)
751static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
752 assert(Val->getType()->isPointerTy());
753
754 const DataLayout &DL = BB->getModule()->getDataLayout();
755 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
756 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
757 // inside InstructionDereferencesPointer either.
758 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
759 for (Instruction &I : *BB)
760 if (InstructionDereferencesPointer(&I, UnderlyingVal))
761 return true;
762 return false;
763}
764
Owen Anderson64c2c572010-12-20 18:18:16 +0000765bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
766 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000767 LVILatticeVal Result; // Start Undefined.
768
Nick Lewycky55a700b2010-12-18 01:00:40 +0000769 // If this is the entry block, we must be asking about an argument. The
770 // value is overdefined.
771 if (BB == &BB->getParent()->getEntryBlock()) {
772 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
Philip Reames3f83dbe2016-04-27 00:30:55 +0000773 // Bofore giving up, see if we can prove the pointer non-null local to
774 // this particular block.
775 if (Val->getType()->isPointerTy() &&
776 (isKnownNonNull(Val) || isObjectDereferencedInBlock(Val, BB))) {
Chris Lattner229907c2011-07-18 04:54:35 +0000777 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000778 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
779 } else {
780 Result.markOverdefined();
781 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000782 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000783 return true;
784 }
785
786 // Loop over all of our predecessors, merging what we know from them into
787 // result.
788 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000789 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000790 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000791 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000792 if (EdgesMissing)
793 continue;
794
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000795 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000796
797 // If we hit overdefined, exit early. The BlockVals entry is already set
798 // to overdefined.
799 if (Result.isOverdefined()) {
800 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000801 << "' - overdefined because of pred (non local).\n");
Artur Pilipenkoadcd01f2016-08-09 09:14:29 +0000802 // Before giving up, see if we can prove the pointer non-null local to
Philip Reames3f83dbe2016-04-27 00:30:55 +0000803 // this particular block.
804 if (Val->getType()->isPointerTy() &&
805 isObjectDereferencedInBlock(Val, BB)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000806 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000807 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
808 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000809
Owen Anderson64c2c572010-12-20 18:18:16 +0000810 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000811 return true;
812 }
813 }
814 if (EdgesMissing)
815 return false;
816
817 // Return the merged value, which is more precise than 'overdefined'.
818 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000819 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000820 return true;
821}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000822
Owen Anderson64c2c572010-12-20 18:18:16 +0000823bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
824 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000825 LVILatticeVal Result; // Start Undefined.
826
827 // Loop over all of our predecessors, merging what we know from them into
828 // result.
829 bool EdgesMissing = false;
830 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
831 BasicBlock *PhiBB = PN->getIncomingBlock(i);
832 Value *PhiVal = PN->getIncomingValue(i);
833 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000834 // Note that we can provide PN as the context value to getEdgeValue, even
835 // though the results will be cached, because PN is the value being used as
836 // the cache key in the caller.
Hal Finkel7e184492014-09-07 20:29:59 +0000837 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000838 if (EdgesMissing)
839 continue;
840
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000841 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000842
843 // If we hit overdefined, exit early. The BlockVals entry is already set
844 // to overdefined.
845 if (Result.isOverdefined()) {
846 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000847 << "' - overdefined because of pred (local).\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000848
Owen Anderson64c2c572010-12-20 18:18:16 +0000849 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000850 return true;
851 }
852 }
853 if (EdgesMissing)
854 return false;
855
856 // Return the merged value, which is more precise than 'overdefined'.
857 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000858 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000859 return true;
860}
861
Artur Pilipenko933c07a2016-08-10 13:38:07 +0000862static LVILatticeVal getValueFromCondition(Value *Val, Value *Cond,
863 bool isTrueDest = true);
Hal Finkel7e184492014-09-07 20:29:59 +0000864
Philip Reamesd1f829d2016-02-02 21:57:37 +0000865// If we can determine a constraint on the value given conditions assumed by
866// the program, intersect those constraints with BBLV
867void LazyValueInfoCache::intersectAssumeBlockValueConstantRange(Value *Val,
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000868 LVILatticeVal &BBLV,
869 Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000870 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
871 if (!BBI)
872 return;
873
Chandler Carruth66b31302015-01-04 12:03:27 +0000874 for (auto &AssumeVH : AC->assumptions()) {
875 if (!AssumeVH)
876 continue;
877 auto *I = cast<CallInst>(AssumeVH);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000878 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +0000879 continue;
880
Artur Pilipenko933c07a2016-08-10 13:38:07 +0000881 BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
Hal Finkel7e184492014-09-07 20:29:59 +0000882 }
883}
884
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000885bool LazyValueInfoCache::solveBlockValueSelect(LVILatticeVal &BBLV,
886 SelectInst *SI, BasicBlock *BB) {
887
888 // Recurse on our inputs if needed
889 if (!hasBlockValue(SI->getTrueValue(), BB)) {
890 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
891 return false;
892 BBLV.markOverdefined();
893 return true;
894 }
895 LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
896 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
897 // extra slots in the table if we can.
898 if (TrueVal.isOverdefined()) {
899 BBLV.markOverdefined();
900 return true;
901 }
902
903 if (!hasBlockValue(SI->getFalseValue(), BB)) {
904 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
905 return false;
906 BBLV.markOverdefined();
907 return true;
908 }
909 LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
910 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
911 // extra slots in the table if we can.
912 if (FalseVal.isOverdefined()) {
913 BBLV.markOverdefined();
914 return true;
915 }
916
Philip Reamesadf0e352016-02-26 22:53:59 +0000917 if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
918 ConstantRange TrueCR = TrueVal.getConstantRange();
919 ConstantRange FalseCR = FalseVal.getConstantRange();
920 Value *LHS = nullptr;
921 Value *RHS = nullptr;
922 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
923 // Is this a min specifically of our two inputs? (Avoid the risk of
924 // ValueTracking getting smarter looking back past our immediate inputs.)
925 if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
926 LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
927 switch (SPR.Flavor) {
928 default:
929 llvm_unreachable("unexpected minmax type!");
930 case SPF_SMIN: /// Signed minimum
931 BBLV.markConstantRange(TrueCR.smin(FalseCR));
932 return true;
933 case SPF_UMIN: /// Unsigned minimum
934 BBLV.markConstantRange(TrueCR.umin(FalseCR));
935 return true;
936 case SPF_SMAX: /// Signed maximum
937 BBLV.markConstantRange(TrueCR.smax(FalseCR));
938 return true;
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000939 case SPF_UMAX: /// Unsigned maximum
Philip Reamesadf0e352016-02-26 22:53:59 +0000940 BBLV.markConstantRange(TrueCR.umax(FalseCR));
941 return true;
942 };
943 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000944
Philip Reamesadf0e352016-02-26 22:53:59 +0000945 // TODO: ABS, NABS from the SelectPatternResult
946 }
947
Philip Reames854a84c2016-02-12 00:09:18 +0000948 // Can we constrain the facts about the true and false values by using the
949 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
950 // TODO: We could potentially refine an overdefined true value above.
Artur Pilipenko2e19f592016-08-02 16:20:48 +0000951 Value *Cond = SI->getCondition();
Artur Pilipenko933c07a2016-08-10 13:38:07 +0000952 TrueVal = intersect(TrueVal,
953 getValueFromCondition(SI->getTrueValue(), Cond, true));
954 FalseVal = intersect(FalseVal,
955 getValueFromCondition(SI->getFalseValue(), Cond, false));
Philip Reames854a84c2016-02-12 00:09:18 +0000956
Artur Pilipenko2e19f592016-08-02 16:20:48 +0000957 // Handle clamp idioms such as:
958 // %24 = constantrange<0, 17>
959 // %39 = icmp eq i32 %24, 0
960 // %40 = add i32 %24, -1
961 // %siv.next = select i1 %39, i32 16, i32 %40
962 // %siv.next = constantrange<0, 17> not <-1, 17>
963 // In general, this can handle any clamp idiom which tests the edge
964 // condition via an equality or inequality.
965 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
Philip Reamesadf0e352016-02-26 22:53:59 +0000966 ICmpInst::Predicate Pred = ICI->getPredicate();
967 Value *A = ICI->getOperand(0);
968 if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
969 auto addConstants = [](ConstantInt *A, ConstantInt *B) {
970 assert(A->getType() == B->getType());
971 return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
972 };
973 // See if either input is A + C2, subject to the constraint from the
974 // condition that A != C when that input is used. We can assume that
975 // that input doesn't include C + C2.
976 ConstantInt *CIAdded;
977 switch (Pred) {
Philip Reames70b39182016-02-27 05:18:30 +0000978 default: break;
Philip Reamesadf0e352016-02-26 22:53:59 +0000979 case ICmpInst::ICMP_EQ:
980 if (match(SI->getFalseValue(), m_Add(m_Specific(A),
981 m_ConstantInt(CIAdded)))) {
982 auto ResNot = addConstants(CIBase, CIAdded);
983 FalseVal = intersect(FalseVal,
984 LVILatticeVal::getNot(ResNot));
985 }
986 break;
987 case ICmpInst::ICMP_NE:
988 if (match(SI->getTrueValue(), m_Add(m_Specific(A),
989 m_ConstantInt(CIAdded)))) {
990 auto ResNot = addConstants(CIBase, CIAdded);
991 TrueVal = intersect(TrueVal,
992 LVILatticeVal::getNot(ResNot));
993 }
994 break;
995 };
996 }
997 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000998
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000999 LVILatticeVal Result; // Start Undefined.
1000 Result.mergeIn(TrueVal, DL);
1001 Result.mergeIn(FalseVal, DL);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001002 BBLV = Result;
1003 return true;
1004}
1005
Philip Reames66715772016-04-25 18:30:31 +00001006bool LazyValueInfoCache::solveBlockValueCast(LVILatticeVal &BBLV,
1007 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001008 BasicBlock *BB) {
1009 if (!BBI->getOperand(0)->getType()->isSized()) {
1010 // Without knowing how wide the input is, we can't analyze it in any useful
1011 // way.
1012 BBLV.markOverdefined();
1013 return true;
1014 }
Philip Reamesf105db42016-04-26 23:27:33 +00001015
1016 // Filter out casts we don't know how to reason about before attempting to
1017 // recurse on our operand. This can cut a long search short if we know we're
1018 // not going to be able to get any useful information anways.
1019 switch (BBI->getOpcode()) {
1020 case Instruction::Trunc:
1021 case Instruction::SExt:
1022 case Instruction::ZExt:
1023 case Instruction::BitCast:
1024 break;
1025 default:
1026 // Unhandled instructions are overdefined.
1027 DEBUG(dbgs() << " compute BB '" << BB->getName()
1028 << "' - overdefined (unknown cast).\n");
1029 BBLV.markOverdefined();
1030 return true;
1031 }
1032
Philip Reames38c87c22016-04-26 21:48:16 +00001033 // Figure out the range of the LHS. If that fails, we still apply the
1034 // transfer rule on the full set since we may be able to locally infer
1035 // interesting facts.
1036 if (!hasBlockValue(BBI->getOperand(0), BB))
Hans Wennborg45172ac2014-11-25 17:23:05 +00001037 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
Philip Reames38c87c22016-04-26 21:48:16 +00001038 // More work to do before applying this transfer rule.
Hans Wennborg45172ac2014-11-25 17:23:05 +00001039 return false;
Philip Reames38c87c22016-04-26 21:48:16 +00001040
1041 const unsigned OperandBitWidth =
Philip Reamese5030e82016-04-26 22:52:30 +00001042 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
Philip Reames38c87c22016-04-26 21:48:16 +00001043 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1044 if (hasBlockValue(BBI->getOperand(0), BB)) {
1045 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
1046 intersectAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
1047 if (LHSVal.isConstantRange())
1048 LHSRange = LHSVal.getConstantRange();
Nick Lewycky55a700b2010-12-18 01:00:40 +00001049 }
1050
Philip Reames38c87c22016-04-26 21:48:16 +00001051 const unsigned ResultBitWidth =
1052 cast<IntegerType>(BBI->getType())->getBitWidth();
Philip Reames66715772016-04-25 18:30:31 +00001053
1054 // NOTE: We're currently limited by the set of operations that ConstantRange
1055 // can evaluate symbolically. Enhancing that set will allows us to analyze
1056 // more definitions.
1057 LVILatticeVal Result;
1058 switch (BBI->getOpcode()) {
1059 case Instruction::Trunc:
Philip Reames38c87c22016-04-26 21:48:16 +00001060 Result.markConstantRange(LHSRange.truncate(ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001061 break;
1062 case Instruction::SExt:
Philip Reames38c87c22016-04-26 21:48:16 +00001063 Result.markConstantRange(LHSRange.signExtend(ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001064 break;
1065 case Instruction::ZExt:
Philip Reames38c87c22016-04-26 21:48:16 +00001066 Result.markConstantRange(LHSRange.zeroExtend(ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001067 break;
1068 case Instruction::BitCast:
1069 Result.markConstantRange(LHSRange);
1070 break;
Philip Reames66715772016-04-25 18:30:31 +00001071 default:
Philip Reamesf105db42016-04-26 23:27:33 +00001072 // Should be dead if the code above is correct
1073 llvm_unreachable("inconsistent with above");
Philip Reames66715772016-04-25 18:30:31 +00001074 break;
Owen Anderson80d19f02010-08-18 21:11:37 +00001075 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001076
Philip Reames66715772016-04-25 18:30:31 +00001077 BBLV = Result;
1078 return true;
1079}
1080
1081bool LazyValueInfoCache::solveBlockValueBinaryOp(LVILatticeVal &BBLV,
1082 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001083 BasicBlock *BB) {
Philip Reames66715772016-04-25 18:30:31 +00001084
Philip Reames053c2a62016-04-26 23:10:35 +00001085 assert(BBI->getOperand(0)->getType()->isSized() &&
1086 "all operands to binary operators are sized");
Philip Reamesf105db42016-04-26 23:27:33 +00001087
1088 // Filter out operators we don't know how to reason about before attempting to
1089 // recurse on our operand(s). This can cut a long search short if we know
1090 // we're not going to be able to get any useful information anways.
1091 switch (BBI->getOpcode()) {
1092 case Instruction::Add:
1093 case Instruction::Sub:
1094 case Instruction::Mul:
1095 case Instruction::UDiv:
1096 case Instruction::Shl:
1097 case Instruction::LShr:
1098 case Instruction::And:
1099 case Instruction::Or:
1100 // continue into the code below
1101 break;
1102 default:
1103 // Unhandled instructions are overdefined.
1104 DEBUG(dbgs() << " compute BB '" << BB->getName()
1105 << "' - overdefined (unknown binary operator).\n");
1106 BBLV.markOverdefined();
1107 return true;
1108 };
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001109
Philip Reames053c2a62016-04-26 23:10:35 +00001110 // Figure out the range of the LHS. If that fails, use a conservative range,
1111 // but apply the transfer rule anyways. This lets us pick up facts from
1112 // expressions like "and i32 (call i32 @foo()), 32"
1113 if (!hasBlockValue(BBI->getOperand(0), BB))
1114 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
1115 // More work to do before applying this transfer rule.
1116 return false;
1117
1118 const unsigned OperandBitWidth =
1119 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
1120 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1121 if (hasBlockValue(BBI->getOperand(0), BB)) {
1122 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
1123 intersectAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
1124 if (LHSVal.isConstantRange())
1125 LHSRange = LHSVal.getConstantRange();
Philip Reames66715772016-04-25 18:30:31 +00001126 }
Philip Reames66715772016-04-25 18:30:31 +00001127
1128 ConstantInt *RHS = cast<ConstantInt>(BBI->getOperand(1));
1129 ConstantRange RHSRange = ConstantRange(RHS->getValue());
1130
Owen Anderson80d19f02010-08-18 21:11:37 +00001131 // NOTE: We're currently limited by the set of operations that ConstantRange
1132 // can evaluate symbolically. Enhancing that set will allows us to analyze
1133 // more definitions.
Owen Anderson64c2c572010-12-20 18:18:16 +00001134 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +00001135 switch (BBI->getOpcode()) {
1136 case Instruction::Add:
1137 Result.markConstantRange(LHSRange.add(RHSRange));
1138 break;
1139 case Instruction::Sub:
1140 Result.markConstantRange(LHSRange.sub(RHSRange));
1141 break;
1142 case Instruction::Mul:
1143 Result.markConstantRange(LHSRange.multiply(RHSRange));
1144 break;
1145 case Instruction::UDiv:
1146 Result.markConstantRange(LHSRange.udiv(RHSRange));
1147 break;
1148 case Instruction::Shl:
1149 Result.markConstantRange(LHSRange.shl(RHSRange));
1150 break;
1151 case Instruction::LShr:
1152 Result.markConstantRange(LHSRange.lshr(RHSRange));
1153 break;
Nick Lewyckyad48e012010-09-07 05:39:02 +00001154 case Instruction::And:
1155 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
1156 break;
1157 case Instruction::Or:
1158 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
1159 break;
Owen Anderson80d19f02010-08-18 21:11:37 +00001160 default:
Philip Reamesf105db42016-04-26 23:27:33 +00001161 // Should be dead if the code above is correct
1162 llvm_unreachable("inconsistent with above");
Owen Anderson80d19f02010-08-18 21:11:37 +00001163 break;
1164 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001165
Owen Anderson64c2c572010-12-20 18:18:16 +00001166 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +00001167 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +00001168}
1169
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001170static LVILatticeVal getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1171 bool isTrueDest) {
Artur Pilipenko21472912016-08-08 14:08:37 +00001172 Value *LHS = ICI->getOperand(0);
1173 Value *RHS = ICI->getOperand(1);
1174 CmpInst::Predicate Predicate = ICI->getPredicate();
1175
1176 if (isa<Constant>(RHS)) {
1177 if (ICI->isEquality() && LHS == Val) {
Hal Finkel7e184492014-09-07 20:29:59 +00001178 // We know that V has the RHS constant if this is a true SETEQ or
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001179 // false SETNE.
Artur Pilipenko21472912016-08-08 14:08:37 +00001180 if (isTrueDest == (Predicate == ICmpInst::ICMP_EQ))
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001181 return LVILatticeVal::get(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001182 else
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001183 return LVILatticeVal::getNot(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001184 }
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001185 }
Hal Finkel7e184492014-09-07 20:29:59 +00001186
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001187 if (!Val->getType()->isIntegerTy())
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001188 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001189
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001190 // Use ConstantRange::makeAllowedICmpRegion in order to determine the possible
1191 // range of Val guaranteed by the condition. Recognize comparisons in the from
1192 // of:
1193 // icmp <pred> Val, ...
Artur Pilipenko63562582016-08-12 10:05:11 +00001194 // icmp <pred> (add Val, Offset), ...
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001195 // The latter is the range checking idiom that InstCombine produces. Subtract
1196 // the offset from the allowed range for RHS in this case.
Artur Pilipenkoeed618d2016-08-08 14:33:11 +00001197
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001198 // Val or (add Val, Offset) can be on either hand of the comparison
1199 if (LHS != Val && !match(LHS, m_Add(m_Specific(Val), m_ConstantInt()))) {
1200 std::swap(LHS, RHS);
1201 Predicate = CmpInst::getSwappedPredicate(Predicate);
1202 }
Hal Finkel7e184492014-09-07 20:29:59 +00001203
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001204 ConstantInt *Offset = nullptr;
Artur Pilipenko63562582016-08-12 10:05:11 +00001205 if (LHS != Val)
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001206 match(LHS, m_Add(m_Specific(Val), m_ConstantInt(Offset)));
Hal Finkel7e184492014-09-07 20:29:59 +00001207
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001208 if (LHS == Val || Offset) {
1209 // Calculate the range of values that are allowed by the comparison
1210 ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1211 /*isFullSet=*/true);
1212 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1213 RHSRange = ConstantRange(CI->getValue());
1214
1215 // If we're interested in the false dest, invert the condition
1216 CmpInst::Predicate Pred =
1217 isTrueDest ? Predicate : CmpInst::getInversePredicate(Predicate);
1218 ConstantRange TrueValues =
1219 ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1220
1221 if (Offset) // Apply the offset from above.
1222 TrueValues = TrueValues.subtract(Offset->getValue());
1223
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001224 return LVILatticeVal::getRange(std::move(TrueValues));
Hal Finkel7e184492014-09-07 20:29:59 +00001225 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001226
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001227 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001228}
1229
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001230static LVILatticeVal
1231getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1232 DenseMap<Value*, LVILatticeVal> &Visited);
1233
1234static LVILatticeVal
1235getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1236 DenseMap<Value*, LVILatticeVal> &Visited) {
1237 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1238 return getValueFromICmpCondition(Val, ICI, isTrueDest);
1239
1240 // Handle conditions in the form of (cond1 && cond2), we know that on the
1241 // true dest path both of the conditions hold.
1242 if (!isTrueDest)
1243 return LVILatticeVal::getOverdefined();
1244
1245 BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond);
1246 if (!BO || BO->getOpcode() != BinaryOperator::And)
1247 return LVILatticeVal::getOverdefined();
1248
1249 auto RHS = getValueFromCondition(Val, BO->getOperand(0), isTrueDest, Visited);
1250 auto LHS = getValueFromCondition(Val, BO->getOperand(1), isTrueDest, Visited);
1251 return intersect(RHS, LHS);
1252}
1253
1254static LVILatticeVal
1255getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1256 DenseMap<Value*, LVILatticeVal> &Visited) {
1257 auto I = Visited.find(Cond);
1258 if (I != Visited.end())
1259 return I->second;
1260 return Visited[Cond] = getValueFromConditionImpl(Val, Cond, isTrueDest,
1261 Visited);
1262}
1263
1264LVILatticeVal getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest) {
1265 assert(Cond && "precondition");
1266 DenseMap<Value*, LVILatticeVal> Visited;
1267 return getValueFromCondition(Val, Cond, isTrueDest, Visited);
1268}
1269
Nuno Lopese6e04902012-06-28 01:16:18 +00001270/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
Philip Reames13f73242016-02-01 23:21:11 +00001271/// Val is not constrained on the edge. Result is unspecified if return value
1272/// is false.
Nuno Lopese6e04902012-06-28 01:16:18 +00001273static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1274 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001275 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +00001276 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +00001277 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1278 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +00001279 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +00001280 if (BI->isConditional() &&
1281 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1282 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1283 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1284 "BBTo isn't a successor of BBFrom");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001285
Chris Lattner19019ea2009-11-11 22:48:44 +00001286 // If V is the condition of the branch itself, then we know exactly what
1287 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +00001288 if (BI->getCondition() == Val) {
1289 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +00001290 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001291 return true;
1292 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001293
Chris Lattner19019ea2009-11-11 22:48:44 +00001294 // If the condition of the branch is an equality comparison, we may be
1295 // able to infer the value.
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001296 Result = getValueFromCondition(Val, BI->getCondition(), isTrueDest);
1297 if (!Result.isOverdefined())
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001298 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001299 }
1300 }
Chris Lattner77358782009-11-15 20:02:12 +00001301
1302 // If the edge was formed by a switch on the value, then we may know exactly
1303 // what it is.
1304 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001305 if (SI->getCondition() != Val)
1306 return false;
1307
1308 bool DefaultCase = SI->getDefaultDest() == BBTo;
1309 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1310 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1311
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001312 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001313 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +00001314 if (DefaultCase) {
1315 // It is possible that the default destination is the destination of
1316 // some cases. There is no need to perform difference for those cases.
1317 if (i.getCaseSuccessor() != BBTo)
1318 EdgesVals = EdgesVals.difference(EdgeVal);
1319 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +00001320 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +00001321 }
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001322 Result = LVILatticeVal::getRange(std::move(EdgesVals));
Nuno Lopes8650fb82012-06-28 16:13:37 +00001323 return true;
Chris Lattner77358782009-11-15 20:02:12 +00001324 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001325 return false;
1326}
1327
Sanjay Patel938e2792015-01-09 16:35:37 +00001328/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1329/// the basic block if the edge does not constrain Val.
Nuno Lopese6e04902012-06-28 01:16:18 +00001330bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +00001331 BasicBlock *BBTo, LVILatticeVal &Result,
1332 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +00001333 // If already a constant, there is nothing to compute.
1334 if (Constant *VC = dyn_cast<Constant>(Val)) {
1335 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001336 return true;
1337 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001338
Philip Reames44456b82016-02-02 03:15:40 +00001339 LVILatticeVal LocalResult;
1340 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1341 // If we couldn't constrain the value on the edge, LocalResult doesn't
1342 // provide any information.
1343 LocalResult.markOverdefined();
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001344
Philip Reames44456b82016-02-02 03:15:40 +00001345 if (hasSingleValue(LocalResult)) {
1346 // Can't get any more precise here
1347 Result = LocalResult;
Nuno Lopese6e04902012-06-28 01:16:18 +00001348 return true;
1349 }
1350
1351 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +00001352 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1353 return false;
Philip Reames44456b82016-02-02 03:15:40 +00001354 // No new information.
1355 Result = LocalResult;
Hans Wennborg45172ac2014-11-25 17:23:05 +00001356 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +00001357 }
1358
Philip Reames44456b82016-02-02 03:15:40 +00001359 // Try to intersect ranges of the BB and the constraint on the edge.
1360 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001361 intersectAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +00001362 // We can use the context instruction (generically the ultimate instruction
1363 // the calling pass is trying to simplify) here, even though the result of
1364 // this function is generally cached when called from the solve* functions
1365 // (and that cached result might be used with queries using a different
1366 // context instruction), because when this function is called from the solve*
1367 // functions, the context instruction is not provided. When called from
1368 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
1369 // but then the result is not cached.
Philip Reamesd1f829d2016-02-02 21:57:37 +00001370 intersectAssumeBlockValueConstantRange(Val, InBlock, CxtI);
Philip Reames44456b82016-02-02 03:15:40 +00001371
1372 Result = intersect(LocalResult, InBlock);
Nuno Lopese6e04902012-06-28 01:16:18 +00001373 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001374}
1375
Hal Finkel7e184492014-09-07 20:29:59 +00001376LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
1377 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001378 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001379 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001380
Hans Wennborg45172ac2014-11-25 17:23:05 +00001381 assert(BlockValueStack.empty() && BlockValueSet.empty());
Philip Reamesbb781b42016-02-10 21:46:32 +00001382 if (!hasBlockValue(V, BB)) {
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001383 pushBlockValue(std::make_pair(BB, V));
Philip Reamesbb781b42016-02-10 21:46:32 +00001384 solve();
1385 }
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001386 LVILatticeVal Result = getBlockValue(V, BB);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001387 intersectAssumeBlockValueConstantRange(V, Result, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001388
1389 DEBUG(dbgs() << " Result = " << Result << "\n");
1390 return Result;
1391}
1392
1393LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1394 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1395 << CxtI->getName() << "'\n");
1396
Philip Reamesbb781b42016-02-10 21:46:32 +00001397 if (auto *C = dyn_cast<Constant>(V))
1398 return LVILatticeVal::get(C);
1399
Philip Reamesd1f829d2016-02-02 21:57:37 +00001400 LVILatticeVal Result = LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +00001401 if (auto *I = dyn_cast<Instruction>(V))
1402 Result = getFromRangeMetadata(I);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001403 intersectAssumeBlockValueConstantRange(V, Result, CxtI);
Philip Reames2c275cc2016-02-02 00:45:30 +00001404
David Greene37e98092009-12-23 20:43:58 +00001405 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001406 return Result;
1407}
Chris Lattner19019ea2009-11-11 22:48:44 +00001408
Chris Lattneraf025d32009-11-15 19:59:49 +00001409LVILatticeVal LazyValueInfoCache::
Hal Finkel7e184492014-09-07 20:29:59 +00001410getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1411 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001412 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001413 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001414
Nick Lewycky55a700b2010-12-18 01:00:40 +00001415 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001416 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001417 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001418 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001419 (void)WasFastQuery;
1420 assert(WasFastQuery && "More work to do after problem solved?");
1421 }
1422
David Greene37e98092009-12-23 20:43:58 +00001423 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001424 return Result;
1425}
1426
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001427void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1428 BasicBlock *NewSucc) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001429 // When an edge in the graph has been threaded, values that we could not
1430 // determine a value for before (i.e. were marked overdefined) may be
1431 // possible to solve now. We do NOT try to proactively update these values.
1432 // Instead, we clear their entries from the cache, and allow lazy updating to
1433 // recompute them when needed.
1434
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001435 // The updating process is fairly simple: we need to drop cached info
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001436 // for all values that were marked overdefined in OldSucc, and for those same
1437 // values in any successor of OldSucc (except NewSucc) in which they were
1438 // also marked overdefined.
1439 std::vector<BasicBlock*> worklist;
1440 worklist.push_back(OldSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001441
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001442 auto I = OverDefinedCache.find(OldSucc);
1443 if (I == OverDefinedCache.end())
1444 return; // Nothing to process here.
Bruno Cardoso Lopes7a1483e2015-08-21 21:18:26 +00001445 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001446
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001447 // Use a worklist to perform a depth-first search of OldSucc's successors.
1448 // NOTE: We do not need a visited list since any blocks we have already
1449 // visited will have had their overdefined markers cleared already, and we
1450 // thus won't loop to their successors.
1451 while (!worklist.empty()) {
1452 BasicBlock *ToUpdate = worklist.back();
1453 worklist.pop_back();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001454
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001455 // Skip blocks only accessible through NewSucc.
1456 if (ToUpdate == NewSucc) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001457
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001458 bool changed = false;
Bruno Cardoso Lopes7a1483e2015-08-21 21:18:26 +00001459 for (Value *V : ValsToClear) {
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001460 // If a value was marked overdefined in OldSucc, and is here too...
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001461 auto OI = OverDefinedCache.find(ToUpdate);
1462 if (OI == OverDefinedCache.end())
1463 continue;
1464 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
1465 if (!ValueSet.count(V))
1466 continue;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001467
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001468 ValueSet.erase(V);
1469 if (ValueSet.empty())
1470 OverDefinedCache.erase(OI);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001471
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001472 // If we removed anything, then we potentially need to update
Owen Andersonaac5a722010-07-27 23:58:11 +00001473 // blocks successors too.
1474 changed = true;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001475 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001476
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001477 if (!changed) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001478
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001479 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1480 }
1481}
1482
Chris Lattneraf025d32009-11-15 19:59:49 +00001483//===----------------------------------------------------------------------===//
1484// LazyValueInfo Impl
1485//===----------------------------------------------------------------------===//
1486
Sanjay Patel2a385e22015-01-09 16:47:20 +00001487/// This lazily constructs the LazyValueInfoCache.
Chandler Carruth66b31302015-01-04 12:03:27 +00001488static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001489 const DataLayout *DL,
Hal Finkel7e184492014-09-07 20:29:59 +00001490 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001491 if (!PImpl) {
1492 assert(DL && "getCache() called with a null DataLayout");
1493 PImpl = new LazyValueInfoCache(AC, *DL, DT);
1494 }
Chris Lattneraf025d32009-11-15 19:59:49 +00001495 return *static_cast<LazyValueInfoCache*>(PImpl);
1496}
1497
Sean Silva687019f2016-06-13 22:01:25 +00001498bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
1499 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001500 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001501
1502 DominatorTreeWrapperPass *DTWP =
1503 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Sean Silva687019f2016-06-13 22:01:25 +00001504 Info.DT = DTWP ? &DTWP->getDomTree() : nullptr;
1505 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001506
Sean Silva687019f2016-06-13 22:01:25 +00001507 if (Info.PImpl)
1508 getCache(Info.PImpl, Info.AC, &DL, Info.DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001509
Owen Anderson208636f2010-08-18 18:39:01 +00001510 // Fully lazy.
1511 return false;
1512}
1513
Sean Silva687019f2016-06-13 22:01:25 +00001514void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier43a33062011-12-02 01:26:24 +00001515 AU.setPreservesAll();
Chandler Carruth66b31302015-01-04 12:03:27 +00001516 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001517 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001518}
1519
Sean Silva687019f2016-06-13 22:01:25 +00001520LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1521
1522LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1523
Chris Lattneraf025d32009-11-15 19:59:49 +00001524void LazyValueInfo::releaseMemory() {
1525 // If the cache was allocated, free it.
1526 if (PImpl) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001527 delete &getCache(PImpl, AC, nullptr);
Craig Topper9f008862014-04-15 04:59:12 +00001528 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001529 }
1530}
1531
Sean Silva687019f2016-06-13 22:01:25 +00001532void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1533
1534LazyValueInfo LazyValueAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1535 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1536 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1537 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1538
1539 return LazyValueInfo(&AC, &TLI, DT);
1540}
1541
Hal Finkel7e184492014-09-07 20:29:59 +00001542Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1543 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001544 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001545 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001546 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001547
Chris Lattner19019ea2009-11-11 22:48:44 +00001548 if (Result.isConstant())
1549 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001550 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001551 ConstantRange CR = Result.getConstantRange();
1552 if (const APInt *SingleVal = CR.getSingleElement())
1553 return ConstantInt::get(V->getContext(), *SingleVal);
1554 }
Craig Topper9f008862014-04-15 04:59:12 +00001555 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001556}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001557
John Regehre1c481d2016-05-02 19:58:00 +00001558ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00001559 Instruction *CxtI) {
John Regehre1c481d2016-05-02 19:58:00 +00001560 assert(V->getType()->isIntegerTy());
1561 unsigned Width = V->getType()->getIntegerBitWidth();
1562 const DataLayout &DL = BB->getModule()->getDataLayout();
1563 LVILatticeVal Result =
1564 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
John Regehre1c481d2016-05-02 19:58:00 +00001565 if (Result.isUndefined())
1566 return ConstantRange(Width, /*isFullSet=*/false);
1567 if (Result.isConstantRange())
1568 return Result.getConstantRange();
Artur Pilipenkoa4b6a702016-08-10 12:54:54 +00001569 // We represent ConstantInt constants as constant ranges but other kinds
1570 // of integer constants, i.e. ConstantExpr will be tagged as constants
1571 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1572 "ConstantInt value must be represented as constantrange");
Davide Italianobd543d02016-05-25 22:29:34 +00001573 return ConstantRange(Width, /*isFullSet=*/true);
John Regehre1c481d2016-05-02 19:58:00 +00001574}
1575
Sanjay Patel2a385e22015-01-09 16:47:20 +00001576/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001577/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001578Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001579 BasicBlock *ToBB,
1580 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001581 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001582 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001583 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001584
Chris Lattnerd5e25432009-11-12 01:29:10 +00001585 if (Result.isConstant())
1586 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001587 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001588 ConstantRange CR = Result.getConstantRange();
1589 if (const APInt *SingleVal = CR.getSingleElement())
1590 return ConstantInt::get(V->getContext(), *SingleVal);
1591 }
Craig Topper9f008862014-04-15 04:59:12 +00001592 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001593}
1594
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001595static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1596 LVILatticeVal &Result,
1597 const DataLayout &DL,
1598 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001599
Chris Lattner565ee2f2009-11-12 04:36:58 +00001600 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001601 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001602 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001603 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001604 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001605 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001606 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1607 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001608 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001609
Owen Anderson185fe002010-08-10 20:03:09 +00001610 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001611 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001612 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001613
Owen Anderson185fe002010-08-10 20:03:09 +00001614 ConstantRange CR = Result.getConstantRange();
1615 if (Pred == ICmpInst::ICMP_EQ) {
1616 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001617 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001618
Owen Anderson185fe002010-08-10 20:03:09 +00001619 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001620 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001621 } else if (Pred == ICmpInst::ICMP_NE) {
1622 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001623 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001624
Owen Anderson185fe002010-08-10 20:03:09 +00001625 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001626 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001627 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001628
Owen Anderson185fe002010-08-10 20:03:09 +00001629 // Handle more complex predicates.
Nick Lewycky11678bd2010-12-15 18:57:18 +00001630 ConstantRange TrueValues =
1631 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1632 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001633 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001634 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001635 return LazyValueInfo::False;
1636 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001637 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001638
Chris Lattneraf025d32009-11-15 19:59:49 +00001639 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001640 // If this is an equality comparison, we can try to fold it knowing that
1641 // "V != C1".
1642 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001643 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001644 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001645 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001646 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001647 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001648 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001649 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001650 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001651 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001652 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001653 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001654 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001655 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001656 }
Hal Finkel7e184492014-09-07 20:29:59 +00001657 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001658 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001659
Hal Finkel7e184492014-09-07 20:29:59 +00001660 return LazyValueInfo::Unknown;
1661}
1662
Sanjay Patel2a385e22015-01-09 16:47:20 +00001663/// Determine whether the specified value comparison with a constant is known to
1664/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001665LazyValueInfo::Tristate
1666LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1667 BasicBlock *FromBB, BasicBlock *ToBB,
1668 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001669 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001670 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001671 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001672
1673 return getPredicateResult(Pred, C, Result, DL, TLI);
1674}
1675
1676LazyValueInfo::Tristate
1677LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1678 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001679 const DataLayout &DL = CxtI->getModule()->getDataLayout();
1680 LVILatticeVal Result = getCache(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001681 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1682 if (Ret != Unknown)
1683 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001684
Philip Reamesaeefae02015-11-04 01:47:04 +00001685 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1686 // LVI as a whole tries to compute a lattice value which is conservatively
1687 // correct at a given location. In this case, we have a predicate which we
1688 // weren't able to prove about the merged result, and we're pushing that
1689 // predicate back along each incoming edge to see if we can prove it
1690 // separately for each input. As a motivating example, consider:
1691 // bb1:
1692 // %v1 = ... ; constantrange<1, 5>
1693 // br label %merge
1694 // bb2:
1695 // %v2 = ... ; constantrange<10, 20>
1696 // br label %merge
1697 // merge:
1698 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1699 // %pred = icmp eq i32 %phi, 8
1700 // We can't tell from the lattice value for '%phi' that '%pred' is false
1701 // along each path, but by checking the predicate over each input separately,
1702 // we can.
1703 // We limit the search to one step backwards from the current BB and value.
1704 // We could consider extending this to search further backwards through the
1705 // CFG and/or value graph, but there are non-obvious compile time vs quality
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001706 // tradeoffs.
Philip Reames66ab0f02015-06-16 00:49:59 +00001707 if (CxtI) {
Philip Reamesbb11d622015-08-31 18:31:48 +00001708 BasicBlock *BB = CxtI->getParent();
1709
1710 // Function entry or an unreachable block. Bail to avoid confusing
1711 // analysis below.
1712 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1713 if (PI == PE)
1714 return Unknown;
1715
1716 // If V is a PHI node in the same block as the context, we need to ask
1717 // questions about the predicate as applied to the incoming value along
1718 // each edge. This is useful for eliminating cases where the predicate is
1719 // known along all incoming edges.
1720 if (auto *PHI = dyn_cast<PHINode>(V))
1721 if (PHI->getParent() == BB) {
1722 Tristate Baseline = Unknown;
1723 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1724 Value *Incoming = PHI->getIncomingValue(i);
1725 BasicBlock *PredBB = PHI->getIncomingBlock(i);
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001726 // Note that PredBB may be BB itself.
Philip Reamesbb11d622015-08-31 18:31:48 +00001727 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1728 CxtI);
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001729
Philip Reamesbb11d622015-08-31 18:31:48 +00001730 // Keep going as long as we've seen a consistent known result for
1731 // all inputs.
1732 Baseline = (i == 0) ? Result /* First iteration */
1733 : (Baseline == Result ? Baseline : Unknown); /* All others */
1734 if (Baseline == Unknown)
1735 break;
1736 }
1737 if (Baseline != Unknown)
1738 return Baseline;
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001739 }
Philip Reamesbb11d622015-08-31 18:31:48 +00001740
Philip Reames66ab0f02015-06-16 00:49:59 +00001741 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001742 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001743 // on all incoming edges.
Philip Reamesbb11d622015-08-31 18:31:48 +00001744 if (!isa<Instruction>(V) ||
1745 cast<Instruction>(V)->getParent() != BB) {
Philip Reames66ab0f02015-06-16 00:49:59 +00001746 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001747 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001748 // the value of the comparison in this block.
1749 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1750 if (Baseline != Unknown) {
1751 // Check that all remaining incoming values match the first one.
1752 while (++PI != PE) {
1753 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1754 if (Ret != Baseline) break;
1755 }
1756 // If we terminated early, then one of the values didn't match.
1757 if (PI == PE) {
1758 return Baseline;
1759 }
1760 }
1761 }
1762 }
1763 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001764}
1765
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001766void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001767 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001768 if (PImpl) {
1769 const DataLayout &DL = PredBB->getModule()->getDataLayout();
1770 getCache(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1771 }
Owen Anderson208636f2010-08-18 18:39:01 +00001772}
1773
1774void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001775 if (PImpl) {
1776 const DataLayout &DL = BB->getModule()->getDataLayout();
1777 getCache(PImpl, AC, &DL, DT).eraseBlock(BB);
1778 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001779}