blob: db51ba52b48574dddca1e7b00df459db8aba104d [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 }
Chris Lattner19019ea2009-11-11 22:48:44 +0000227 return markOverdefined();
Nick Lewycky11678bd2010-12-15 18:57:18 +0000228 }
229
230 if (isNotConstant()) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000231 if (RHS.isNotConstant()) {
232 if (Val == RHS.Val)
233 return false;
234 return markOverdefined();
235 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000236 return markOverdefined();
237 }
238
239 assert(isConstantRange() && "New LVILattice type?");
240 if (!RHS.isConstantRange())
241 return markOverdefined();
242
243 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
244 if (NewR.isFullSet())
245 return markOverdefined();
246 return markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000247 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000248};
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000249
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000250} // end anonymous namespace.
251
Chris Lattner19019ea2009-11-11 22:48:44 +0000252namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000253raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
254 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000255raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
256 if (Val.isUndefined())
257 return OS << "undefined";
258 if (Val.isOverdefined())
259 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000260
261 if (Val.isNotConstant())
262 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Davide Italianobd543d02016-05-25 22:29:34 +0000263 if (Val.isConstantRange())
Owen Anderson8afac042010-08-09 20:50:46 +0000264 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
265 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000266 return OS << "constant<" << *Val.getConstant() << '>';
267}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000268}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000269
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000270/// Returns true if this lattice value represents at most one possible value.
271/// This is as precise as any lattice value can get while still representing
272/// reachable code.
Benjamin Kramerc321e532016-06-08 19:09:22 +0000273static bool hasSingleValue(const LVILatticeVal &Val) {
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000274 if (Val.isConstantRange() &&
275 Val.getConstantRange().isSingleElement())
276 // Integer constants are single element ranges
277 return true;
278 if (Val.isConstant())
279 // Non integer constants
280 return true;
281 return false;
282}
283
284/// Combine two sets of facts about the same value into a single set of
285/// facts. Note that this method is not suitable for merging facts along
286/// different paths in a CFG; that's what the mergeIn function is for. This
287/// is for merging facts gathered about the same value at the same location
288/// through two independent means.
289/// Notes:
290/// * This method does not promise to return the most precise possible lattice
291/// value implied by A and B. It is allowed to return any lattice element
292/// which is at least as strong as *either* A or B (unless our facts
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000293/// conflict, see below).
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000294/// * Due to unreachable code, the intersection of two lattice values could be
295/// contradictory. If this happens, we return some valid lattice value so as
296/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
297/// we do not make this guarantee. TODO: This would be a useful enhancement.
298static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
299 // Undefined is the strongest state. It means the value is known to be along
300 // an unreachable path.
301 if (A.isUndefined())
302 return A;
303 if (B.isUndefined())
304 return B;
305
306 // If we gave up for one, but got a useable fact from the other, use it.
307 if (A.isOverdefined())
308 return B;
309 if (B.isOverdefined())
310 return A;
311
312 // Can't get any more precise than constants.
313 if (hasSingleValue(A))
314 return A;
315 if (hasSingleValue(B))
316 return B;
317
318 // Could be either constant range or not constant here.
319 if (!A.isConstantRange() || !B.isConstantRange()) {
320 // TODO: Arbitrary choice, could be improved
321 return A;
322 }
323
324 // Intersect two constant ranges
325 ConstantRange Range =
326 A.getConstantRange().intersectWith(B.getConstantRange());
327 // Note: An empty range is implicitly converted to overdefined internally.
328 // TODO: We could instead use Undefined here since we've proven a conflict
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000329 // and thus know this path must be unreachable.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000330 return LVILatticeVal::getRange(std::move(Range));
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000331}
Philip Reamesd1f829d2016-02-02 21:57:37 +0000332
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000333//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000334// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000335//===----------------------------------------------------------------------===//
336
Chris Lattneraf025d32009-11-15 19:59:49 +0000337namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000338 /// A callback value handle updates the cache when values are erased.
Owen Anderson118ac802011-01-05 21:15:29 +0000339 class LazyValueInfoCache;
David Blaikie774b5842015-08-03 22:30:24 +0000340 struct LVIValueHandle final : public CallbackVH {
Justin Lebar58b377e2016-07-27 22:33:36 +0000341 // Needs to access getValPtr(), which is protected.
342 friend struct DenseMapInfo<LVIValueHandle>;
343
Owen Anderson118ac802011-01-05 21:15:29 +0000344 LazyValueInfoCache *Parent;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000345
Owen Anderson118ac802011-01-05 21:15:29 +0000346 LVIValueHandle(Value *V, LazyValueInfoCache *P)
347 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000348
349 void deleted() override;
350 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000351 deleted();
352 }
353 };
Justin Lebar58b377e2016-07-27 22:33:36 +0000354} // end anonymous namespace
Owen Anderson118ac802011-01-05 21:15:29 +0000355
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000356namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000357 /// This is the cache kept by LazyValueInfo which
Chris Lattneraf025d32009-11-15 19:59:49 +0000358 /// maintains information about queries across the clients' queries.
359 class LazyValueInfoCache {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000360 /// This is all of the cached block information for exactly one Value*.
361 /// The entries are sorted by the BasicBlock* of the
Chris Lattneraf025d32009-11-15 19:59:49 +0000362 /// entries, allowing us to do a lookup with a binary search.
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000363 /// Over-defined lattice values are recorded in OverDefinedCache to reduce
364 /// memory overhead.
Justin Lebar58b377e2016-07-27 22:33:36 +0000365 struct ValueCacheEntryTy {
366 ValueCacheEntryTy(Value *V, LazyValueInfoCache *P) : Handle(V, P) {}
367 LVIValueHandle Handle;
368 SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4> BlockVals;
369 };
Chris Lattneraf025d32009-11-15 19:59:49 +0000370
Sanjay Patel2a385e22015-01-09 16:47:20 +0000371 /// This is all of the cached information for all values,
Owen Anderson6f060af2011-01-05 23:26:22 +0000372 /// mapped from Value* to key information.
Justin Lebar58b377e2016-07-27 22:33:36 +0000373 DenseMap<Value *, std::unique_ptr<ValueCacheEntryTy>> ValueCache;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000374
Sanjay Patel2a385e22015-01-09 16:47:20 +0000375 /// This tracks, on a per-block basis, the set of values that are
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000376 /// over-defined at the end of that block.
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000377 typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
378 OverDefinedCacheTy;
379 OverDefinedCacheTy OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000380
Sanjay Patel2a385e22015-01-09 16:47:20 +0000381 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000382 /// don't spend time removing unused blocks from our caches.
383 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
384
Philip Reames9db79482016-09-12 22:38:44 +0000385 public:
Hans Wennborg45172ac2014-11-25 17:23:05 +0000386 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
387 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000388
389 // Insert over-defined values into their own cache to reduce memory
390 // overhead.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000391 if (Result.isOverdefined())
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000392 OverDefinedCache[BB].insert(Val);
Justin Lebar58b377e2016-07-27 22:33:36 +0000393 else {
394 auto It = ValueCache.find_as(Val);
395 if (It == ValueCache.end()) {
396 ValueCache[Val] = make_unique<ValueCacheEntryTy>(Val, this);
397 It = ValueCache.find_as(Val);
398 assert(It != ValueCache.end() && "Val was just added to the map!");
399 }
400 It->second->BlockVals[BB] = Result;
401 }
Hans Wennborg45172ac2014-11-25 17:23:05 +0000402 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000403
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000404 bool isOverdefined(Value *V, BasicBlock *BB) const {
405 auto ODI = OverDefinedCache.find(BB);
406
407 if (ODI == OverDefinedCache.end())
408 return false;
409
410 return ODI->second.count(V);
411 }
412
Philip Reames9db79482016-09-12 22:38:44 +0000413 bool hasCachedValueInfo(Value *V, BasicBlock *BB) const {
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000414 if (isOverdefined(V, BB))
415 return true;
416
Justin Lebar58b377e2016-07-27 22:33:36 +0000417 auto I = ValueCache.find_as(V);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000418 if (I == ValueCache.end())
419 return false;
420
Justin Lebar58b377e2016-07-27 22:33:36 +0000421 return I->second->BlockVals.count(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000422 }
423
Philip Reames9db79482016-09-12 22:38:44 +0000424 LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) const {
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000425 if (isOverdefined(V, BB))
426 return LVILatticeVal::getOverdefined();
427
Justin Lebar58b377e2016-07-27 22:33:36 +0000428 auto I = ValueCache.find_as(V);
429 if (I == ValueCache.end())
430 return LVILatticeVal();
431 auto BBI = I->second->BlockVals.find(BB);
432 if (BBI == I->second->BlockVals.end())
433 return LVILatticeVal();
434 return BBI->second;
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000435 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000436
Philip Reames92e5e1b2016-09-12 21:46:58 +0000437 /// clear - Empty the cache.
438 void clear() {
439 SeenBlocks.clear();
440 ValueCache.clear();
441 OverDefinedCache.clear();
442 }
443
Philip Reamesb627aec2016-09-12 22:03:36 +0000444 /// Inform the cache that a given value has been deleted.
445 void eraseValue(Value *V);
446
447 /// This is part of the update interface to inform the cache
448 /// that a block has been deleted.
449 void eraseBlock(BasicBlock *BB);
450
Philip Reames9db79482016-09-12 22:38:44 +0000451 /// Updates the cache to remove any influence an overdefined value in
452 /// OldSucc might have (unless also overdefined in NewSucc). This just
453 /// flushes elements from the cache and does not add any.
454 void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
455
Philip Reames92e5e1b2016-09-12 21:46:58 +0000456 friend struct LVIValueHandle;
457 };
Philip Reamesb627aec2016-09-12 22:03:36 +0000458}
Philip Reames92e5e1b2016-09-12 21:46:58 +0000459
Philip Reamesb627aec2016-09-12 22:03:36 +0000460void LazyValueInfoCache::eraseValue(Value *V) {
461 SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
462 for (auto &I : OverDefinedCache) {
463 SmallPtrSetImpl<Value *> &ValueSet = I.second;
464 if (ValueSet.count(V))
465 ValueSet.erase(V);
466 if (ValueSet.empty())
467 ToErase.push_back(I.first);
468 }
469 for (auto &BB : ToErase)
470 OverDefinedCache.erase(BB);
471
472 ValueCache.erase(V);
473}
474
475void LVIValueHandle::deleted() {
476 // This erasure deallocates *this, so it MUST happen after we're done
477 // using any and all members of *this.
478 Parent->eraseValue(*this);
479}
480
481void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
482 // Shortcut if we have never seen this block.
483 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
484 if (I == SeenBlocks.end())
485 return;
486 SeenBlocks.erase(I);
487
488 auto ODI = OverDefinedCache.find(BB);
489 if (ODI != OverDefinedCache.end())
490 OverDefinedCache.erase(ODI);
491
492 for (auto &I : ValueCache)
493 I.second->BlockVals.erase(BB);
494}
495
Philip Reames9db79482016-09-12 22:38:44 +0000496void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
497 BasicBlock *NewSucc) {
498 // When an edge in the graph has been threaded, values that we could not
499 // determine a value for before (i.e. were marked overdefined) may be
500 // possible to solve now. We do NOT try to proactively update these values.
501 // Instead, we clear their entries from the cache, and allow lazy updating to
502 // recompute them when needed.
503
504 // The updating process is fairly simple: we need to drop cached info
505 // for all values that were marked overdefined in OldSucc, and for those same
506 // values in any successor of OldSucc (except NewSucc) in which they were
507 // also marked overdefined.
508 std::vector<BasicBlock*> worklist;
509 worklist.push_back(OldSucc);
510
511 auto I = OverDefinedCache.find(OldSucc);
512 if (I == OverDefinedCache.end())
513 return; // Nothing to process here.
514 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
515
516 // Use a worklist to perform a depth-first search of OldSucc's successors.
517 // NOTE: We do not need a visited list since any blocks we have already
518 // visited will have had their overdefined markers cleared already, and we
519 // thus won't loop to their successors.
520 while (!worklist.empty()) {
521 BasicBlock *ToUpdate = worklist.back();
522 worklist.pop_back();
523
524 // Skip blocks only accessible through NewSucc.
525 if (ToUpdate == NewSucc) continue;
526
527 bool changed = false;
528 for (Value *V : ValsToClear) {
529 // If a value was marked overdefined in OldSucc, and is here too...
530 auto OI = OverDefinedCache.find(ToUpdate);
531 if (OI == OverDefinedCache.end())
532 continue;
533 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
534 if (!ValueSet.count(V))
535 continue;
536
537 ValueSet.erase(V);
538 if (ValueSet.empty())
539 OverDefinedCache.erase(OI);
540
541 // If we removed anything, then we potentially need to update
542 // blocks successors too.
543 changed = true;
544 }
545
546 if (!changed) continue;
547
548 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
549 }
550}
551
Philip Reamesb627aec2016-09-12 22:03:36 +0000552namespace {
Philip Reames92e5e1b2016-09-12 21:46:58 +0000553 // The actual implementation of the lazy analysis and update. Note that the
554 // inheritance from LazyValueInfoCache is intended to be temporary while
555 // splitting the code and then transitioning to a has-a relationship.
Philip Reames9db79482016-09-12 22:38:44 +0000556 class LazyValueInfoImpl {
557
558 /// Cached results from previous queries
559 LazyValueInfoCache TheCache;
Philip Reames92e5e1b2016-09-12 21:46:58 +0000560
561 /// This stack holds the state of the value solver during a query.
562 /// It basically emulates the callstack of the naive
563 /// recursive value lookup process.
564 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
565
566 /// Keeps track of which block-value pairs are in BlockValueStack.
567 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
568
569 /// Push BV onto BlockValueStack unless it's already in there.
570 /// Returns true on success.
571 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
572 if (!BlockValueSet.insert(BV).second)
573 return false; // It's already in the stack.
574
575 DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
576 << "\n");
577 BlockValueStack.push(BV);
578 return true;
579 }
580
581 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
582 const DataLayout &DL; ///< A mandatory DataLayout
583 DominatorTree *DT; ///< An optional DT pointer.
584
585 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
586 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
587 LVILatticeVal &Result, Instruction *CxtI = nullptr);
588 bool hasBlockValue(Value *Val, BasicBlock *BB);
589
590 // These methods process one work item and may add more. A false value
591 // returned means that the work item was not completely processed and must
592 // be revisited after going through the new items.
593 bool solveBlockValue(Value *Val, BasicBlock *BB);
Philip Reames05c435e2016-12-06 03:22:03 +0000594 bool solveBlockValueImpl(LVILatticeVal &Res, Value *Val, BasicBlock *BB);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000595 bool solveBlockValueNonLocal(LVILatticeVal &BBLV, Value *Val, BasicBlock *BB);
596 bool solveBlockValuePHINode(LVILatticeVal &BBLV, PHINode *PN, BasicBlock *BB);
597 bool solveBlockValueSelect(LVILatticeVal &BBLV, SelectInst *S,
598 BasicBlock *BB);
599 bool solveBlockValueBinaryOp(LVILatticeVal &BBLV, Instruction *BBI,
600 BasicBlock *BB);
601 bool solveBlockValueCast(LVILatticeVal &BBLV, Instruction *BBI,
602 BasicBlock *BB);
603 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
604 LVILatticeVal &BBLV,
605 Instruction *BBI);
606
607 void solve();
608
609 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000610 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000611 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000612 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
613 Instruction *CxtI = nullptr);
614
Sanjay Patel2a385e22015-01-09 16:47:20 +0000615 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000616 /// value for the specified Value* at the specified instruction (generally
617 /// from an assume intrinsic).
618 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000619
Sanjay Patel2a385e22015-01-09 16:47:20 +0000620 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000621 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000622 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
623 Instruction *CxtI = nullptr);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000624
Philip Reames9db79482016-09-12 22:38:44 +0000625 /// Complete flush all previously computed values
626 void clear() {
627 TheCache.clear();
628 }
629
630 /// This is part of the update interface to inform the cache
631 /// that a block has been deleted.
632 void eraseBlock(BasicBlock *BB) {
633 TheCache.eraseBlock(BB);
634 }
635
Sanjay Patel2a385e22015-01-09 16:47:20 +0000636 /// This is the update interface to inform the cache that an edge from
637 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000638 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000639
Philip Reames92e5e1b2016-09-12 21:46:58 +0000640 LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000641 DominatorTree *DT = nullptr)
642 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000643 };
644} // end anonymous namespace
645
Philip Reames92e5e1b2016-09-12 21:46:58 +0000646void LazyValueInfoImpl::solve() {
Owen Anderson6f060af2011-01-05 23:26:22 +0000647 while (!BlockValueStack.empty()) {
648 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000649 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
650
Nuno Lopese6e04902012-06-28 01:16:18 +0000651 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000652 // The work item was completely processed.
653 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
Philip Reames9db79482016-09-12 22:38:44 +0000654 assert(TheCache.hasCachedValueInfo(e.second, e.first) &&
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000655 "Result should be in cache!");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000656
Philip Reames44456b82016-02-02 03:15:40 +0000657 DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
Philip Reames9db79482016-09-12 22:38:44 +0000658 << " = " << TheCache.getCachedValueInfo(e.second, e.first) << "\n");
Philip Reames44456b82016-02-02 03:15:40 +0000659
Owen Anderson6f060af2011-01-05 23:26:22 +0000660 BlockValueStack.pop();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000661 BlockValueSet.erase(e);
662 } else {
663 // More work needs to be done before revisiting.
664 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000665 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000666 }
667}
668
Philip Reames92e5e1b2016-09-12 21:46:58 +0000669bool LazyValueInfoImpl::hasBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000670 // If already a constant, there is nothing to compute.
671 if (isa<Constant>(Val))
672 return true;
673
Philip Reames9db79482016-09-12 22:38:44 +0000674 return TheCache.hasCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000675}
676
Philip Reames92e5e1b2016-09-12 21:46:58 +0000677LVILatticeVal LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000678 // If already a constant, there is nothing to compute.
679 if (Constant *VC = dyn_cast<Constant>(Val))
680 return LVILatticeVal::get(VC);
681
Philip Reames9db79482016-09-12 22:38:44 +0000682 return TheCache.getCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000683}
684
Philip Reameseb3e9da2015-10-29 03:57:17 +0000685static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
686 switch (BBI->getOpcode()) {
687 default: break;
688 case Instruction::Load:
689 case Instruction::Call:
690 case Instruction::Invoke:
NAKAMURA Takumibd072a92016-07-25 00:59:46 +0000691 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
Philip Reames70efccd2015-10-29 04:21:49 +0000692 if (isa<IntegerType>(BBI->getType())) {
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000693 return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
Philip Reameseb3e9da2015-10-29 03:57:17 +0000694 }
695 break;
696 };
Philip Reamesd1f829d2016-02-02 21:57:37 +0000697 // Nothing known - will be intersected with other facts
698 return LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +0000699}
700
Philip Reames92e5e1b2016-09-12 21:46:58 +0000701bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000702 if (isa<Constant>(Val))
703 return true;
704
Philip Reames9db79482016-09-12 22:38:44 +0000705 if (TheCache.hasCachedValueInfo(Val, BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000706 // If we have a cached value, use that.
707 DEBUG(dbgs() << " reuse BB '" << BB->getName()
Philip Reames9db79482016-09-12 22:38:44 +0000708 << "' val=" << TheCache.getCachedValueInfo(Val, BB) << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000709
Hans Wennborg45172ac2014-11-25 17:23:05 +0000710 // Since we're reusing a cached value, we don't need to update the
711 // OverDefinedCache. The cache will have been properly updated whenever the
712 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000713 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000714 }
715
Hans Wennborg45172ac2014-11-25 17:23:05 +0000716 // Hold off inserting this value into the Cache in case we have to return
717 // false and come back later.
718 LVILatticeVal Res;
Philip Reames05c435e2016-12-06 03:22:03 +0000719 if (!solveBlockValueImpl(Res, Val, BB))
720 // Work pushed, will revisit
721 return false;
722
723 TheCache.insertResult(Val, BB, Res);
724 return true;
725}
726
727bool LazyValueInfoImpl::solveBlockValueImpl(LVILatticeVal &Res,
728 Value *Val, BasicBlock *BB) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000729
Chris Lattneraf025d32009-11-15 19:59:49 +0000730 Instruction *BBI = dyn_cast<Instruction>(Val);
Philip Reames05c435e2016-12-06 03:22:03 +0000731 if (!BBI || BBI->getParent() != BB)
732 return solveBlockValueNonLocal(Res, Val, BB);
Chris Lattner2c708562009-11-15 20:00:52 +0000733
Philip Reames05c435e2016-12-06 03:22:03 +0000734 if (PHINode *PN = dyn_cast<PHINode>(BBI))
735 return solveBlockValuePHINode(Res, PN, BB);
Owen Anderson80d19f02010-08-18 21:11:37 +0000736
Philip Reames05c435e2016-12-06 03:22:03 +0000737 if (auto *SI = dyn_cast<SelectInst>(BBI))
738 return solveBlockValueSelect(Res, SI, BB);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000739
Philip Reames2ab964e2016-04-27 01:02:25 +0000740 // If this value is a nonnull pointer, record it's range and bailout. Note
741 // that for all other pointer typed values, we terminate the search at the
742 // definition. We could easily extend this to look through geps, bitcasts,
743 // and the like to prove non-nullness, but it's not clear that's worth it
744 // compile time wise. The context-insensative value walk done inside
745 // isKnownNonNull gets most of the profitable cases at much less expense.
746 // This does mean that we have a sensativity to where the defining
747 // instruction is placed, even if it could legally be hoisted much higher.
748 // That is unfortunate.
Igor Laevsky0fa48192015-09-18 13:01:48 +0000749 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
750 if (PT && isKnownNonNull(BBI)) {
751 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
Hans Wennborg45172ac2014-11-25 17:23:05 +0000752 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000753 }
Davide Italianobd543d02016-05-25 22:29:34 +0000754 if (BBI->getType()->isIntegerTy()) {
Philip Reames05c435e2016-12-06 03:22:03 +0000755 if (isa<CastInst>(BBI))
756 return solveBlockValueCast(Res, BBI, BB);
757
Philip Reames2ab964e2016-04-27 01:02:25 +0000758 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
Philip Reames05c435e2016-12-06 03:22:03 +0000759 if (BO && isa<ConstantInt>(BO->getOperand(1)))
760 return solveBlockValueBinaryOp(Res, BBI, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000761 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000762
Philip Reamesa0c9f6e2016-03-04 22:27:39 +0000763 DEBUG(dbgs() << " compute BB '" << BB->getName()
764 << "' - unknown inst def found.\n");
765 Res = getFromRangeMetadata(BBI);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000766 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000767}
768
769static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
770 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
771 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000772 GetUnderlyingObject(L->getPointerOperand(),
773 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000774 }
775 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
776 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000777 GetUnderlyingObject(S->getPointerOperand(),
778 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000779 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000780 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
781 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000782
783 // FIXME: check whether it has a valuerange that excludes zero?
784 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
785 if (!Len || Len->isZero()) return false;
786
Eli Friedman7a5fc692011-05-31 20:40:16 +0000787 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000788 if (GetUnderlyingObject(MI->getRawDest(),
789 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000790 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000791 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000792 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000793 if (GetUnderlyingObject(MTI->getRawSource(),
794 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000795 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000796 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000797 return false;
798}
799
Philip Reames3f83dbe2016-04-27 00:30:55 +0000800/// Return true if the allocation associated with Val is ever dereferenced
801/// within the given basic block. This establishes the fact Val is not null,
802/// but does not imply that the memory at Val is dereferenceable. (Val may
803/// point off the end of the dereferenceable part of the object.)
804static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
805 assert(Val->getType()->isPointerTy());
806
807 const DataLayout &DL = BB->getModule()->getDataLayout();
808 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
809 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
810 // inside InstructionDereferencesPointer either.
811 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
812 for (Instruction &I : *BB)
813 if (InstructionDereferencesPointer(&I, UnderlyingVal))
814 return true;
815 return false;
816}
817
Philip Reames92e5e1b2016-09-12 21:46:58 +0000818bool LazyValueInfoImpl::solveBlockValueNonLocal(LVILatticeVal &BBLV,
Owen Anderson64c2c572010-12-20 18:18:16 +0000819 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000820 LVILatticeVal Result; // Start Undefined.
821
Nick Lewycky55a700b2010-12-18 01:00:40 +0000822 // If this is the entry block, we must be asking about an argument. The
823 // value is overdefined.
824 if (BB == &BB->getParent()->getEntryBlock()) {
825 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
Philip Reames3f83dbe2016-04-27 00:30:55 +0000826 // Bofore giving up, see if we can prove the pointer non-null local to
827 // this particular block.
828 if (Val->getType()->isPointerTy() &&
829 (isKnownNonNull(Val) || isObjectDereferencedInBlock(Val, BB))) {
Chris Lattner229907c2011-07-18 04:54:35 +0000830 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000831 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
832 } else {
Philip Reames1baaef12016-12-06 03:01:08 +0000833 Result = LVILatticeVal::getOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000834 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000835 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000836 return true;
837 }
838
839 // Loop over all of our predecessors, merging what we know from them into
840 // result.
841 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000842 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000843 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000844 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000845 if (EdgesMissing)
846 continue;
847
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000848 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000849
850 // If we hit overdefined, exit early. The BlockVals entry is already set
851 // to overdefined.
852 if (Result.isOverdefined()) {
853 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000854 << "' - overdefined because of pred (non local).\n");
Artur Pilipenkoadcd01f2016-08-09 09:14:29 +0000855 // Before giving up, see if we can prove the pointer non-null local to
Philip Reames3f83dbe2016-04-27 00:30:55 +0000856 // this particular block.
857 if (Val->getType()->isPointerTy() &&
858 isObjectDereferencedInBlock(Val, BB)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000859 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000860 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
861 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000862
Owen Anderson64c2c572010-12-20 18:18:16 +0000863 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000864 return true;
865 }
866 }
867 if (EdgesMissing)
868 return false;
869
870 // Return the merged value, which is more precise than 'overdefined'.
871 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000872 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000873 return true;
874}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000875
Philip Reames92e5e1b2016-09-12 21:46:58 +0000876bool LazyValueInfoImpl::solveBlockValuePHINode(LVILatticeVal &BBLV,
Owen Anderson64c2c572010-12-20 18:18:16 +0000877 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000878 LVILatticeVal Result; // Start Undefined.
879
880 // Loop over all of our predecessors, merging what we know from them into
881 // result.
882 bool EdgesMissing = false;
883 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
884 BasicBlock *PhiBB = PN->getIncomingBlock(i);
885 Value *PhiVal = PN->getIncomingValue(i);
886 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000887 // Note that we can provide PN as the context value to getEdgeValue, even
888 // though the results will be cached, because PN is the value being used as
889 // the cache key in the caller.
Hal Finkel7e184492014-09-07 20:29:59 +0000890 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000891 if (EdgesMissing)
892 continue;
893
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000894 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000895
896 // If we hit overdefined, exit early. The BlockVals entry is already set
897 // to overdefined.
898 if (Result.isOverdefined()) {
899 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000900 << "' - overdefined because of pred (local).\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000901
Owen Anderson64c2c572010-12-20 18:18:16 +0000902 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000903 return true;
904 }
905 }
906 if (EdgesMissing)
907 return false;
908
909 // Return the merged value, which is more precise than 'overdefined'.
910 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000911 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000912 return true;
913}
914
Artur Pilipenko933c07a2016-08-10 13:38:07 +0000915static LVILatticeVal getValueFromCondition(Value *Val, Value *Cond,
916 bool isTrueDest = true);
Hal Finkel7e184492014-09-07 20:29:59 +0000917
Philip Reamesd1f829d2016-02-02 21:57:37 +0000918// If we can determine a constraint on the value given conditions assumed by
919// the program, intersect those constraints with BBLV
Philip Reames92e5e1b2016-09-12 21:46:58 +0000920void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000921 Value *Val, LVILatticeVal &BBLV, Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000922 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
923 if (!BBI)
924 return;
925
Chandler Carruth66b31302015-01-04 12:03:27 +0000926 for (auto &AssumeVH : AC->assumptions()) {
927 if (!AssumeVH)
928 continue;
929 auto *I = cast<CallInst>(AssumeVH);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000930 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +0000931 continue;
932
Artur Pilipenko933c07a2016-08-10 13:38:07 +0000933 BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
Hal Finkel7e184492014-09-07 20:29:59 +0000934 }
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000935
936 // If guards are not used in the module, don't spend time looking for them
937 auto *GuardDecl = BBI->getModule()->getFunction(
938 Intrinsic::getName(Intrinsic::experimental_guard));
939 if (!GuardDecl || GuardDecl->use_empty())
940 return;
941
Artur Pilipenko47dc0982016-10-21 15:02:21 +0000942 for (Instruction &I : make_range(BBI->getIterator().getReverse(),
943 BBI->getParent()->rend())) {
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000944 Value *Cond = nullptr;
Artur Pilipenko47dc0982016-10-21 15:02:21 +0000945 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
946 BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000947 }
Hal Finkel7e184492014-09-07 20:29:59 +0000948}
949
Philip Reames92e5e1b2016-09-12 21:46:58 +0000950bool LazyValueInfoImpl::solveBlockValueSelect(LVILatticeVal &BBLV,
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000951 SelectInst *SI, BasicBlock *BB) {
952
953 // Recurse on our inputs if needed
954 if (!hasBlockValue(SI->getTrueValue(), BB)) {
955 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
956 return false;
Philip Reames1baaef12016-12-06 03:01:08 +0000957 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000958 return true;
959 }
960 LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
961 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
962 // extra slots in the table if we can.
963 if (TrueVal.isOverdefined()) {
Philip Reames1baaef12016-12-06 03:01:08 +0000964 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000965 return true;
966 }
967
968 if (!hasBlockValue(SI->getFalseValue(), BB)) {
969 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
970 return false;
Philip Reames1baaef12016-12-06 03:01:08 +0000971 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000972 return true;
973 }
974 LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
975 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
976 // extra slots in the table if we can.
977 if (FalseVal.isOverdefined()) {
Philip Reames1baaef12016-12-06 03:01:08 +0000978 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000979 return true;
980 }
981
Philip Reamesadf0e352016-02-26 22:53:59 +0000982 if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
983 ConstantRange TrueCR = TrueVal.getConstantRange();
984 ConstantRange FalseCR = FalseVal.getConstantRange();
985 Value *LHS = nullptr;
986 Value *RHS = nullptr;
987 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
988 // Is this a min specifically of our two inputs? (Avoid the risk of
989 // ValueTracking getting smarter looking back past our immediate inputs.)
990 if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
991 LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
Philip Reamesb2949622016-12-06 02:54:16 +0000992 ConstantRange ResultCR = [&]() {
993 switch (SPR.Flavor) {
994 default:
995 llvm_unreachable("unexpected minmax type!");
996 case SPF_SMIN: /// Signed minimum
997 return TrueCR.smin(FalseCR);
998 case SPF_UMIN: /// Unsigned minimum
999 return TrueCR.umin(FalseCR);
1000 case SPF_SMAX: /// Signed maximum
1001 return TrueCR.smax(FalseCR);
1002 case SPF_UMAX: /// Unsigned maximum
1003 return TrueCR.umax(FalseCR);
1004 };
1005 }();
1006 BBLV = LVILatticeVal::getRange(ResultCR);
1007 return true;
Philip Reamesadf0e352016-02-26 22:53:59 +00001008 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001009
Philip Reamesadf0e352016-02-26 22:53:59 +00001010 // TODO: ABS, NABS from the SelectPatternResult
1011 }
1012
Philip Reames854a84c2016-02-12 00:09:18 +00001013 // Can we constrain the facts about the true and false values by using the
1014 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
1015 // TODO: We could potentially refine an overdefined true value above.
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001016 Value *Cond = SI->getCondition();
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001017 TrueVal = intersect(TrueVal,
1018 getValueFromCondition(SI->getTrueValue(), Cond, true));
1019 FalseVal = intersect(FalseVal,
1020 getValueFromCondition(SI->getFalseValue(), Cond, false));
Philip Reames854a84c2016-02-12 00:09:18 +00001021
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001022 // Handle clamp idioms such as:
1023 // %24 = constantrange<0, 17>
1024 // %39 = icmp eq i32 %24, 0
1025 // %40 = add i32 %24, -1
1026 // %siv.next = select i1 %39, i32 16, i32 %40
1027 // %siv.next = constantrange<0, 17> not <-1, 17>
1028 // In general, this can handle any clamp idiom which tests the edge
1029 // condition via an equality or inequality.
1030 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
Philip Reamesadf0e352016-02-26 22:53:59 +00001031 ICmpInst::Predicate Pred = ICI->getPredicate();
1032 Value *A = ICI->getOperand(0);
1033 if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
1034 auto addConstants = [](ConstantInt *A, ConstantInt *B) {
1035 assert(A->getType() == B->getType());
1036 return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
1037 };
1038 // See if either input is A + C2, subject to the constraint from the
1039 // condition that A != C when that input is used. We can assume that
1040 // that input doesn't include C + C2.
1041 ConstantInt *CIAdded;
1042 switch (Pred) {
Philip Reames70b39182016-02-27 05:18:30 +00001043 default: break;
Philip Reamesadf0e352016-02-26 22:53:59 +00001044 case ICmpInst::ICMP_EQ:
1045 if (match(SI->getFalseValue(), m_Add(m_Specific(A),
1046 m_ConstantInt(CIAdded)))) {
1047 auto ResNot = addConstants(CIBase, CIAdded);
1048 FalseVal = intersect(FalseVal,
1049 LVILatticeVal::getNot(ResNot));
1050 }
1051 break;
1052 case ICmpInst::ICMP_NE:
1053 if (match(SI->getTrueValue(), m_Add(m_Specific(A),
1054 m_ConstantInt(CIAdded)))) {
1055 auto ResNot = addConstants(CIBase, CIAdded);
1056 TrueVal = intersect(TrueVal,
1057 LVILatticeVal::getNot(ResNot));
1058 }
1059 break;
1060 };
1061 }
1062 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001063
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001064 LVILatticeVal Result; // Start Undefined.
1065 Result.mergeIn(TrueVal, DL);
1066 Result.mergeIn(FalseVal, DL);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001067 BBLV = Result;
1068 return true;
1069}
1070
Philip Reames92e5e1b2016-09-12 21:46:58 +00001071bool LazyValueInfoImpl::solveBlockValueCast(LVILatticeVal &BBLV,
Philip Reames66715772016-04-25 18:30:31 +00001072 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001073 BasicBlock *BB) {
1074 if (!BBI->getOperand(0)->getType()->isSized()) {
1075 // Without knowing how wide the input is, we can't analyze it in any useful
1076 // way.
Philip Reames1baaef12016-12-06 03:01:08 +00001077 BBLV = LVILatticeVal::getOverdefined();
Philip Reamese5030e82016-04-26 22:52:30 +00001078 return true;
1079 }
Philip Reamesf105db42016-04-26 23:27:33 +00001080
1081 // Filter out casts we don't know how to reason about before attempting to
1082 // recurse on our operand. This can cut a long search short if we know we're
1083 // not going to be able to get any useful information anways.
1084 switch (BBI->getOpcode()) {
1085 case Instruction::Trunc:
1086 case Instruction::SExt:
1087 case Instruction::ZExt:
1088 case Instruction::BitCast:
1089 break;
1090 default:
1091 // Unhandled instructions are overdefined.
1092 DEBUG(dbgs() << " compute BB '" << BB->getName()
1093 << "' - overdefined (unknown cast).\n");
Philip Reames1baaef12016-12-06 03:01:08 +00001094 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesf105db42016-04-26 23:27:33 +00001095 return true;
1096 }
1097
Philip Reames38c87c22016-04-26 21:48:16 +00001098 // Figure out the range of the LHS. If that fails, we still apply the
1099 // transfer rule on the full set since we may be able to locally infer
1100 // interesting facts.
1101 if (!hasBlockValue(BBI->getOperand(0), BB))
Hans Wennborg45172ac2014-11-25 17:23:05 +00001102 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
Philip Reames38c87c22016-04-26 21:48:16 +00001103 // More work to do before applying this transfer rule.
Hans Wennborg45172ac2014-11-25 17:23:05 +00001104 return false;
Philip Reames38c87c22016-04-26 21:48:16 +00001105
1106 const unsigned OperandBitWidth =
Philip Reamese5030e82016-04-26 22:52:30 +00001107 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
Philip Reames38c87c22016-04-26 21:48:16 +00001108 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1109 if (hasBlockValue(BBI->getOperand(0), BB)) {
1110 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001111 intersectAssumeOrGuardBlockValueConstantRange(BBI->getOperand(0), LHSVal,
1112 BBI);
Philip Reames38c87c22016-04-26 21:48:16 +00001113 if (LHSVal.isConstantRange())
1114 LHSRange = LHSVal.getConstantRange();
Nick Lewycky55a700b2010-12-18 01:00:40 +00001115 }
1116
Philip Reames38c87c22016-04-26 21:48:16 +00001117 const unsigned ResultBitWidth =
1118 cast<IntegerType>(BBI->getType())->getBitWidth();
Philip Reames66715772016-04-25 18:30:31 +00001119
1120 // NOTE: We're currently limited by the set of operations that ConstantRange
1121 // can evaluate symbolically. Enhancing that set will allows us to analyze
1122 // more definitions.
Philip Reames4d00af12016-12-01 20:08:47 +00001123 auto CastOp = (Instruction::CastOps) BBI->getOpcode();
Philip Reames0e613f72016-12-06 02:36:58 +00001124 BBLV = LVILatticeVal::getRange(LHSRange.castOp(CastOp, ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001125 return true;
1126}
1127
Philip Reames92e5e1b2016-09-12 21:46:58 +00001128bool LazyValueInfoImpl::solveBlockValueBinaryOp(LVILatticeVal &BBLV,
Philip Reames66715772016-04-25 18:30:31 +00001129 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001130 BasicBlock *BB) {
Philip Reames66715772016-04-25 18:30:31 +00001131
Philip Reames053c2a62016-04-26 23:10:35 +00001132 assert(BBI->getOperand(0)->getType()->isSized() &&
1133 "all operands to binary operators are sized");
Philip Reamesf105db42016-04-26 23:27:33 +00001134
1135 // Filter out operators we don't know how to reason about before attempting to
1136 // recurse on our operand(s). This can cut a long search short if we know
1137 // we're not going to be able to get any useful information anways.
1138 switch (BBI->getOpcode()) {
1139 case Instruction::Add:
1140 case Instruction::Sub:
1141 case Instruction::Mul:
1142 case Instruction::UDiv:
1143 case Instruction::Shl:
1144 case Instruction::LShr:
1145 case Instruction::And:
1146 case Instruction::Or:
1147 // continue into the code below
1148 break;
1149 default:
1150 // Unhandled instructions are overdefined.
1151 DEBUG(dbgs() << " compute BB '" << BB->getName()
1152 << "' - overdefined (unknown binary operator).\n");
Philip Reames1baaef12016-12-06 03:01:08 +00001153 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesf105db42016-04-26 23:27:33 +00001154 return true;
1155 };
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001156
Philip Reames053c2a62016-04-26 23:10:35 +00001157 // Figure out the range of the LHS. If that fails, use a conservative range,
1158 // but apply the transfer rule anyways. This lets us pick up facts from
1159 // expressions like "and i32 (call i32 @foo()), 32"
1160 if (!hasBlockValue(BBI->getOperand(0), BB))
1161 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
1162 // More work to do before applying this transfer rule.
1163 return false;
1164
1165 const unsigned OperandBitWidth =
1166 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
1167 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1168 if (hasBlockValue(BBI->getOperand(0), BB)) {
1169 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001170 intersectAssumeOrGuardBlockValueConstantRange(BBI->getOperand(0), LHSVal,
1171 BBI);
Philip Reames053c2a62016-04-26 23:10:35 +00001172 if (LHSVal.isConstantRange())
1173 LHSRange = LHSVal.getConstantRange();
Philip Reames66715772016-04-25 18:30:31 +00001174 }
Philip Reames66715772016-04-25 18:30:31 +00001175
1176 ConstantInt *RHS = cast<ConstantInt>(BBI->getOperand(1));
1177 ConstantRange RHSRange = ConstantRange(RHS->getValue());
1178
Owen Anderson80d19f02010-08-18 21:11:37 +00001179 // NOTE: We're currently limited by the set of operations that ConstantRange
1180 // can evaluate symbolically. Enhancing that set will allows us to analyze
1181 // more definitions.
Philip Reames4d00af12016-12-01 20:08:47 +00001182 auto BinOp = (Instruction::BinaryOps) BBI->getOpcode();
Philip Reames0e613f72016-12-06 02:36:58 +00001183 BBLV = LVILatticeVal::getRange(LHSRange.binaryOp(BinOp, RHSRange));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001184 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +00001185}
1186
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001187static LVILatticeVal getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1188 bool isTrueDest) {
Artur Pilipenko21472912016-08-08 14:08:37 +00001189 Value *LHS = ICI->getOperand(0);
1190 Value *RHS = ICI->getOperand(1);
1191 CmpInst::Predicate Predicate = ICI->getPredicate();
1192
1193 if (isa<Constant>(RHS)) {
1194 if (ICI->isEquality() && LHS == Val) {
Hal Finkel7e184492014-09-07 20:29:59 +00001195 // We know that V has the RHS constant if this is a true SETEQ or
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001196 // false SETNE.
Artur Pilipenko21472912016-08-08 14:08:37 +00001197 if (isTrueDest == (Predicate == ICmpInst::ICMP_EQ))
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001198 return LVILatticeVal::get(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001199 else
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001200 return LVILatticeVal::getNot(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001201 }
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001202 }
Hal Finkel7e184492014-09-07 20:29:59 +00001203
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001204 if (!Val->getType()->isIntegerTy())
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001205 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001206
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001207 // Use ConstantRange::makeAllowedICmpRegion in order to determine the possible
1208 // range of Val guaranteed by the condition. Recognize comparisons in the from
1209 // of:
1210 // icmp <pred> Val, ...
Artur Pilipenko63562582016-08-12 10:05:11 +00001211 // icmp <pred> (add Val, Offset), ...
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001212 // The latter is the range checking idiom that InstCombine produces. Subtract
1213 // the offset from the allowed range for RHS in this case.
Artur Pilipenkoeed618d2016-08-08 14:33:11 +00001214
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001215 // Val or (add Val, Offset) can be on either hand of the comparison
1216 if (LHS != Val && !match(LHS, m_Add(m_Specific(Val), m_ConstantInt()))) {
1217 std::swap(LHS, RHS);
1218 Predicate = CmpInst::getSwappedPredicate(Predicate);
1219 }
Hal Finkel7e184492014-09-07 20:29:59 +00001220
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001221 ConstantInt *Offset = nullptr;
Artur Pilipenko63562582016-08-12 10:05:11 +00001222 if (LHS != Val)
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001223 match(LHS, m_Add(m_Specific(Val), m_ConstantInt(Offset)));
Hal Finkel7e184492014-09-07 20:29:59 +00001224
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001225 if (LHS == Val || Offset) {
1226 // Calculate the range of values that are allowed by the comparison
1227 ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1228 /*isFullSet=*/true);
1229 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1230 RHSRange = ConstantRange(CI->getValue());
Artur Pilipenko6669f252016-08-12 10:14:11 +00001231 else if (Instruction *I = dyn_cast<Instruction>(RHS))
1232 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1233 RHSRange = getConstantRangeFromMetadata(*Ranges);
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001234
1235 // If we're interested in the false dest, invert the condition
1236 CmpInst::Predicate Pred =
1237 isTrueDest ? Predicate : CmpInst::getInversePredicate(Predicate);
1238 ConstantRange TrueValues =
1239 ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1240
1241 if (Offset) // Apply the offset from above.
1242 TrueValues = TrueValues.subtract(Offset->getValue());
1243
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001244 return LVILatticeVal::getRange(std::move(TrueValues));
Hal Finkel7e184492014-09-07 20:29:59 +00001245 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001246
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001247 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001248}
1249
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001250static LVILatticeVal
1251getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1252 DenseMap<Value*, LVILatticeVal> &Visited);
1253
1254static LVILatticeVal
1255getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1256 DenseMap<Value*, LVILatticeVal> &Visited) {
1257 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1258 return getValueFromICmpCondition(Val, ICI, isTrueDest);
1259
1260 // Handle conditions in the form of (cond1 && cond2), we know that on the
1261 // true dest path both of the conditions hold.
1262 if (!isTrueDest)
1263 return LVILatticeVal::getOverdefined();
1264
1265 BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond);
1266 if (!BO || BO->getOpcode() != BinaryOperator::And)
1267 return LVILatticeVal::getOverdefined();
1268
1269 auto RHS = getValueFromCondition(Val, BO->getOperand(0), isTrueDest, Visited);
1270 auto LHS = getValueFromCondition(Val, BO->getOperand(1), isTrueDest, Visited);
1271 return intersect(RHS, LHS);
1272}
1273
1274static LVILatticeVal
1275getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1276 DenseMap<Value*, LVILatticeVal> &Visited) {
1277 auto I = Visited.find(Cond);
1278 if (I != Visited.end())
1279 return I->second;
Artur Pilipenkob6230882016-08-12 15:08:15 +00001280
1281 auto Result = getValueFromConditionImpl(Val, Cond, isTrueDest, Visited);
1282 Visited[Cond] = Result;
1283 return Result;
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001284}
1285
1286LVILatticeVal getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest) {
1287 assert(Cond && "precondition");
1288 DenseMap<Value*, LVILatticeVal> Visited;
1289 return getValueFromCondition(Val, Cond, isTrueDest, Visited);
1290}
1291
Nuno Lopese6e04902012-06-28 01:16:18 +00001292/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
Philip Reames13f73242016-02-01 23:21:11 +00001293/// Val is not constrained on the edge. Result is unspecified if return value
1294/// is false.
Nuno Lopese6e04902012-06-28 01:16:18 +00001295static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1296 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001297 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +00001298 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +00001299 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1300 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +00001301 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +00001302 if (BI->isConditional() &&
1303 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1304 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1305 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1306 "BBTo isn't a successor of BBFrom");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001307
Chris Lattner19019ea2009-11-11 22:48:44 +00001308 // If V is the condition of the branch itself, then we know exactly what
1309 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +00001310 if (BI->getCondition() == Val) {
1311 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +00001312 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001313 return true;
1314 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001315
Chris Lattner19019ea2009-11-11 22:48:44 +00001316 // If the condition of the branch is an equality comparison, we may be
1317 // able to infer the value.
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001318 Result = getValueFromCondition(Val, BI->getCondition(), isTrueDest);
1319 if (!Result.isOverdefined())
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001320 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001321 }
1322 }
Chris Lattner77358782009-11-15 20:02:12 +00001323
1324 // If the edge was formed by a switch on the value, then we may know exactly
1325 // what it is.
1326 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001327 if (SI->getCondition() != Val)
1328 return false;
1329
1330 bool DefaultCase = SI->getDefaultDest() == BBTo;
1331 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1332 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1333
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001334 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001335 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +00001336 if (DefaultCase) {
1337 // It is possible that the default destination is the destination of
1338 // some cases. There is no need to perform difference for those cases.
1339 if (i.getCaseSuccessor() != BBTo)
1340 EdgesVals = EdgesVals.difference(EdgeVal);
1341 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +00001342 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +00001343 }
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001344 Result = LVILatticeVal::getRange(std::move(EdgesVals));
Nuno Lopes8650fb82012-06-28 16:13:37 +00001345 return true;
Chris Lattner77358782009-11-15 20:02:12 +00001346 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001347 return false;
1348}
1349
Sanjay Patel938e2792015-01-09 16:35:37 +00001350/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1351/// the basic block if the edge does not constrain Val.
Philip Reames92e5e1b2016-09-12 21:46:58 +00001352bool LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +00001353 BasicBlock *BBTo, LVILatticeVal &Result,
1354 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +00001355 // If already a constant, there is nothing to compute.
1356 if (Constant *VC = dyn_cast<Constant>(Val)) {
1357 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001358 return true;
1359 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001360
Philip Reames44456b82016-02-02 03:15:40 +00001361 LVILatticeVal LocalResult;
1362 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1363 // If we couldn't constrain the value on the edge, LocalResult doesn't
1364 // provide any information.
Philip Reames1baaef12016-12-06 03:01:08 +00001365 LocalResult = LVILatticeVal::getOverdefined();
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001366
Philip Reames44456b82016-02-02 03:15:40 +00001367 if (hasSingleValue(LocalResult)) {
1368 // Can't get any more precise here
1369 Result = LocalResult;
Nuno Lopese6e04902012-06-28 01:16:18 +00001370 return true;
1371 }
1372
1373 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +00001374 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1375 return false;
Philip Reames44456b82016-02-02 03:15:40 +00001376 // No new information.
1377 Result = LocalResult;
Hans Wennborg45172ac2014-11-25 17:23:05 +00001378 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +00001379 }
1380
Philip Reames44456b82016-02-02 03:15:40 +00001381 // Try to intersect ranges of the BB and the constraint on the edge.
1382 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001383 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock,
1384 BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +00001385 // We can use the context instruction (generically the ultimate instruction
1386 // the calling pass is trying to simplify) here, even though the result of
1387 // this function is generally cached when called from the solve* functions
1388 // (and that cached result might be used with queries using a different
1389 // context instruction), because when this function is called from the solve*
1390 // functions, the context instruction is not provided. When called from
Philip Reames92e5e1b2016-09-12 21:46:58 +00001391 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
Hal Finkel2400c962014-10-16 00:40:05 +00001392 // but then the result is not cached.
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001393 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
Philip Reames44456b82016-02-02 03:15:40 +00001394
1395 Result = intersect(LocalResult, InBlock);
Nuno Lopese6e04902012-06-28 01:16:18 +00001396 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001397}
1398
Philip Reames92e5e1b2016-09-12 21:46:58 +00001399LVILatticeVal LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
Hal Finkel7e184492014-09-07 20:29:59 +00001400 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001401 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001402 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001403
Hans Wennborg45172ac2014-11-25 17:23:05 +00001404 assert(BlockValueStack.empty() && BlockValueSet.empty());
Philip Reamesbb781b42016-02-10 21:46:32 +00001405 if (!hasBlockValue(V, BB)) {
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001406 pushBlockValue(std::make_pair(BB, V));
Philip Reamesbb781b42016-02-10 21:46:32 +00001407 solve();
1408 }
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001409 LVILatticeVal Result = getBlockValue(V, BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001410 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001411
1412 DEBUG(dbgs() << " Result = " << Result << "\n");
1413 return Result;
1414}
1415
Philip Reames92e5e1b2016-09-12 21:46:58 +00001416LVILatticeVal LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001417 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1418 << CxtI->getName() << "'\n");
1419
Philip Reamesbb781b42016-02-10 21:46:32 +00001420 if (auto *C = dyn_cast<Constant>(V))
1421 return LVILatticeVal::get(C);
1422
Philip Reamesd1f829d2016-02-02 21:57:37 +00001423 LVILatticeVal Result = LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +00001424 if (auto *I = dyn_cast<Instruction>(V))
1425 Result = getFromRangeMetadata(I);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001426 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
Philip Reames2c275cc2016-02-02 00:45:30 +00001427
David Greene37e98092009-12-23 20:43:58 +00001428 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001429 return Result;
1430}
Chris Lattner19019ea2009-11-11 22:48:44 +00001431
Philip Reames92e5e1b2016-09-12 21:46:58 +00001432LVILatticeVal LazyValueInfoImpl::
Hal Finkel7e184492014-09-07 20:29:59 +00001433getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1434 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001435 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001436 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001437
Nick Lewycky55a700b2010-12-18 01:00:40 +00001438 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001439 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001440 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001441 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001442 (void)WasFastQuery;
1443 assert(WasFastQuery && "More work to do after problem solved?");
1444 }
1445
David Greene37e98092009-12-23 20:43:58 +00001446 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001447 return Result;
1448}
1449
Philip Reames92e5e1b2016-09-12 21:46:58 +00001450void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Philip Reames9db79482016-09-12 22:38:44 +00001451 BasicBlock *NewSucc) {
1452 TheCache.threadEdgeImpl(OldSucc, NewSucc);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001453}
1454
Chris Lattneraf025d32009-11-15 19:59:49 +00001455//===----------------------------------------------------------------------===//
1456// LazyValueInfo Impl
1457//===----------------------------------------------------------------------===//
1458
Philip Reames92e5e1b2016-09-12 21:46:58 +00001459/// This lazily constructs the LazyValueInfoImpl.
1460static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
1461 const DataLayout *DL,
1462 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001463 if (!PImpl) {
1464 assert(DL && "getCache() called with a null DataLayout");
Philip Reames92e5e1b2016-09-12 21:46:58 +00001465 PImpl = new LazyValueInfoImpl(AC, *DL, DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001466 }
Philip Reames92e5e1b2016-09-12 21:46:58 +00001467 return *static_cast<LazyValueInfoImpl*>(PImpl);
Chris Lattneraf025d32009-11-15 19:59:49 +00001468}
1469
Sean Silva687019f2016-06-13 22:01:25 +00001470bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
1471 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001472 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001473
1474 DominatorTreeWrapperPass *DTWP =
1475 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Sean Silva687019f2016-06-13 22:01:25 +00001476 Info.DT = DTWP ? &DTWP->getDomTree() : nullptr;
1477 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001478
Sean Silva687019f2016-06-13 22:01:25 +00001479 if (Info.PImpl)
Philip Reames92e5e1b2016-09-12 21:46:58 +00001480 getImpl(Info.PImpl, Info.AC, &DL, Info.DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001481
Owen Anderson208636f2010-08-18 18:39:01 +00001482 // Fully lazy.
1483 return false;
1484}
1485
Sean Silva687019f2016-06-13 22:01:25 +00001486void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier43a33062011-12-02 01:26:24 +00001487 AU.setPreservesAll();
Chandler Carruth66b31302015-01-04 12:03:27 +00001488 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001489 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001490}
1491
Sean Silva687019f2016-06-13 22:01:25 +00001492LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1493
1494LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1495
Chris Lattneraf025d32009-11-15 19:59:49 +00001496void LazyValueInfo::releaseMemory() {
1497 // If the cache was allocated, free it.
1498 if (PImpl) {
Philip Reames92e5e1b2016-09-12 21:46:58 +00001499 delete &getImpl(PImpl, AC, nullptr);
Craig Topper9f008862014-04-15 04:59:12 +00001500 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001501 }
1502}
1503
Sean Silva687019f2016-06-13 22:01:25 +00001504void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1505
1506LazyValueInfo LazyValueAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1507 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1508 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1509 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1510
1511 return LazyValueInfo(&AC, &TLI, DT);
1512}
1513
Wei Mif160e342016-09-15 06:28:34 +00001514/// Returns true if we can statically tell that this value will never be a
1515/// "useful" constant. In practice, this means we've got something like an
1516/// alloca or a malloc call for which a comparison against a constant can
1517/// only be guarding dead code. Note that we are potentially giving up some
1518/// precision in dead code (a constant result) in favour of avoiding a
1519/// expensive search for a easily answered common query.
1520static bool isKnownNonConstant(Value *V) {
1521 V = V->stripPointerCasts();
1522 // The return val of alloc cannot be a Constant.
1523 if (isa<AllocaInst>(V))
1524 return true;
1525 return false;
1526}
1527
Hal Finkel7e184492014-09-07 20:29:59 +00001528Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1529 Instruction *CxtI) {
Wei Mif160e342016-09-15 06:28:34 +00001530 // Bail out early if V is known not to be a Constant.
1531 if (isKnownNonConstant(V))
1532 return nullptr;
1533
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001534 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001535 LVILatticeVal Result =
Philip Reames92e5e1b2016-09-12 21:46:58 +00001536 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001537
Chris Lattner19019ea2009-11-11 22:48:44 +00001538 if (Result.isConstant())
1539 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001540 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001541 ConstantRange CR = Result.getConstantRange();
1542 if (const APInt *SingleVal = CR.getSingleElement())
1543 return ConstantInt::get(V->getContext(), *SingleVal);
1544 }
Craig Topper9f008862014-04-15 04:59:12 +00001545 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001546}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001547
John Regehre1c481d2016-05-02 19:58:00 +00001548ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00001549 Instruction *CxtI) {
John Regehre1c481d2016-05-02 19:58:00 +00001550 assert(V->getType()->isIntegerTy());
1551 unsigned Width = V->getType()->getIntegerBitWidth();
1552 const DataLayout &DL = BB->getModule()->getDataLayout();
1553 LVILatticeVal Result =
Philip Reames92e5e1b2016-09-12 21:46:58 +00001554 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
John Regehre1c481d2016-05-02 19:58:00 +00001555 if (Result.isUndefined())
1556 return ConstantRange(Width, /*isFullSet=*/false);
1557 if (Result.isConstantRange())
1558 return Result.getConstantRange();
Artur Pilipenkoa4b6a702016-08-10 12:54:54 +00001559 // We represent ConstantInt constants as constant ranges but other kinds
1560 // of integer constants, i.e. ConstantExpr will be tagged as constants
1561 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1562 "ConstantInt value must be represented as constantrange");
Davide Italianobd543d02016-05-25 22:29:34 +00001563 return ConstantRange(Width, /*isFullSet=*/true);
John Regehre1c481d2016-05-02 19:58:00 +00001564}
1565
Sanjay Patel2a385e22015-01-09 16:47:20 +00001566/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001567/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001568Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001569 BasicBlock *ToBB,
1570 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001571 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001572 LVILatticeVal Result =
Philip Reames92e5e1b2016-09-12 21:46:58 +00001573 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001574
Chris Lattnerd5e25432009-11-12 01:29:10 +00001575 if (Result.isConstant())
1576 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001577 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001578 ConstantRange CR = Result.getConstantRange();
1579 if (const APInt *SingleVal = CR.getSingleElement())
1580 return ConstantInt::get(V->getContext(), *SingleVal);
1581 }
Craig Topper9f008862014-04-15 04:59:12 +00001582 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001583}
1584
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001585static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1586 LVILatticeVal &Result,
1587 const DataLayout &DL,
1588 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001589
Chris Lattner565ee2f2009-11-12 04:36:58 +00001590 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001591 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001592 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001593 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001594 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001595 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001596 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1597 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001598 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001599
Owen Anderson185fe002010-08-10 20:03:09 +00001600 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001601 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001602 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001603
Owen Anderson185fe002010-08-10 20:03:09 +00001604 ConstantRange CR = Result.getConstantRange();
1605 if (Pred == ICmpInst::ICMP_EQ) {
1606 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001607 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001608
Owen Anderson185fe002010-08-10 20:03:09 +00001609 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001610 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001611 } else if (Pred == ICmpInst::ICMP_NE) {
1612 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001613 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001614
Owen Anderson185fe002010-08-10 20:03:09 +00001615 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001616 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001617 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001618
Owen Anderson185fe002010-08-10 20:03:09 +00001619 // Handle more complex predicates.
Sanjoy Das1f7b8132016-10-02 00:09:57 +00001620 ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
1621 (ICmpInst::Predicate)Pred, CI->getValue());
Nick Lewycky11678bd2010-12-15 18:57:18 +00001622 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001623 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001624 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001625 return LazyValueInfo::False;
1626 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001627 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001628
Chris Lattneraf025d32009-11-15 19:59:49 +00001629 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001630 // If this is an equality comparison, we can try to fold it knowing that
1631 // "V != C1".
1632 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001633 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001634 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001635 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001636 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001637 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001638 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001639 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001640 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001641 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001642 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001643 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001644 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001645 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001646 }
Hal Finkel7e184492014-09-07 20:29:59 +00001647 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001648 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001649
Hal Finkel7e184492014-09-07 20:29:59 +00001650 return LazyValueInfo::Unknown;
1651}
1652
Sanjay Patel2a385e22015-01-09 16:47:20 +00001653/// Determine whether the specified value comparison with a constant is known to
1654/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001655LazyValueInfo::Tristate
1656LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1657 BasicBlock *FromBB, BasicBlock *ToBB,
1658 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001659 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001660 LVILatticeVal Result =
Philip Reames92e5e1b2016-09-12 21:46:58 +00001661 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001662
1663 return getPredicateResult(Pred, C, Result, DL, TLI);
1664}
1665
1666LazyValueInfo::Tristate
1667LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1668 Instruction *CxtI) {
Wei Mif160e342016-09-15 06:28:34 +00001669 // Is or is not NonNull are common predicates being queried. If
1670 // isKnownNonNull can tell us the result of the predicate, we can
1671 // return it quickly. But this is only a fastpath, and falling
1672 // through would still be correct.
1673 if (V->getType()->isPointerTy() && C->isNullValue() &&
1674 isKnownNonNull(V->stripPointerCasts())) {
1675 if (Pred == ICmpInst::ICMP_EQ)
1676 return LazyValueInfo::False;
1677 else if (Pred == ICmpInst::ICMP_NE)
1678 return LazyValueInfo::True;
1679 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001680 const DataLayout &DL = CxtI->getModule()->getDataLayout();
Philip Reames92e5e1b2016-09-12 21:46:58 +00001681 LVILatticeVal Result = getImpl(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001682 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1683 if (Ret != Unknown)
1684 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001685
Philip Reamesaeefae02015-11-04 01:47:04 +00001686 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1687 // LVI as a whole tries to compute a lattice value which is conservatively
1688 // correct at a given location. In this case, we have a predicate which we
1689 // weren't able to prove about the merged result, and we're pushing that
1690 // predicate back along each incoming edge to see if we can prove it
1691 // separately for each input. As a motivating example, consider:
1692 // bb1:
1693 // %v1 = ... ; constantrange<1, 5>
1694 // br label %merge
1695 // bb2:
1696 // %v2 = ... ; constantrange<10, 20>
1697 // br label %merge
1698 // merge:
1699 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1700 // %pred = icmp eq i32 %phi, 8
1701 // We can't tell from the lattice value for '%phi' that '%pred' is false
1702 // along each path, but by checking the predicate over each input separately,
1703 // we can.
1704 // We limit the search to one step backwards from the current BB and value.
1705 // We could consider extending this to search further backwards through the
1706 // CFG and/or value graph, but there are non-obvious compile time vs quality
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001707 // tradeoffs.
Philip Reames66ab0f02015-06-16 00:49:59 +00001708 if (CxtI) {
Philip Reamesbb11d622015-08-31 18:31:48 +00001709 BasicBlock *BB = CxtI->getParent();
1710
1711 // Function entry or an unreachable block. Bail to avoid confusing
1712 // analysis below.
1713 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1714 if (PI == PE)
1715 return Unknown;
1716
1717 // If V is a PHI node in the same block as the context, we need to ask
1718 // questions about the predicate as applied to the incoming value along
1719 // each edge. This is useful for eliminating cases where the predicate is
1720 // known along all incoming edges.
1721 if (auto *PHI = dyn_cast<PHINode>(V))
1722 if (PHI->getParent() == BB) {
1723 Tristate Baseline = Unknown;
1724 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1725 Value *Incoming = PHI->getIncomingValue(i);
1726 BasicBlock *PredBB = PHI->getIncomingBlock(i);
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001727 // Note that PredBB may be BB itself.
Philip Reamesbb11d622015-08-31 18:31:48 +00001728 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1729 CxtI);
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001730
Philip Reamesbb11d622015-08-31 18:31:48 +00001731 // Keep going as long as we've seen a consistent known result for
1732 // all inputs.
1733 Baseline = (i == 0) ? Result /* First iteration */
1734 : (Baseline == Result ? Baseline : Unknown); /* All others */
1735 if (Baseline == Unknown)
1736 break;
1737 }
1738 if (Baseline != Unknown)
1739 return Baseline;
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001740 }
Philip Reamesbb11d622015-08-31 18:31:48 +00001741
Philip Reames66ab0f02015-06-16 00:49:59 +00001742 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001743 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001744 // on all incoming edges.
Philip Reamesbb11d622015-08-31 18:31:48 +00001745 if (!isa<Instruction>(V) ||
1746 cast<Instruction>(V)->getParent() != BB) {
Philip Reames66ab0f02015-06-16 00:49:59 +00001747 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001748 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001749 // the value of the comparison in this block.
1750 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1751 if (Baseline != Unknown) {
1752 // Check that all remaining incoming values match the first one.
1753 while (++PI != PE) {
1754 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1755 if (Ret != Baseline) break;
1756 }
1757 // If we terminated early, then one of the values didn't match.
1758 if (PI == PE) {
1759 return Baseline;
1760 }
1761 }
1762 }
1763 }
1764 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001765}
1766
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001767void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001768 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001769 if (PImpl) {
1770 const DataLayout &DL = PredBB->getModule()->getDataLayout();
Philip Reames92e5e1b2016-09-12 21:46:58 +00001771 getImpl(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001772 }
Owen Anderson208636f2010-08-18 18:39:01 +00001773}
1774
1775void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001776 if (PImpl) {
1777 const DataLayout &DL = BB->getModule()->getDataLayout();
Philip Reames92e5e1b2016-09-12 21:46:58 +00001778 getImpl(PImpl, AC, &DL, DT).eraseBlock(BB);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001779 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001780}