blob: 7a740e9b3dbdc9fe349c223ef4ca6b2c4690b4dd [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"
Daniel Jasperaec2fa32016-12-19 08:22:17 +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
Daniel Berlin9c92a462017-02-08 15:22:52 +000042// This is the number of worklist items we will process to try to discover an
43// answer for a given value.
44static const unsigned MaxProcessedPerValue = 500;
45
Sean Silva687019f2016-06-13 22:01:25 +000046char LazyValueInfoWrapperPass::ID = 0;
47INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
Chad Rosier43a33062011-12-02 01:26:24 +000048 "Lazy Value Information Analysis", false, true)
Daniel Jasperaec2fa32016-12-19 08:22:17 +000049INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000050INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Sean Silva687019f2016-06-13 22:01:25 +000051INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
Owen Andersondf7a4f22010-10-07 22:25:06 +000052 "Lazy Value Information Analysis", false, true)
Chris Lattner741c94c2009-11-11 00:22:30 +000053
54namespace llvm {
Sean Silva687019f2016-06-13 22:01:25 +000055 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
Chris Lattner741c94c2009-11-11 00:22:30 +000056}
57
Chandler Carruthdab4eae2016-11-23 17:53:26 +000058AnalysisKey LazyValueAnalysis::Key;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000059
60//===----------------------------------------------------------------------===//
61// LVILatticeVal
62//===----------------------------------------------------------------------===//
63
Sanjay Patel2a385e22015-01-09 16:47:20 +000064/// This is the information tracked by LazyValueInfo for each value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000065///
66/// FIXME: This is basically just for bringup, this can be made a lot more rich
67/// in the future.
68///
69namespace {
70class LVILatticeVal {
71 enum LatticeValueTy {
Philip Reames3bb28322016-04-25 18:48:43 +000072 /// This Value has no known value yet. As a result, this implies the
73 /// producing instruction is dead. Caution: We use this as the starting
74 /// state in our local meet rules. In this usage, it's taken to mean
NAKAMURA Takumif2529512016-07-04 01:26:27 +000075 /// "nothing known yet".
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000076 undefined,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000077
Philip Reames02bb6a62016-12-07 04:48:50 +000078 /// This Value has a specific constant value. (For constant integers,
79 /// constantrange is used instead. Integer typed constantexprs can appear
80 /// as constant.)
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000081 constant,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000082
Philip Reames02bb6a62016-12-07 04:48:50 +000083 /// This Value is known to not have the specified value. (For constant
84 /// integers, constantrange is used instead. As above, integer typed
85 /// constantexprs can appear here.)
Chris Lattner565ee2f2009-11-12 04:36:58 +000086 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000087
Philip Reames3bb28322016-04-25 18:48:43 +000088 /// The Value falls within this range. (Used only for integer typed values.)
Owen Anderson0f306a42010-08-05 22:59:19 +000089 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000090
Philip Reames3bb28322016-04-25 18:48:43 +000091 /// We can not precisely model the dynamic values this value might take.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000092 overdefined
93 };
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000094
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000095 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000096 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000097 LatticeValueTy Tag;
98 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +000099 ConstantRange Range;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000100
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000101public:
Craig Topper9f008862014-04-15 04:59:12 +0000102 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000103
Chris Lattner19019ea2009-11-11 22:48:44 +0000104 static LVILatticeVal get(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.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +0000108 return Res;
109 }
Chris Lattner565ee2f2009-11-12 04:36:58 +0000110 static LVILatticeVal getNot(Constant *C) {
111 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000112 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000113 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000114 return Res;
115 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000116 static LVILatticeVal getRange(ConstantRange CR) {
117 LVILatticeVal Res;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000118 Res.markConstantRange(std::move(CR));
Owen Anderson5f1dd092010-08-10 23:20:01 +0000119 return Res;
120 }
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000121 static LVILatticeVal getOverdefined() {
122 LVILatticeVal Res;
123 Res.markOverdefined();
124 return Res;
125 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000126
Owen Anderson0f306a42010-08-05 22:59:19 +0000127 bool isUndefined() const { return Tag == undefined; }
128 bool isConstant() const { return Tag == constant; }
129 bool isNotConstant() const { return Tag == notconstant; }
130 bool isConstantRange() const { return Tag == constantrange; }
131 bool isOverdefined() const { return Tag == overdefined; }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000132
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000133 Constant *getConstant() const {
134 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000135 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000136 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000137
Chris Lattner565ee2f2009-11-12 04:36:58 +0000138 Constant *getNotConstant() const {
139 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000140 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000141 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000142
Owen Anderson0f306a42010-08-05 22:59:19 +0000143 ConstantRange getConstantRange() const {
144 assert(isConstantRange() &&
145 "Cannot get the constant-range of a non-constant-range!");
146 return Range;
147 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000148
Philip Reames1baaef12016-12-06 03:01:08 +0000149private:
Philip Reames71a49672016-12-07 01:03:56 +0000150 void markOverdefined() {
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000151 if (isOverdefined())
Philip Reames71a49672016-12-07 01:03:56 +0000152 return;
Owen Andersonc3a14132010-08-05 22:10:46 +0000153 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000154 }
155
Philip Reames71a49672016-12-07 01:03:56 +0000156 void markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000157 assert(V && "Marking constant with NULL");
Philip Reames71a49672016-12-07 01:03:56 +0000158 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
159 markConstantRange(ConstantRange(CI->getValue()));
160 return;
161 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000162 if (isa<UndefValue>(V))
Philip Reames71a49672016-12-07 01:03:56 +0000163 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000164
165 assert((!isConstant() || getConstant() == V) &&
166 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000167 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000168 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000169 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000170 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000171
Philip Reames71a49672016-12-07 01:03:56 +0000172 void markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000173 assert(V && "Marking constant with NULL");
Philip Reames71a49672016-12-07 01:03:56 +0000174 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
175 markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
176 return;
177 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000178 if (isa<UndefValue>(V))
Philip Reames71a49672016-12-07 01:03:56 +0000179 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000180
181 assert((!isConstant() || getConstant() != V) &&
182 "Marking constant !constant with same value");
183 assert((!isNotConstant() || getNotConstant() == V) &&
184 "Marking !constant with different value");
185 assert(isUndefined() || isConstant());
186 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000187 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000188 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000189
Philip Reames71a49672016-12-07 01:03:56 +0000190 void markConstantRange(ConstantRange NewR) {
Owen Anderson0f306a42010-08-05 22:59:19 +0000191 if (isConstantRange()) {
192 if (NewR.isEmptySet())
Philip Reames71a49672016-12-07 01:03:56 +0000193 markOverdefined();
194 else {
Philip Reames71a49672016-12-07 01:03:56 +0000195 Range = std::move(NewR);
196 }
197 return;
Owen Anderson0f306a42010-08-05 22:59:19 +0000198 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000199
Owen Anderson0f306a42010-08-05 22:59:19 +0000200 assert(isUndefined());
201 if (NewR.isEmptySet())
Philip Reames71a49672016-12-07 01:03:56 +0000202 markOverdefined();
203 else {
204 Tag = constantrange;
205 Range = std::move(NewR);
206 }
Owen Anderson0f306a42010-08-05 22:59:19 +0000207 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000208
Philip Reamesb2949622016-12-06 02:54:16 +0000209public:
210
Sanjay Patel2a385e22015-01-09 16:47:20 +0000211 /// Merge the specified lattice value into this one, updating this
Chris Lattner19019ea2009-11-11 22:48:44 +0000212 /// one and returning true if anything changed.
Philip Reamesb47a7192016-12-07 00:54:21 +0000213 void mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
214 if (RHS.isUndefined() || isOverdefined())
215 return;
216 if (RHS.isOverdefined()) {
217 markOverdefined();
218 return;
219 }
Chris Lattner19019ea2009-11-11 22:48:44 +0000220
Nick Lewycky11678bd2010-12-15 18:57:18 +0000221 if (isUndefined()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000222 *this = RHS;
223 return;
Chris Lattner22db4b52009-11-12 04:57:13 +0000224 }
225
Nick Lewycky11678bd2010-12-15 18:57:18 +0000226 if (isConstant()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000227 if (RHS.isConstant() && Val == RHS.Val)
228 return;
229 markOverdefined();
230 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000231 }
232
233 if (isNotConstant()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000234 if (RHS.isNotConstant() && Val == RHS.Val)
235 return;
236 markOverdefined();
237 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000238 }
239
240 assert(isConstantRange() && "New LVILattice type?");
Philip Reames02bb6a62016-12-07 04:48:50 +0000241 if (!RHS.isConstantRange()) {
242 // We can get here if we've encountered a constantexpr of integer type
243 // and merge it with a constantrange.
244 markOverdefined();
245 return;
246 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000247 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
248 if (NewR.isFullSet())
Philip Reamesb47a7192016-12-07 00:54:21 +0000249 markOverdefined();
250 else
251 markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000252 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000253};
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000254
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000255} // end anonymous namespace.
256
Chris Lattner19019ea2009-11-11 22:48:44 +0000257namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000258raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
259 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000260raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
261 if (Val.isUndefined())
262 return OS << "undefined";
263 if (Val.isOverdefined())
264 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000265
266 if (Val.isNotConstant())
267 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Davide Italianobd543d02016-05-25 22:29:34 +0000268 if (Val.isConstantRange())
Owen Anderson8afac042010-08-09 20:50:46 +0000269 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
270 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000271 return OS << "constant<" << *Val.getConstant() << '>';
272}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000273}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000274
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000275/// Returns true if this lattice value represents at most one possible value.
276/// This is as precise as any lattice value can get while still representing
277/// reachable code.
Benjamin Kramerc321e532016-06-08 19:09:22 +0000278static bool hasSingleValue(const LVILatticeVal &Val) {
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000279 if (Val.isConstantRange() &&
280 Val.getConstantRange().isSingleElement())
281 // Integer constants are single element ranges
282 return true;
283 if (Val.isConstant())
284 // Non integer constants
285 return true;
286 return false;
287}
288
289/// Combine two sets of facts about the same value into a single set of
290/// facts. Note that this method is not suitable for merging facts along
291/// different paths in a CFG; that's what the mergeIn function is for. This
292/// is for merging facts gathered about the same value at the same location
293/// through two independent means.
294/// Notes:
295/// * This method does not promise to return the most precise possible lattice
296/// value implied by A and B. It is allowed to return any lattice element
297/// which is at least as strong as *either* A or B (unless our facts
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000298/// conflict, see below).
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000299/// * Due to unreachable code, the intersection of two lattice values could be
300/// contradictory. If this happens, we return some valid lattice value so as
301/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
302/// we do not make this guarantee. TODO: This would be a useful enhancement.
303static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
304 // Undefined is the strongest state. It means the value is known to be along
305 // an unreachable path.
306 if (A.isUndefined())
307 return A;
308 if (B.isUndefined())
309 return B;
310
311 // If we gave up for one, but got a useable fact from the other, use it.
312 if (A.isOverdefined())
313 return B;
314 if (B.isOverdefined())
315 return A;
316
317 // Can't get any more precise than constants.
318 if (hasSingleValue(A))
319 return A;
320 if (hasSingleValue(B))
321 return B;
322
323 // Could be either constant range or not constant here.
324 if (!A.isConstantRange() || !B.isConstantRange()) {
325 // TODO: Arbitrary choice, could be improved
326 return A;
327 }
328
329 // Intersect two constant ranges
330 ConstantRange Range =
331 A.getConstantRange().intersectWith(B.getConstantRange());
332 // Note: An empty range is implicitly converted to overdefined internally.
333 // TODO: We could instead use Undefined here since we've proven a conflict
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000334 // and thus know this path must be unreachable.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000335 return LVILatticeVal::getRange(std::move(Range));
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000336}
Philip Reamesd1f829d2016-02-02 21:57:37 +0000337
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000338//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000339// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000340//===----------------------------------------------------------------------===//
341
Chris Lattneraf025d32009-11-15 19:59:49 +0000342namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000343 /// A callback value handle updates the cache when values are erased.
Owen Anderson118ac802011-01-05 21:15:29 +0000344 class LazyValueInfoCache;
David Blaikie774b5842015-08-03 22:30:24 +0000345 struct LVIValueHandle final : public CallbackVH {
Justin Lebar58b377e2016-07-27 22:33:36 +0000346 // Needs to access getValPtr(), which is protected.
347 friend struct DenseMapInfo<LVIValueHandle>;
348
Owen Anderson118ac802011-01-05 21:15:29 +0000349 LazyValueInfoCache *Parent;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000350
Owen Anderson118ac802011-01-05 21:15:29 +0000351 LVIValueHandle(Value *V, LazyValueInfoCache *P)
352 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000353
354 void deleted() override;
355 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000356 deleted();
357 }
358 };
Justin Lebar58b377e2016-07-27 22:33:36 +0000359} // end anonymous namespace
Owen Anderson118ac802011-01-05 21:15:29 +0000360
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000361namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000362 /// This is the cache kept by LazyValueInfo which
Chris Lattneraf025d32009-11-15 19:59:49 +0000363 /// maintains information about queries across the clients' queries.
364 class LazyValueInfoCache {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000365 /// This is all of the cached block information for exactly one Value*.
366 /// The entries are sorted by the BasicBlock* of the
Chris Lattneraf025d32009-11-15 19:59:49 +0000367 /// entries, allowing us to do a lookup with a binary search.
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000368 /// Over-defined lattice values are recorded in OverDefinedCache to reduce
369 /// memory overhead.
Justin Lebar58b377e2016-07-27 22:33:36 +0000370 struct ValueCacheEntryTy {
371 ValueCacheEntryTy(Value *V, LazyValueInfoCache *P) : Handle(V, P) {}
372 LVIValueHandle Handle;
Chandler Carruth6acdca72017-01-24 12:55:57 +0000373 SmallDenseMap<PoisoningVH<BasicBlock>, LVILatticeVal, 4> BlockVals;
Justin Lebar58b377e2016-07-27 22:33:36 +0000374 };
Chris Lattneraf025d32009-11-15 19:59:49 +0000375
Sanjay Patel2a385e22015-01-09 16:47:20 +0000376 /// This is all of the cached information for all values,
Owen Anderson6f060af2011-01-05 23:26:22 +0000377 /// mapped from Value* to key information.
Justin Lebar58b377e2016-07-27 22:33:36 +0000378 DenseMap<Value *, std::unique_ptr<ValueCacheEntryTy>> ValueCache;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000379
Sanjay Patel2a385e22015-01-09 16:47:20 +0000380 /// This tracks, on a per-block basis, the set of values that are
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000381 /// over-defined at the end of that block.
Chandler Carruth6acdca72017-01-24 12:55:57 +0000382 typedef DenseMap<PoisoningVH<BasicBlock>, SmallPtrSet<Value *, 4>>
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000383 OverDefinedCacheTy;
384 OverDefinedCacheTy OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000385
Sanjay Patel2a385e22015-01-09 16:47:20 +0000386 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000387 /// don't spend time removing unused blocks from our caches.
Chandler Carruth6acdca72017-01-24 12:55:57 +0000388 DenseSet<PoisoningVH<BasicBlock> > SeenBlocks;
Benjamin Kramer36647082011-12-03 15:16:45 +0000389
Philip Reames9db79482016-09-12 22:38:44 +0000390 public:
Hans Wennborg45172ac2014-11-25 17:23:05 +0000391 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
392 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000393
394 // Insert over-defined values into their own cache to reduce memory
395 // overhead.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000396 if (Result.isOverdefined())
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000397 OverDefinedCache[BB].insert(Val);
Justin Lebar58b377e2016-07-27 22:33:36 +0000398 else {
399 auto It = ValueCache.find_as(Val);
400 if (It == ValueCache.end()) {
401 ValueCache[Val] = make_unique<ValueCacheEntryTy>(Val, this);
402 It = ValueCache.find_as(Val);
403 assert(It != ValueCache.end() && "Val was just added to the map!");
404 }
405 It->second->BlockVals[BB] = Result;
406 }
Hans Wennborg45172ac2014-11-25 17:23:05 +0000407 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000408
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000409 bool isOverdefined(Value *V, BasicBlock *BB) const {
410 auto ODI = OverDefinedCache.find(BB);
411
412 if (ODI == OverDefinedCache.end())
413 return false;
414
415 return ODI->second.count(V);
416 }
417
Philip Reames9db79482016-09-12 22:38:44 +0000418 bool hasCachedValueInfo(Value *V, BasicBlock *BB) const {
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000419 if (isOverdefined(V, BB))
420 return true;
421
Justin Lebar58b377e2016-07-27 22:33:36 +0000422 auto I = ValueCache.find_as(V);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000423 if (I == ValueCache.end())
424 return false;
425
Justin Lebar58b377e2016-07-27 22:33:36 +0000426 return I->second->BlockVals.count(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000427 }
428
Philip Reames9db79482016-09-12 22:38:44 +0000429 LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) const {
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000430 if (isOverdefined(V, BB))
431 return LVILatticeVal::getOverdefined();
432
Justin Lebar58b377e2016-07-27 22:33:36 +0000433 auto I = ValueCache.find_as(V);
434 if (I == ValueCache.end())
435 return LVILatticeVal();
436 auto BBI = I->second->BlockVals.find(BB);
437 if (BBI == I->second->BlockVals.end())
438 return LVILatticeVal();
439 return BBI->second;
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000440 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000441
Philip Reames92e5e1b2016-09-12 21:46:58 +0000442 /// clear - Empty the cache.
443 void clear() {
444 SeenBlocks.clear();
445 ValueCache.clear();
446 OverDefinedCache.clear();
447 }
448
Philip Reamesb627aec2016-09-12 22:03:36 +0000449 /// Inform the cache that a given value has been deleted.
450 void eraseValue(Value *V);
451
452 /// This is part of the update interface to inform the cache
453 /// that a block has been deleted.
454 void eraseBlock(BasicBlock *BB);
455
Philip Reames9db79482016-09-12 22:38:44 +0000456 /// Updates the cache to remove any influence an overdefined value in
457 /// OldSucc might have (unless also overdefined in NewSucc). This just
458 /// flushes elements from the cache and does not add any.
459 void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
460
Philip Reames92e5e1b2016-09-12 21:46:58 +0000461 friend struct LVIValueHandle;
462 };
Philip Reamesb627aec2016-09-12 22:03:36 +0000463}
Philip Reames92e5e1b2016-09-12 21:46:58 +0000464
Philip Reamesb627aec2016-09-12 22:03:36 +0000465void LazyValueInfoCache::eraseValue(Value *V) {
Chandler Carruth41421df2017-01-26 08:31:54 +0000466 for (auto I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E;) {
467 // Copy and increment the iterator immediately so we can erase behind
468 // ourselves.
469 auto Iter = I++;
470 SmallPtrSetImpl<Value *> &ValueSet = Iter->second;
Philip Reamesfdbb05b2016-12-30 22:09:10 +0000471 ValueSet.erase(V);
Philip Reamesb627aec2016-09-12 22:03:36 +0000472 if (ValueSet.empty())
Chandler Carruth41421df2017-01-26 08:31:54 +0000473 OverDefinedCache.erase(Iter);
Philip Reamesb627aec2016-09-12 22:03:36 +0000474 }
Philip Reamesb627aec2016-09-12 22:03:36 +0000475
476 ValueCache.erase(V);
477}
478
479void LVIValueHandle::deleted() {
480 // This erasure deallocates *this, so it MUST happen after we're done
481 // using any and all members of *this.
482 Parent->eraseValue(*this);
483}
484
485void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
486 // Shortcut if we have never seen this block.
Chandler Carruth6acdca72017-01-24 12:55:57 +0000487 DenseSet<PoisoningVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
Philip Reamesb627aec2016-09-12 22:03:36 +0000488 if (I == SeenBlocks.end())
489 return;
490 SeenBlocks.erase(I);
491
492 auto ODI = OverDefinedCache.find(BB);
493 if (ODI != OverDefinedCache.end())
494 OverDefinedCache.erase(ODI);
495
496 for (auto &I : ValueCache)
497 I.second->BlockVals.erase(BB);
498}
499
Philip Reames9db79482016-09-12 22:38:44 +0000500void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
501 BasicBlock *NewSucc) {
502 // When an edge in the graph has been threaded, values that we could not
503 // determine a value for before (i.e. were marked overdefined) may be
504 // possible to solve now. We do NOT try to proactively update these values.
505 // Instead, we clear their entries from the cache, and allow lazy updating to
506 // recompute them when needed.
507
508 // The updating process is fairly simple: we need to drop cached info
509 // for all values that were marked overdefined in OldSucc, and for those same
510 // values in any successor of OldSucc (except NewSucc) in which they were
511 // also marked overdefined.
512 std::vector<BasicBlock*> worklist;
513 worklist.push_back(OldSucc);
514
515 auto I = OverDefinedCache.find(OldSucc);
516 if (I == OverDefinedCache.end())
517 return; // Nothing to process here.
518 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
519
520 // Use a worklist to perform a depth-first search of OldSucc's successors.
521 // NOTE: We do not need a visited list since any blocks we have already
522 // visited will have had their overdefined markers cleared already, and we
523 // thus won't loop to their successors.
524 while (!worklist.empty()) {
525 BasicBlock *ToUpdate = worklist.back();
526 worklist.pop_back();
527
528 // Skip blocks only accessible through NewSucc.
529 if (ToUpdate == NewSucc) continue;
530
Philip Reames1e48efc2016-12-30 17:56:47 +0000531 // If a value was marked overdefined in OldSucc, and is here too...
532 auto OI = OverDefinedCache.find(ToUpdate);
533 if (OI == OverDefinedCache.end())
534 continue;
535 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
536
Philip Reames9db79482016-09-12 22:38:44 +0000537 bool changed = false;
538 for (Value *V : ValsToClear) {
Philip Reamesfdbb05b2016-12-30 22:09:10 +0000539 if (!ValueSet.erase(V))
Philip Reames9db79482016-09-12 22:38:44 +0000540 continue;
541
Philip Reames9db79482016-09-12 22:38:44 +0000542 // If we removed anything, then we potentially need to update
543 // blocks successors too.
544 changed = true;
Philip Reames1e48efc2016-12-30 17:56:47 +0000545
546 if (ValueSet.empty()) {
547 OverDefinedCache.erase(OI);
548 break;
549 }
Philip Reames9db79482016-09-12 22:38:44 +0000550 }
551
552 if (!changed) continue;
553
554 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
555 }
556}
557
Philip Reamesb627aec2016-09-12 22:03:36 +0000558namespace {
Philip Reames92e5e1b2016-09-12 21:46:58 +0000559 // The actual implementation of the lazy analysis and update. Note that the
560 // inheritance from LazyValueInfoCache is intended to be temporary while
561 // splitting the code and then transitioning to a has-a relationship.
Philip Reames9db79482016-09-12 22:38:44 +0000562 class LazyValueInfoImpl {
563
564 /// Cached results from previous queries
565 LazyValueInfoCache TheCache;
Philip Reames92e5e1b2016-09-12 21:46:58 +0000566
567 /// This stack holds the state of the value solver during a query.
568 /// It basically emulates the callstack of the naive
569 /// recursive value lookup process.
Daniel Berlin9c92a462017-02-08 15:22:52 +0000570 SmallVector<std::pair<BasicBlock*, Value*>, 8> BlockValueStack;
Philip Reames92e5e1b2016-09-12 21:46:58 +0000571
572 /// Keeps track of which block-value pairs are in BlockValueStack.
573 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
574
575 /// Push BV onto BlockValueStack unless it's already in there.
576 /// Returns true on success.
577 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
578 if (!BlockValueSet.insert(BV).second)
579 return false; // It's already in the stack.
580
581 DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
582 << "\n");
Daniel Berlin9c92a462017-02-08 15:22:52 +0000583 BlockValueStack.push_back(BV);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000584 return true;
585 }
586
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000587 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
Philip Reames92e5e1b2016-09-12 21:46:58 +0000588 const DataLayout &DL; ///< A mandatory DataLayout
589 DominatorTree *DT; ///< An optional DT pointer.
590
591 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
592 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
593 LVILatticeVal &Result, Instruction *CxtI = nullptr);
594 bool hasBlockValue(Value *Val, BasicBlock *BB);
595
596 // These methods process one work item and may add more. A false value
597 // returned means that the work item was not completely processed and must
598 // be revisited after going through the new items.
599 bool solveBlockValue(Value *Val, BasicBlock *BB);
Philip Reames05c435e2016-12-06 03:22:03 +0000600 bool solveBlockValueImpl(LVILatticeVal &Res, Value *Val, BasicBlock *BB);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000601 bool solveBlockValueNonLocal(LVILatticeVal &BBLV, Value *Val, BasicBlock *BB);
602 bool solveBlockValuePHINode(LVILatticeVal &BBLV, PHINode *PN, BasicBlock *BB);
603 bool solveBlockValueSelect(LVILatticeVal &BBLV, SelectInst *S,
604 BasicBlock *BB);
605 bool solveBlockValueBinaryOp(LVILatticeVal &BBLV, Instruction *BBI,
606 BasicBlock *BB);
607 bool solveBlockValueCast(LVILatticeVal &BBLV, Instruction *BBI,
608 BasicBlock *BB);
609 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
610 LVILatticeVal &BBLV,
611 Instruction *BBI);
612
613 void solve();
614
615 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000616 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000617 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000618 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
619 Instruction *CxtI = nullptr);
620
Sanjay Patel2a385e22015-01-09 16:47:20 +0000621 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000622 /// value for the specified Value* at the specified instruction (generally
623 /// from an assume intrinsic).
624 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000625
Sanjay Patel2a385e22015-01-09 16:47:20 +0000626 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000627 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000628 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
629 Instruction *CxtI = nullptr);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000630
Philip Reames9db79482016-09-12 22:38:44 +0000631 /// Complete flush all previously computed values
632 void clear() {
633 TheCache.clear();
634 }
635
636 /// This is part of the update interface to inform the cache
637 /// that a block has been deleted.
638 void eraseBlock(BasicBlock *BB) {
639 TheCache.eraseBlock(BB);
640 }
641
Sanjay Patel2a385e22015-01-09 16:47:20 +0000642 /// This is the update interface to inform the cache that an edge from
643 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000644 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000645
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000646 LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
647 DominatorTree *DT = nullptr)
648 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000649 };
650} // end anonymous namespace
651
Philip Reames92e5e1b2016-09-12 21:46:58 +0000652void LazyValueInfoImpl::solve() {
Daniel Berlin9c92a462017-02-08 15:22:52 +0000653 SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack(
654 BlockValueStack.begin(), BlockValueStack.end());
655
656 unsigned processedCount = 0;
Owen Anderson6f060af2011-01-05 23:26:22 +0000657 while (!BlockValueStack.empty()) {
Daniel Berlin9c92a462017-02-08 15:22:52 +0000658 processedCount++;
659 // Abort if we have to process too many values to get a result for this one.
660 // Because of the design of the overdefined cache currently being per-block
661 // to avoid naming-related issues (IE it wants to try to give different
662 // results for the same name in different blocks), overdefined results don't
663 // get cached globally, which in turn means we will often try to rediscover
664 // the same overdefined result again and again. Once something like
665 // PredicateInfo is used in LVI or CVP, we should be able to make the
666 // overdefined cache global, and remove this throttle.
667 if (processedCount > MaxProcessedPerValue) {
668 DEBUG(dbgs() << "Giving up on stack because we are getting too deep\n");
669 // Fill in the original values
670 while (!StartingStack.empty()) {
671 std::pair<BasicBlock *, Value *> &e = StartingStack.back();
672 TheCache.insertResult(e.second, e.first,
673 LVILatticeVal::getOverdefined());
674 StartingStack.pop_back();
675 }
676 BlockValueSet.clear();
677 BlockValueStack.clear();
678 return;
679 }
Vitaly Buka9987d982017-02-09 09:28:05 +0000680 std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000681 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
682
Nuno Lopese6e04902012-06-28 01:16:18 +0000683 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000684 // The work item was completely processed.
Daniel Berlin9c92a462017-02-08 15:22:52 +0000685 assert(BlockValueStack.back() == e && "Nothing should have been pushed!");
Philip Reames9db79482016-09-12 22:38:44 +0000686 assert(TheCache.hasCachedValueInfo(e.second, e.first) &&
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000687 "Result should be in cache!");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000688
Philip Reames44456b82016-02-02 03:15:40 +0000689 DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
Philip Reames9db79482016-09-12 22:38:44 +0000690 << " = " << TheCache.getCachedValueInfo(e.second, e.first) << "\n");
Philip Reames44456b82016-02-02 03:15:40 +0000691
Daniel Berlin9c92a462017-02-08 15:22:52 +0000692 BlockValueStack.pop_back();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000693 BlockValueSet.erase(e);
694 } else {
695 // More work needs to be done before revisiting.
Daniel Berlin9c92a462017-02-08 15:22:52 +0000696 assert(BlockValueStack.back() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000697 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000698 }
699}
700
Philip Reames92e5e1b2016-09-12 21:46:58 +0000701bool LazyValueInfoImpl::hasBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000702 // If already a constant, there is nothing to compute.
703 if (isa<Constant>(Val))
704 return true;
705
Philip Reames9db79482016-09-12 22:38:44 +0000706 return TheCache.hasCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000707}
708
Philip Reames92e5e1b2016-09-12 21:46:58 +0000709LVILatticeVal LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000710 // If already a constant, there is nothing to compute.
711 if (Constant *VC = dyn_cast<Constant>(Val))
712 return LVILatticeVal::get(VC);
713
Philip Reames9db79482016-09-12 22:38:44 +0000714 return TheCache.getCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000715}
716
Philip Reameseb3e9da2015-10-29 03:57:17 +0000717static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
718 switch (BBI->getOpcode()) {
719 default: break;
720 case Instruction::Load:
721 case Instruction::Call:
722 case Instruction::Invoke:
NAKAMURA Takumibd072a92016-07-25 00:59:46 +0000723 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
Philip Reames70efccd2015-10-29 04:21:49 +0000724 if (isa<IntegerType>(BBI->getType())) {
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000725 return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
Philip Reameseb3e9da2015-10-29 03:57:17 +0000726 }
727 break;
728 };
Philip Reamesd1f829d2016-02-02 21:57:37 +0000729 // Nothing known - will be intersected with other facts
730 return LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +0000731}
732
Philip Reames92e5e1b2016-09-12 21:46:58 +0000733bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000734 if (isa<Constant>(Val))
735 return true;
736
Philip Reames9db79482016-09-12 22:38:44 +0000737 if (TheCache.hasCachedValueInfo(Val, BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000738 // If we have a cached value, use that.
739 DEBUG(dbgs() << " reuse BB '" << BB->getName()
Philip Reames9db79482016-09-12 22:38:44 +0000740 << "' val=" << TheCache.getCachedValueInfo(Val, BB) << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000741
Hans Wennborg45172ac2014-11-25 17:23:05 +0000742 // Since we're reusing a cached value, we don't need to update the
743 // OverDefinedCache. The cache will have been properly updated whenever the
744 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000745 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000746 }
747
Hans Wennborg45172ac2014-11-25 17:23:05 +0000748 // Hold off inserting this value into the Cache in case we have to return
749 // false and come back later.
750 LVILatticeVal Res;
Philip Reames05c435e2016-12-06 03:22:03 +0000751 if (!solveBlockValueImpl(Res, Val, BB))
752 // Work pushed, will revisit
753 return false;
754
755 TheCache.insertResult(Val, BB, Res);
756 return true;
757}
758
759bool LazyValueInfoImpl::solveBlockValueImpl(LVILatticeVal &Res,
760 Value *Val, BasicBlock *BB) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000761
Chris Lattneraf025d32009-11-15 19:59:49 +0000762 Instruction *BBI = dyn_cast<Instruction>(Val);
Philip Reames05c435e2016-12-06 03:22:03 +0000763 if (!BBI || BBI->getParent() != BB)
764 return solveBlockValueNonLocal(Res, Val, BB);
Chris Lattner2c708562009-11-15 20:00:52 +0000765
Philip Reames05c435e2016-12-06 03:22:03 +0000766 if (PHINode *PN = dyn_cast<PHINode>(BBI))
767 return solveBlockValuePHINode(Res, PN, BB);
Owen Anderson80d19f02010-08-18 21:11:37 +0000768
Philip Reames05c435e2016-12-06 03:22:03 +0000769 if (auto *SI = dyn_cast<SelectInst>(BBI))
770 return solveBlockValueSelect(Res, SI, BB);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000771
Philip Reames2ab964e2016-04-27 01:02:25 +0000772 // If this value is a nonnull pointer, record it's range and bailout. Note
773 // that for all other pointer typed values, we terminate the search at the
774 // definition. We could easily extend this to look through geps, bitcasts,
775 // and the like to prove non-nullness, but it's not clear that's worth it
776 // compile time wise. The context-insensative value walk done inside
777 // isKnownNonNull gets most of the profitable cases at much less expense.
778 // This does mean that we have a sensativity to where the defining
779 // instruction is placed, even if it could legally be hoisted much higher.
780 // That is unfortunate.
Igor Laevsky0fa48192015-09-18 13:01:48 +0000781 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
782 if (PT && isKnownNonNull(BBI)) {
783 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
Hans Wennborg45172ac2014-11-25 17:23:05 +0000784 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000785 }
Davide Italianobd543d02016-05-25 22:29:34 +0000786 if (BBI->getType()->isIntegerTy()) {
Philip Reames05c435e2016-12-06 03:22:03 +0000787 if (isa<CastInst>(BBI))
788 return solveBlockValueCast(Res, BBI, BB);
789
Philip Reames2ab964e2016-04-27 01:02:25 +0000790 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
Philip Reames05c435e2016-12-06 03:22:03 +0000791 if (BO && isa<ConstantInt>(BO->getOperand(1)))
792 return solveBlockValueBinaryOp(Res, BBI, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000793 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000794
Philip Reamesa0c9f6e2016-03-04 22:27:39 +0000795 DEBUG(dbgs() << " compute BB '" << BB->getName()
796 << "' - unknown inst def found.\n");
797 Res = getFromRangeMetadata(BBI);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000798 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000799}
800
801static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
802 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
803 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000804 GetUnderlyingObject(L->getPointerOperand(),
805 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000806 }
807 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
808 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000809 GetUnderlyingObject(S->getPointerOperand(),
810 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000811 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000812 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
813 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000814
815 // FIXME: check whether it has a valuerange that excludes zero?
816 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
817 if (!Len || Len->isZero()) return false;
818
Eli Friedman7a5fc692011-05-31 20:40:16 +0000819 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000820 if (GetUnderlyingObject(MI->getRawDest(),
821 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000822 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000823 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000824 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000825 if (GetUnderlyingObject(MTI->getRawSource(),
826 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000827 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000828 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000829 return false;
830}
831
Philip Reames3f83dbe2016-04-27 00:30:55 +0000832/// Return true if the allocation associated with Val is ever dereferenced
833/// within the given basic block. This establishes the fact Val is not null,
834/// but does not imply that the memory at Val is dereferenceable. (Val may
835/// point off the end of the dereferenceable part of the object.)
836static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
837 assert(Val->getType()->isPointerTy());
838
839 const DataLayout &DL = BB->getModule()->getDataLayout();
840 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
841 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
842 // inside InstructionDereferencesPointer either.
843 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
844 for (Instruction &I : *BB)
845 if (InstructionDereferencesPointer(&I, UnderlyingVal))
846 return true;
847 return false;
848}
849
Philip Reames92e5e1b2016-09-12 21:46:58 +0000850bool LazyValueInfoImpl::solveBlockValueNonLocal(LVILatticeVal &BBLV,
Owen Anderson64c2c572010-12-20 18:18:16 +0000851 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000852 LVILatticeVal Result; // Start Undefined.
853
Nick Lewycky55a700b2010-12-18 01:00:40 +0000854 // If this is the entry block, we must be asking about an argument. The
855 // value is overdefined.
856 if (BB == &BB->getParent()->getEntryBlock()) {
857 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
Philip Reames3f83dbe2016-04-27 00:30:55 +0000858 // Bofore giving up, see if we can prove the pointer non-null local to
859 // this particular block.
860 if (Val->getType()->isPointerTy() &&
861 (isKnownNonNull(Val) || isObjectDereferencedInBlock(Val, BB))) {
Chris Lattner229907c2011-07-18 04:54:35 +0000862 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000863 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
864 } else {
Philip Reames1baaef12016-12-06 03:01:08 +0000865 Result = LVILatticeVal::getOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000866 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000867 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000868 return true;
869 }
870
871 // Loop over all of our predecessors, merging what we know from them into
Philip Reamesc80bd042017-02-07 00:25:24 +0000872 // result. If we encounter an unexplored predecessor, we eagerly explore it
873 // in a depth first manner. In practice, this has the effect of discovering
874 // paths we can't analyze eagerly without spending compile times analyzing
875 // other paths. This heuristic benefits from the fact that predecessors are
876 // frequently arranged such that dominating ones come first and we quickly
877 // find a path to function entry. TODO: We should consider explicitly
878 // canonicalizing to make this true rather than relying on this happy
879 // accident.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000880 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000881 LVILatticeVal EdgeResult;
Philip Reamesc80bd042017-02-07 00:25:24 +0000882 if (!getEdgeValue(Val, *PI, BB, EdgeResult))
883 // Explore that input, then return here
884 return false;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000885
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000886 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000887
888 // If we hit overdefined, exit early. The BlockVals entry is already set
889 // to overdefined.
890 if (Result.isOverdefined()) {
891 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000892 << "' - overdefined because of pred (non local).\n");
Artur Pilipenkoadcd01f2016-08-09 09:14:29 +0000893 // Before giving up, see if we can prove the pointer non-null local to
Philip Reames3f83dbe2016-04-27 00:30:55 +0000894 // this particular block.
895 if (Val->getType()->isPointerTy() &&
896 isObjectDereferencedInBlock(Val, BB)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000897 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000898 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
899 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000900
Owen Anderson64c2c572010-12-20 18:18:16 +0000901 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000902 return true;
903 }
904 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000905
906 // Return the merged value, which is more precise than 'overdefined'.
907 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000908 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000909 return true;
910}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000911
Philip Reames92e5e1b2016-09-12 21:46:58 +0000912bool LazyValueInfoImpl::solveBlockValuePHINode(LVILatticeVal &BBLV,
Owen Anderson64c2c572010-12-20 18:18:16 +0000913 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000914 LVILatticeVal Result; // Start Undefined.
915
916 // Loop over all of our predecessors, merging what we know from them into
Philip Reamesc80bd042017-02-07 00:25:24 +0000917 // result. See the comment about the chosen traversal order in
918 // solveBlockValueNonLocal; the same reasoning applies here.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000919 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
920 BasicBlock *PhiBB = PN->getIncomingBlock(i);
921 Value *PhiVal = PN->getIncomingValue(i);
922 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000923 // Note that we can provide PN as the context value to getEdgeValue, even
924 // though the results will be cached, because PN is the value being used as
925 // the cache key in the caller.
Philip Reamesc80bd042017-02-07 00:25:24 +0000926 if (!getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN))
927 // Explore that input, then return here
928 return false;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000929
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000930 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000931
932 // If we hit overdefined, exit early. The BlockVals entry is already set
933 // to overdefined.
934 if (Result.isOverdefined()) {
935 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000936 << "' - overdefined because of pred (local).\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000937
Owen Anderson64c2c572010-12-20 18:18:16 +0000938 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000939 return true;
940 }
941 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000942
943 // Return the merged value, which is more precise than 'overdefined'.
944 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000945 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000946 return true;
947}
948
Artur Pilipenko933c07a2016-08-10 13:38:07 +0000949static LVILatticeVal getValueFromCondition(Value *Val, Value *Cond,
950 bool isTrueDest = true);
Hal Finkel7e184492014-09-07 20:29:59 +0000951
Philip Reamesd1f829d2016-02-02 21:57:37 +0000952// If we can determine a constraint on the value given conditions assumed by
953// the program, intersect those constraints with BBLV
Philip Reames92e5e1b2016-09-12 21:46:58 +0000954void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000955 Value *Val, LVILatticeVal &BBLV, Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000956 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
957 if (!BBI)
958 return;
959
Hal Finkel8a9a7832017-01-11 13:24:24 +0000960 for (auto &AssumeVH : AC->assumptionsFor(Val)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000961 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000962 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000963 auto *I = cast<CallInst>(AssumeVH);
964 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +0000965 continue;
966
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000967 BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
Hal Finkel7e184492014-09-07 20:29:59 +0000968 }
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000969
970 // If guards are not used in the module, don't spend time looking for them
971 auto *GuardDecl = BBI->getModule()->getFunction(
972 Intrinsic::getName(Intrinsic::experimental_guard));
973 if (!GuardDecl || GuardDecl->use_empty())
974 return;
975
Artur Pilipenko47dc0982016-10-21 15:02:21 +0000976 for (Instruction &I : make_range(BBI->getIterator().getReverse(),
977 BBI->getParent()->rend())) {
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000978 Value *Cond = nullptr;
Artur Pilipenko47dc0982016-10-21 15:02:21 +0000979 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
980 BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000981 }
Hal Finkel7e184492014-09-07 20:29:59 +0000982}
983
Philip Reames92e5e1b2016-09-12 21:46:58 +0000984bool LazyValueInfoImpl::solveBlockValueSelect(LVILatticeVal &BBLV,
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000985 SelectInst *SI, BasicBlock *BB) {
986
987 // Recurse on our inputs if needed
988 if (!hasBlockValue(SI->getTrueValue(), BB)) {
989 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
990 return false;
Philip Reames1baaef12016-12-06 03:01:08 +0000991 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000992 return true;
993 }
994 LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
995 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
996 // extra slots in the table if we can.
997 if (TrueVal.isOverdefined()) {
Philip Reames1baaef12016-12-06 03:01:08 +0000998 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000999 return true;
1000 }
1001
1002 if (!hasBlockValue(SI->getFalseValue(), BB)) {
1003 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
1004 return false;
Philip Reames1baaef12016-12-06 03:01:08 +00001005 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001006 return true;
1007 }
1008 LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
1009 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
1010 // extra slots in the table if we can.
1011 if (FalseVal.isOverdefined()) {
Philip Reames1baaef12016-12-06 03:01:08 +00001012 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001013 return true;
1014 }
1015
Philip Reamesadf0e352016-02-26 22:53:59 +00001016 if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
1017 ConstantRange TrueCR = TrueVal.getConstantRange();
1018 ConstantRange FalseCR = FalseVal.getConstantRange();
1019 Value *LHS = nullptr;
1020 Value *RHS = nullptr;
1021 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
1022 // Is this a min specifically of our two inputs? (Avoid the risk of
1023 // ValueTracking getting smarter looking back past our immediate inputs.)
1024 if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
1025 LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
Philip Reamesb2949622016-12-06 02:54:16 +00001026 ConstantRange ResultCR = [&]() {
1027 switch (SPR.Flavor) {
1028 default:
1029 llvm_unreachable("unexpected minmax type!");
1030 case SPF_SMIN: /// Signed minimum
1031 return TrueCR.smin(FalseCR);
1032 case SPF_UMIN: /// Unsigned minimum
1033 return TrueCR.umin(FalseCR);
1034 case SPF_SMAX: /// Signed maximum
1035 return TrueCR.smax(FalseCR);
1036 case SPF_UMAX: /// Unsigned maximum
1037 return TrueCR.umax(FalseCR);
1038 };
1039 }();
1040 BBLV = LVILatticeVal::getRange(ResultCR);
1041 return true;
Philip Reamesadf0e352016-02-26 22:53:59 +00001042 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001043
Philip Reamesadf0e352016-02-26 22:53:59 +00001044 // TODO: ABS, NABS from the SelectPatternResult
1045 }
1046
Philip Reames854a84c2016-02-12 00:09:18 +00001047 // Can we constrain the facts about the true and false values by using the
1048 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
1049 // TODO: We could potentially refine an overdefined true value above.
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001050 Value *Cond = SI->getCondition();
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001051 TrueVal = intersect(TrueVal,
1052 getValueFromCondition(SI->getTrueValue(), Cond, true));
1053 FalseVal = intersect(FalseVal,
1054 getValueFromCondition(SI->getFalseValue(), Cond, false));
Philip Reames854a84c2016-02-12 00:09:18 +00001055
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001056 // Handle clamp idioms such as:
1057 // %24 = constantrange<0, 17>
1058 // %39 = icmp eq i32 %24, 0
1059 // %40 = add i32 %24, -1
1060 // %siv.next = select i1 %39, i32 16, i32 %40
1061 // %siv.next = constantrange<0, 17> not <-1, 17>
1062 // In general, this can handle any clamp idiom which tests the edge
1063 // condition via an equality or inequality.
1064 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
Philip Reamesadf0e352016-02-26 22:53:59 +00001065 ICmpInst::Predicate Pred = ICI->getPredicate();
1066 Value *A = ICI->getOperand(0);
1067 if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
1068 auto addConstants = [](ConstantInt *A, ConstantInt *B) {
1069 assert(A->getType() == B->getType());
1070 return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
1071 };
1072 // See if either input is A + C2, subject to the constraint from the
1073 // condition that A != C when that input is used. We can assume that
1074 // that input doesn't include C + C2.
1075 ConstantInt *CIAdded;
1076 switch (Pred) {
Philip Reames70b39182016-02-27 05:18:30 +00001077 default: break;
Philip Reamesadf0e352016-02-26 22:53:59 +00001078 case ICmpInst::ICMP_EQ:
1079 if (match(SI->getFalseValue(), m_Add(m_Specific(A),
1080 m_ConstantInt(CIAdded)))) {
1081 auto ResNot = addConstants(CIBase, CIAdded);
1082 FalseVal = intersect(FalseVal,
1083 LVILatticeVal::getNot(ResNot));
1084 }
1085 break;
1086 case ICmpInst::ICMP_NE:
1087 if (match(SI->getTrueValue(), m_Add(m_Specific(A),
1088 m_ConstantInt(CIAdded)))) {
1089 auto ResNot = addConstants(CIBase, CIAdded);
1090 TrueVal = intersect(TrueVal,
1091 LVILatticeVal::getNot(ResNot));
1092 }
1093 break;
1094 };
1095 }
1096 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001097
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001098 LVILatticeVal Result; // Start Undefined.
1099 Result.mergeIn(TrueVal, DL);
1100 Result.mergeIn(FalseVal, DL);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001101 BBLV = Result;
1102 return true;
1103}
1104
Philip Reames92e5e1b2016-09-12 21:46:58 +00001105bool LazyValueInfoImpl::solveBlockValueCast(LVILatticeVal &BBLV,
Philip Reames66715772016-04-25 18:30:31 +00001106 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001107 BasicBlock *BB) {
1108 if (!BBI->getOperand(0)->getType()->isSized()) {
1109 // Without knowing how wide the input is, we can't analyze it in any useful
1110 // way.
Philip Reames1baaef12016-12-06 03:01:08 +00001111 BBLV = LVILatticeVal::getOverdefined();
Philip Reamese5030e82016-04-26 22:52:30 +00001112 return true;
1113 }
Philip Reamesf105db42016-04-26 23:27:33 +00001114
1115 // Filter out casts we don't know how to reason about before attempting to
1116 // recurse on our operand. This can cut a long search short if we know we're
1117 // not going to be able to get any useful information anways.
1118 switch (BBI->getOpcode()) {
1119 case Instruction::Trunc:
1120 case Instruction::SExt:
1121 case Instruction::ZExt:
1122 case Instruction::BitCast:
1123 break;
1124 default:
1125 // Unhandled instructions are overdefined.
1126 DEBUG(dbgs() << " compute BB '" << BB->getName()
1127 << "' - overdefined (unknown cast).\n");
Philip Reames1baaef12016-12-06 03:01:08 +00001128 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesf105db42016-04-26 23:27:33 +00001129 return true;
1130 }
1131
Philip Reames38c87c22016-04-26 21:48:16 +00001132 // Figure out the range of the LHS. If that fails, we still apply the
1133 // transfer rule on the full set since we may be able to locally infer
1134 // interesting facts.
1135 if (!hasBlockValue(BBI->getOperand(0), BB))
Hans Wennborg45172ac2014-11-25 17:23:05 +00001136 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
Philip Reames38c87c22016-04-26 21:48:16 +00001137 // More work to do before applying this transfer rule.
Hans Wennborg45172ac2014-11-25 17:23:05 +00001138 return false;
Philip Reames38c87c22016-04-26 21:48:16 +00001139
1140 const unsigned OperandBitWidth =
Philip Reamese5030e82016-04-26 22:52:30 +00001141 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
Philip Reames38c87c22016-04-26 21:48:16 +00001142 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1143 if (hasBlockValue(BBI->getOperand(0), BB)) {
1144 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001145 intersectAssumeOrGuardBlockValueConstantRange(BBI->getOperand(0), LHSVal,
1146 BBI);
Philip Reames38c87c22016-04-26 21:48:16 +00001147 if (LHSVal.isConstantRange())
1148 LHSRange = LHSVal.getConstantRange();
Nick Lewycky55a700b2010-12-18 01:00:40 +00001149 }
1150
Philip Reames38c87c22016-04-26 21:48:16 +00001151 const unsigned ResultBitWidth =
1152 cast<IntegerType>(BBI->getType())->getBitWidth();
Philip Reames66715772016-04-25 18:30:31 +00001153
1154 // NOTE: We're currently limited by the set of operations that ConstantRange
1155 // can evaluate symbolically. Enhancing that set will allows us to analyze
1156 // more definitions.
Philip Reames4d00af12016-12-01 20:08:47 +00001157 auto CastOp = (Instruction::CastOps) BBI->getOpcode();
Philip Reames0e613f72016-12-06 02:36:58 +00001158 BBLV = LVILatticeVal::getRange(LHSRange.castOp(CastOp, ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001159 return true;
1160}
1161
Philip Reames92e5e1b2016-09-12 21:46:58 +00001162bool LazyValueInfoImpl::solveBlockValueBinaryOp(LVILatticeVal &BBLV,
Philip Reames66715772016-04-25 18:30:31 +00001163 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001164 BasicBlock *BB) {
Philip Reames66715772016-04-25 18:30:31 +00001165
Philip Reames053c2a62016-04-26 23:10:35 +00001166 assert(BBI->getOperand(0)->getType()->isSized() &&
1167 "all operands to binary operators are sized");
Philip Reamesf105db42016-04-26 23:27:33 +00001168
1169 // Filter out operators we don't know how to reason about before attempting to
1170 // recurse on our operand(s). This can cut a long search short if we know
1171 // we're not going to be able to get any useful information anways.
1172 switch (BBI->getOpcode()) {
1173 case Instruction::Add:
1174 case Instruction::Sub:
1175 case Instruction::Mul:
1176 case Instruction::UDiv:
1177 case Instruction::Shl:
1178 case Instruction::LShr:
1179 case Instruction::And:
1180 case Instruction::Or:
1181 // continue into the code below
1182 break;
1183 default:
1184 // Unhandled instructions are overdefined.
1185 DEBUG(dbgs() << " compute BB '" << BB->getName()
1186 << "' - overdefined (unknown binary operator).\n");
Philip Reames1baaef12016-12-06 03:01:08 +00001187 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesf105db42016-04-26 23:27:33 +00001188 return true;
1189 };
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001190
Philip Reames053c2a62016-04-26 23:10:35 +00001191 // Figure out the range of the LHS. If that fails, use a conservative range,
1192 // but apply the transfer rule anyways. This lets us pick up facts from
1193 // expressions like "and i32 (call i32 @foo()), 32"
1194 if (!hasBlockValue(BBI->getOperand(0), BB))
1195 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
1196 // More work to do before applying this transfer rule.
1197 return false;
1198
1199 const unsigned OperandBitWidth =
1200 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
1201 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1202 if (hasBlockValue(BBI->getOperand(0), BB)) {
1203 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001204 intersectAssumeOrGuardBlockValueConstantRange(BBI->getOperand(0), LHSVal,
1205 BBI);
Philip Reames053c2a62016-04-26 23:10:35 +00001206 if (LHSVal.isConstantRange())
1207 LHSRange = LHSVal.getConstantRange();
Philip Reames66715772016-04-25 18:30:31 +00001208 }
Philip Reames66715772016-04-25 18:30:31 +00001209
1210 ConstantInt *RHS = cast<ConstantInt>(BBI->getOperand(1));
1211 ConstantRange RHSRange = ConstantRange(RHS->getValue());
1212
Owen Anderson80d19f02010-08-18 21:11:37 +00001213 // NOTE: We're currently limited by the set of operations that ConstantRange
1214 // can evaluate symbolically. Enhancing that set will allows us to analyze
1215 // more definitions.
Philip Reames4d00af12016-12-01 20:08:47 +00001216 auto BinOp = (Instruction::BinaryOps) BBI->getOpcode();
Philip Reames0e613f72016-12-06 02:36:58 +00001217 BBLV = LVILatticeVal::getRange(LHSRange.binaryOp(BinOp, RHSRange));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001218 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +00001219}
1220
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001221static LVILatticeVal getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1222 bool isTrueDest) {
Artur Pilipenko21472912016-08-08 14:08:37 +00001223 Value *LHS = ICI->getOperand(0);
1224 Value *RHS = ICI->getOperand(1);
1225 CmpInst::Predicate Predicate = ICI->getPredicate();
1226
1227 if (isa<Constant>(RHS)) {
1228 if (ICI->isEquality() && LHS == Val) {
Hal Finkel7e184492014-09-07 20:29:59 +00001229 // We know that V has the RHS constant if this is a true SETEQ or
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001230 // false SETNE.
Artur Pilipenko21472912016-08-08 14:08:37 +00001231 if (isTrueDest == (Predicate == ICmpInst::ICMP_EQ))
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001232 return LVILatticeVal::get(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001233 else
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001234 return LVILatticeVal::getNot(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001235 }
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001236 }
Hal Finkel7e184492014-09-07 20:29:59 +00001237
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001238 if (!Val->getType()->isIntegerTy())
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001239 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001240
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001241 // Use ConstantRange::makeAllowedICmpRegion in order to determine the possible
1242 // range of Val guaranteed by the condition. Recognize comparisons in the from
1243 // of:
1244 // icmp <pred> Val, ...
Artur Pilipenko63562582016-08-12 10:05:11 +00001245 // icmp <pred> (add Val, Offset), ...
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001246 // The latter is the range checking idiom that InstCombine produces. Subtract
1247 // the offset from the allowed range for RHS in this case.
Artur Pilipenkoeed618d2016-08-08 14:33:11 +00001248
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001249 // Val or (add Val, Offset) can be on either hand of the comparison
1250 if (LHS != Val && !match(LHS, m_Add(m_Specific(Val), m_ConstantInt()))) {
1251 std::swap(LHS, RHS);
1252 Predicate = CmpInst::getSwappedPredicate(Predicate);
1253 }
Hal Finkel7e184492014-09-07 20:29:59 +00001254
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001255 ConstantInt *Offset = nullptr;
Artur Pilipenko63562582016-08-12 10:05:11 +00001256 if (LHS != Val)
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001257 match(LHS, m_Add(m_Specific(Val), m_ConstantInt(Offset)));
Hal Finkel7e184492014-09-07 20:29:59 +00001258
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001259 if (LHS == Val || Offset) {
1260 // Calculate the range of values that are allowed by the comparison
1261 ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1262 /*isFullSet=*/true);
1263 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1264 RHSRange = ConstantRange(CI->getValue());
Artur Pilipenko6669f252016-08-12 10:14:11 +00001265 else if (Instruction *I = dyn_cast<Instruction>(RHS))
1266 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1267 RHSRange = getConstantRangeFromMetadata(*Ranges);
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001268
1269 // If we're interested in the false dest, invert the condition
1270 CmpInst::Predicate Pred =
1271 isTrueDest ? Predicate : CmpInst::getInversePredicate(Predicate);
1272 ConstantRange TrueValues =
1273 ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1274
1275 if (Offset) // Apply the offset from above.
1276 TrueValues = TrueValues.subtract(Offset->getValue());
1277
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001278 return LVILatticeVal::getRange(std::move(TrueValues));
Hal Finkel7e184492014-09-07 20:29:59 +00001279 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001280
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001281 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001282}
1283
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001284static LVILatticeVal
1285getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1286 DenseMap<Value*, LVILatticeVal> &Visited);
1287
1288static LVILatticeVal
1289getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1290 DenseMap<Value*, LVILatticeVal> &Visited) {
1291 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1292 return getValueFromICmpCondition(Val, ICI, isTrueDest);
1293
1294 // Handle conditions in the form of (cond1 && cond2), we know that on the
1295 // true dest path both of the conditions hold.
1296 if (!isTrueDest)
1297 return LVILatticeVal::getOverdefined();
1298
1299 BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond);
1300 if (!BO || BO->getOpcode() != BinaryOperator::And)
1301 return LVILatticeVal::getOverdefined();
1302
1303 auto RHS = getValueFromCondition(Val, BO->getOperand(0), isTrueDest, Visited);
1304 auto LHS = getValueFromCondition(Val, BO->getOperand(1), isTrueDest, Visited);
1305 return intersect(RHS, LHS);
1306}
1307
1308static LVILatticeVal
1309getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1310 DenseMap<Value*, LVILatticeVal> &Visited) {
1311 auto I = Visited.find(Cond);
1312 if (I != Visited.end())
1313 return I->second;
Artur Pilipenkob6230882016-08-12 15:08:15 +00001314
1315 auto Result = getValueFromConditionImpl(Val, Cond, isTrueDest, Visited);
1316 Visited[Cond] = Result;
1317 return Result;
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001318}
1319
1320LVILatticeVal getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest) {
1321 assert(Cond && "precondition");
1322 DenseMap<Value*, LVILatticeVal> Visited;
1323 return getValueFromCondition(Val, Cond, isTrueDest, Visited);
1324}
1325
Nuno Lopese6e04902012-06-28 01:16:18 +00001326/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
Philip Reames13f73242016-02-01 23:21:11 +00001327/// Val is not constrained on the edge. Result is unspecified if return value
1328/// is false.
Nuno Lopese6e04902012-06-28 01:16:18 +00001329static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1330 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001331 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +00001332 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +00001333 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1334 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +00001335 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +00001336 if (BI->isConditional() &&
1337 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1338 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1339 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1340 "BBTo isn't a successor of BBFrom");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001341
Chris Lattner19019ea2009-11-11 22:48:44 +00001342 // If V is the condition of the branch itself, then we know exactly what
1343 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +00001344 if (BI->getCondition() == Val) {
1345 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +00001346 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001347 return true;
1348 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001349
Chris Lattner19019ea2009-11-11 22:48:44 +00001350 // If the condition of the branch is an equality comparison, we may be
1351 // able to infer the value.
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001352 Result = getValueFromCondition(Val, BI->getCondition(), isTrueDest);
1353 if (!Result.isOverdefined())
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001354 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001355 }
1356 }
Chris Lattner77358782009-11-15 20:02:12 +00001357
1358 // If the edge was formed by a switch on the value, then we may know exactly
1359 // what it is.
1360 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001361 if (SI->getCondition() != Val)
1362 return false;
1363
1364 bool DefaultCase = SI->getDefaultDest() == BBTo;
1365 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1366 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1367
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001368 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001369 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +00001370 if (DefaultCase) {
1371 // It is possible that the default destination is the destination of
1372 // some cases. There is no need to perform difference for those cases.
1373 if (i.getCaseSuccessor() != BBTo)
1374 EdgesVals = EdgesVals.difference(EdgeVal);
1375 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +00001376 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +00001377 }
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001378 Result = LVILatticeVal::getRange(std::move(EdgesVals));
Nuno Lopes8650fb82012-06-28 16:13:37 +00001379 return true;
Chris Lattner77358782009-11-15 20:02:12 +00001380 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001381 return false;
1382}
1383
Sanjay Patel938e2792015-01-09 16:35:37 +00001384/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1385/// the basic block if the edge does not constrain Val.
Philip Reames92e5e1b2016-09-12 21:46:58 +00001386bool LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Xin Tong68ea9aa2017-02-24 20:59:26 +00001387 BasicBlock *BBTo, LVILatticeVal &Result,
1388 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +00001389 // If already a constant, there is nothing to compute.
1390 if (Constant *VC = dyn_cast<Constant>(Val)) {
1391 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001392 return true;
1393 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001394
Philip Reames44456b82016-02-02 03:15:40 +00001395 LVILatticeVal LocalResult;
1396 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1397 // If we couldn't constrain the value on the edge, LocalResult doesn't
1398 // provide any information.
Philip Reames1baaef12016-12-06 03:01:08 +00001399 LocalResult = LVILatticeVal::getOverdefined();
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001400
Philip Reames44456b82016-02-02 03:15:40 +00001401 if (hasSingleValue(LocalResult)) {
1402 // Can't get any more precise here
1403 Result = LocalResult;
Nuno Lopese6e04902012-06-28 01:16:18 +00001404 return true;
1405 }
1406
1407 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +00001408 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1409 return false;
Philip Reames44456b82016-02-02 03:15:40 +00001410 // No new information.
1411 Result = LocalResult;
Hans Wennborg45172ac2014-11-25 17:23:05 +00001412 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +00001413 }
1414
Philip Reames44456b82016-02-02 03:15:40 +00001415 // Try to intersect ranges of the BB and the constraint on the edge.
1416 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001417 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock,
1418 BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +00001419 // We can use the context instruction (generically the ultimate instruction
1420 // the calling pass is trying to simplify) here, even though the result of
1421 // this function is generally cached when called from the solve* functions
1422 // (and that cached result might be used with queries using a different
1423 // context instruction), because when this function is called from the solve*
1424 // functions, the context instruction is not provided. When called from
Philip Reames92e5e1b2016-09-12 21:46:58 +00001425 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
Hal Finkel2400c962014-10-16 00:40:05 +00001426 // but then the result is not cached.
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001427 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
Philip Reames44456b82016-02-02 03:15:40 +00001428
1429 Result = intersect(LocalResult, InBlock);
Nuno Lopese6e04902012-06-28 01:16:18 +00001430 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001431}
1432
Philip Reames92e5e1b2016-09-12 21:46:58 +00001433LVILatticeVal LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
Hal Finkel7e184492014-09-07 20:29:59 +00001434 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001435 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001436 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001437
Hans Wennborg45172ac2014-11-25 17:23:05 +00001438 assert(BlockValueStack.empty() && BlockValueSet.empty());
Philip Reamesbb781b42016-02-10 21:46:32 +00001439 if (!hasBlockValue(V, BB)) {
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001440 pushBlockValue(std::make_pair(BB, V));
Philip Reamesbb781b42016-02-10 21:46:32 +00001441 solve();
1442 }
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001443 LVILatticeVal Result = getBlockValue(V, BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001444 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001445
1446 DEBUG(dbgs() << " Result = " << Result << "\n");
1447 return Result;
1448}
1449
Philip Reames92e5e1b2016-09-12 21:46:58 +00001450LVILatticeVal LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001451 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1452 << CxtI->getName() << "'\n");
1453
Philip Reamesbb781b42016-02-10 21:46:32 +00001454 if (auto *C = dyn_cast<Constant>(V))
1455 return LVILatticeVal::get(C);
1456
Philip Reamesd1f829d2016-02-02 21:57:37 +00001457 LVILatticeVal Result = LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +00001458 if (auto *I = dyn_cast<Instruction>(V))
1459 Result = getFromRangeMetadata(I);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001460 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
Philip Reames2c275cc2016-02-02 00:45:30 +00001461
David Greene37e98092009-12-23 20:43:58 +00001462 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001463 return Result;
1464}
Chris Lattner19019ea2009-11-11 22:48:44 +00001465
Philip Reames92e5e1b2016-09-12 21:46:58 +00001466LVILatticeVal LazyValueInfoImpl::
Hal Finkel7e184492014-09-07 20:29:59 +00001467getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1468 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001469 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001470 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001471
Nick Lewycky55a700b2010-12-18 01:00:40 +00001472 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001473 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001474 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001475 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001476 (void)WasFastQuery;
1477 assert(WasFastQuery && "More work to do after problem solved?");
1478 }
1479
David Greene37e98092009-12-23 20:43:58 +00001480 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001481 return Result;
1482}
1483
Philip Reames92e5e1b2016-09-12 21:46:58 +00001484void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Philip Reames9db79482016-09-12 22:38:44 +00001485 BasicBlock *NewSucc) {
1486 TheCache.threadEdgeImpl(OldSucc, NewSucc);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001487}
1488
Chris Lattneraf025d32009-11-15 19:59:49 +00001489//===----------------------------------------------------------------------===//
1490// LazyValueInfo Impl
1491//===----------------------------------------------------------------------===//
1492
Philip Reames92e5e1b2016-09-12 21:46:58 +00001493/// This lazily constructs the LazyValueInfoImpl.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001494static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
1495 const DataLayout *DL,
Philip Reames92e5e1b2016-09-12 21:46:58 +00001496 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001497 if (!PImpl) {
1498 assert(DL && "getCache() called with a null DataLayout");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001499 PImpl = new LazyValueInfoImpl(AC, *DL, DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001500 }
Philip Reames92e5e1b2016-09-12 21:46:58 +00001501 return *static_cast<LazyValueInfoImpl*>(PImpl);
Chris Lattneraf025d32009-11-15 19:59:49 +00001502}
1503
Sean Silva687019f2016-06-13 22:01:25 +00001504bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001505 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001506 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001507
1508 DominatorTreeWrapperPass *DTWP =
1509 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Sean Silva687019f2016-06-13 22:01:25 +00001510 Info.DT = DTWP ? &DTWP->getDomTree() : nullptr;
1511 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001512
Sean Silva687019f2016-06-13 22:01:25 +00001513 if (Info.PImpl)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001514 getImpl(Info.PImpl, Info.AC, &DL, Info.DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001515
Owen Anderson208636f2010-08-18 18:39:01 +00001516 // Fully lazy.
1517 return false;
1518}
1519
Sean Silva687019f2016-06-13 22:01:25 +00001520void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier43a33062011-12-02 01:26:24 +00001521 AU.setPreservesAll();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001522 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001523 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001524}
1525
Sean Silva687019f2016-06-13 22:01:25 +00001526LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1527
1528LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1529
Chris Lattneraf025d32009-11-15 19:59:49 +00001530void LazyValueInfo::releaseMemory() {
1531 // If the cache was allocated, free it.
1532 if (PImpl) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001533 delete &getImpl(PImpl, AC, nullptr);
Craig Topper9f008862014-04-15 04:59:12 +00001534 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001535 }
1536}
1537
Chandler Carrutha504f2b2017-01-23 06:35:12 +00001538bool LazyValueInfo::invalidate(Function &F, const PreservedAnalyses &PA,
1539 FunctionAnalysisManager::Invalidator &Inv) {
1540 // We need to invalidate if we have either failed to preserve this analyses
1541 // result directly or if any of its dependencies have been invalidated.
1542 auto PAC = PA.getChecker<LazyValueAnalysis>();
1543 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
1544 (DT && Inv.invalidate<DominatorTreeAnalysis>(F, PA)))
1545 return true;
1546
1547 return false;
1548}
1549
Sean Silva687019f2016-06-13 22:01:25 +00001550void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1551
1552LazyValueInfo LazyValueAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001553 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
Sean Silva687019f2016-06-13 22:01:25 +00001554 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1555 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1556
Anna Thomasa10e3e42017-03-12 14:06:41 +00001557 return LazyValueInfo(&AC, &F.getParent()->getDataLayout(), &TLI, DT);
Sean Silva687019f2016-06-13 22:01:25 +00001558}
1559
Wei Mif160e342016-09-15 06:28:34 +00001560/// Returns true if we can statically tell that this value will never be a
1561/// "useful" constant. In practice, this means we've got something like an
1562/// alloca or a malloc call for which a comparison against a constant can
1563/// only be guarding dead code. Note that we are potentially giving up some
1564/// precision in dead code (a constant result) in favour of avoiding a
1565/// expensive search for a easily answered common query.
1566static bool isKnownNonConstant(Value *V) {
1567 V = V->stripPointerCasts();
1568 // The return val of alloc cannot be a Constant.
1569 if (isa<AllocaInst>(V))
1570 return true;
1571 return false;
1572}
1573
Hal Finkel7e184492014-09-07 20:29:59 +00001574Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1575 Instruction *CxtI) {
Wei Mif160e342016-09-15 06:28:34 +00001576 // Bail out early if V is known not to be a Constant.
1577 if (isKnownNonConstant(V))
1578 return nullptr;
1579
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001580 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001581 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001582 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001583
Chris Lattner19019ea2009-11-11 22:48:44 +00001584 if (Result.isConstant())
1585 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001586 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001587 ConstantRange CR = Result.getConstantRange();
1588 if (const APInt *SingleVal = CR.getSingleElement())
1589 return ConstantInt::get(V->getContext(), *SingleVal);
1590 }
Craig Topper9f008862014-04-15 04:59:12 +00001591 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001592}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001593
John Regehre1c481d2016-05-02 19:58:00 +00001594ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00001595 Instruction *CxtI) {
John Regehre1c481d2016-05-02 19:58:00 +00001596 assert(V->getType()->isIntegerTy());
1597 unsigned Width = V->getType()->getIntegerBitWidth();
1598 const DataLayout &DL = BB->getModule()->getDataLayout();
1599 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001600 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
John Regehre1c481d2016-05-02 19:58:00 +00001601 if (Result.isUndefined())
1602 return ConstantRange(Width, /*isFullSet=*/false);
1603 if (Result.isConstantRange())
1604 return Result.getConstantRange();
Artur Pilipenkoa4b6a702016-08-10 12:54:54 +00001605 // We represent ConstantInt constants as constant ranges but other kinds
1606 // of integer constants, i.e. ConstantExpr will be tagged as constants
1607 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1608 "ConstantInt value must be represented as constantrange");
Davide Italianobd543d02016-05-25 22:29:34 +00001609 return ConstantRange(Width, /*isFullSet=*/true);
John Regehre1c481d2016-05-02 19:58:00 +00001610}
1611
Sanjay Patel2a385e22015-01-09 16:47:20 +00001612/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001613/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001614Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001615 BasicBlock *ToBB,
1616 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001617 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001618 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001619 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001620
Chris Lattnerd5e25432009-11-12 01:29:10 +00001621 if (Result.isConstant())
1622 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001623 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001624 ConstantRange CR = Result.getConstantRange();
1625 if (const APInt *SingleVal = CR.getSingleElement())
1626 return ConstantInt::get(V->getContext(), *SingleVal);
1627 }
Craig Topper9f008862014-04-15 04:59:12 +00001628 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001629}
1630
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001631static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1632 LVILatticeVal &Result,
1633 const DataLayout &DL,
1634 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001635
Chris Lattner565ee2f2009-11-12 04:36:58 +00001636 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001637 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001638 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001639 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001640 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001641 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001642 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1643 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001644 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001645
Owen Anderson185fe002010-08-10 20:03:09 +00001646 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001647 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001648 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001649
Owen Anderson185fe002010-08-10 20:03:09 +00001650 ConstantRange CR = Result.getConstantRange();
1651 if (Pred == ICmpInst::ICMP_EQ) {
1652 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001653 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001654
Owen Anderson185fe002010-08-10 20:03:09 +00001655 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001656 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001657 } else if (Pred == ICmpInst::ICMP_NE) {
1658 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001659 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001660
Owen Anderson185fe002010-08-10 20:03:09 +00001661 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001662 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001663 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001664
Owen Anderson185fe002010-08-10 20:03:09 +00001665 // Handle more complex predicates.
Sanjoy Das1f7b8132016-10-02 00:09:57 +00001666 ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
1667 (ICmpInst::Predicate)Pred, CI->getValue());
Nick Lewycky11678bd2010-12-15 18:57:18 +00001668 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001669 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001670 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001671 return LazyValueInfo::False;
1672 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001673 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001674
Chris Lattneraf025d32009-11-15 19:59:49 +00001675 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001676 // If this is an equality comparison, we can try to fold it knowing that
1677 // "V != C1".
1678 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001679 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001680 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001681 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001682 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001683 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001684 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001685 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001686 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001687 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001688 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001689 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001690 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001691 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001692 }
Hal Finkel7e184492014-09-07 20:29:59 +00001693 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001694 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001695
Hal Finkel7e184492014-09-07 20:29:59 +00001696 return LazyValueInfo::Unknown;
1697}
1698
Sanjay Patel2a385e22015-01-09 16:47:20 +00001699/// Determine whether the specified value comparison with a constant is known to
1700/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001701LazyValueInfo::Tristate
1702LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1703 BasicBlock *FromBB, BasicBlock *ToBB,
1704 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001705 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001706 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001707 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001708
1709 return getPredicateResult(Pred, C, Result, DL, TLI);
1710}
1711
1712LazyValueInfo::Tristate
1713LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1714 Instruction *CxtI) {
Wei Mif160e342016-09-15 06:28:34 +00001715 // Is or is not NonNull are common predicates being queried. If
1716 // isKnownNonNull can tell us the result of the predicate, we can
1717 // return it quickly. But this is only a fastpath, and falling
1718 // through would still be correct.
1719 if (V->getType()->isPointerTy() && C->isNullValue() &&
1720 isKnownNonNull(V->stripPointerCasts())) {
1721 if (Pred == ICmpInst::ICMP_EQ)
1722 return LazyValueInfo::False;
1723 else if (Pred == ICmpInst::ICMP_NE)
1724 return LazyValueInfo::True;
1725 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001726 const DataLayout &DL = CxtI->getModule()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001727 LVILatticeVal Result = getImpl(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001728 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1729 if (Ret != Unknown)
1730 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001731
Philip Reamesaeefae02015-11-04 01:47:04 +00001732 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1733 // LVI as a whole tries to compute a lattice value which is conservatively
1734 // correct at a given location. In this case, we have a predicate which we
1735 // weren't able to prove about the merged result, and we're pushing that
1736 // predicate back along each incoming edge to see if we can prove it
1737 // separately for each input. As a motivating example, consider:
1738 // bb1:
1739 // %v1 = ... ; constantrange<1, 5>
1740 // br label %merge
1741 // bb2:
1742 // %v2 = ... ; constantrange<10, 20>
1743 // br label %merge
1744 // merge:
1745 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1746 // %pred = icmp eq i32 %phi, 8
1747 // We can't tell from the lattice value for '%phi' that '%pred' is false
1748 // along each path, but by checking the predicate over each input separately,
1749 // we can.
1750 // We limit the search to one step backwards from the current BB and value.
1751 // We could consider extending this to search further backwards through the
1752 // CFG and/or value graph, but there are non-obvious compile time vs quality
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001753 // tradeoffs.
Philip Reames66ab0f02015-06-16 00:49:59 +00001754 if (CxtI) {
Philip Reamesbb11d622015-08-31 18:31:48 +00001755 BasicBlock *BB = CxtI->getParent();
1756
1757 // Function entry or an unreachable block. Bail to avoid confusing
1758 // analysis below.
1759 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1760 if (PI == PE)
1761 return Unknown;
1762
1763 // If V is a PHI node in the same block as the context, we need to ask
1764 // questions about the predicate as applied to the incoming value along
1765 // each edge. This is useful for eliminating cases where the predicate is
1766 // known along all incoming edges.
1767 if (auto *PHI = dyn_cast<PHINode>(V))
1768 if (PHI->getParent() == BB) {
1769 Tristate Baseline = Unknown;
1770 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1771 Value *Incoming = PHI->getIncomingValue(i);
1772 BasicBlock *PredBB = PHI->getIncomingBlock(i);
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001773 // Note that PredBB may be BB itself.
Philip Reamesbb11d622015-08-31 18:31:48 +00001774 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1775 CxtI);
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001776
Philip Reamesbb11d622015-08-31 18:31:48 +00001777 // Keep going as long as we've seen a consistent known result for
1778 // all inputs.
1779 Baseline = (i == 0) ? Result /* First iteration */
1780 : (Baseline == Result ? Baseline : Unknown); /* All others */
1781 if (Baseline == Unknown)
1782 break;
1783 }
1784 if (Baseline != Unknown)
1785 return Baseline;
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001786 }
Philip Reamesbb11d622015-08-31 18:31:48 +00001787
Philip Reames66ab0f02015-06-16 00:49:59 +00001788 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001789 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001790 // on all incoming edges.
Philip Reamesbb11d622015-08-31 18:31:48 +00001791 if (!isa<Instruction>(V) ||
1792 cast<Instruction>(V)->getParent() != BB) {
Philip Reames66ab0f02015-06-16 00:49:59 +00001793 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001794 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001795 // the value of the comparison in this block.
1796 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1797 if (Baseline != Unknown) {
1798 // Check that all remaining incoming values match the first one.
1799 while (++PI != PE) {
1800 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1801 if (Ret != Baseline) break;
1802 }
1803 // If we terminated early, then one of the values didn't match.
1804 if (PI == PE) {
1805 return Baseline;
1806 }
1807 }
1808 }
1809 }
1810 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001811}
1812
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001813void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001814 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001815 if (PImpl) {
1816 const DataLayout &DL = PredBB->getModule()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001817 getImpl(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001818 }
Owen Anderson208636f2010-08-18 18:39:01 +00001819}
1820
1821void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001822 if (PImpl) {
1823 const DataLayout &DL = BB->getModule()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001824 getImpl(PImpl, AC, &DL, DT).eraseBlock(BB);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001825 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001826}