blob: 6bce7c6d35e01e0b0be5d472d2eea7decf7ff360 [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"
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +000029#include "llvm/IR/Intrinsics.h"
Philip Reameseb3e9da2015-10-29 03:57:17 +000030#include "llvm/IR/LLVMContext.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000031#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000032#include "llvm/IR/ValueHandle.h"
Chris Lattnerb584d1e2009-11-12 01:22:16 +000033#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/raw_ostream.h"
Bill Wendling4ec081a2012-01-11 23:43:34 +000035#include <map>
Nick Lewycky55a700b2010-12-18 01:00:40 +000036#include <stack>
Chris Lattner741c94c2009-11-11 00:22:30 +000037using namespace llvm;
Benjamin Kramerd9d80b12012-03-02 15:34:43 +000038using namespace PatternMatch;
Chris Lattner741c94c2009-11-11 00:22:30 +000039
Chandler Carruthf1221bd2014-04-22 02:48:03 +000040#define DEBUG_TYPE "lazy-value-info"
41
Sean Silva687019f2016-06-13 22:01:25 +000042char LazyValueInfoWrapperPass::ID = 0;
43INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
Chad Rosier43a33062011-12-02 01:26:24 +000044 "Lazy Value Information Analysis", false, true)
Chandler Carruth66b31302015-01-04 12:03:27 +000045INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000046INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Sean Silva687019f2016-06-13 22:01:25 +000047INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
Owen Andersondf7a4f22010-10-07 22:25:06 +000048 "Lazy Value Information Analysis", false, true)
Chris Lattner741c94c2009-11-11 00:22:30 +000049
50namespace llvm {
Sean Silva687019f2016-06-13 22:01:25 +000051 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
Chris Lattner741c94c2009-11-11 00:22:30 +000052}
53
Chandler Carruthdab4eae2016-11-23 17:53:26 +000054AnalysisKey LazyValueAnalysis::Key;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000055
56//===----------------------------------------------------------------------===//
57// LVILatticeVal
58//===----------------------------------------------------------------------===//
59
Sanjay Patel2a385e22015-01-09 16:47:20 +000060/// This is the information tracked by LazyValueInfo for each value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000061///
62/// FIXME: This is basically just for bringup, this can be made a lot more rich
63/// in the future.
64///
65namespace {
66class LVILatticeVal {
67 enum LatticeValueTy {
Philip Reames3bb28322016-04-25 18:48:43 +000068 /// This Value has no known value yet. As a result, this implies the
69 /// producing instruction is dead. Caution: We use this as the starting
70 /// state in our local meet rules. In this usage, it's taken to mean
NAKAMURA Takumif2529512016-07-04 01:26:27 +000071 /// "nothing known yet".
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000072 undefined,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000073
Philip Reames3bb28322016-04-25 18:48:43 +000074 /// This Value has a specific constant value. (For integers, constantrange
75 /// is used instead.)
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000076 constant,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000077
Philip Reames3bb28322016-04-25 18:48:43 +000078 /// This Value is known to not have the specified value. (For integers,
79 /// constantrange is used instead.)
Chris Lattner565ee2f2009-11-12 04:36:58 +000080 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000081
Philip Reames3bb28322016-04-25 18:48:43 +000082 /// The Value falls within this range. (Used only for integer typed values.)
Owen Anderson0f306a42010-08-05 22:59:19 +000083 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000084
Philip Reames3bb28322016-04-25 18:48:43 +000085 /// We can not precisely model the dynamic values this value might take.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000086 overdefined
87 };
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000088
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000089 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000090 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000091 LatticeValueTy Tag;
92 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +000093 ConstantRange Range;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000094
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000095public:
Craig Topper9f008862014-04-15 04:59:12 +000096 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000097
Chris Lattner19019ea2009-11-11 22:48:44 +000098 static LVILatticeVal get(Constant *C) {
99 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000100 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000101 Res.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +0000102 return Res;
103 }
Chris Lattner565ee2f2009-11-12 04:36:58 +0000104 static LVILatticeVal getNot(Constant *C) {
105 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000106 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000107 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000108 return Res;
109 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000110 static LVILatticeVal getRange(ConstantRange CR) {
111 LVILatticeVal Res;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000112 Res.markConstantRange(std::move(CR));
Owen Anderson5f1dd092010-08-10 23:20:01 +0000113 return Res;
114 }
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000115 static LVILatticeVal getOverdefined() {
116 LVILatticeVal Res;
117 Res.markOverdefined();
118 return Res;
119 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000120
Owen Anderson0f306a42010-08-05 22:59:19 +0000121 bool isUndefined() const { return Tag == undefined; }
122 bool isConstant() const { return Tag == constant; }
123 bool isNotConstant() const { return Tag == notconstant; }
124 bool isConstantRange() const { return Tag == constantrange; }
125 bool isOverdefined() const { return Tag == overdefined; }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000126
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000127 Constant *getConstant() const {
128 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000129 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000130 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000131
Chris Lattner565ee2f2009-11-12 04:36:58 +0000132 Constant *getNotConstant() const {
133 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000134 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000135 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000136
Owen Anderson0f306a42010-08-05 22:59:19 +0000137 ConstantRange getConstantRange() const {
138 assert(isConstantRange() &&
139 "Cannot get the constant-range of a non-constant-range!");
140 return Range;
141 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000142
Philip Reames1baaef12016-12-06 03:01:08 +0000143private:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000144 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000145 bool markOverdefined() {
146 if (isOverdefined())
147 return false;
Owen Andersonc3a14132010-08-05 22:10:46 +0000148 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000149 return true;
150 }
151
Sanjay Patel2a385e22015-01-09 16:47:20 +0000152 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000153 bool markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000154 assert(V && "Marking constant with NULL");
155 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
156 return markConstantRange(ConstantRange(CI->getValue()));
157 if (isa<UndefValue>(V))
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000158 return false;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000159
160 assert((!isConstant() || getConstant() == V) &&
161 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000162 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000163 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000164 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000165 return true;
166 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000167
Sanjay Patel2a385e22015-01-09 16:47:20 +0000168 /// Return true if this is a change in status.
Chris Lattner565ee2f2009-11-12 04:36:58 +0000169 bool markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000170 assert(V && "Marking constant with NULL");
Nick Lewycky11678bd2010-12-15 18:57:18 +0000171 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
172 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
173 if (isa<UndefValue>(V))
174 return false;
175
176 assert((!isConstant() || getConstant() != V) &&
177 "Marking constant !constant with same value");
178 assert((!isNotConstant() || getNotConstant() == V) &&
179 "Marking !constant with different value");
180 assert(isUndefined() || isConstant());
181 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000182 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000183 return true;
184 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000185
Sanjay Patel2a385e22015-01-09 16:47:20 +0000186 /// Return true if this is a change in status.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000187 bool markConstantRange(ConstantRange NewR) {
Owen Anderson0f306a42010-08-05 22:59:19 +0000188 if (isConstantRange()) {
189 if (NewR.isEmptySet())
190 return markOverdefined();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000191
Nuno Lopese6e04902012-06-28 01:16:18 +0000192 bool changed = Range != NewR;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000193 Range = std::move(NewR);
Owen Anderson0f306a42010-08-05 22:59:19 +0000194 return changed;
195 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000196
Owen Anderson0f306a42010-08-05 22:59:19 +0000197 assert(isUndefined());
198 if (NewR.isEmptySet())
199 return markOverdefined();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000200
Owen Anderson0f306a42010-08-05 22:59:19 +0000201 Tag = constantrange;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000202 Range = std::move(NewR);
Owen Anderson0f306a42010-08-05 22:59:19 +0000203 return true;
204 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000205
Philip Reamesb2949622016-12-06 02:54:16 +0000206public:
207
Sanjay Patel2a385e22015-01-09 16:47:20 +0000208 /// Merge the specified lattice value into this one, updating this
Chris Lattner19019ea2009-11-11 22:48:44 +0000209 /// one and returning true if anything changed.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000210 bool mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
Chris Lattner19019ea2009-11-11 22:48:44 +0000211 if (RHS.isUndefined() || isOverdefined()) return false;
212 if (RHS.isOverdefined()) return markOverdefined();
213
Nick Lewycky11678bd2010-12-15 18:57:18 +0000214 if (isUndefined()) {
215 Tag = RHS.Tag;
216 Val = RHS.Val;
217 Range = RHS.Range;
218 return true;
Chris Lattner22db4b52009-11-12 04:57:13 +0000219 }
220
Nick Lewycky11678bd2010-12-15 18:57:18 +0000221 if (isConstant()) {
222 if (RHS.isConstant()) {
223 if (Val == RHS.Val)
224 return false;
225 return markOverdefined();
226 }
227
228 if (RHS.isNotConstant()) {
229 if (Val == RHS.Val)
230 return markOverdefined();
231
232 // Unless we can prove that the two Constants are different, we must
233 // move to overdefined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000234 if (ConstantInt *Res =
235 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
236 CmpInst::ICMP_NE, getConstant(), RHS.getNotConstant(), DL)))
Nick Lewycky11678bd2010-12-15 18:57:18 +0000237 if (Res->isOne())
238 return markNotConstant(RHS.getNotConstant());
239
240 return markOverdefined();
241 }
242
Chris Lattner19019ea2009-11-11 22:48:44 +0000243 return markOverdefined();
Nick Lewycky11678bd2010-12-15 18:57:18 +0000244 }
245
246 if (isNotConstant()) {
247 if (RHS.isConstant()) {
248 if (Val == RHS.Val)
249 return markOverdefined();
250
251 // Unless we can prove that the two Constants are different, we must
252 // move to overdefined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000253 if (ConstantInt *Res =
254 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
255 CmpInst::ICMP_NE, getNotConstant(), RHS.getConstant(), DL)))
Nick Lewycky11678bd2010-12-15 18:57:18 +0000256 if (Res->isOne())
257 return false;
258
259 return markOverdefined();
260 }
261
262 if (RHS.isNotConstant()) {
263 if (Val == RHS.Val)
264 return false;
265 return markOverdefined();
266 }
267
268 return markOverdefined();
269 }
270
271 assert(isConstantRange() && "New LVILattice type?");
272 if (!RHS.isConstantRange())
273 return markOverdefined();
274
275 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
276 if (NewR.isFullSet())
277 return markOverdefined();
278 return markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000279 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000280};
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000281
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000282} // end anonymous namespace.
283
Chris Lattner19019ea2009-11-11 22:48:44 +0000284namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000285raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
286 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000287raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
288 if (Val.isUndefined())
289 return OS << "undefined";
290 if (Val.isOverdefined())
291 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000292
293 if (Val.isNotConstant())
294 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Davide Italianobd543d02016-05-25 22:29:34 +0000295 if (Val.isConstantRange())
Owen Anderson8afac042010-08-09 20:50:46 +0000296 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
297 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000298 return OS << "constant<" << *Val.getConstant() << '>';
299}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000300}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000301
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000302/// Returns true if this lattice value represents at most one possible value.
303/// This is as precise as any lattice value can get while still representing
304/// reachable code.
Benjamin Kramerc321e532016-06-08 19:09:22 +0000305static bool hasSingleValue(const LVILatticeVal &Val) {
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000306 if (Val.isConstantRange() &&
307 Val.getConstantRange().isSingleElement())
308 // Integer constants are single element ranges
309 return true;
310 if (Val.isConstant())
311 // Non integer constants
312 return true;
313 return false;
314}
315
316/// Combine two sets of facts about the same value into a single set of
317/// facts. Note that this method is not suitable for merging facts along
318/// different paths in a CFG; that's what the mergeIn function is for. This
319/// is for merging facts gathered about the same value at the same location
320/// through two independent means.
321/// Notes:
322/// * This method does not promise to return the most precise possible lattice
323/// value implied by A and B. It is allowed to return any lattice element
324/// which is at least as strong as *either* A or B (unless our facts
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000325/// conflict, see below).
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000326/// * Due to unreachable code, the intersection of two lattice values could be
327/// contradictory. If this happens, we return some valid lattice value so as
328/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
329/// we do not make this guarantee. TODO: This would be a useful enhancement.
330static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
331 // Undefined is the strongest state. It means the value is known to be along
332 // an unreachable path.
333 if (A.isUndefined())
334 return A;
335 if (B.isUndefined())
336 return B;
337
338 // If we gave up for one, but got a useable fact from the other, use it.
339 if (A.isOverdefined())
340 return B;
341 if (B.isOverdefined())
342 return A;
343
344 // Can't get any more precise than constants.
345 if (hasSingleValue(A))
346 return A;
347 if (hasSingleValue(B))
348 return B;
349
350 // Could be either constant range or not constant here.
351 if (!A.isConstantRange() || !B.isConstantRange()) {
352 // TODO: Arbitrary choice, could be improved
353 return A;
354 }
355
356 // Intersect two constant ranges
357 ConstantRange Range =
358 A.getConstantRange().intersectWith(B.getConstantRange());
359 // Note: An empty range is implicitly converted to overdefined internally.
360 // TODO: We could instead use Undefined here since we've proven a conflict
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000361 // and thus know this path must be unreachable.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000362 return LVILatticeVal::getRange(std::move(Range));
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000363}
Philip Reamesd1f829d2016-02-02 21:57:37 +0000364
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000365//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000366// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000367//===----------------------------------------------------------------------===//
368
Chris Lattneraf025d32009-11-15 19:59:49 +0000369namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000370 /// A callback value handle updates the cache when values are erased.
Owen Anderson118ac802011-01-05 21:15:29 +0000371 class LazyValueInfoCache;
David Blaikie774b5842015-08-03 22:30:24 +0000372 struct LVIValueHandle final : public CallbackVH {
Justin Lebar58b377e2016-07-27 22:33:36 +0000373 // Needs to access getValPtr(), which is protected.
374 friend struct DenseMapInfo<LVIValueHandle>;
375
Owen Anderson118ac802011-01-05 21:15:29 +0000376 LazyValueInfoCache *Parent;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000377
Owen Anderson118ac802011-01-05 21:15:29 +0000378 LVIValueHandle(Value *V, LazyValueInfoCache *P)
379 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000380
381 void deleted() override;
382 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000383 deleted();
384 }
385 };
Justin Lebar58b377e2016-07-27 22:33:36 +0000386} // end anonymous namespace
Owen Anderson118ac802011-01-05 21:15:29 +0000387
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000388namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000389 /// This is the cache kept by LazyValueInfo which
Chris Lattneraf025d32009-11-15 19:59:49 +0000390 /// maintains information about queries across the clients' queries.
391 class LazyValueInfoCache {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000392 /// This is all of the cached block information for exactly one Value*.
393 /// The entries are sorted by the BasicBlock* of the
Chris Lattneraf025d32009-11-15 19:59:49 +0000394 /// entries, allowing us to do a lookup with a binary search.
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000395 /// Over-defined lattice values are recorded in OverDefinedCache to reduce
396 /// memory overhead.
Justin Lebar58b377e2016-07-27 22:33:36 +0000397 struct ValueCacheEntryTy {
398 ValueCacheEntryTy(Value *V, LazyValueInfoCache *P) : Handle(V, P) {}
399 LVIValueHandle Handle;
400 SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4> BlockVals;
401 };
Chris Lattneraf025d32009-11-15 19:59:49 +0000402
Sanjay Patel2a385e22015-01-09 16:47:20 +0000403 /// This is all of the cached information for all values,
Owen Anderson6f060af2011-01-05 23:26:22 +0000404 /// mapped from Value* to key information.
Justin Lebar58b377e2016-07-27 22:33:36 +0000405 DenseMap<Value *, std::unique_ptr<ValueCacheEntryTy>> ValueCache;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000406
Sanjay Patel2a385e22015-01-09 16:47:20 +0000407 /// This tracks, on a per-block basis, the set of values that are
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000408 /// over-defined at the end of that block.
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000409 typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
410 OverDefinedCacheTy;
411 OverDefinedCacheTy OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000412
Sanjay Patel2a385e22015-01-09 16:47:20 +0000413 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000414 /// don't spend time removing unused blocks from our caches.
415 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
416
Philip Reames9db79482016-09-12 22:38:44 +0000417 public:
Hans Wennborg45172ac2014-11-25 17:23:05 +0000418 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
419 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000420
421 // Insert over-defined values into their own cache to reduce memory
422 // overhead.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000423 if (Result.isOverdefined())
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000424 OverDefinedCache[BB].insert(Val);
Justin Lebar58b377e2016-07-27 22:33:36 +0000425 else {
426 auto It = ValueCache.find_as(Val);
427 if (It == ValueCache.end()) {
428 ValueCache[Val] = make_unique<ValueCacheEntryTy>(Val, this);
429 It = ValueCache.find_as(Val);
430 assert(It != ValueCache.end() && "Val was just added to the map!");
431 }
432 It->second->BlockVals[BB] = Result;
433 }
Hans Wennborg45172ac2014-11-25 17:23:05 +0000434 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000435
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000436 bool isOverdefined(Value *V, BasicBlock *BB) const {
437 auto ODI = OverDefinedCache.find(BB);
438
439 if (ODI == OverDefinedCache.end())
440 return false;
441
442 return ODI->second.count(V);
443 }
444
Philip Reames9db79482016-09-12 22:38:44 +0000445 bool hasCachedValueInfo(Value *V, BasicBlock *BB) const {
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000446 if (isOverdefined(V, BB))
447 return true;
448
Justin Lebar58b377e2016-07-27 22:33:36 +0000449 auto I = ValueCache.find_as(V);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000450 if (I == ValueCache.end())
451 return false;
452
Justin Lebar58b377e2016-07-27 22:33:36 +0000453 return I->second->BlockVals.count(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000454 }
455
Philip Reames9db79482016-09-12 22:38:44 +0000456 LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) const {
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000457 if (isOverdefined(V, BB))
458 return LVILatticeVal::getOverdefined();
459
Justin Lebar58b377e2016-07-27 22:33:36 +0000460 auto I = ValueCache.find_as(V);
461 if (I == ValueCache.end())
462 return LVILatticeVal();
463 auto BBI = I->second->BlockVals.find(BB);
464 if (BBI == I->second->BlockVals.end())
465 return LVILatticeVal();
466 return BBI->second;
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000467 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000468
Philip Reames92e5e1b2016-09-12 21:46:58 +0000469 /// clear - Empty the cache.
470 void clear() {
471 SeenBlocks.clear();
472 ValueCache.clear();
473 OverDefinedCache.clear();
474 }
475
Philip Reamesb627aec2016-09-12 22:03:36 +0000476 /// Inform the cache that a given value has been deleted.
477 void eraseValue(Value *V);
478
479 /// This is part of the update interface to inform the cache
480 /// that a block has been deleted.
481 void eraseBlock(BasicBlock *BB);
482
Philip Reames9db79482016-09-12 22:38:44 +0000483 /// Updates the cache to remove any influence an overdefined value in
484 /// OldSucc might have (unless also overdefined in NewSucc). This just
485 /// flushes elements from the cache and does not add any.
486 void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
487
Philip Reames92e5e1b2016-09-12 21:46:58 +0000488 friend struct LVIValueHandle;
489 };
Philip Reamesb627aec2016-09-12 22:03:36 +0000490}
Philip Reames92e5e1b2016-09-12 21:46:58 +0000491
Philip Reamesb627aec2016-09-12 22:03:36 +0000492void LazyValueInfoCache::eraseValue(Value *V) {
493 SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
494 for (auto &I : OverDefinedCache) {
495 SmallPtrSetImpl<Value *> &ValueSet = I.second;
496 if (ValueSet.count(V))
497 ValueSet.erase(V);
498 if (ValueSet.empty())
499 ToErase.push_back(I.first);
500 }
501 for (auto &BB : ToErase)
502 OverDefinedCache.erase(BB);
503
504 ValueCache.erase(V);
505}
506
507void LVIValueHandle::deleted() {
508 // This erasure deallocates *this, so it MUST happen after we're done
509 // using any and all members of *this.
510 Parent->eraseValue(*this);
511}
512
513void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
514 // Shortcut if we have never seen this block.
515 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
516 if (I == SeenBlocks.end())
517 return;
518 SeenBlocks.erase(I);
519
520 auto ODI = OverDefinedCache.find(BB);
521 if (ODI != OverDefinedCache.end())
522 OverDefinedCache.erase(ODI);
523
524 for (auto &I : ValueCache)
525 I.second->BlockVals.erase(BB);
526}
527
Philip Reames9db79482016-09-12 22:38:44 +0000528void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
529 BasicBlock *NewSucc) {
530 // When an edge in the graph has been threaded, values that we could not
531 // determine a value for before (i.e. were marked overdefined) may be
532 // possible to solve now. We do NOT try to proactively update these values.
533 // Instead, we clear their entries from the cache, and allow lazy updating to
534 // recompute them when needed.
535
536 // The updating process is fairly simple: we need to drop cached info
537 // for all values that were marked overdefined in OldSucc, and for those same
538 // values in any successor of OldSucc (except NewSucc) in which they were
539 // also marked overdefined.
540 std::vector<BasicBlock*> worklist;
541 worklist.push_back(OldSucc);
542
543 auto I = OverDefinedCache.find(OldSucc);
544 if (I == OverDefinedCache.end())
545 return; // Nothing to process here.
546 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
547
548 // Use a worklist to perform a depth-first search of OldSucc's successors.
549 // NOTE: We do not need a visited list since any blocks we have already
550 // visited will have had their overdefined markers cleared already, and we
551 // thus won't loop to their successors.
552 while (!worklist.empty()) {
553 BasicBlock *ToUpdate = worklist.back();
554 worklist.pop_back();
555
556 // Skip blocks only accessible through NewSucc.
557 if (ToUpdate == NewSucc) continue;
558
559 bool changed = false;
560 for (Value *V : ValsToClear) {
561 // If a value was marked overdefined in OldSucc, and is here too...
562 auto OI = OverDefinedCache.find(ToUpdate);
563 if (OI == OverDefinedCache.end())
564 continue;
565 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
566 if (!ValueSet.count(V))
567 continue;
568
569 ValueSet.erase(V);
570 if (ValueSet.empty())
571 OverDefinedCache.erase(OI);
572
573 // If we removed anything, then we potentially need to update
574 // blocks successors too.
575 changed = true;
576 }
577
578 if (!changed) continue;
579
580 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
581 }
582}
583
Philip Reamesb627aec2016-09-12 22:03:36 +0000584namespace {
Philip Reames92e5e1b2016-09-12 21:46:58 +0000585 // The actual implementation of the lazy analysis and update. Note that the
586 // inheritance from LazyValueInfoCache is intended to be temporary while
587 // splitting the code and then transitioning to a has-a relationship.
Philip Reames9db79482016-09-12 22:38:44 +0000588 class LazyValueInfoImpl {
589
590 /// Cached results from previous queries
591 LazyValueInfoCache TheCache;
Philip Reames92e5e1b2016-09-12 21:46:58 +0000592
593 /// This stack holds the state of the value solver during a query.
594 /// It basically emulates the callstack of the naive
595 /// recursive value lookup process.
596 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
597
598 /// Keeps track of which block-value pairs are in BlockValueStack.
599 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
600
601 /// Push BV onto BlockValueStack unless it's already in there.
602 /// Returns true on success.
603 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
604 if (!BlockValueSet.insert(BV).second)
605 return false; // It's already in the stack.
606
607 DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
608 << "\n");
609 BlockValueStack.push(BV);
610 return true;
611 }
612
613 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
614 const DataLayout &DL; ///< A mandatory DataLayout
615 DominatorTree *DT; ///< An optional DT pointer.
616
617 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
618 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
619 LVILatticeVal &Result, Instruction *CxtI = nullptr);
620 bool hasBlockValue(Value *Val, BasicBlock *BB);
621
622 // These methods process one work item and may add more. A false value
623 // returned means that the work item was not completely processed and must
624 // be revisited after going through the new items.
625 bool solveBlockValue(Value *Val, BasicBlock *BB);
Philip Reames05c435e2016-12-06 03:22:03 +0000626 bool solveBlockValueImpl(LVILatticeVal &Res, Value *Val, BasicBlock *BB);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000627 bool solveBlockValueNonLocal(LVILatticeVal &BBLV, Value *Val, BasicBlock *BB);
628 bool solveBlockValuePHINode(LVILatticeVal &BBLV, PHINode *PN, BasicBlock *BB);
629 bool solveBlockValueSelect(LVILatticeVal &BBLV, SelectInst *S,
630 BasicBlock *BB);
631 bool solveBlockValueBinaryOp(LVILatticeVal &BBLV, Instruction *BBI,
632 BasicBlock *BB);
633 bool solveBlockValueCast(LVILatticeVal &BBLV, Instruction *BBI,
634 BasicBlock *BB);
635 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
636 LVILatticeVal &BBLV,
637 Instruction *BBI);
638
639 void solve();
640
641 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000642 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000643 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000644 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
645 Instruction *CxtI = nullptr);
646
Sanjay Patel2a385e22015-01-09 16:47:20 +0000647 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000648 /// value for the specified Value* at the specified instruction (generally
649 /// from an assume intrinsic).
650 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000651
Sanjay Patel2a385e22015-01-09 16:47:20 +0000652 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000653 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000654 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
655 Instruction *CxtI = nullptr);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000656
Philip Reames9db79482016-09-12 22:38:44 +0000657 /// Complete flush all previously computed values
658 void clear() {
659 TheCache.clear();
660 }
661
662 /// This is part of the update interface to inform the cache
663 /// that a block has been deleted.
664 void eraseBlock(BasicBlock *BB) {
665 TheCache.eraseBlock(BB);
666 }
667
Sanjay Patel2a385e22015-01-09 16:47:20 +0000668 /// This is the update interface to inform the cache that an edge from
669 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000670 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000671
Philip Reames92e5e1b2016-09-12 21:46:58 +0000672 LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000673 DominatorTree *DT = nullptr)
674 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000675 };
676} // end anonymous namespace
677
Philip Reames92e5e1b2016-09-12 21:46:58 +0000678void LazyValueInfoImpl::solve() {
Owen Anderson6f060af2011-01-05 23:26:22 +0000679 while (!BlockValueStack.empty()) {
680 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000681 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
682
Nuno Lopese6e04902012-06-28 01:16:18 +0000683 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000684 // The work item was completely processed.
685 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
Philip Reames9db79482016-09-12 22:38:44 +0000686 assert(TheCache.hasCachedValueInfo(e.second, e.first) &&
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000687 "Result should be in cache!");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000688
Philip Reames44456b82016-02-02 03:15:40 +0000689 DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
Philip Reames9db79482016-09-12 22:38:44 +0000690 << " = " << TheCache.getCachedValueInfo(e.second, e.first) << "\n");
Philip Reames44456b82016-02-02 03:15:40 +0000691
Owen Anderson6f060af2011-01-05 23:26:22 +0000692 BlockValueStack.pop();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000693 BlockValueSet.erase(e);
694 } else {
695 // More work needs to be done before revisiting.
696 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000697 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000698 }
699}
700
Philip Reames92e5e1b2016-09-12 21:46:58 +0000701bool LazyValueInfoImpl::hasBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000702 // If already a constant, there is nothing to compute.
703 if (isa<Constant>(Val))
704 return true;
705
Philip Reames9db79482016-09-12 22:38:44 +0000706 return TheCache.hasCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000707}
708
Philip Reames92e5e1b2016-09-12 21:46:58 +0000709LVILatticeVal LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000710 // If already a constant, there is nothing to compute.
711 if (Constant *VC = dyn_cast<Constant>(Val))
712 return LVILatticeVal::get(VC);
713
Philip Reames9db79482016-09-12 22:38:44 +0000714 return TheCache.getCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000715}
716
Philip Reameseb3e9da2015-10-29 03:57:17 +0000717static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
718 switch (BBI->getOpcode()) {
719 default: break;
720 case Instruction::Load:
721 case Instruction::Call:
722 case Instruction::Invoke:
NAKAMURA Takumibd072a92016-07-25 00:59:46 +0000723 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
Philip Reames70efccd2015-10-29 04:21:49 +0000724 if (isa<IntegerType>(BBI->getType())) {
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000725 return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
Philip Reameseb3e9da2015-10-29 03:57:17 +0000726 }
727 break;
728 };
Philip Reamesd1f829d2016-02-02 21:57:37 +0000729 // Nothing known - will be intersected with other facts
730 return LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +0000731}
732
Philip Reames92e5e1b2016-09-12 21:46:58 +0000733bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000734 if (isa<Constant>(Val))
735 return true;
736
Philip Reames9db79482016-09-12 22:38:44 +0000737 if (TheCache.hasCachedValueInfo(Val, BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000738 // If we have a cached value, use that.
739 DEBUG(dbgs() << " reuse BB '" << BB->getName()
Philip Reames9db79482016-09-12 22:38:44 +0000740 << "' val=" << TheCache.getCachedValueInfo(Val, BB) << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000741
Hans Wennborg45172ac2014-11-25 17:23:05 +0000742 // Since we're reusing a cached value, we don't need to update the
743 // OverDefinedCache. The cache will have been properly updated whenever the
744 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000745 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000746 }
747
Hans Wennborg45172ac2014-11-25 17:23:05 +0000748 // Hold off inserting this value into the Cache in case we have to return
749 // false and come back later.
750 LVILatticeVal Res;
Philip Reames05c435e2016-12-06 03:22:03 +0000751 if (!solveBlockValueImpl(Res, Val, BB))
752 // Work pushed, will revisit
753 return false;
754
755 TheCache.insertResult(Val, BB, Res);
756 return true;
757}
758
759bool LazyValueInfoImpl::solveBlockValueImpl(LVILatticeVal &Res,
760 Value *Val, BasicBlock *BB) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000761
Chris Lattneraf025d32009-11-15 19:59:49 +0000762 Instruction *BBI = dyn_cast<Instruction>(Val);
Philip Reames05c435e2016-12-06 03:22:03 +0000763 if (!BBI || BBI->getParent() != BB)
764 return solveBlockValueNonLocal(Res, Val, BB);
Chris Lattner2c708562009-11-15 20:00:52 +0000765
Philip Reames05c435e2016-12-06 03:22:03 +0000766 if (PHINode *PN = dyn_cast<PHINode>(BBI))
767 return solveBlockValuePHINode(Res, PN, BB);
Owen Anderson80d19f02010-08-18 21:11:37 +0000768
Philip Reames05c435e2016-12-06 03:22:03 +0000769 if (auto *SI = dyn_cast<SelectInst>(BBI))
770 return solveBlockValueSelect(Res, SI, BB);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000771
Philip Reames2ab964e2016-04-27 01:02:25 +0000772 // If this value is a nonnull pointer, record it's range and bailout. Note
773 // that for all other pointer typed values, we terminate the search at the
774 // definition. We could easily extend this to look through geps, bitcasts,
775 // and the like to prove non-nullness, but it's not clear that's worth it
776 // compile time wise. The context-insensative value walk done inside
777 // isKnownNonNull gets most of the profitable cases at much less expense.
778 // This does mean that we have a sensativity to where the defining
779 // instruction is placed, even if it could legally be hoisted much higher.
780 // That is unfortunate.
Igor Laevsky0fa48192015-09-18 13:01:48 +0000781 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
782 if (PT && isKnownNonNull(BBI)) {
783 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
Hans Wennborg45172ac2014-11-25 17:23:05 +0000784 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000785 }
Davide Italianobd543d02016-05-25 22:29:34 +0000786 if (BBI->getType()->isIntegerTy()) {
Philip Reames05c435e2016-12-06 03:22:03 +0000787 if (isa<CastInst>(BBI))
788 return solveBlockValueCast(Res, BBI, BB);
789
Philip Reames2ab964e2016-04-27 01:02:25 +0000790 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
Philip Reames05c435e2016-12-06 03:22:03 +0000791 if (BO && isa<ConstantInt>(BO->getOperand(1)))
792 return solveBlockValueBinaryOp(Res, BBI, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000793 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000794
Philip Reamesa0c9f6e2016-03-04 22:27:39 +0000795 DEBUG(dbgs() << " compute BB '" << BB->getName()
796 << "' - unknown inst def found.\n");
797 Res = getFromRangeMetadata(BBI);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000798 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000799}
800
801static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
802 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
803 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000804 GetUnderlyingObject(L->getPointerOperand(),
805 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000806 }
807 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
808 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000809 GetUnderlyingObject(S->getPointerOperand(),
810 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000811 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000812 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
813 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000814
815 // FIXME: check whether it has a valuerange that excludes zero?
816 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
817 if (!Len || Len->isZero()) return false;
818
Eli Friedman7a5fc692011-05-31 20:40:16 +0000819 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000820 if (GetUnderlyingObject(MI->getRawDest(),
821 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000822 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000823 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000824 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000825 if (GetUnderlyingObject(MTI->getRawSource(),
826 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000827 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000828 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000829 return false;
830}
831
Philip Reames3f83dbe2016-04-27 00:30:55 +0000832/// Return true if the allocation associated with Val is ever dereferenced
833/// within the given basic block. This establishes the fact Val is not null,
834/// but does not imply that the memory at Val is dereferenceable. (Val may
835/// point off the end of the dereferenceable part of the object.)
836static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
837 assert(Val->getType()->isPointerTy());
838
839 const DataLayout &DL = BB->getModule()->getDataLayout();
840 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
841 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
842 // inside InstructionDereferencesPointer either.
843 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
844 for (Instruction &I : *BB)
845 if (InstructionDereferencesPointer(&I, UnderlyingVal))
846 return true;
847 return false;
848}
849
Philip Reames92e5e1b2016-09-12 21:46:58 +0000850bool LazyValueInfoImpl::solveBlockValueNonLocal(LVILatticeVal &BBLV,
Owen Anderson64c2c572010-12-20 18:18:16 +0000851 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000852 LVILatticeVal Result; // Start Undefined.
853
Nick Lewycky55a700b2010-12-18 01:00:40 +0000854 // If this is the entry block, we must be asking about an argument. The
855 // value is overdefined.
856 if (BB == &BB->getParent()->getEntryBlock()) {
857 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
Philip Reames3f83dbe2016-04-27 00:30:55 +0000858 // Bofore giving up, see if we can prove the pointer non-null local to
859 // this particular block.
860 if (Val->getType()->isPointerTy() &&
861 (isKnownNonNull(Val) || isObjectDereferencedInBlock(Val, BB))) {
Chris Lattner229907c2011-07-18 04:54:35 +0000862 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000863 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
864 } else {
Philip Reames1baaef12016-12-06 03:01:08 +0000865 Result = LVILatticeVal::getOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000866 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000867 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000868 return true;
869 }
870
871 // Loop over all of our predecessors, merging what we know from them into
872 // result.
873 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000874 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000875 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000876 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000877 if (EdgesMissing)
878 continue;
879
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000880 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000881
882 // If we hit overdefined, exit early. The BlockVals entry is already set
883 // to overdefined.
884 if (Result.isOverdefined()) {
885 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000886 << "' - overdefined because of pred (non local).\n");
Artur Pilipenkoadcd01f2016-08-09 09:14:29 +0000887 // Before giving up, see if we can prove the pointer non-null local to
Philip Reames3f83dbe2016-04-27 00:30:55 +0000888 // this particular block.
889 if (Val->getType()->isPointerTy() &&
890 isObjectDereferencedInBlock(Val, BB)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000891 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000892 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
893 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000894
Owen Anderson64c2c572010-12-20 18:18:16 +0000895 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000896 return true;
897 }
898 }
899 if (EdgesMissing)
900 return false;
901
902 // Return the merged value, which is more precise than 'overdefined'.
903 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000904 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000905 return true;
906}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000907
Philip Reames92e5e1b2016-09-12 21:46:58 +0000908bool LazyValueInfoImpl::solveBlockValuePHINode(LVILatticeVal &BBLV,
Owen Anderson64c2c572010-12-20 18:18:16 +0000909 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000910 LVILatticeVal Result; // Start Undefined.
911
912 // Loop over all of our predecessors, merging what we know from them into
913 // result.
914 bool EdgesMissing = false;
915 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
916 BasicBlock *PhiBB = PN->getIncomingBlock(i);
917 Value *PhiVal = PN->getIncomingValue(i);
918 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000919 // Note that we can provide PN as the context value to getEdgeValue, even
920 // though the results will be cached, because PN is the value being used as
921 // the cache key in the caller.
Hal Finkel7e184492014-09-07 20:29:59 +0000922 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000923 if (EdgesMissing)
924 continue;
925
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000926 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000927
928 // If we hit overdefined, exit early. The BlockVals entry is already set
929 // to overdefined.
930 if (Result.isOverdefined()) {
931 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000932 << "' - overdefined because of pred (local).\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000933
Owen Anderson64c2c572010-12-20 18:18:16 +0000934 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000935 return true;
936 }
937 }
938 if (EdgesMissing)
939 return false;
940
941 // Return the merged value, which is more precise than 'overdefined'.
942 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000943 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000944 return true;
945}
946
Artur Pilipenko933c07a2016-08-10 13:38:07 +0000947static LVILatticeVal getValueFromCondition(Value *Val, Value *Cond,
948 bool isTrueDest = true);
Hal Finkel7e184492014-09-07 20:29:59 +0000949
Philip Reamesd1f829d2016-02-02 21:57:37 +0000950// If we can determine a constraint on the value given conditions assumed by
951// the program, intersect those constraints with BBLV
Philip Reames92e5e1b2016-09-12 21:46:58 +0000952void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000953 Value *Val, LVILatticeVal &BBLV, Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000954 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
955 if (!BBI)
956 return;
957
Chandler Carruth66b31302015-01-04 12:03:27 +0000958 for (auto &AssumeVH : AC->assumptions()) {
959 if (!AssumeVH)
960 continue;
961 auto *I = cast<CallInst>(AssumeVH);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000962 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +0000963 continue;
964
Artur Pilipenko933c07a2016-08-10 13:38:07 +0000965 BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
Hal Finkel7e184492014-09-07 20:29:59 +0000966 }
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000967
968 // If guards are not used in the module, don't spend time looking for them
969 auto *GuardDecl = BBI->getModule()->getFunction(
970 Intrinsic::getName(Intrinsic::experimental_guard));
971 if (!GuardDecl || GuardDecl->use_empty())
972 return;
973
Artur Pilipenko47dc0982016-10-21 15:02:21 +0000974 for (Instruction &I : make_range(BBI->getIterator().getReverse(),
975 BBI->getParent()->rend())) {
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000976 Value *Cond = nullptr;
Artur Pilipenko47dc0982016-10-21 15:02:21 +0000977 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
978 BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000979 }
Hal Finkel7e184492014-09-07 20:29:59 +0000980}
981
Philip Reames92e5e1b2016-09-12 21:46:58 +0000982bool LazyValueInfoImpl::solveBlockValueSelect(LVILatticeVal &BBLV,
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000983 SelectInst *SI, BasicBlock *BB) {
984
985 // Recurse on our inputs if needed
986 if (!hasBlockValue(SI->getTrueValue(), BB)) {
987 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
988 return false;
Philip Reames1baaef12016-12-06 03:01:08 +0000989 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000990 return true;
991 }
992 LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
993 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
994 // extra slots in the table if we can.
995 if (TrueVal.isOverdefined()) {
Philip Reames1baaef12016-12-06 03:01:08 +0000996 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000997 return true;
998 }
999
1000 if (!hasBlockValue(SI->getFalseValue(), BB)) {
1001 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
1002 return false;
Philip Reames1baaef12016-12-06 03:01:08 +00001003 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001004 return true;
1005 }
1006 LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
1007 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
1008 // extra slots in the table if we can.
1009 if (FalseVal.isOverdefined()) {
Philip Reames1baaef12016-12-06 03:01:08 +00001010 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001011 return true;
1012 }
1013
Philip Reamesadf0e352016-02-26 22:53:59 +00001014 if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
1015 ConstantRange TrueCR = TrueVal.getConstantRange();
1016 ConstantRange FalseCR = FalseVal.getConstantRange();
1017 Value *LHS = nullptr;
1018 Value *RHS = nullptr;
1019 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
1020 // Is this a min specifically of our two inputs? (Avoid the risk of
1021 // ValueTracking getting smarter looking back past our immediate inputs.)
1022 if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
1023 LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
Philip Reamesb2949622016-12-06 02:54:16 +00001024 ConstantRange ResultCR = [&]() {
1025 switch (SPR.Flavor) {
1026 default:
1027 llvm_unreachable("unexpected minmax type!");
1028 case SPF_SMIN: /// Signed minimum
1029 return TrueCR.smin(FalseCR);
1030 case SPF_UMIN: /// Unsigned minimum
1031 return TrueCR.umin(FalseCR);
1032 case SPF_SMAX: /// Signed maximum
1033 return TrueCR.smax(FalseCR);
1034 case SPF_UMAX: /// Unsigned maximum
1035 return TrueCR.umax(FalseCR);
1036 };
1037 }();
1038 BBLV = LVILatticeVal::getRange(ResultCR);
1039 return true;
Philip Reamesadf0e352016-02-26 22:53:59 +00001040 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001041
Philip Reamesadf0e352016-02-26 22:53:59 +00001042 // TODO: ABS, NABS from the SelectPatternResult
1043 }
1044
Philip Reames854a84c2016-02-12 00:09:18 +00001045 // Can we constrain the facts about the true and false values by using the
1046 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
1047 // TODO: We could potentially refine an overdefined true value above.
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001048 Value *Cond = SI->getCondition();
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001049 TrueVal = intersect(TrueVal,
1050 getValueFromCondition(SI->getTrueValue(), Cond, true));
1051 FalseVal = intersect(FalseVal,
1052 getValueFromCondition(SI->getFalseValue(), Cond, false));
Philip Reames854a84c2016-02-12 00:09:18 +00001053
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001054 // Handle clamp idioms such as:
1055 // %24 = constantrange<0, 17>
1056 // %39 = icmp eq i32 %24, 0
1057 // %40 = add i32 %24, -1
1058 // %siv.next = select i1 %39, i32 16, i32 %40
1059 // %siv.next = constantrange<0, 17> not <-1, 17>
1060 // In general, this can handle any clamp idiom which tests the edge
1061 // condition via an equality or inequality.
1062 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
Philip Reamesadf0e352016-02-26 22:53:59 +00001063 ICmpInst::Predicate Pred = ICI->getPredicate();
1064 Value *A = ICI->getOperand(0);
1065 if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
1066 auto addConstants = [](ConstantInt *A, ConstantInt *B) {
1067 assert(A->getType() == B->getType());
1068 return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
1069 };
1070 // See if either input is A + C2, subject to the constraint from the
1071 // condition that A != C when that input is used. We can assume that
1072 // that input doesn't include C + C2.
1073 ConstantInt *CIAdded;
1074 switch (Pred) {
Philip Reames70b39182016-02-27 05:18:30 +00001075 default: break;
Philip Reamesadf0e352016-02-26 22:53:59 +00001076 case ICmpInst::ICMP_EQ:
1077 if (match(SI->getFalseValue(), m_Add(m_Specific(A),
1078 m_ConstantInt(CIAdded)))) {
1079 auto ResNot = addConstants(CIBase, CIAdded);
1080 FalseVal = intersect(FalseVal,
1081 LVILatticeVal::getNot(ResNot));
1082 }
1083 break;
1084 case ICmpInst::ICMP_NE:
1085 if (match(SI->getTrueValue(), m_Add(m_Specific(A),
1086 m_ConstantInt(CIAdded)))) {
1087 auto ResNot = addConstants(CIBase, CIAdded);
1088 TrueVal = intersect(TrueVal,
1089 LVILatticeVal::getNot(ResNot));
1090 }
1091 break;
1092 };
1093 }
1094 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001095
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001096 LVILatticeVal Result; // Start Undefined.
1097 Result.mergeIn(TrueVal, DL);
1098 Result.mergeIn(FalseVal, DL);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001099 BBLV = Result;
1100 return true;
1101}
1102
Philip Reames92e5e1b2016-09-12 21:46:58 +00001103bool LazyValueInfoImpl::solveBlockValueCast(LVILatticeVal &BBLV,
Philip Reames66715772016-04-25 18:30:31 +00001104 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001105 BasicBlock *BB) {
1106 if (!BBI->getOperand(0)->getType()->isSized()) {
1107 // Without knowing how wide the input is, we can't analyze it in any useful
1108 // way.
Philip Reames1baaef12016-12-06 03:01:08 +00001109 BBLV = LVILatticeVal::getOverdefined();
Philip Reamese5030e82016-04-26 22:52:30 +00001110 return true;
1111 }
Philip Reamesf105db42016-04-26 23:27:33 +00001112
1113 // Filter out casts we don't know how to reason about before attempting to
1114 // recurse on our operand. This can cut a long search short if we know we're
1115 // not going to be able to get any useful information anways.
1116 switch (BBI->getOpcode()) {
1117 case Instruction::Trunc:
1118 case Instruction::SExt:
1119 case Instruction::ZExt:
1120 case Instruction::BitCast:
1121 break;
1122 default:
1123 // Unhandled instructions are overdefined.
1124 DEBUG(dbgs() << " compute BB '" << BB->getName()
1125 << "' - overdefined (unknown cast).\n");
Philip Reames1baaef12016-12-06 03:01:08 +00001126 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesf105db42016-04-26 23:27:33 +00001127 return true;
1128 }
1129
Philip Reames38c87c22016-04-26 21:48:16 +00001130 // Figure out the range of the LHS. If that fails, we still apply the
1131 // transfer rule on the full set since we may be able to locally infer
1132 // interesting facts.
1133 if (!hasBlockValue(BBI->getOperand(0), BB))
Hans Wennborg45172ac2014-11-25 17:23:05 +00001134 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
Philip Reames38c87c22016-04-26 21:48:16 +00001135 // More work to do before applying this transfer rule.
Hans Wennborg45172ac2014-11-25 17:23:05 +00001136 return false;
Philip Reames38c87c22016-04-26 21:48:16 +00001137
1138 const unsigned OperandBitWidth =
Philip Reamese5030e82016-04-26 22:52:30 +00001139 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
Philip Reames38c87c22016-04-26 21:48:16 +00001140 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1141 if (hasBlockValue(BBI->getOperand(0), BB)) {
1142 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001143 intersectAssumeOrGuardBlockValueConstantRange(BBI->getOperand(0), LHSVal,
1144 BBI);
Philip Reames38c87c22016-04-26 21:48:16 +00001145 if (LHSVal.isConstantRange())
1146 LHSRange = LHSVal.getConstantRange();
Nick Lewycky55a700b2010-12-18 01:00:40 +00001147 }
1148
Philip Reames38c87c22016-04-26 21:48:16 +00001149 const unsigned ResultBitWidth =
1150 cast<IntegerType>(BBI->getType())->getBitWidth();
Philip Reames66715772016-04-25 18:30:31 +00001151
1152 // NOTE: We're currently limited by the set of operations that ConstantRange
1153 // can evaluate symbolically. Enhancing that set will allows us to analyze
1154 // more definitions.
Philip Reames4d00af12016-12-01 20:08:47 +00001155 auto CastOp = (Instruction::CastOps) BBI->getOpcode();
Philip Reames0e613f72016-12-06 02:36:58 +00001156 BBLV = LVILatticeVal::getRange(LHSRange.castOp(CastOp, ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001157 return true;
1158}
1159
Philip Reames92e5e1b2016-09-12 21:46:58 +00001160bool LazyValueInfoImpl::solveBlockValueBinaryOp(LVILatticeVal &BBLV,
Philip Reames66715772016-04-25 18:30:31 +00001161 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001162 BasicBlock *BB) {
Philip Reames66715772016-04-25 18:30:31 +00001163
Philip Reames053c2a62016-04-26 23:10:35 +00001164 assert(BBI->getOperand(0)->getType()->isSized() &&
1165 "all operands to binary operators are sized");
Philip Reamesf105db42016-04-26 23:27:33 +00001166
1167 // Filter out operators we don't know how to reason about before attempting to
1168 // recurse on our operand(s). This can cut a long search short if we know
1169 // we're not going to be able to get any useful information anways.
1170 switch (BBI->getOpcode()) {
1171 case Instruction::Add:
1172 case Instruction::Sub:
1173 case Instruction::Mul:
1174 case Instruction::UDiv:
1175 case Instruction::Shl:
1176 case Instruction::LShr:
1177 case Instruction::And:
1178 case Instruction::Or:
1179 // continue into the code below
1180 break;
1181 default:
1182 // Unhandled instructions are overdefined.
1183 DEBUG(dbgs() << " compute BB '" << BB->getName()
1184 << "' - overdefined (unknown binary operator).\n");
Philip Reames1baaef12016-12-06 03:01:08 +00001185 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesf105db42016-04-26 23:27:33 +00001186 return true;
1187 };
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001188
Philip Reames053c2a62016-04-26 23:10:35 +00001189 // Figure out the range of the LHS. If that fails, use a conservative range,
1190 // but apply the transfer rule anyways. This lets us pick up facts from
1191 // expressions like "and i32 (call i32 @foo()), 32"
1192 if (!hasBlockValue(BBI->getOperand(0), BB))
1193 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
1194 // More work to do before applying this transfer rule.
1195 return false;
1196
1197 const unsigned OperandBitWidth =
1198 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
1199 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1200 if (hasBlockValue(BBI->getOperand(0), BB)) {
1201 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001202 intersectAssumeOrGuardBlockValueConstantRange(BBI->getOperand(0), LHSVal,
1203 BBI);
Philip Reames053c2a62016-04-26 23:10:35 +00001204 if (LHSVal.isConstantRange())
1205 LHSRange = LHSVal.getConstantRange();
Philip Reames66715772016-04-25 18:30:31 +00001206 }
Philip Reames66715772016-04-25 18:30:31 +00001207
1208 ConstantInt *RHS = cast<ConstantInt>(BBI->getOperand(1));
1209 ConstantRange RHSRange = ConstantRange(RHS->getValue());
1210
Owen Anderson80d19f02010-08-18 21:11:37 +00001211 // NOTE: We're currently limited by the set of operations that ConstantRange
1212 // can evaluate symbolically. Enhancing that set will allows us to analyze
1213 // more definitions.
Philip Reames4d00af12016-12-01 20:08:47 +00001214 auto BinOp = (Instruction::BinaryOps) BBI->getOpcode();
Philip Reames0e613f72016-12-06 02:36:58 +00001215 BBLV = LVILatticeVal::getRange(LHSRange.binaryOp(BinOp, RHSRange));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001216 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +00001217}
1218
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001219static LVILatticeVal getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1220 bool isTrueDest) {
Artur Pilipenko21472912016-08-08 14:08:37 +00001221 Value *LHS = ICI->getOperand(0);
1222 Value *RHS = ICI->getOperand(1);
1223 CmpInst::Predicate Predicate = ICI->getPredicate();
1224
1225 if (isa<Constant>(RHS)) {
1226 if (ICI->isEquality() && LHS == Val) {
Hal Finkel7e184492014-09-07 20:29:59 +00001227 // We know that V has the RHS constant if this is a true SETEQ or
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001228 // false SETNE.
Artur Pilipenko21472912016-08-08 14:08:37 +00001229 if (isTrueDest == (Predicate == ICmpInst::ICMP_EQ))
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001230 return LVILatticeVal::get(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001231 else
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001232 return LVILatticeVal::getNot(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001233 }
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001234 }
Hal Finkel7e184492014-09-07 20:29:59 +00001235
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001236 if (!Val->getType()->isIntegerTy())
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001237 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001238
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001239 // Use ConstantRange::makeAllowedICmpRegion in order to determine the possible
1240 // range of Val guaranteed by the condition. Recognize comparisons in the from
1241 // of:
1242 // icmp <pred> Val, ...
Artur Pilipenko63562582016-08-12 10:05:11 +00001243 // icmp <pred> (add Val, Offset), ...
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001244 // The latter is the range checking idiom that InstCombine produces. Subtract
1245 // the offset from the allowed range for RHS in this case.
Artur Pilipenkoeed618d2016-08-08 14:33:11 +00001246
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001247 // Val or (add Val, Offset) can be on either hand of the comparison
1248 if (LHS != Val && !match(LHS, m_Add(m_Specific(Val), m_ConstantInt()))) {
1249 std::swap(LHS, RHS);
1250 Predicate = CmpInst::getSwappedPredicate(Predicate);
1251 }
Hal Finkel7e184492014-09-07 20:29:59 +00001252
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001253 ConstantInt *Offset = nullptr;
Artur Pilipenko63562582016-08-12 10:05:11 +00001254 if (LHS != Val)
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001255 match(LHS, m_Add(m_Specific(Val), m_ConstantInt(Offset)));
Hal Finkel7e184492014-09-07 20:29:59 +00001256
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001257 if (LHS == Val || Offset) {
1258 // Calculate the range of values that are allowed by the comparison
1259 ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1260 /*isFullSet=*/true);
1261 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1262 RHSRange = ConstantRange(CI->getValue());
Artur Pilipenko6669f252016-08-12 10:14:11 +00001263 else if (Instruction *I = dyn_cast<Instruction>(RHS))
1264 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1265 RHSRange = getConstantRangeFromMetadata(*Ranges);
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001266
1267 // If we're interested in the false dest, invert the condition
1268 CmpInst::Predicate Pred =
1269 isTrueDest ? Predicate : CmpInst::getInversePredicate(Predicate);
1270 ConstantRange TrueValues =
1271 ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1272
1273 if (Offset) // Apply the offset from above.
1274 TrueValues = TrueValues.subtract(Offset->getValue());
1275
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001276 return LVILatticeVal::getRange(std::move(TrueValues));
Hal Finkel7e184492014-09-07 20:29:59 +00001277 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001278
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001279 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001280}
1281
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001282static LVILatticeVal
1283getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1284 DenseMap<Value*, LVILatticeVal> &Visited);
1285
1286static LVILatticeVal
1287getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1288 DenseMap<Value*, LVILatticeVal> &Visited) {
1289 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1290 return getValueFromICmpCondition(Val, ICI, isTrueDest);
1291
1292 // Handle conditions in the form of (cond1 && cond2), we know that on the
1293 // true dest path both of the conditions hold.
1294 if (!isTrueDest)
1295 return LVILatticeVal::getOverdefined();
1296
1297 BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond);
1298 if (!BO || BO->getOpcode() != BinaryOperator::And)
1299 return LVILatticeVal::getOverdefined();
1300
1301 auto RHS = getValueFromCondition(Val, BO->getOperand(0), isTrueDest, Visited);
1302 auto LHS = getValueFromCondition(Val, BO->getOperand(1), isTrueDest, Visited);
1303 return intersect(RHS, LHS);
1304}
1305
1306static LVILatticeVal
1307getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1308 DenseMap<Value*, LVILatticeVal> &Visited) {
1309 auto I = Visited.find(Cond);
1310 if (I != Visited.end())
1311 return I->second;
Artur Pilipenkob6230882016-08-12 15:08:15 +00001312
1313 auto Result = getValueFromConditionImpl(Val, Cond, isTrueDest, Visited);
1314 Visited[Cond] = Result;
1315 return Result;
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001316}
1317
1318LVILatticeVal getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest) {
1319 assert(Cond && "precondition");
1320 DenseMap<Value*, LVILatticeVal> Visited;
1321 return getValueFromCondition(Val, Cond, isTrueDest, Visited);
1322}
1323
Nuno Lopese6e04902012-06-28 01:16:18 +00001324/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
Philip Reames13f73242016-02-01 23:21:11 +00001325/// Val is not constrained on the edge. Result is unspecified if return value
1326/// is false.
Nuno Lopese6e04902012-06-28 01:16:18 +00001327static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1328 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001329 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +00001330 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +00001331 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1332 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +00001333 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +00001334 if (BI->isConditional() &&
1335 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1336 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1337 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1338 "BBTo isn't a successor of BBFrom");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001339
Chris Lattner19019ea2009-11-11 22:48:44 +00001340 // If V is the condition of the branch itself, then we know exactly what
1341 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +00001342 if (BI->getCondition() == Val) {
1343 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +00001344 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001345 return true;
1346 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001347
Chris Lattner19019ea2009-11-11 22:48:44 +00001348 // If the condition of the branch is an equality comparison, we may be
1349 // able to infer the value.
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001350 Result = getValueFromCondition(Val, BI->getCondition(), isTrueDest);
1351 if (!Result.isOverdefined())
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001352 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001353 }
1354 }
Chris Lattner77358782009-11-15 20:02:12 +00001355
1356 // If the edge was formed by a switch on the value, then we may know exactly
1357 // what it is.
1358 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001359 if (SI->getCondition() != Val)
1360 return false;
1361
1362 bool DefaultCase = SI->getDefaultDest() == BBTo;
1363 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1364 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1365
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001366 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001367 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +00001368 if (DefaultCase) {
1369 // It is possible that the default destination is the destination of
1370 // some cases. There is no need to perform difference for those cases.
1371 if (i.getCaseSuccessor() != BBTo)
1372 EdgesVals = EdgesVals.difference(EdgeVal);
1373 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +00001374 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +00001375 }
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001376 Result = LVILatticeVal::getRange(std::move(EdgesVals));
Nuno Lopes8650fb82012-06-28 16:13:37 +00001377 return true;
Chris Lattner77358782009-11-15 20:02:12 +00001378 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001379 return false;
1380}
1381
Sanjay Patel938e2792015-01-09 16:35:37 +00001382/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1383/// the basic block if the edge does not constrain Val.
Philip Reames92e5e1b2016-09-12 21:46:58 +00001384bool LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +00001385 BasicBlock *BBTo, LVILatticeVal &Result,
1386 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +00001387 // If already a constant, there is nothing to compute.
1388 if (Constant *VC = dyn_cast<Constant>(Val)) {
1389 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001390 return true;
1391 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001392
Philip Reames44456b82016-02-02 03:15:40 +00001393 LVILatticeVal LocalResult;
1394 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1395 // If we couldn't constrain the value on the edge, LocalResult doesn't
1396 // provide any information.
Philip Reames1baaef12016-12-06 03:01:08 +00001397 LocalResult = LVILatticeVal::getOverdefined();
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001398
Philip Reames44456b82016-02-02 03:15:40 +00001399 if (hasSingleValue(LocalResult)) {
1400 // Can't get any more precise here
1401 Result = LocalResult;
Nuno Lopese6e04902012-06-28 01:16:18 +00001402 return true;
1403 }
1404
1405 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +00001406 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1407 return false;
Philip Reames44456b82016-02-02 03:15:40 +00001408 // No new information.
1409 Result = LocalResult;
Hans Wennborg45172ac2014-11-25 17:23:05 +00001410 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +00001411 }
1412
Philip Reames44456b82016-02-02 03:15:40 +00001413 // Try to intersect ranges of the BB and the constraint on the edge.
1414 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001415 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock,
1416 BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +00001417 // We can use the context instruction (generically the ultimate instruction
1418 // the calling pass is trying to simplify) here, even though the result of
1419 // this function is generally cached when called from the solve* functions
1420 // (and that cached result might be used with queries using a different
1421 // context instruction), because when this function is called from the solve*
1422 // functions, the context instruction is not provided. When called from
Philip Reames92e5e1b2016-09-12 21:46:58 +00001423 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
Hal Finkel2400c962014-10-16 00:40:05 +00001424 // but then the result is not cached.
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001425 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
Philip Reames44456b82016-02-02 03:15:40 +00001426
1427 Result = intersect(LocalResult, InBlock);
Nuno Lopese6e04902012-06-28 01:16:18 +00001428 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001429}
1430
Philip Reames92e5e1b2016-09-12 21:46:58 +00001431LVILatticeVal LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
Hal Finkel7e184492014-09-07 20:29:59 +00001432 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001433 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001434 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001435
Hans Wennborg45172ac2014-11-25 17:23:05 +00001436 assert(BlockValueStack.empty() && BlockValueSet.empty());
Philip Reamesbb781b42016-02-10 21:46:32 +00001437 if (!hasBlockValue(V, BB)) {
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001438 pushBlockValue(std::make_pair(BB, V));
Philip Reamesbb781b42016-02-10 21:46:32 +00001439 solve();
1440 }
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001441 LVILatticeVal Result = getBlockValue(V, BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001442 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001443
1444 DEBUG(dbgs() << " Result = " << Result << "\n");
1445 return Result;
1446}
1447
Philip Reames92e5e1b2016-09-12 21:46:58 +00001448LVILatticeVal LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001449 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1450 << CxtI->getName() << "'\n");
1451
Philip Reamesbb781b42016-02-10 21:46:32 +00001452 if (auto *C = dyn_cast<Constant>(V))
1453 return LVILatticeVal::get(C);
1454
Philip Reamesd1f829d2016-02-02 21:57:37 +00001455 LVILatticeVal Result = LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +00001456 if (auto *I = dyn_cast<Instruction>(V))
1457 Result = getFromRangeMetadata(I);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001458 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
Philip Reames2c275cc2016-02-02 00:45:30 +00001459
David Greene37e98092009-12-23 20:43:58 +00001460 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001461 return Result;
1462}
Chris Lattner19019ea2009-11-11 22:48:44 +00001463
Philip Reames92e5e1b2016-09-12 21:46:58 +00001464LVILatticeVal LazyValueInfoImpl::
Hal Finkel7e184492014-09-07 20:29:59 +00001465getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1466 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001467 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001468 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001469
Nick Lewycky55a700b2010-12-18 01:00:40 +00001470 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001471 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001472 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001473 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001474 (void)WasFastQuery;
1475 assert(WasFastQuery && "More work to do after problem solved?");
1476 }
1477
David Greene37e98092009-12-23 20:43:58 +00001478 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001479 return Result;
1480}
1481
Philip Reames92e5e1b2016-09-12 21:46:58 +00001482void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Philip Reames9db79482016-09-12 22:38:44 +00001483 BasicBlock *NewSucc) {
1484 TheCache.threadEdgeImpl(OldSucc, NewSucc);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001485}
1486
Chris Lattneraf025d32009-11-15 19:59:49 +00001487//===----------------------------------------------------------------------===//
1488// LazyValueInfo Impl
1489//===----------------------------------------------------------------------===//
1490
Philip Reames92e5e1b2016-09-12 21:46:58 +00001491/// This lazily constructs the LazyValueInfoImpl.
1492static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
1493 const DataLayout *DL,
1494 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001495 if (!PImpl) {
1496 assert(DL && "getCache() called with a null DataLayout");
Philip Reames92e5e1b2016-09-12 21:46:58 +00001497 PImpl = new LazyValueInfoImpl(AC, *DL, DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001498 }
Philip Reames92e5e1b2016-09-12 21:46:58 +00001499 return *static_cast<LazyValueInfoImpl*>(PImpl);
Chris Lattneraf025d32009-11-15 19:59:49 +00001500}
1501
Sean Silva687019f2016-06-13 22:01:25 +00001502bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
1503 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001504 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001505
1506 DominatorTreeWrapperPass *DTWP =
1507 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Sean Silva687019f2016-06-13 22:01:25 +00001508 Info.DT = DTWP ? &DTWP->getDomTree() : nullptr;
1509 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001510
Sean Silva687019f2016-06-13 22:01:25 +00001511 if (Info.PImpl)
Philip Reames92e5e1b2016-09-12 21:46:58 +00001512 getImpl(Info.PImpl, Info.AC, &DL, Info.DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001513
Owen Anderson208636f2010-08-18 18:39:01 +00001514 // Fully lazy.
1515 return false;
1516}
1517
Sean Silva687019f2016-06-13 22:01:25 +00001518void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier43a33062011-12-02 01:26:24 +00001519 AU.setPreservesAll();
Chandler Carruth66b31302015-01-04 12:03:27 +00001520 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001521 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001522}
1523
Sean Silva687019f2016-06-13 22:01:25 +00001524LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1525
1526LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1527
Chris Lattneraf025d32009-11-15 19:59:49 +00001528void LazyValueInfo::releaseMemory() {
1529 // If the cache was allocated, free it.
1530 if (PImpl) {
Philip Reames92e5e1b2016-09-12 21:46:58 +00001531 delete &getImpl(PImpl, AC, nullptr);
Craig Topper9f008862014-04-15 04:59:12 +00001532 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001533 }
1534}
1535
Sean Silva687019f2016-06-13 22:01:25 +00001536void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1537
1538LazyValueInfo LazyValueAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1539 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1540 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1541 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1542
1543 return LazyValueInfo(&AC, &TLI, DT);
1544}
1545
Wei Mif160e342016-09-15 06:28:34 +00001546/// Returns true if we can statically tell that this value will never be a
1547/// "useful" constant. In practice, this means we've got something like an
1548/// alloca or a malloc call for which a comparison against a constant can
1549/// only be guarding dead code. Note that we are potentially giving up some
1550/// precision in dead code (a constant result) in favour of avoiding a
1551/// expensive search for a easily answered common query.
1552static bool isKnownNonConstant(Value *V) {
1553 V = V->stripPointerCasts();
1554 // The return val of alloc cannot be a Constant.
1555 if (isa<AllocaInst>(V))
1556 return true;
1557 return false;
1558}
1559
Hal Finkel7e184492014-09-07 20:29:59 +00001560Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1561 Instruction *CxtI) {
Wei Mif160e342016-09-15 06:28:34 +00001562 // Bail out early if V is known not to be a Constant.
1563 if (isKnownNonConstant(V))
1564 return nullptr;
1565
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001566 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001567 LVILatticeVal Result =
Philip Reames92e5e1b2016-09-12 21:46:58 +00001568 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001569
Chris Lattner19019ea2009-11-11 22:48:44 +00001570 if (Result.isConstant())
1571 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001572 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001573 ConstantRange CR = Result.getConstantRange();
1574 if (const APInt *SingleVal = CR.getSingleElement())
1575 return ConstantInt::get(V->getContext(), *SingleVal);
1576 }
Craig Topper9f008862014-04-15 04:59:12 +00001577 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001578}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001579
John Regehre1c481d2016-05-02 19:58:00 +00001580ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00001581 Instruction *CxtI) {
John Regehre1c481d2016-05-02 19:58:00 +00001582 assert(V->getType()->isIntegerTy());
1583 unsigned Width = V->getType()->getIntegerBitWidth();
1584 const DataLayout &DL = BB->getModule()->getDataLayout();
1585 LVILatticeVal Result =
Philip Reames92e5e1b2016-09-12 21:46:58 +00001586 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
John Regehre1c481d2016-05-02 19:58:00 +00001587 if (Result.isUndefined())
1588 return ConstantRange(Width, /*isFullSet=*/false);
1589 if (Result.isConstantRange())
1590 return Result.getConstantRange();
Artur Pilipenkoa4b6a702016-08-10 12:54:54 +00001591 // We represent ConstantInt constants as constant ranges but other kinds
1592 // of integer constants, i.e. ConstantExpr will be tagged as constants
1593 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1594 "ConstantInt value must be represented as constantrange");
Davide Italianobd543d02016-05-25 22:29:34 +00001595 return ConstantRange(Width, /*isFullSet=*/true);
John Regehre1c481d2016-05-02 19:58:00 +00001596}
1597
Sanjay Patel2a385e22015-01-09 16:47:20 +00001598/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001599/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001600Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001601 BasicBlock *ToBB,
1602 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001603 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001604 LVILatticeVal Result =
Philip Reames92e5e1b2016-09-12 21:46:58 +00001605 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001606
Chris Lattnerd5e25432009-11-12 01:29:10 +00001607 if (Result.isConstant())
1608 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001609 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001610 ConstantRange CR = Result.getConstantRange();
1611 if (const APInt *SingleVal = CR.getSingleElement())
1612 return ConstantInt::get(V->getContext(), *SingleVal);
1613 }
Craig Topper9f008862014-04-15 04:59:12 +00001614 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001615}
1616
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001617static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1618 LVILatticeVal &Result,
1619 const DataLayout &DL,
1620 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001621
Chris Lattner565ee2f2009-11-12 04:36:58 +00001622 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001623 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001624 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001625 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001626 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001627 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001628 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1629 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001630 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001631
Owen Anderson185fe002010-08-10 20:03:09 +00001632 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001633 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001634 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001635
Owen Anderson185fe002010-08-10 20:03:09 +00001636 ConstantRange CR = Result.getConstantRange();
1637 if (Pred == ICmpInst::ICMP_EQ) {
1638 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001639 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001640
Owen Anderson185fe002010-08-10 20:03:09 +00001641 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001642 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001643 } else if (Pred == ICmpInst::ICMP_NE) {
1644 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001645 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001646
Owen Anderson185fe002010-08-10 20:03:09 +00001647 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001648 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001649 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001650
Owen Anderson185fe002010-08-10 20:03:09 +00001651 // Handle more complex predicates.
Sanjoy Das1f7b8132016-10-02 00:09:57 +00001652 ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
1653 (ICmpInst::Predicate)Pred, CI->getValue());
Nick Lewycky11678bd2010-12-15 18:57:18 +00001654 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001655 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001656 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001657 return LazyValueInfo::False;
1658 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001659 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001660
Chris Lattneraf025d32009-11-15 19:59:49 +00001661 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001662 // If this is an equality comparison, we can try to fold it knowing that
1663 // "V != C1".
1664 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001665 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001666 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001667 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001668 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001669 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001670 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001671 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001672 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001673 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001674 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001675 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001676 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001677 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001678 }
Hal Finkel7e184492014-09-07 20:29:59 +00001679 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001680 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001681
Hal Finkel7e184492014-09-07 20:29:59 +00001682 return LazyValueInfo::Unknown;
1683}
1684
Sanjay Patel2a385e22015-01-09 16:47:20 +00001685/// Determine whether the specified value comparison with a constant is known to
1686/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001687LazyValueInfo::Tristate
1688LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1689 BasicBlock *FromBB, BasicBlock *ToBB,
1690 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001691 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001692 LVILatticeVal Result =
Philip Reames92e5e1b2016-09-12 21:46:58 +00001693 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001694
1695 return getPredicateResult(Pred, C, Result, DL, TLI);
1696}
1697
1698LazyValueInfo::Tristate
1699LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1700 Instruction *CxtI) {
Wei Mif160e342016-09-15 06:28:34 +00001701 // Is or is not NonNull are common predicates being queried. If
1702 // isKnownNonNull can tell us the result of the predicate, we can
1703 // return it quickly. But this is only a fastpath, and falling
1704 // through would still be correct.
1705 if (V->getType()->isPointerTy() && C->isNullValue() &&
1706 isKnownNonNull(V->stripPointerCasts())) {
1707 if (Pred == ICmpInst::ICMP_EQ)
1708 return LazyValueInfo::False;
1709 else if (Pred == ICmpInst::ICMP_NE)
1710 return LazyValueInfo::True;
1711 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001712 const DataLayout &DL = CxtI->getModule()->getDataLayout();
Philip Reames92e5e1b2016-09-12 21:46:58 +00001713 LVILatticeVal Result = getImpl(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001714 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1715 if (Ret != Unknown)
1716 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001717
Philip Reamesaeefae02015-11-04 01:47:04 +00001718 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1719 // LVI as a whole tries to compute a lattice value which is conservatively
1720 // correct at a given location. In this case, we have a predicate which we
1721 // weren't able to prove about the merged result, and we're pushing that
1722 // predicate back along each incoming edge to see if we can prove it
1723 // separately for each input. As a motivating example, consider:
1724 // bb1:
1725 // %v1 = ... ; constantrange<1, 5>
1726 // br label %merge
1727 // bb2:
1728 // %v2 = ... ; constantrange<10, 20>
1729 // br label %merge
1730 // merge:
1731 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1732 // %pred = icmp eq i32 %phi, 8
1733 // We can't tell from the lattice value for '%phi' that '%pred' is false
1734 // along each path, but by checking the predicate over each input separately,
1735 // we can.
1736 // We limit the search to one step backwards from the current BB and value.
1737 // We could consider extending this to search further backwards through the
1738 // CFG and/or value graph, but there are non-obvious compile time vs quality
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001739 // tradeoffs.
Philip Reames66ab0f02015-06-16 00:49:59 +00001740 if (CxtI) {
Philip Reamesbb11d622015-08-31 18:31:48 +00001741 BasicBlock *BB = CxtI->getParent();
1742
1743 // Function entry or an unreachable block. Bail to avoid confusing
1744 // analysis below.
1745 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1746 if (PI == PE)
1747 return Unknown;
1748
1749 // If V is a PHI node in the same block as the context, we need to ask
1750 // questions about the predicate as applied to the incoming value along
1751 // each edge. This is useful for eliminating cases where the predicate is
1752 // known along all incoming edges.
1753 if (auto *PHI = dyn_cast<PHINode>(V))
1754 if (PHI->getParent() == BB) {
1755 Tristate Baseline = Unknown;
1756 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1757 Value *Incoming = PHI->getIncomingValue(i);
1758 BasicBlock *PredBB = PHI->getIncomingBlock(i);
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001759 // Note that PredBB may be BB itself.
Philip Reamesbb11d622015-08-31 18:31:48 +00001760 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1761 CxtI);
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001762
Philip Reamesbb11d622015-08-31 18:31:48 +00001763 // Keep going as long as we've seen a consistent known result for
1764 // all inputs.
1765 Baseline = (i == 0) ? Result /* First iteration */
1766 : (Baseline == Result ? Baseline : Unknown); /* All others */
1767 if (Baseline == Unknown)
1768 break;
1769 }
1770 if (Baseline != Unknown)
1771 return Baseline;
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001772 }
Philip Reamesbb11d622015-08-31 18:31:48 +00001773
Philip Reames66ab0f02015-06-16 00:49:59 +00001774 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001775 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001776 // on all incoming edges.
Philip Reamesbb11d622015-08-31 18:31:48 +00001777 if (!isa<Instruction>(V) ||
1778 cast<Instruction>(V)->getParent() != BB) {
Philip Reames66ab0f02015-06-16 00:49:59 +00001779 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001780 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001781 // the value of the comparison in this block.
1782 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1783 if (Baseline != Unknown) {
1784 // Check that all remaining incoming values match the first one.
1785 while (++PI != PE) {
1786 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1787 if (Ret != Baseline) break;
1788 }
1789 // If we terminated early, then one of the values didn't match.
1790 if (PI == PE) {
1791 return Baseline;
1792 }
1793 }
1794 }
1795 }
1796 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001797}
1798
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001799void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001800 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001801 if (PImpl) {
1802 const DataLayout &DL = PredBB->getModule()->getDataLayout();
Philip Reames92e5e1b2016-09-12 21:46:58 +00001803 getImpl(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001804 }
Owen Anderson208636f2010-08-18 18:39:01 +00001805}
1806
1807void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001808 if (PImpl) {
1809 const DataLayout &DL = BB->getModule()->getDataLayout();
Philip Reames92e5e1b2016-09-12 21:46:58 +00001810 getImpl(PImpl, AC, &DL, DT).eraseBlock(BB);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001811 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001812}