blob: 92c81072517f7bc6a5ad529e9481b3fb71b7af48 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +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 implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000039#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000040#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000041#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000042#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000043#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000044#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000045#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000046#include "clang/Basic/TargetInfo.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000079 // for it directly. Otherwise use the type after adjustment.
80 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000081 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
George Burgess IVe3763372016-12-22 02:50:20 +0000112 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
113 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
114 const FunctionDecl *Callee = CE->getDirectCallee();
115 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
116 }
117
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
120 ///
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
124 return nullptr;
125
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. Ignore it.
129 if (const auto *Cast = dyn_cast<CastExpr>(E))
130 E = Cast->getSubExpr()->IgnoreParens();
131
132 if (const auto *CE = dyn_cast<CallExpr>(E))
133 return getAllocSizeAttr(CE) ? CE : nullptr;
134 return nullptr;
135 }
136
137 /// Determines whether or not the given Base contains a call to a function
138 /// with the alloc_size attribute.
139 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
140 const auto *E = Base.dyn_cast<const Expr *>();
141 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
142 }
143
144 /// Determines if an LValue with the given LValueBase will have an unsized
145 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000146 /// Find the path length and type of the most-derived subobject in the given
147 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000148 static unsigned
149 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
150 ArrayRef<APValue::LValuePathEntry> Path,
151 uint64_t &ArraySize, QualType &Type, bool &IsArray) {
152 // This only accepts LValueBases from APValues, and APValues don't support
153 // arrays that lack size info.
154 assert(!isBaseAnAllocSizeCall(Base) &&
155 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000156 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000157 Type = getType(Base);
158
Richard Smith80815602011-11-07 05:07:52 +0000159 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 if (Type->isArrayType()) {
161 const ConstantArrayType *CAT =
George Burgess IVe3763372016-12-22 02:50:20 +0000162 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
Richard Smitha8105bc2012-01-06 16:39:00 +0000163 Type = CAT->getElementType();
164 ArraySize = CAT->getSize().getZExtValue();
165 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000166 IsArray = true;
Richard Smith66c96992012-02-18 22:04:06 +0000167 } else if (Type->isAnyComplexType()) {
168 const ComplexType *CT = Type->castAs<ComplexType>();
169 Type = CT->getElementType();
170 ArraySize = 2;
171 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000172 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000173 } else if (const FieldDecl *FD = getAsField(Path[I])) {
174 Type = FD->getType();
175 ArraySize = 0;
176 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000177 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000178 } else {
Richard Smith80815602011-11-07 05:07:52 +0000179 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000180 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000181 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000182 }
Richard Smith80815602011-11-07 05:07:52 +0000183 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000184 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000185 }
186
Richard Smitha8105bc2012-01-06 16:39:00 +0000187 // The order of this enum is important for diagnostics.
188 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000189 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000190 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000191 };
192
Richard Smith96e0c102011-11-04 02:25:55 +0000193 /// A path from a glvalue to a subobject of that glvalue.
194 struct SubobjectDesignator {
195 /// True if the subobject was named in a manner not supported by C++11. Such
196 /// lvalues can still be folded, but they are not core constant expressions
197 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000198 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000199
Richard Smitha8105bc2012-01-06 16:39:00 +0000200 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000201 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000202
George Burgess IVe3763372016-12-22 02:50:20 +0000203 /// Indicator of whether the first entry is an unsized array.
204 unsigned FirstEntryIsAnUnsizedArray : 1;
205
George Burgess IVa51c4072015-10-16 01:49:01 +0000206 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000207 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000208
Richard Smitha8105bc2012-01-06 16:39:00 +0000209 /// The length of the path to the most-derived object of which this is a
210 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000211 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000212
George Burgess IVa51c4072015-10-16 01:49:01 +0000213 /// The size of the array of which the most-derived object is an element.
214 /// This will always be 0 if the most-derived object is not an array
215 /// element. 0 is not an indicator of whether or not the most-derived object
216 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000217 ///
218 /// If the current array is an unsized array, the value of this is
219 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 uint64_t MostDerivedArraySize;
221
222 /// The type of the most derived object referred to by this address.
223 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000224
Richard Smith80815602011-11-07 05:07:52 +0000225 typedef APValue::LValuePathEntry PathEntry;
226
Richard Smith96e0c102011-11-04 02:25:55 +0000227 /// The entries on the path from the glvalue to the designated subobject.
228 SmallVector<PathEntry, 8> Entries;
229
Richard Smitha8105bc2012-01-06 16:39:00 +0000230 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000231
Richard Smitha8105bc2012-01-06 16:39:00 +0000232 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000233 : Invalid(false), IsOnePastTheEnd(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000234 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
235 MostDerivedPathLength(0), MostDerivedArraySize(0),
236 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000237
238 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000239 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000240 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
241 MostDerivedPathLength(0), MostDerivedArraySize(0) {
242 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000243 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000245 ArrayRef<PathEntry> VEntries = V.getLValuePath();
246 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
George Burgess IVa51c4072015-10-16 01:49:01 +0000247 if (V.getLValueBase()) {
248 bool IsArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000249 MostDerivedPathLength = findMostDerivedSubobject(
250 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
251 MostDerivedType, IsArray);
George Burgess IVa51c4072015-10-16 01:49:01 +0000252 MostDerivedIsArrayElement = IsArray;
253 }
Richard Smith80815602011-11-07 05:07:52 +0000254 }
255 }
256
Richard Smith96e0c102011-11-04 02:25:55 +0000257 void setInvalid() {
258 Invalid = true;
259 Entries.clear();
260 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000261
George Burgess IVe3763372016-12-22 02:50:20 +0000262 /// Determine whether the most derived subobject is an array without a
263 /// known bound.
264 bool isMostDerivedAnUnsizedArray() const {
265 assert(!Invalid && "Calling this makes no sense on invalid designators");
266 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
267 }
268
269 /// Determine what the most derived array's size is. Results in an assertion
270 /// failure if the most derived array lacks a size.
271 uint64_t getMostDerivedArraySize() const {
272 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
273 return MostDerivedArraySize;
274 }
275
Richard Smitha8105bc2012-01-06 16:39:00 +0000276 /// Determine whether this is a one-past-the-end pointer.
277 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000278 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000279 if (IsOnePastTheEnd)
280 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000281 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000282 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
283 return true;
284 return false;
285 }
286
287 /// Check that this refers to a valid subobject.
288 bool isValidSubobject() const {
289 if (Invalid)
290 return false;
291 return !isOnePastTheEnd();
292 }
293 /// Check that this refers to a valid subobject, and if not, produce a
294 /// relevant diagnostic and set the designator as invalid.
295 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
296
297 /// Update this designator to refer to the first element within this array.
298 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000299 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000300 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000301 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000302
303 // This is a most-derived object.
304 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000305 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000306 MostDerivedArraySize = CAT->getSize().getZExtValue();
307 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000308 }
George Burgess IVe3763372016-12-22 02:50:20 +0000309 /// Update this designator to refer to the first element within the array of
310 /// elements of type T. This is an array of unknown size.
311 void addUnsizedArrayUnchecked(QualType ElemTy) {
312 PathEntry Entry;
313 Entry.ArrayIndex = 0;
314 Entries.push_back(Entry);
315
316 MostDerivedType = ElemTy;
317 MostDerivedIsArrayElement = true;
318 // The value in MostDerivedArraySize is undefined in this case. So, set it
319 // to an arbitrary value that's likely to loudly break things if it's
320 // used.
321 MostDerivedArraySize = std::numeric_limits<uint64_t>::max() / 2;
322 MostDerivedPathLength = Entries.size();
323 }
Richard Smith96e0c102011-11-04 02:25:55 +0000324 /// Update this designator to refer to the given base or member of this
325 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000326 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000327 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000328 APValue::BaseOrMemberType Value(D, Virtual);
329 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000330 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000331
332 // If this isn't a base class, it's a new most-derived object.
333 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
334 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000335 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000336 MostDerivedArraySize = 0;
337 MostDerivedPathLength = Entries.size();
338 }
Richard Smith96e0c102011-11-04 02:25:55 +0000339 }
Richard Smith66c96992012-02-18 22:04:06 +0000340 /// Update this designator to refer to the given complex component.
341 void addComplexUnchecked(QualType EltTy, bool Imag) {
342 PathEntry Entry;
343 Entry.ArrayIndex = Imag;
344 Entries.push_back(Entry);
345
346 // This is technically a most-derived object, though in practice this
347 // is unlikely to matter.
348 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000349 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000350 MostDerivedArraySize = 2;
351 MostDerivedPathLength = Entries.size();
352 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000353 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000354 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000355 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000356 if (Invalid) return;
George Burgess IVe3763372016-12-22 02:50:20 +0000357 if (isMostDerivedAnUnsizedArray()) {
358 // Can't verify -- trust that the user is doing the right thing (or if
359 // not, trust that the caller will catch the bad behavior).
360 Entries.back().ArrayIndex += N;
361 return;
362 }
George Burgess IVa51c4072015-10-16 01:49:01 +0000363 if (MostDerivedPathLength == Entries.size() &&
364 MostDerivedIsArrayElement) {
Richard Smith80815602011-11-07 05:07:52 +0000365 Entries.back().ArrayIndex += N;
George Burgess IVe3763372016-12-22 02:50:20 +0000366 if (Entries.back().ArrayIndex > getMostDerivedArraySize()) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000367 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
368 setInvalid();
369 }
Richard Smith96e0c102011-11-04 02:25:55 +0000370 return;
371 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000372 // [expr.add]p4: For the purposes of these operators, a pointer to a
373 // nonarray object behaves the same as a pointer to the first element of
374 // an array of length one with the type of the object as its element type.
375 if (IsOnePastTheEnd && N == (uint64_t)-1)
376 IsOnePastTheEnd = false;
377 else if (!IsOnePastTheEnd && N == 1)
378 IsOnePastTheEnd = true;
379 else if (N != 0) {
380 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000381 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000382 }
Richard Smith96e0c102011-11-04 02:25:55 +0000383 }
384 };
385
Richard Smith254a73d2011-10-28 22:34:42 +0000386 /// A stack frame in the constexpr call stack.
387 struct CallStackFrame {
388 EvalInfo &Info;
389
390 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000391 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000392
Richard Smithf6f003a2011-12-16 19:06:07 +0000393 /// Callee - The function which was called.
394 const FunctionDecl *Callee;
395
Richard Smithd62306a2011-11-10 06:34:14 +0000396 /// This - The binding for the this pointer in this call, if any.
397 const LValue *This;
398
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000399 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000400 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000401 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000402
Eli Friedman4830ec82012-06-25 21:21:08 +0000403 // Note that we intentionally use std::map here so that references to
404 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000405 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000406 typedef MapTy::const_iterator temp_iterator;
407 /// Temporaries - Temporary lvalues materialized within this stack frame.
408 MapTy Temporaries;
409
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000410 /// CallLoc - The location of the call expression for this call.
411 SourceLocation CallLoc;
412
413 /// Index - The call index of this call.
414 unsigned Index;
415
Richard Smithf6f003a2011-12-16 19:06:07 +0000416 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
417 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000418 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000419 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000420
421 APValue *getTemporary(const void *Key) {
422 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000423 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000424 }
425 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000426 };
427
Richard Smith852c9db2013-04-20 22:23:05 +0000428 /// Temporarily override 'this'.
429 class ThisOverrideRAII {
430 public:
431 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
432 : Frame(Frame), OldThis(Frame.This) {
433 if (Enable)
434 Frame.This = NewThis;
435 }
436 ~ThisOverrideRAII() {
437 Frame.This = OldThis;
438 }
439 private:
440 CallStackFrame &Frame;
441 const LValue *OldThis;
442 };
443
Richard Smith92b1ce02011-12-12 09:28:41 +0000444 /// A partial diagnostic which we might know in advance that we are not going
445 /// to emit.
446 class OptionalDiagnostic {
447 PartialDiagnostic *Diag;
448
449 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000450 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
451 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000452
453 template<typename T>
454 OptionalDiagnostic &operator<<(const T &v) {
455 if (Diag)
456 *Diag << v;
457 return *this;
458 }
Richard Smithfe800032012-01-31 04:08:20 +0000459
460 OptionalDiagnostic &operator<<(const APSInt &I) {
461 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000462 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000463 I.toString(Buffer);
464 *Diag << StringRef(Buffer.data(), Buffer.size());
465 }
466 return *this;
467 }
468
469 OptionalDiagnostic &operator<<(const APFloat &F) {
470 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000471 // FIXME: Force the precision of the source value down so we don't
472 // print digits which are usually useless (we don't really care here if
473 // we truncate a digit by accident in edge cases). Ideally,
474 // APFloat::toString would automatically print the shortest
475 // representation which rounds to the correct value, but it's a bit
476 // tricky to implement.
477 unsigned precision =
478 llvm::APFloat::semanticsPrecision(F.getSemantics());
479 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000480 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000481 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000482 *Diag << StringRef(Buffer.data(), Buffer.size());
483 }
484 return *this;
485 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000486 };
487
Richard Smith08d6a2c2013-07-24 07:11:57 +0000488 /// A cleanup, and a flag indicating whether it is lifetime-extended.
489 class Cleanup {
490 llvm::PointerIntPair<APValue*, 1, bool> Value;
491
492 public:
493 Cleanup(APValue *Val, bool IsLifetimeExtended)
494 : Value(Val, IsLifetimeExtended) {}
495
496 bool isLifetimeExtended() const { return Value.getInt(); }
497 void endLifetime() {
498 *Value.getPointer() = APValue();
499 }
500 };
501
Richard Smithb228a862012-02-15 02:18:13 +0000502 /// EvalInfo - This is a private struct used by the evaluator to capture
503 /// information about a subexpression as it is folded. It retains information
504 /// about the AST context, but also maintains information about the folded
505 /// expression.
506 ///
507 /// If an expression could be evaluated, it is still possible it is not a C
508 /// "integer constant expression" or constant expression. If not, this struct
509 /// captures information about how and why not.
510 ///
511 /// One bit of information passed *into* the request for constant folding
512 /// indicates whether the subexpression is "evaluated" or not according to C
513 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
514 /// evaluate the expression regardless of what the RHS is, but C only allows
515 /// certain things in certain situations.
Reid Kleckner06df4022016-12-13 19:48:32 +0000516 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000517 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000518
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000519 /// EvalStatus - Contains information about the evaluation.
520 Expr::EvalStatus &EvalStatus;
521
522 /// CurrentCall - The top of the constexpr call stack.
523 CallStackFrame *CurrentCall;
524
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000525 /// CallStackDepth - The number of calls in the call stack right now.
526 unsigned CallStackDepth;
527
Richard Smithb228a862012-02-15 02:18:13 +0000528 /// NextCallIndex - The next call index to assign.
529 unsigned NextCallIndex;
530
Richard Smitha3d3bd22013-05-08 02:12:03 +0000531 /// StepsLeft - The remaining number of evaluation steps we're permitted
532 /// to perform. This is essentially a limit for the number of statements
533 /// we will evaluate.
534 unsigned StepsLeft;
535
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000536 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000537 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000538 CallStackFrame BottomFrame;
539
Richard Smith08d6a2c2013-07-24 07:11:57 +0000540 /// A stack of values whose lifetimes end at the end of some surrounding
541 /// evaluation frame.
542 llvm::SmallVector<Cleanup, 16> CleanupStack;
543
Richard Smithd62306a2011-11-10 06:34:14 +0000544 /// EvaluatingDecl - This is the declaration whose initializer is being
545 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000546 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000547
548 /// EvaluatingDeclValue - This is the value being constructed for the
549 /// declaration whose initializer is being evaluated, if any.
550 APValue *EvaluatingDeclValue;
551
Richard Smith410306b2016-12-12 02:53:20 +0000552 /// The current array initialization index, if we're performing array
553 /// initialization.
554 uint64_t ArrayInitIndex = -1;
555
Richard Smith357362d2011-12-13 06:39:58 +0000556 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
557 /// notes attached to it will also be stored, otherwise they will not be.
558 bool HasActiveDiagnostic;
559
Richard Smith0c6124b2015-12-03 01:36:22 +0000560 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
561 /// fold (not just why it's not strictly a constant expression)?
562 bool HasFoldFailureDiagnostic;
563
George Burgess IV8c892b52016-05-25 22:31:54 +0000564 /// \brief Whether or not we're currently speculatively evaluating.
565 bool IsSpeculativelyEvaluating;
566
Richard Smith6d4c6582013-11-05 22:18:15 +0000567 enum EvaluationMode {
568 /// Evaluate as a constant expression. Stop if we find that the expression
569 /// is not a constant expression.
570 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000571
Richard Smith6d4c6582013-11-05 22:18:15 +0000572 /// Evaluate as a potential constant expression. Keep going if we hit a
573 /// construct that we can't evaluate yet (because we don't yet know the
574 /// value of something) but stop if we hit something that could never be
575 /// a constant expression.
576 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000577
Richard Smith6d4c6582013-11-05 22:18:15 +0000578 /// Fold the expression to a constant. Stop if we hit a side-effect that
579 /// we can't model.
580 EM_ConstantFold,
581
582 /// Evaluate the expression looking for integer overflow and similar
583 /// issues. Don't worry about side-effects, and try to visit all
584 /// subexpressions.
585 EM_EvaluateForOverflow,
586
587 /// Evaluate in any way we know how. Don't worry about side-effects that
588 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000589 EM_IgnoreSideEffects,
590
591 /// Evaluate as a constant expression. Stop if we find that the expression
592 /// is not a constant expression. Some expressions can be retried in the
593 /// optimizer if we don't constant fold them here, but in an unevaluated
594 /// context we try to fold them immediately since the optimizer never
595 /// gets a chance to look at it.
596 EM_ConstantExpressionUnevaluated,
597
598 /// Evaluate as a potential constant expression. Keep going if we hit a
599 /// construct that we can't evaluate yet (because we don't yet know the
600 /// value of something) but stop if we hit something that could never be
601 /// a constant expression. Some expressions can be retried in the
602 /// optimizer if we don't constant fold them here, but in an unevaluated
603 /// context we try to fold them immediately since the optimizer never
604 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000605 EM_PotentialConstantExpressionUnevaluated,
606
George Burgess IVe3763372016-12-22 02:50:20 +0000607 /// Evaluate as a constant expression. Continue evaluating if either:
608 /// - We find a MemberExpr with a base that can't be evaluated.
609 /// - We find a variable initialized with a call to a function that has
610 /// the alloc_size attribute on it.
611 /// In either case, the LValue returned shall have an invalid base; in the
612 /// former, the base will be the invalid MemberExpr, in the latter, the
613 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
614 /// said CallExpr.
615 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000616 } EvalMode;
617
618 /// Are we checking whether the expression is a potential constant
619 /// expression?
620 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000621 return EvalMode == EM_PotentialConstantExpression ||
622 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000623 }
624
625 /// Are we checking an expression for overflow?
626 // FIXME: We should check for any kind of undefined or suspicious behavior
627 // in such constructs, not just overflow.
628 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
629
630 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000631 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000632 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000633 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000634 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
635 EvaluatingDecl((const ValueDecl *)nullptr),
636 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000637 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
638 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000639
Richard Smith7525ff62013-05-09 07:14:00 +0000640 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
641 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000642 EvaluatingDeclValue = &Value;
643 }
644
David Blaikiebbafb8a2012-03-11 07:00:24 +0000645 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000646
Richard Smith357362d2011-12-13 06:39:58 +0000647 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000648 // Don't perform any constexpr calls (other than the call we're checking)
649 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000650 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000651 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000652 if (NextCallIndex == 0) {
653 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000654 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000655 return false;
656 }
Richard Smith357362d2011-12-13 06:39:58 +0000657 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
658 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000659 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000660 << getLangOpts().ConstexprCallDepth;
661 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000662 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000663
Richard Smithb228a862012-02-15 02:18:13 +0000664 CallStackFrame *getCallFrame(unsigned CallIndex) {
665 assert(CallIndex && "no call index in getCallFrame");
666 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
667 // be null in this loop.
668 CallStackFrame *Frame = CurrentCall;
669 while (Frame->Index > CallIndex)
670 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000671 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000672 }
673
Richard Smitha3d3bd22013-05-08 02:12:03 +0000674 bool nextStep(const Stmt *S) {
675 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000676 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000677 return false;
678 }
679 --StepsLeft;
680 return true;
681 }
682
Richard Smith357362d2011-12-13 06:39:58 +0000683 private:
684 /// Add a diagnostic to the diagnostics list.
685 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
686 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
687 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
688 return EvalStatus.Diag->back().second;
689 }
690
Richard Smithf6f003a2011-12-16 19:06:07 +0000691 /// Add notes containing a call stack to the current point of evaluation.
692 void addCallStack(unsigned Limit);
693
Faisal Valie690b7a2016-07-02 22:34:24 +0000694 private:
695 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
696 unsigned ExtraNotes, bool IsCCEDiag) {
697
Richard Smith92b1ce02011-12-12 09:28:41 +0000698 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000699 // If we have a prior diagnostic, it will be noting that the expression
700 // isn't a constant expression. This diagnostic is more important,
701 // unless we require this evaluation to produce a constant expression.
702 //
703 // FIXME: We might want to show both diagnostics to the user in
704 // EM_ConstantFold mode.
705 if (!EvalStatus.Diag->empty()) {
706 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000707 case EM_ConstantFold:
708 case EM_IgnoreSideEffects:
709 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000710 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000711 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000712 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000713 case EM_ConstantExpression:
714 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000715 case EM_ConstantExpressionUnevaluated:
716 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000717 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000718 HasActiveDiagnostic = false;
719 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000720 }
721 }
722
Richard Smithf6f003a2011-12-16 19:06:07 +0000723 unsigned CallStackNotes = CallStackDepth - 1;
724 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
725 if (Limit)
726 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000727 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000728 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000729
Richard Smith357362d2011-12-13 06:39:58 +0000730 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000731 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000732 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000733 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
734 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000735 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000736 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000737 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000738 }
Richard Smith357362d2011-12-13 06:39:58 +0000739 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000740 return OptionalDiagnostic();
741 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000742 public:
743 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
744 OptionalDiagnostic
745 FFDiag(SourceLocation Loc,
746 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
747 unsigned ExtraNotes = 0) {
748 return Diag(Loc, DiagId, ExtraNotes, false);
749 }
750
751 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000752 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000753 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000754 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000755 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000756 HasActiveDiagnostic = false;
757 return OptionalDiagnostic();
758 }
759
Richard Smith92b1ce02011-12-12 09:28:41 +0000760 /// Diagnose that the evaluation does not produce a C++11 core constant
761 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000762 ///
763 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
764 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000765 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000766 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000767 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000768 // Don't override a previous diagnostic. Don't bother collecting
769 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000770 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000771 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000772 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000773 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000774 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000775 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000776 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
777 = diag::note_invalid_subexpr_in_const_expr,
778 unsigned ExtraNotes = 0) {
779 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
780 }
Richard Smith357362d2011-12-13 06:39:58 +0000781 /// Add a note to a prior diagnostic.
782 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
783 if (!HasActiveDiagnostic)
784 return OptionalDiagnostic();
785 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000786 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000787
788 /// Add a stack of notes to a prior diagnostic.
789 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
790 if (HasActiveDiagnostic) {
791 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
792 Diags.begin(), Diags.end());
793 }
794 }
Richard Smith253c2a32012-01-27 01:14:48 +0000795
Richard Smith6d4c6582013-11-05 22:18:15 +0000796 /// Should we continue evaluation after encountering a side-effect that we
797 /// couldn't model?
798 bool keepEvaluatingAfterSideEffect() {
799 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000800 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000801 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000802 case EM_EvaluateForOverflow:
803 case EM_IgnoreSideEffects:
804 return true;
805
Richard Smith6d4c6582013-11-05 22:18:15 +0000806 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000807 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000808 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000809 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000810 return false;
811 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000812 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000813 }
814
815 /// Note that we have had a side-effect, and determine whether we should
816 /// keep evaluating.
817 bool noteSideEffect() {
818 EvalStatus.HasSideEffects = true;
819 return keepEvaluatingAfterSideEffect();
820 }
821
Richard Smithce8eca52015-12-08 03:21:47 +0000822 /// Should we continue evaluation after encountering undefined behavior?
823 bool keepEvaluatingAfterUndefinedBehavior() {
824 switch (EvalMode) {
825 case EM_EvaluateForOverflow:
826 case EM_IgnoreSideEffects:
827 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000828 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000829 return true;
830
831 case EM_PotentialConstantExpression:
832 case EM_PotentialConstantExpressionUnevaluated:
833 case EM_ConstantExpression:
834 case EM_ConstantExpressionUnevaluated:
835 return false;
836 }
837 llvm_unreachable("Missed EvalMode case");
838 }
839
840 /// Note that we hit something that was technically undefined behavior, but
841 /// that we can evaluate past it (such as signed overflow or floating-point
842 /// division by zero.)
843 bool noteUndefinedBehavior() {
844 EvalStatus.HasUndefinedBehavior = true;
845 return keepEvaluatingAfterUndefinedBehavior();
846 }
847
Richard Smith253c2a32012-01-27 01:14:48 +0000848 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000849 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000850 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000851 if (!StepsLeft)
852 return false;
853
854 switch (EvalMode) {
855 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000856 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000857 case EM_EvaluateForOverflow:
858 return true;
859
860 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000861 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000862 case EM_ConstantFold:
863 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000864 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000865 return false;
866 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000867 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000868 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000869
George Burgess IV8c892b52016-05-25 22:31:54 +0000870 /// Notes that we failed to evaluate an expression that other expressions
871 /// directly depend on, and determine if we should keep evaluating. This
872 /// should only be called if we actually intend to keep evaluating.
873 ///
874 /// Call noteSideEffect() instead if we may be able to ignore the value that
875 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
876 ///
877 /// (Foo(), 1) // use noteSideEffect
878 /// (Foo() || true) // use noteSideEffect
879 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000880 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000881 // Failure when evaluating some expression often means there is some
882 // subexpression whose evaluation was skipped. Therefore, (because we
883 // don't track whether we skipped an expression when unwinding after an
884 // evaluation failure) every evaluation failure that bubbles up from a
885 // subexpression implies that a side-effect has potentially happened. We
886 // skip setting the HasSideEffects flag to true until we decide to
887 // continue evaluating after that point, which happens here.
888 bool KeepGoing = keepEvaluatingAfterFailure();
889 EvalStatus.HasSideEffects |= KeepGoing;
890 return KeepGoing;
891 }
892
George Burgess IV3a03fab2015-09-04 21:28:13 +0000893 bool allowInvalidBaseExpr() const {
George Burgess IVe3763372016-12-22 02:50:20 +0000894 return EvalMode == EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000895 }
Richard Smith410306b2016-12-12 02:53:20 +0000896
897 class ArrayInitLoopIndex {
898 EvalInfo &Info;
899 uint64_t OuterIndex;
900
901 public:
902 ArrayInitLoopIndex(EvalInfo &Info)
903 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
904 Info.ArrayInitIndex = 0;
905 }
906 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
907
908 operator uint64_t&() { return Info.ArrayInitIndex; }
909 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000910 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000911
912 /// Object used to treat all foldable expressions as constant expressions.
913 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000914 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000915 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000916 bool HadNoPriorDiags;
917 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000918
Richard Smith6d4c6582013-11-05 22:18:15 +0000919 explicit FoldConstant(EvalInfo &Info, bool Enabled)
920 : Info(Info),
921 Enabled(Enabled),
922 HadNoPriorDiags(Info.EvalStatus.Diag &&
923 Info.EvalStatus.Diag->empty() &&
924 !Info.EvalStatus.HasSideEffects),
925 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000926 if (Enabled &&
927 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
928 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000929 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000930 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000931 void keepDiagnostics() { Enabled = false; }
932 ~FoldConstant() {
933 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000934 !Info.EvalStatus.HasSideEffects)
935 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000936 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000937 }
938 };
Richard Smith17100ba2012-02-16 02:46:34 +0000939
George Burgess IV3a03fab2015-09-04 21:28:13 +0000940 /// RAII object used to treat the current evaluation as the correct pointer
941 /// offset fold for the current EvalMode
942 struct FoldOffsetRAII {
943 EvalInfo &Info;
944 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +0000945 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +0000946 : Info(Info), OldMode(Info.EvalMode) {
947 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +0000948 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000949 }
950
951 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
952 };
953
George Burgess IV8c892b52016-05-25 22:31:54 +0000954 /// RAII object used to optionally suppress diagnostics and side-effects from
955 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000956 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000957 /// Pair of EvalInfo, and a bit that stores whether or not we were
958 /// speculatively evaluating when we created this RAII.
959 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000960 Expr::EvalStatus Old;
961
George Burgess IV8c892b52016-05-25 22:31:54 +0000962 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
963 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
964 Old = Other.Old;
965 Other.InfoAndOldSpecEval.setPointer(nullptr);
966 }
967
968 void maybeRestoreState() {
969 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
970 if (!Info)
971 return;
972
973 Info->EvalStatus = Old;
974 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
975 }
976
Richard Smith17100ba2012-02-16 02:46:34 +0000977 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000978 SpeculativeEvaluationRAII() = default;
979
980 SpeculativeEvaluationRAII(
981 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
982 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
983 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000984 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000985 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000986 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000987
988 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
989 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
990 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +0000991 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000992
993 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
994 maybeRestoreState();
995 moveFromAndCancel(std::move(Other));
996 return *this;
997 }
998
999 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001000 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001001
1002 /// RAII object wrapping a full-expression or block scope, and handling
1003 /// the ending of the lifetime of temporaries created within it.
1004 template<bool IsFullExpression>
1005 class ScopeRAII {
1006 EvalInfo &Info;
1007 unsigned OldStackSize;
1008 public:
1009 ScopeRAII(EvalInfo &Info)
1010 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1011 ~ScopeRAII() {
1012 // Body moved to a static method to encourage the compiler to inline away
1013 // instances of this class.
1014 cleanup(Info, OldStackSize);
1015 }
1016 private:
1017 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1018 unsigned NewEnd = OldStackSize;
1019 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1020 I != N; ++I) {
1021 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1022 // Full-expression cleanup of a lifetime-extended temporary: nothing
1023 // to do, just move this cleanup to the right place in the stack.
1024 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1025 ++NewEnd;
1026 } else {
1027 // End the lifetime of the object.
1028 Info.CleanupStack[I].endLifetime();
1029 }
1030 }
1031 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1032 Info.CleanupStack.end());
1033 }
1034 };
1035 typedef ScopeRAII<false> BlockScopeRAII;
1036 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001037}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001038
Richard Smitha8105bc2012-01-06 16:39:00 +00001039bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1040 CheckSubobjectKind CSK) {
1041 if (Invalid)
1042 return false;
1043 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001044 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001045 << CSK;
1046 setInvalid();
1047 return false;
1048 }
1049 return true;
1050}
1051
1052void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1053 const Expr *E, uint64_t N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001054 // If we're complaining, we must be able to statically determine the size of
1055 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001056 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001057 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +00001058 << static_cast<int>(N) << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001059 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001060 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001061 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +00001062 << static_cast<int>(N) << /*non-array*/ 1;
1063 setInvalid();
1064}
1065
Richard Smithf6f003a2011-12-16 19:06:07 +00001066CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1067 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001068 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001069 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1070 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001071 Info.CurrentCall = this;
1072 ++Info.CallStackDepth;
1073}
1074
1075CallStackFrame::~CallStackFrame() {
1076 assert(Info.CurrentCall == this && "calls retired out of order");
1077 --Info.CallStackDepth;
1078 Info.CurrentCall = Caller;
1079}
1080
Richard Smith08d6a2c2013-07-24 07:11:57 +00001081APValue &CallStackFrame::createTemporary(const void *Key,
1082 bool IsLifetimeExtended) {
1083 APValue &Result = Temporaries[Key];
1084 assert(Result.isUninit() && "temporary created multiple times");
1085 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1086 return Result;
1087}
1088
Richard Smith84401042013-06-03 05:03:02 +00001089static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001090
1091void EvalInfo::addCallStack(unsigned Limit) {
1092 // Determine which calls to skip, if any.
1093 unsigned ActiveCalls = CallStackDepth - 1;
1094 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1095 if (Limit && Limit < ActiveCalls) {
1096 SkipStart = Limit / 2 + Limit % 2;
1097 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001098 }
1099
Richard Smithf6f003a2011-12-16 19:06:07 +00001100 // Walk the call stack and add the diagnostics.
1101 unsigned CallIdx = 0;
1102 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1103 Frame = Frame->Caller, ++CallIdx) {
1104 // Skip this call?
1105 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1106 if (CallIdx == SkipStart) {
1107 // Note that we're skipping calls.
1108 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1109 << unsigned(ActiveCalls - Limit);
1110 }
1111 continue;
1112 }
1113
Richard Smith5179eb72016-06-28 19:03:57 +00001114 // Use a different note for an inheriting constructor, because from the
1115 // user's perspective it's not really a function at all.
1116 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1117 if (CD->isInheritingConstructor()) {
1118 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1119 << CD->getParent();
1120 continue;
1121 }
1122 }
1123
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001124 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001125 llvm::raw_svector_ostream Out(Buffer);
1126 describeCall(Frame, Out);
1127 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1128 }
1129}
1130
1131namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001132 struct ComplexValue {
1133 private:
1134 bool IsInt;
1135
1136 public:
1137 APSInt IntReal, IntImag;
1138 APFloat FloatReal, FloatImag;
1139
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001140 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001141
1142 void makeComplexFloat() { IsInt = false; }
1143 bool isComplexFloat() const { return !IsInt; }
1144 APFloat &getComplexFloatReal() { return FloatReal; }
1145 APFloat &getComplexFloatImag() { return FloatImag; }
1146
1147 void makeComplexInt() { IsInt = true; }
1148 bool isComplexInt() const { return IsInt; }
1149 APSInt &getComplexIntReal() { return IntReal; }
1150 APSInt &getComplexIntImag() { return IntImag; }
1151
Richard Smith2e312c82012-03-03 22:46:17 +00001152 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001153 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001154 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001155 else
Richard Smith2e312c82012-03-03 22:46:17 +00001156 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001157 }
Richard Smith2e312c82012-03-03 22:46:17 +00001158 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001159 assert(v.isComplexFloat() || v.isComplexInt());
1160 if (v.isComplexFloat()) {
1161 makeComplexFloat();
1162 FloatReal = v.getComplexFloatReal();
1163 FloatImag = v.getComplexFloatImag();
1164 } else {
1165 makeComplexInt();
1166 IntReal = v.getComplexIntReal();
1167 IntImag = v.getComplexIntImag();
1168 }
1169 }
John McCall93d91dc2010-05-07 17:22:02 +00001170 };
John McCall45d55e42010-05-07 21:00:08 +00001171
1172 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001173 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001174 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001175 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001176 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001177 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001178 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001179
Richard Smithce40ad62011-11-12 22:28:03 +00001180 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001181 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001182 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001183 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001184 SubobjectDesignator &getLValueDesignator() { return Designator; }
1185 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001186 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001187
Richard Smith2e312c82012-03-03 22:46:17 +00001188 void moveInto(APValue &V) const {
1189 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001190 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1191 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001192 else {
1193 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1194 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1195 "Unsized array with a valid base?");
Richard Smith2e312c82012-03-03 22:46:17 +00001196 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001197 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001198 }
John McCall45d55e42010-05-07 21:00:08 +00001199 }
Richard Smith2e312c82012-03-03 22:46:17 +00001200 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001201 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001202 Base = V.getLValueBase();
1203 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001204 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001205 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001206 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001207 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001208 }
1209
Yaxun Liu402804b2016-12-15 08:09:08 +00001210 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1211 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
George Burgess IVe3763372016-12-22 02:50:20 +00001212#ifndef NDEBUG
1213 // We only allow a few types of invalid bases. Enforce that here.
1214 if (BInvalid) {
1215 const auto *E = B.get<const Expr *>();
1216 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1217 "Unexpected type of invalid base");
1218 }
1219#endif
1220
Richard Smithce40ad62011-11-12 22:28:03 +00001221 Base = B;
Yaxun Liu402804b2016-12-15 08:09:08 +00001222 Offset = CharUnits::fromQuantity(Offset_);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001223 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001224 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001225 Designator = SubobjectDesignator(getType(B));
Yaxun Liu402804b2016-12-15 08:09:08 +00001226 IsNullPtr = IsNullPtr_;
Richard Smitha8105bc2012-01-06 16:39:00 +00001227 }
1228
George Burgess IV3a03fab2015-09-04 21:28:13 +00001229 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1230 set(B, I, true);
1231 }
1232
Richard Smitha8105bc2012-01-06 16:39:00 +00001233 // Check that this LValue is not based on a null pointer. If it is, produce
1234 // a diagnostic and mark the designator as invalid.
1235 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1236 CheckSubobjectKind CSK) {
1237 if (Designator.Invalid)
1238 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001239 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001240 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001241 << CSK;
1242 Designator.setInvalid();
1243 return false;
1244 }
1245 return true;
1246 }
1247
1248 // Check this LValue refers to an object. If not, set the designator to be
1249 // invalid and emit a diagnostic.
1250 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001251 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001252 Designator.checkSubobject(Info, E, CSK);
1253 }
1254
1255 void addDecl(EvalInfo &Info, const Expr *E,
1256 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001257 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1258 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001259 }
George Burgess IVe3763372016-12-22 02:50:20 +00001260 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1261 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1262 assert(isBaseAnAllocSizeCall(Base) &&
1263 "Only alloc_size bases can have unsized arrays");
1264 Designator.FirstEntryIsAnUnsizedArray = true;
1265 Designator.addUnsizedArrayUnchecked(ElemTy);
1266 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001267 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001268 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1269 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001270 }
Richard Smith66c96992012-02-18 22:04:06 +00001271 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001272 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1273 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001274 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001275 void clearIsNullPointer() {
1276 IsNullPtr = false;
1277 }
1278 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, uint64_t Index,
1279 CharUnits ElementSize) {
1280 // Compute the new offset in the appropriate width.
1281 Offset += Index * ElementSize;
1282 if (Index && checkNullPointer(Info, E, CSK_ArrayIndex))
1283 Designator.adjustIndex(Info, E, Index);
1284 if (Index)
1285 clearIsNullPointer();
1286 }
1287 void adjustOffset(CharUnits N) {
1288 Offset += N;
1289 if (N.getQuantity())
1290 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001291 }
John McCall45d55e42010-05-07 21:00:08 +00001292 };
Richard Smith027bf112011-11-17 22:56:20 +00001293
1294 struct MemberPtr {
1295 MemberPtr() {}
1296 explicit MemberPtr(const ValueDecl *Decl) :
1297 DeclAndIsDerivedMember(Decl, false), Path() {}
1298
1299 /// The member or (direct or indirect) field referred to by this member
1300 /// pointer, or 0 if this is a null member pointer.
1301 const ValueDecl *getDecl() const {
1302 return DeclAndIsDerivedMember.getPointer();
1303 }
1304 /// Is this actually a member of some type derived from the relevant class?
1305 bool isDerivedMember() const {
1306 return DeclAndIsDerivedMember.getInt();
1307 }
1308 /// Get the class which the declaration actually lives in.
1309 const CXXRecordDecl *getContainingRecord() const {
1310 return cast<CXXRecordDecl>(
1311 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1312 }
1313
Richard Smith2e312c82012-03-03 22:46:17 +00001314 void moveInto(APValue &V) const {
1315 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001316 }
Richard Smith2e312c82012-03-03 22:46:17 +00001317 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001318 assert(V.isMemberPointer());
1319 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1320 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1321 Path.clear();
1322 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1323 Path.insert(Path.end(), P.begin(), P.end());
1324 }
1325
1326 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1327 /// whether the member is a member of some class derived from the class type
1328 /// of the member pointer.
1329 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1330 /// Path - The path of base/derived classes from the member declaration's
1331 /// class (exclusive) to the class type of the member pointer (inclusive).
1332 SmallVector<const CXXRecordDecl*, 4> Path;
1333
1334 /// Perform a cast towards the class of the Decl (either up or down the
1335 /// hierarchy).
1336 bool castBack(const CXXRecordDecl *Class) {
1337 assert(!Path.empty());
1338 const CXXRecordDecl *Expected;
1339 if (Path.size() >= 2)
1340 Expected = Path[Path.size() - 2];
1341 else
1342 Expected = getContainingRecord();
1343 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1344 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1345 // if B does not contain the original member and is not a base or
1346 // derived class of the class containing the original member, the result
1347 // of the cast is undefined.
1348 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1349 // (D::*). We consider that to be a language defect.
1350 return false;
1351 }
1352 Path.pop_back();
1353 return true;
1354 }
1355 /// Perform a base-to-derived member pointer cast.
1356 bool castToDerived(const CXXRecordDecl *Derived) {
1357 if (!getDecl())
1358 return true;
1359 if (!isDerivedMember()) {
1360 Path.push_back(Derived);
1361 return true;
1362 }
1363 if (!castBack(Derived))
1364 return false;
1365 if (Path.empty())
1366 DeclAndIsDerivedMember.setInt(false);
1367 return true;
1368 }
1369 /// Perform a derived-to-base member pointer cast.
1370 bool castToBase(const CXXRecordDecl *Base) {
1371 if (!getDecl())
1372 return true;
1373 if (Path.empty())
1374 DeclAndIsDerivedMember.setInt(true);
1375 if (isDerivedMember()) {
1376 Path.push_back(Base);
1377 return true;
1378 }
1379 return castBack(Base);
1380 }
1381 };
Richard Smith357362d2011-12-13 06:39:58 +00001382
Richard Smith7bb00672012-02-01 01:42:44 +00001383 /// Compare two member pointers, which are assumed to be of the same type.
1384 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1385 if (!LHS.getDecl() || !RHS.getDecl())
1386 return !LHS.getDecl() && !RHS.getDecl();
1387 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1388 return false;
1389 return LHS.Path == RHS.Path;
1390 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001391}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001392
Richard Smith2e312c82012-03-03 22:46:17 +00001393static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001394static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1395 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001396 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001397static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1398static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001399static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1400 EvalInfo &Info);
1401static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001402static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001403static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001404 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001405static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001406static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001407static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001408static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001409
1410//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001411// Misc utilities
1412//===----------------------------------------------------------------------===//
1413
Richard Smith84401042013-06-03 05:03:02 +00001414/// Produce a string describing the given constexpr call.
1415static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1416 unsigned ArgIndex = 0;
1417 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1418 !isa<CXXConstructorDecl>(Frame->Callee) &&
1419 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1420
1421 if (!IsMemberCall)
1422 Out << *Frame->Callee << '(';
1423
1424 if (Frame->This && IsMemberCall) {
1425 APValue Val;
1426 Frame->This->moveInto(Val);
1427 Val.printPretty(Out, Frame->Info.Ctx,
1428 Frame->This->Designator.MostDerivedType);
1429 // FIXME: Add parens around Val if needed.
1430 Out << "->" << *Frame->Callee << '(';
1431 IsMemberCall = false;
1432 }
1433
1434 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1435 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1436 if (ArgIndex > (unsigned)IsMemberCall)
1437 Out << ", ";
1438
1439 const ParmVarDecl *Param = *I;
1440 const APValue &Arg = Frame->Arguments[ArgIndex];
1441 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1442
1443 if (ArgIndex == 0 && IsMemberCall)
1444 Out << "->" << *Frame->Callee << '(';
1445 }
1446
1447 Out << ')';
1448}
1449
Richard Smithd9f663b2013-04-22 15:31:51 +00001450/// Evaluate an expression to see if it had side-effects, and discard its
1451/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001452/// \return \c true if the caller should keep evaluating.
1453static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001454 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001455 if (!Evaluate(Scratch, Info, E))
1456 // We don't need the value, but we might have skipped a side effect here.
1457 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001458 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001459}
1460
Richard Smith861b5b52013-05-07 23:34:45 +00001461/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1462/// return its existing value.
1463static int64_t getExtValue(const APSInt &Value) {
1464 return Value.isSigned() ? Value.getSExtValue()
1465 : static_cast<int64_t>(Value.getZExtValue());
1466}
1467
Richard Smithd62306a2011-11-10 06:34:14 +00001468/// Should this call expression be treated as a string literal?
1469static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001470 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001471 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1472 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1473}
1474
Richard Smithce40ad62011-11-12 22:28:03 +00001475static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001476 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1477 // constant expression of pointer type that evaluates to...
1478
1479 // ... a null pointer value, or a prvalue core constant expression of type
1480 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001481 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001482
Richard Smithce40ad62011-11-12 22:28:03 +00001483 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1484 // ... the address of an object with static storage duration,
1485 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1486 return VD->hasGlobalStorage();
1487 // ... the address of a function,
1488 return isa<FunctionDecl>(D);
1489 }
1490
1491 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001492 switch (E->getStmtClass()) {
1493 default:
1494 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001495 case Expr::CompoundLiteralExprClass: {
1496 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1497 return CLE->isFileScope() && CLE->isLValue();
1498 }
Richard Smithe6c01442013-06-05 00:46:14 +00001499 case Expr::MaterializeTemporaryExprClass:
1500 // A materialized temporary might have been lifetime-extended to static
1501 // storage duration.
1502 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001503 // A string literal has static storage duration.
1504 case Expr::StringLiteralClass:
1505 case Expr::PredefinedExprClass:
1506 case Expr::ObjCStringLiteralClass:
1507 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001508 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001509 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001510 return true;
1511 case Expr::CallExprClass:
1512 return IsStringLiteralCall(cast<CallExpr>(E));
1513 // For GCC compatibility, &&label has static storage duration.
1514 case Expr::AddrLabelExprClass:
1515 return true;
1516 // A Block literal expression may be used as the initialization value for
1517 // Block variables at global or local static scope.
1518 case Expr::BlockExprClass:
1519 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001520 case Expr::ImplicitValueInitExprClass:
1521 // FIXME:
1522 // We can never form an lvalue with an implicit value initialization as its
1523 // base through expression evaluation, so these only appear in one case: the
1524 // implicit variable declaration we invent when checking whether a constexpr
1525 // constructor can produce a constant expression. We must assume that such
1526 // an expression might be a global lvalue.
1527 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001528 }
John McCall95007602010-05-10 23:27:23 +00001529}
1530
Richard Smithb228a862012-02-15 02:18:13 +00001531static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1532 assert(Base && "no location for a null lvalue");
1533 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1534 if (VD)
1535 Info.Note(VD->getLocation(), diag::note_declared_at);
1536 else
Ted Kremenek28831752012-08-23 20:46:57 +00001537 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001538 diag::note_constexpr_temporary_here);
1539}
1540
Richard Smith80815602011-11-07 05:07:52 +00001541/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001542/// value for an address or reference constant expression. Return true if we
1543/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001544static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1545 QualType Type, const LValue &LVal) {
1546 bool IsReferenceType = Type->isReferenceType();
1547
Richard Smith357362d2011-12-13 06:39:58 +00001548 APValue::LValueBase Base = LVal.getLValueBase();
1549 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1550
Richard Smith0dea49e2012-02-18 04:58:18 +00001551 // Check that the object is a global. Note that the fake 'this' object we
1552 // manufacture when checking potential constant expressions is conservatively
1553 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001554 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001555 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001556 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001557 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001558 << IsReferenceType << !Designator.Entries.empty()
1559 << !!VD << VD;
1560 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001561 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001562 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001563 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001564 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001565 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001566 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001567 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001568 LVal.getLValueCallIndex() == 0) &&
1569 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001570
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001571 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1572 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001573 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001574 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001575 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001576
Hans Wennborg82dd8772014-06-25 22:19:48 +00001577 // A dllimport variable never acts like a constant.
1578 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001579 return false;
1580 }
1581 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1582 // __declspec(dllimport) must be handled very carefully:
1583 // We must never initialize an expression with the thunk in C++.
1584 // Doing otherwise would allow the same id-expression to yield
1585 // different addresses for the same function in different translation
1586 // units. However, this means that we must dynamically initialize the
1587 // expression with the contents of the import address table at runtime.
1588 //
1589 // The C language has no notion of ODR; furthermore, it has no notion of
1590 // dynamic initialization. This means that we are permitted to
1591 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001592 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001593 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001594 }
1595 }
1596
Richard Smitha8105bc2012-01-06 16:39:00 +00001597 // Allow address constant expressions to be past-the-end pointers. This is
1598 // an extension: the standard requires them to point to an object.
1599 if (!IsReferenceType)
1600 return true;
1601
1602 // A reference constant expression must refer to an object.
1603 if (!Base) {
1604 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001605 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001606 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001607 }
1608
Richard Smith357362d2011-12-13 06:39:58 +00001609 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001610 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001611 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001612 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001613 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001614 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001615 }
1616
Richard Smith80815602011-11-07 05:07:52 +00001617 return true;
1618}
1619
Richard Smithfddd3842011-12-30 21:15:51 +00001620/// Check that this core constant expression is of literal type, and if not,
1621/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001622static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001623 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001624 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001625 return true;
1626
Richard Smith7525ff62013-05-09 07:14:00 +00001627 // C++1y: A constant initializer for an object o [...] may also invoke
1628 // constexpr constructors for o and its subobjects even if those objects
1629 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001630 //
1631 // C++11 missed this detail for aggregates, so classes like this:
1632 // struct foo_t { union { int i; volatile int j; } u; };
1633 // are not (obviously) initializable like so:
1634 // __attribute__((__require_constant_initialization__))
1635 // static const foo_t x = {{0}};
1636 // because "i" is a subobject with non-literal initialization (due to the
1637 // volatile member of the union). See:
1638 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1639 // Therefore, we use the C++1y behavior.
1640 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001641 return true;
1642
Richard Smithfddd3842011-12-30 21:15:51 +00001643 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001644 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001645 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001646 << E->getType();
1647 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001648 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001649 return false;
1650}
1651
Richard Smith0b0a0b62011-10-29 20:57:55 +00001652/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001653/// constant expression. If not, report an appropriate diagnostic. Does not
1654/// check that the expression is of literal type.
1655static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1656 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001657 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001658 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001659 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001660 return false;
1661 }
1662
Richard Smith77be48a2014-07-31 06:31:19 +00001663 // We allow _Atomic(T) to be initialized from anything that T can be
1664 // initialized from.
1665 if (const AtomicType *AT = Type->getAs<AtomicType>())
1666 Type = AT->getValueType();
1667
Richard Smithb228a862012-02-15 02:18:13 +00001668 // Core issue 1454: For a literal constant expression of array or class type,
1669 // each subobject of its value shall have been initialized by a constant
1670 // expression.
1671 if (Value.isArray()) {
1672 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1673 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1674 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1675 Value.getArrayInitializedElt(I)))
1676 return false;
1677 }
1678 if (!Value.hasArrayFiller())
1679 return true;
1680 return CheckConstantExpression(Info, DiagLoc, EltTy,
1681 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001682 }
Richard Smithb228a862012-02-15 02:18:13 +00001683 if (Value.isUnion() && Value.getUnionField()) {
1684 return CheckConstantExpression(Info, DiagLoc,
1685 Value.getUnionField()->getType(),
1686 Value.getUnionValue());
1687 }
1688 if (Value.isStruct()) {
1689 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1690 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1691 unsigned BaseIndex = 0;
1692 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1693 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1694 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1695 Value.getStructBase(BaseIndex)))
1696 return false;
1697 }
1698 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001699 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001700 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1701 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001702 return false;
1703 }
1704 }
1705
1706 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001707 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001708 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001709 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1710 }
1711
1712 // Everything else is fine.
1713 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001714}
1715
Benjamin Kramer8407df72015-03-09 16:47:52 +00001716static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001717 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001718}
1719
1720static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001721 if (Value.CallIndex)
1722 return false;
1723 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1724 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001725}
1726
Richard Smithcecf1842011-11-01 21:06:14 +00001727static bool IsWeakLValue(const LValue &Value) {
1728 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001729 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001730}
1731
David Majnemerb5116032014-12-09 23:32:34 +00001732static bool isZeroSized(const LValue &Value) {
1733 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001734 if (Decl && isa<VarDecl>(Decl)) {
1735 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001736 if (Ty->isArrayType())
1737 return Ty->isIncompleteType() ||
1738 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001739 }
1740 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001741}
1742
Richard Smith2e312c82012-03-03 22:46:17 +00001743static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001744 // A null base expression indicates a null pointer. These are always
1745 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001746 if (!Value.getLValueBase()) {
1747 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001748 return true;
1749 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001750
Richard Smith027bf112011-11-17 22:56:20 +00001751 // We have a non-null base. These are generally known to be true, but if it's
1752 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001753 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001754 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001755 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001756}
1757
Richard Smith2e312c82012-03-03 22:46:17 +00001758static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001759 switch (Val.getKind()) {
1760 case APValue::Uninitialized:
1761 return false;
1762 case APValue::Int:
1763 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001764 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001765 case APValue::Float:
1766 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001767 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001768 case APValue::ComplexInt:
1769 Result = Val.getComplexIntReal().getBoolValue() ||
1770 Val.getComplexIntImag().getBoolValue();
1771 return true;
1772 case APValue::ComplexFloat:
1773 Result = !Val.getComplexFloatReal().isZero() ||
1774 !Val.getComplexFloatImag().isZero();
1775 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001776 case APValue::LValue:
1777 return EvalPointerValueAsBool(Val, Result);
1778 case APValue::MemberPointer:
1779 Result = Val.getMemberPointerDecl();
1780 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001781 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001782 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001783 case APValue::Struct:
1784 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001785 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001786 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001787 }
1788
Richard Smith11562c52011-10-28 17:51:58 +00001789 llvm_unreachable("unknown APValue kind");
1790}
1791
1792static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1793 EvalInfo &Info) {
1794 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001795 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001796 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001797 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001798 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001799}
1800
Richard Smith357362d2011-12-13 06:39:58 +00001801template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001802static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001803 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001804 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001805 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001806 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001807}
1808
1809static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1810 QualType SrcType, const APFloat &Value,
1811 QualType DestType, APSInt &Result) {
1812 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001813 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001814 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001815
Richard Smith357362d2011-12-13 06:39:58 +00001816 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001817 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001818 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1819 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001820 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001821 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001822}
1823
Richard Smith357362d2011-12-13 06:39:58 +00001824static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1825 QualType SrcType, QualType DestType,
1826 APFloat &Result) {
1827 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001828 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001829 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1830 APFloat::rmNearestTiesToEven, &ignored)
1831 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001832 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001833 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001834}
1835
Richard Smith911e1422012-01-30 22:27:01 +00001836static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1837 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001838 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001839 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001840 APSInt Result = Value;
1841 // Figure out if this is a truncate, extend or noop cast.
1842 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001843 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001844 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001845 return Result;
1846}
1847
Richard Smith357362d2011-12-13 06:39:58 +00001848static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1849 QualType SrcType, const APSInt &Value,
1850 QualType DestType, APFloat &Result) {
1851 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1852 if (Result.convertFromAPInt(Value, Value.isSigned(),
1853 APFloat::rmNearestTiesToEven)
1854 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001855 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001856 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001857}
1858
Richard Smith49ca8aa2013-08-06 07:09:20 +00001859static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1860 APValue &Value, const FieldDecl *FD) {
1861 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1862
1863 if (!Value.isInt()) {
1864 // Trying to store a pointer-cast-to-integer into a bitfield.
1865 // FIXME: In this case, we should provide the diagnostic for casting
1866 // a pointer to an integer.
1867 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001868 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001869 return false;
1870 }
1871
1872 APSInt &Int = Value.getInt();
1873 unsigned OldBitWidth = Int.getBitWidth();
1874 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1875 if (NewBitWidth < OldBitWidth)
1876 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1877 return true;
1878}
1879
Eli Friedman803acb32011-12-22 03:51:45 +00001880static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1881 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001882 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001883 if (!Evaluate(SVal, Info, E))
1884 return false;
1885 if (SVal.isInt()) {
1886 Res = SVal.getInt();
1887 return true;
1888 }
1889 if (SVal.isFloat()) {
1890 Res = SVal.getFloat().bitcastToAPInt();
1891 return true;
1892 }
1893 if (SVal.isVector()) {
1894 QualType VecTy = E->getType();
1895 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1896 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1897 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1898 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1899 Res = llvm::APInt::getNullValue(VecSize);
1900 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1901 APValue &Elt = SVal.getVectorElt(i);
1902 llvm::APInt EltAsInt;
1903 if (Elt.isInt()) {
1904 EltAsInt = Elt.getInt();
1905 } else if (Elt.isFloat()) {
1906 EltAsInt = Elt.getFloat().bitcastToAPInt();
1907 } else {
1908 // Don't try to handle vectors of anything other than int or float
1909 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001910 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001911 return false;
1912 }
1913 unsigned BaseEltSize = EltAsInt.getBitWidth();
1914 if (BigEndian)
1915 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1916 else
1917 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1918 }
1919 return true;
1920 }
1921 // Give up if the input isn't an int, float, or vector. For example, we
1922 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001923 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001924 return false;
1925}
1926
Richard Smith43e77732013-05-07 04:50:00 +00001927/// Perform the given integer operation, which is known to need at most BitWidth
1928/// bits, and check for overflow in the original type (if that type was not an
1929/// unsigned type).
1930template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001931static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1932 const APSInt &LHS, const APSInt &RHS,
1933 unsigned BitWidth, Operation Op,
1934 APSInt &Result) {
1935 if (LHS.isUnsigned()) {
1936 Result = Op(LHS, RHS);
1937 return true;
1938 }
Richard Smith43e77732013-05-07 04:50:00 +00001939
1940 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001941 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001942 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001943 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001944 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001945 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001946 << Result.toString(10) << E->getType();
1947 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001948 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001949 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001950 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001951}
1952
1953/// Perform the given binary integer operation.
1954static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1955 BinaryOperatorKind Opcode, APSInt RHS,
1956 APSInt &Result) {
1957 switch (Opcode) {
1958 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001959 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001960 return false;
1961 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001962 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1963 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001964 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001965 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1966 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001967 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001968 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1969 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001970 case BO_And: Result = LHS & RHS; return true;
1971 case BO_Xor: Result = LHS ^ RHS; return true;
1972 case BO_Or: Result = LHS | RHS; return true;
1973 case BO_Div:
1974 case BO_Rem:
1975 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001976 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00001977 return false;
1978 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001979 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1980 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1981 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001982 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1983 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001984 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1985 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001986 return true;
1987 case BO_Shl: {
1988 if (Info.getLangOpts().OpenCL)
1989 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1990 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1991 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1992 RHS.isUnsigned());
1993 else if (RHS.isSigned() && RHS.isNegative()) {
1994 // During constant-folding, a negative shift is an opposite shift. Such
1995 // a shift is not a constant expression.
1996 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1997 RHS = -RHS;
1998 goto shift_right;
1999 }
2000 shift_left:
2001 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2002 // the shifted type.
2003 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2004 if (SA != RHS) {
2005 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2006 << RHS << E->getType() << LHS.getBitWidth();
2007 } else if (LHS.isSigned()) {
2008 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2009 // operand, and must not overflow the corresponding unsigned type.
2010 if (LHS.isNegative())
2011 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2012 else if (LHS.countLeadingZeros() < SA)
2013 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2014 }
2015 Result = LHS << SA;
2016 return true;
2017 }
2018 case BO_Shr: {
2019 if (Info.getLangOpts().OpenCL)
2020 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2021 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2022 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2023 RHS.isUnsigned());
2024 else if (RHS.isSigned() && RHS.isNegative()) {
2025 // During constant-folding, a negative shift is an opposite shift. Such a
2026 // shift is not a constant expression.
2027 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2028 RHS = -RHS;
2029 goto shift_left;
2030 }
2031 shift_right:
2032 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2033 // shifted type.
2034 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2035 if (SA != RHS)
2036 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2037 << RHS << E->getType() << LHS.getBitWidth();
2038 Result = LHS >> SA;
2039 return true;
2040 }
2041
2042 case BO_LT: Result = LHS < RHS; return true;
2043 case BO_GT: Result = LHS > RHS; return true;
2044 case BO_LE: Result = LHS <= RHS; return true;
2045 case BO_GE: Result = LHS >= RHS; return true;
2046 case BO_EQ: Result = LHS == RHS; return true;
2047 case BO_NE: Result = LHS != RHS; return true;
2048 }
2049}
2050
Richard Smith861b5b52013-05-07 23:34:45 +00002051/// Perform the given binary floating-point operation, in-place, on LHS.
2052static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2053 APFloat &LHS, BinaryOperatorKind Opcode,
2054 const APFloat &RHS) {
2055 switch (Opcode) {
2056 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002057 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002058 return false;
2059 case BO_Mul:
2060 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2061 break;
2062 case BO_Add:
2063 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2064 break;
2065 case BO_Sub:
2066 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2067 break;
2068 case BO_Div:
2069 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2070 break;
2071 }
2072
Richard Smith0c6124b2015-12-03 01:36:22 +00002073 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002074 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002075 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002076 }
Richard Smith861b5b52013-05-07 23:34:45 +00002077 return true;
2078}
2079
Richard Smitha8105bc2012-01-06 16:39:00 +00002080/// Cast an lvalue referring to a base subobject to a derived class, by
2081/// truncating the lvalue's path to the given length.
2082static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2083 const RecordDecl *TruncatedType,
2084 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002085 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002086
2087 // Check we actually point to a derived class object.
2088 if (TruncatedElements == D.Entries.size())
2089 return true;
2090 assert(TruncatedElements >= D.MostDerivedPathLength &&
2091 "not casting to a derived class");
2092 if (!Result.checkSubobject(Info, E, CSK_Derived))
2093 return false;
2094
2095 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002096 const RecordDecl *RD = TruncatedType;
2097 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002098 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002099 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2100 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002101 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002102 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002103 else
Richard Smithd62306a2011-11-10 06:34:14 +00002104 Result.Offset -= Layout.getBaseClassOffset(Base);
2105 RD = Base;
2106 }
Richard Smith027bf112011-11-17 22:56:20 +00002107 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002108 return true;
2109}
2110
John McCalld7bca762012-05-01 00:38:49 +00002111static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002112 const CXXRecordDecl *Derived,
2113 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002114 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002115 if (!RL) {
2116 if (Derived->isInvalidDecl()) return false;
2117 RL = &Info.Ctx.getASTRecordLayout(Derived);
2118 }
2119
Richard Smithd62306a2011-11-10 06:34:14 +00002120 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002121 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002122 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002123}
2124
Richard Smitha8105bc2012-01-06 16:39:00 +00002125static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002126 const CXXRecordDecl *DerivedDecl,
2127 const CXXBaseSpecifier *Base) {
2128 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2129
John McCalld7bca762012-05-01 00:38:49 +00002130 if (!Base->isVirtual())
2131 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002132
Richard Smitha8105bc2012-01-06 16:39:00 +00002133 SubobjectDesignator &D = Obj.Designator;
2134 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002135 return false;
2136
Richard Smitha8105bc2012-01-06 16:39:00 +00002137 // Extract most-derived object and corresponding type.
2138 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2139 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2140 return false;
2141
2142 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002143 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002144 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2145 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002146 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002147 return true;
2148}
2149
Richard Smith84401042013-06-03 05:03:02 +00002150static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2151 QualType Type, LValue &Result) {
2152 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2153 PathE = E->path_end();
2154 PathI != PathE; ++PathI) {
2155 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2156 *PathI))
2157 return false;
2158 Type = (*PathI)->getType();
2159 }
2160 return true;
2161}
2162
Richard Smithd62306a2011-11-10 06:34:14 +00002163/// Update LVal to refer to the given field, which must be a member of the type
2164/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002165static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002166 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002167 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002168 if (!RL) {
2169 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002170 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002171 }
Richard Smithd62306a2011-11-10 06:34:14 +00002172
2173 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002174 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002175 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002176 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002177}
2178
Richard Smith1b78b3d2012-01-25 22:15:11 +00002179/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002180static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002181 LValue &LVal,
2182 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002183 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002184 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002185 return false;
2186 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002187}
2188
Richard Smithd62306a2011-11-10 06:34:14 +00002189/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002190static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2191 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002192 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2193 // extension.
2194 if (Type->isVoidType() || Type->isFunctionType()) {
2195 Size = CharUnits::One();
2196 return true;
2197 }
2198
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002199 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002200 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002201 return false;
2202 }
2203
Richard Smithd62306a2011-11-10 06:34:14 +00002204 if (!Type->isConstantSizeType()) {
2205 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002206 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002207 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002208 return false;
2209 }
2210
2211 Size = Info.Ctx.getTypeSizeInChars(Type);
2212 return true;
2213}
2214
2215/// Update a pointer value to model pointer arithmetic.
2216/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002217/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002218/// \param LVal - The pointer value to be updated.
2219/// \param EltTy - The pointee type represented by LVal.
2220/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002221static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2222 LValue &LVal, QualType EltTy,
2223 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002224 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002225 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002226 return false;
2227
Yaxun Liu402804b2016-12-15 08:09:08 +00002228 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002229 return true;
2230}
2231
Richard Smith66c96992012-02-18 22:04:06 +00002232/// Update an lvalue to refer to a component of a complex number.
2233/// \param Info - Information about the ongoing evaluation.
2234/// \param LVal - The lvalue to be updated.
2235/// \param EltTy - The complex number's component type.
2236/// \param Imag - False for the real component, true for the imaginary.
2237static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2238 LValue &LVal, QualType EltTy,
2239 bool Imag) {
2240 if (Imag) {
2241 CharUnits SizeOfComponent;
2242 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2243 return false;
2244 LVal.Offset += SizeOfComponent;
2245 }
2246 LVal.addComplex(Info, E, EltTy, Imag);
2247 return true;
2248}
2249
Richard Smith27908702011-10-24 17:54:18 +00002250/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002251///
2252/// \param Info Information about the ongoing evaluation.
2253/// \param E An expression to be used when printing diagnostics.
2254/// \param VD The variable whose initializer should be obtained.
2255/// \param Frame The frame in which the variable was created. Must be null
2256/// if this variable is not local to the evaluation.
2257/// \param Result Filled in with a pointer to the value of the variable.
2258static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2259 const VarDecl *VD, CallStackFrame *Frame,
2260 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002261 // If this is a parameter to an active constexpr function call, perform
2262 // argument substitution.
2263 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002264 // Assume arguments of a potential constant expression are unknown
2265 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002266 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002267 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002268 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002269 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002270 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002271 }
Richard Smith3229b742013-05-05 21:17:10 +00002272 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002273 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002274 }
Richard Smith27908702011-10-24 17:54:18 +00002275
Richard Smithd9f663b2013-04-22 15:31:51 +00002276 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002277 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002278 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002279 if (!Result) {
2280 // Assume variables referenced within a lambda's call operator that were
2281 // not declared within the call operator are captures and during checking
2282 // of a potential constant expression, assume they are unknown constant
2283 // expressions.
2284 assert(isLambdaCallOperator(Frame->Callee) &&
2285 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2286 "missing value for local variable");
2287 if (Info.checkingPotentialConstantExpression())
2288 return false;
2289 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002290 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002291 diag::note_unimplemented_constexpr_lambda_feature_ast)
2292 << "captures not currently allowed";
2293 return false;
2294 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002295 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002296 }
2297
Richard Smithd0b4dd62011-12-19 06:19:21 +00002298 // Dig out the initializer, and use the declaration which it's attached to.
2299 const Expr *Init = VD->getAnyInitializer(VD);
2300 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002301 // If we're checking a potential constant expression, the variable could be
2302 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002303 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002304 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002305 return false;
2306 }
2307
Richard Smithd62306a2011-11-10 06:34:14 +00002308 // If we're currently evaluating the initializer of this declaration, use that
2309 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002310 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002311 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002312 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002313 }
2314
Richard Smithcecf1842011-11-01 21:06:14 +00002315 // Never evaluate the initializer of a weak variable. We can't be sure that
2316 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002317 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002318 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002319 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002320 }
Richard Smithcecf1842011-11-01 21:06:14 +00002321
Richard Smithd0b4dd62011-12-19 06:19:21 +00002322 // Check that we can fold the initializer. In C++, we will have already done
2323 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002324 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002325 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002326 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002327 Notes.size() + 1) << VD;
2328 Info.Note(VD->getLocation(), diag::note_declared_at);
2329 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002330 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002331 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002332 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002333 Notes.size() + 1) << VD;
2334 Info.Note(VD->getLocation(), diag::note_declared_at);
2335 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002336 }
Richard Smith27908702011-10-24 17:54:18 +00002337
Richard Smith3229b742013-05-05 21:17:10 +00002338 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002339 return true;
Richard Smith27908702011-10-24 17:54:18 +00002340}
2341
Richard Smith11562c52011-10-28 17:51:58 +00002342static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002343 Qualifiers Quals = T.getQualifiers();
2344 return Quals.hasConst() && !Quals.hasVolatile();
2345}
2346
Richard Smithe97cbd72011-11-11 04:05:33 +00002347/// Get the base index of the given base class within an APValue representing
2348/// the given derived class.
2349static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2350 const CXXRecordDecl *Base) {
2351 Base = Base->getCanonicalDecl();
2352 unsigned Index = 0;
2353 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2354 E = Derived->bases_end(); I != E; ++I, ++Index) {
2355 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2356 return Index;
2357 }
2358
2359 llvm_unreachable("base class missing from derived class's bases list");
2360}
2361
Richard Smith3da88fa2013-04-26 14:36:30 +00002362/// Extract the value of a character from a string literal.
2363static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2364 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002365 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2366 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2367 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002368 const StringLiteral *S = cast<StringLiteral>(Lit);
2369 const ConstantArrayType *CAT =
2370 Info.Ctx.getAsConstantArrayType(S->getType());
2371 assert(CAT && "string literal isn't an array");
2372 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002373 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002374
2375 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002376 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002377 if (Index < S->getLength())
2378 Value = S->getCodeUnit(Index);
2379 return Value;
2380}
2381
Richard Smith3da88fa2013-04-26 14:36:30 +00002382// Expand a string literal into an array of characters.
2383static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2384 APValue &Result) {
2385 const StringLiteral *S = cast<StringLiteral>(Lit);
2386 const ConstantArrayType *CAT =
2387 Info.Ctx.getAsConstantArrayType(S->getType());
2388 assert(CAT && "string literal isn't an array");
2389 QualType CharType = CAT->getElementType();
2390 assert(CharType->isIntegerType() && "unexpected character type");
2391
2392 unsigned Elts = CAT->getSize().getZExtValue();
2393 Result = APValue(APValue::UninitArray(),
2394 std::min(S->getLength(), Elts), Elts);
2395 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2396 CharType->isUnsignedIntegerType());
2397 if (Result.hasArrayFiller())
2398 Result.getArrayFiller() = APValue(Value);
2399 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2400 Value = S->getCodeUnit(I);
2401 Result.getArrayInitializedElt(I) = APValue(Value);
2402 }
2403}
2404
2405// Expand an array so that it has more than Index filled elements.
2406static void expandArray(APValue &Array, unsigned Index) {
2407 unsigned Size = Array.getArraySize();
2408 assert(Index < Size);
2409
2410 // Always at least double the number of elements for which we store a value.
2411 unsigned OldElts = Array.getArrayInitializedElts();
2412 unsigned NewElts = std::max(Index+1, OldElts * 2);
2413 NewElts = std::min(Size, std::max(NewElts, 8u));
2414
2415 // Copy the data across.
2416 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2417 for (unsigned I = 0; I != OldElts; ++I)
2418 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2419 for (unsigned I = OldElts; I != NewElts; ++I)
2420 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2421 if (NewValue.hasArrayFiller())
2422 NewValue.getArrayFiller() = Array.getArrayFiller();
2423 Array.swap(NewValue);
2424}
2425
Richard Smithb01fe402014-09-16 01:24:02 +00002426/// Determine whether a type would actually be read by an lvalue-to-rvalue
2427/// conversion. If it's of class type, we may assume that the copy operation
2428/// is trivial. Note that this is never true for a union type with fields
2429/// (because the copy always "reads" the active member) and always true for
2430/// a non-class type.
2431static bool isReadByLvalueToRvalueConversion(QualType T) {
2432 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2433 if (!RD || (RD->isUnion() && !RD->field_empty()))
2434 return true;
2435 if (RD->isEmpty())
2436 return false;
2437
2438 for (auto *Field : RD->fields())
2439 if (isReadByLvalueToRvalueConversion(Field->getType()))
2440 return true;
2441
2442 for (auto &BaseSpec : RD->bases())
2443 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2444 return true;
2445
2446 return false;
2447}
2448
2449/// Diagnose an attempt to read from any unreadable field within the specified
2450/// type, which might be a class type.
2451static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2452 QualType T) {
2453 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2454 if (!RD)
2455 return false;
2456
2457 if (!RD->hasMutableFields())
2458 return false;
2459
2460 for (auto *Field : RD->fields()) {
2461 // If we're actually going to read this field in some way, then it can't
2462 // be mutable. If we're in a union, then assigning to a mutable field
2463 // (even an empty one) can change the active member, so that's not OK.
2464 // FIXME: Add core issue number for the union case.
2465 if (Field->isMutable() &&
2466 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002467 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002468 Info.Note(Field->getLocation(), diag::note_declared_at);
2469 return true;
2470 }
2471
2472 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2473 return true;
2474 }
2475
2476 for (auto &BaseSpec : RD->bases())
2477 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2478 return true;
2479
2480 // All mutable fields were empty, and thus not actually read.
2481 return false;
2482}
2483
Richard Smith861b5b52013-05-07 23:34:45 +00002484/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002485enum AccessKinds {
2486 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002487 AK_Assign,
2488 AK_Increment,
2489 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002490};
2491
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002492namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002493/// A handle to a complete object (an object that is not a subobject of
2494/// another object).
2495struct CompleteObject {
2496 /// The value of the complete object.
2497 APValue *Value;
2498 /// The type of the complete object.
2499 QualType Type;
2500
Craig Topper36250ad2014-05-12 05:36:57 +00002501 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002502 CompleteObject(APValue *Value, QualType Type)
2503 : Value(Value), Type(Type) {
2504 assert(Value && "missing value for complete object");
2505 }
2506
Aaron Ballman67347662015-02-15 22:00:28 +00002507 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002508};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002509} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002510
Richard Smith3da88fa2013-04-26 14:36:30 +00002511/// Find the designated sub-object of an rvalue.
2512template<typename SubobjectHandler>
2513typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002514findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002515 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002516 if (Sub.Invalid)
2517 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002518 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002519 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002520 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002521 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002522 << handler.AccessKind;
2523 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002524 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002525 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002526 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002527
Richard Smith3229b742013-05-05 21:17:10 +00002528 APValue *O = Obj.Value;
2529 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002530 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002531
Richard Smithd62306a2011-11-10 06:34:14 +00002532 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002533 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2534 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002535 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002536 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002537 return handler.failed();
2538 }
2539
Richard Smith49ca8aa2013-08-06 07:09:20 +00002540 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002541 // If we are reading an object of class type, there may still be more
2542 // things we need to check: if there are any mutable subobjects, we
2543 // cannot perform this read. (This only happens when performing a trivial
2544 // copy or assignment.)
2545 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2546 diagnoseUnreadableFields(Info, E, ObjType))
2547 return handler.failed();
2548
Richard Smith49ca8aa2013-08-06 07:09:20 +00002549 if (!handler.found(*O, ObjType))
2550 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002551
Richard Smith49ca8aa2013-08-06 07:09:20 +00002552 // If we modified a bit-field, truncate it to the right width.
2553 if (handler.AccessKind != AK_Read &&
2554 LastField && LastField->isBitField() &&
2555 !truncateBitfieldValue(Info, E, *O, LastField))
2556 return false;
2557
2558 return true;
2559 }
2560
Craig Topper36250ad2014-05-12 05:36:57 +00002561 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002562 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002563 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002564 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002565 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002566 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002567 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002568 // Note, it should not be possible to form a pointer with a valid
2569 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002570 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002571 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002572 << handler.AccessKind;
2573 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002574 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002575 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002576 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002577
2578 ObjType = CAT->getElementType();
2579
Richard Smith14a94132012-02-17 03:35:37 +00002580 // An array object is represented as either an Array APValue or as an
2581 // LValue which refers to a string literal.
2582 if (O->isLValue()) {
2583 assert(I == N - 1 && "extracting subobject of character?");
2584 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002585 if (handler.AccessKind != AK_Read)
2586 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2587 *O);
2588 else
2589 return handler.foundString(*O, ObjType, Index);
2590 }
2591
2592 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002593 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002594 else if (handler.AccessKind != AK_Read) {
2595 expandArray(*O, Index);
2596 O = &O->getArrayInitializedElt(Index);
2597 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002598 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002599 } else if (ObjType->isAnyComplexType()) {
2600 // Next subobject is a complex number.
2601 uint64_t Index = Sub.Entries[I].ArrayIndex;
2602 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002603 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002604 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002605 << handler.AccessKind;
2606 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002607 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002608 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002609 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002610
2611 bool WasConstQualified = ObjType.isConstQualified();
2612 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2613 if (WasConstQualified)
2614 ObjType.addConst();
2615
Richard Smith66c96992012-02-18 22:04:06 +00002616 assert(I == N - 1 && "extracting subobject of scalar?");
2617 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002618 return handler.found(Index ? O->getComplexIntImag()
2619 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002620 } else {
2621 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002622 return handler.found(Index ? O->getComplexFloatImag()
2623 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002624 }
Richard Smithd62306a2011-11-10 06:34:14 +00002625 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002626 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002627 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002628 << Field;
2629 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002630 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002631 }
2632
Richard Smithd62306a2011-11-10 06:34:14 +00002633 // Next subobject is a class, struct or union field.
2634 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2635 if (RD->isUnion()) {
2636 const FieldDecl *UnionField = O->getUnionField();
2637 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002638 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002639 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002640 << handler.AccessKind << Field << !UnionField << UnionField;
2641 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002642 }
Richard Smithd62306a2011-11-10 06:34:14 +00002643 O = &O->getUnionValue();
2644 } else
2645 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002646
2647 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002648 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002649 if (WasConstQualified && !Field->isMutable())
2650 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002651
2652 if (ObjType.isVolatileQualified()) {
2653 if (Info.getLangOpts().CPlusPlus) {
2654 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002655 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002656 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002657 Info.Note(Field->getLocation(), diag::note_declared_at);
2658 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002659 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002660 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002661 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002662 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002663
2664 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002665 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002666 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002667 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2668 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2669 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002670
2671 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002672 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002673 if (WasConstQualified)
2674 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002675 }
2676 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002677}
2678
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002679namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002680struct ExtractSubobjectHandler {
2681 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002682 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002683
2684 static const AccessKinds AccessKind = AK_Read;
2685
2686 typedef bool result_type;
2687 bool failed() { return false; }
2688 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002689 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002690 return true;
2691 }
2692 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002693 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002694 return true;
2695 }
2696 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002697 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002698 return true;
2699 }
2700 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002701 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002702 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2703 return true;
2704 }
2705};
Richard Smith3229b742013-05-05 21:17:10 +00002706} // end anonymous namespace
2707
Richard Smith3da88fa2013-04-26 14:36:30 +00002708const AccessKinds ExtractSubobjectHandler::AccessKind;
2709
2710/// Extract the designated sub-object of an rvalue.
2711static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002712 const CompleteObject &Obj,
2713 const SubobjectDesignator &Sub,
2714 APValue &Result) {
2715 ExtractSubobjectHandler Handler = { Info, Result };
2716 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002717}
2718
Richard Smith3229b742013-05-05 21:17:10 +00002719namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002720struct ModifySubobjectHandler {
2721 EvalInfo &Info;
2722 APValue &NewVal;
2723 const Expr *E;
2724
2725 typedef bool result_type;
2726 static const AccessKinds AccessKind = AK_Assign;
2727
2728 bool checkConst(QualType QT) {
2729 // Assigning to a const object has undefined behavior.
2730 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002731 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002732 return false;
2733 }
2734 return true;
2735 }
2736
2737 bool failed() { return false; }
2738 bool found(APValue &Subobj, QualType SubobjType) {
2739 if (!checkConst(SubobjType))
2740 return false;
2741 // We've been given ownership of NewVal, so just swap it in.
2742 Subobj.swap(NewVal);
2743 return true;
2744 }
2745 bool found(APSInt &Value, QualType SubobjType) {
2746 if (!checkConst(SubobjType))
2747 return false;
2748 if (!NewVal.isInt()) {
2749 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002750 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002751 return false;
2752 }
2753 Value = NewVal.getInt();
2754 return true;
2755 }
2756 bool found(APFloat &Value, QualType SubobjType) {
2757 if (!checkConst(SubobjType))
2758 return false;
2759 Value = NewVal.getFloat();
2760 return true;
2761 }
2762 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2763 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2764 }
2765};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002766} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002767
Richard Smith3229b742013-05-05 21:17:10 +00002768const AccessKinds ModifySubobjectHandler::AccessKind;
2769
Richard Smith3da88fa2013-04-26 14:36:30 +00002770/// Update the designated sub-object of an rvalue to the given value.
2771static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002772 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002773 const SubobjectDesignator &Sub,
2774 APValue &NewVal) {
2775 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002776 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002777}
2778
Richard Smith84f6dcf2012-02-02 01:16:57 +00002779/// Find the position where two subobject designators diverge, or equivalently
2780/// the length of the common initial subsequence.
2781static unsigned FindDesignatorMismatch(QualType ObjType,
2782 const SubobjectDesignator &A,
2783 const SubobjectDesignator &B,
2784 bool &WasArrayIndex) {
2785 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2786 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002787 if (!ObjType.isNull() &&
2788 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002789 // Next subobject is an array element.
2790 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2791 WasArrayIndex = true;
2792 return I;
2793 }
Richard Smith66c96992012-02-18 22:04:06 +00002794 if (ObjType->isAnyComplexType())
2795 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2796 else
2797 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002798 } else {
2799 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2800 WasArrayIndex = false;
2801 return I;
2802 }
2803 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2804 // Next subobject is a field.
2805 ObjType = FD->getType();
2806 else
2807 // Next subobject is a base class.
2808 ObjType = QualType();
2809 }
2810 }
2811 WasArrayIndex = false;
2812 return I;
2813}
2814
2815/// Determine whether the given subobject designators refer to elements of the
2816/// same array object.
2817static bool AreElementsOfSameArray(QualType ObjType,
2818 const SubobjectDesignator &A,
2819 const SubobjectDesignator &B) {
2820 if (A.Entries.size() != B.Entries.size())
2821 return false;
2822
George Burgess IVa51c4072015-10-16 01:49:01 +00002823 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002824 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2825 // A is a subobject of the array element.
2826 return false;
2827
2828 // If A (and B) designates an array element, the last entry will be the array
2829 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2830 // of length 1' case, and the entire path must match.
2831 bool WasArrayIndex;
2832 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2833 return CommonLength >= A.Entries.size() - IsArray;
2834}
2835
Richard Smith3229b742013-05-05 21:17:10 +00002836/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002837static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2838 AccessKinds AK, const LValue &LVal,
2839 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002840 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002841 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002842 return CompleteObject();
2843 }
2844
Craig Topper36250ad2014-05-12 05:36:57 +00002845 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002846 if (LVal.CallIndex) {
2847 Frame = Info.getCallFrame(LVal.CallIndex);
2848 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002849 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002850 << AK << LVal.Base.is<const ValueDecl*>();
2851 NoteLValueLocation(Info, LVal.Base);
2852 return CompleteObject();
2853 }
Richard Smith3229b742013-05-05 21:17:10 +00002854 }
2855
2856 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2857 // is not a constant expression (even if the object is non-volatile). We also
2858 // apply this rule to C++98, in order to conform to the expected 'volatile'
2859 // semantics.
2860 if (LValType.isVolatileQualified()) {
2861 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002862 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002863 << AK << LValType;
2864 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002865 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002866 return CompleteObject();
2867 }
2868
2869 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002870 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002871 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002872
2873 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2874 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2875 // In C++11, constexpr, non-volatile variables initialized with constant
2876 // expressions are constant expressions too. Inside constexpr functions,
2877 // parameters are constant expressions even if they're non-const.
2878 // In C++1y, objects local to a constant expression (those with a Frame) are
2879 // both readable and writable inside constant expressions.
2880 // In C, such things can also be folded, although they are not ICEs.
2881 const VarDecl *VD = dyn_cast<VarDecl>(D);
2882 if (VD) {
2883 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2884 VD = VDef;
2885 }
2886 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002887 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002888 return CompleteObject();
2889 }
2890
2891 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002892 if (BaseType.isVolatileQualified()) {
2893 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002894 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002895 << AK << 1 << VD;
2896 Info.Note(VD->getLocation(), diag::note_declared_at);
2897 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002898 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002899 }
2900 return CompleteObject();
2901 }
2902
2903 // Unless we're looking at a local variable or argument in a constexpr call,
2904 // the variable we're reading must be const.
2905 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002906 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002907 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2908 // OK, we can read and modify an object if we're in the process of
2909 // evaluating its initializer, because its lifetime began in this
2910 // evaluation.
2911 } else if (AK != AK_Read) {
2912 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002913 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002914 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00002915 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002916 // OK, we can read this variable.
2917 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002918 // In OpenCL if a variable is in constant address space it is a const value.
2919 if (!(BaseType.isConstQualified() ||
2920 (Info.getLangOpts().OpenCL &&
2921 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002922 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002923 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002924 Info.Note(VD->getLocation(), diag::note_declared_at);
2925 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002926 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002927 }
2928 return CompleteObject();
2929 }
2930 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2931 // We support folding of const floating-point types, in order to make
2932 // static const data members of such types (supported as an extension)
2933 // more useful.
2934 if (Info.getLangOpts().CPlusPlus11) {
2935 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2936 Info.Note(VD->getLocation(), diag::note_declared_at);
2937 } else {
2938 Info.CCEDiag(E);
2939 }
George Burgess IVb5316982016-12-27 05:33:20 +00002940 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
2941 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
2942 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00002943 } else {
2944 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002945 if (Info.checkingPotentialConstantExpression() &&
2946 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2947 // The definition of this variable could be constexpr. We can't
2948 // access it right now, but may be able to in future.
2949 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002950 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002951 Info.Note(VD->getLocation(), diag::note_declared_at);
2952 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002953 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002954 }
2955 return CompleteObject();
2956 }
2957 }
2958
2959 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2960 return CompleteObject();
2961 } else {
2962 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2963
2964 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002965 if (const MaterializeTemporaryExpr *MTE =
2966 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2967 assert(MTE->getStorageDuration() == SD_Static &&
2968 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002969
Richard Smithe6c01442013-06-05 00:46:14 +00002970 // Per C++1y [expr.const]p2:
2971 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2972 // - a [...] glvalue of integral or enumeration type that refers to
2973 // a non-volatile const object [...]
2974 // [...]
2975 // - a [...] glvalue of literal type that refers to a non-volatile
2976 // object whose lifetime began within the evaluation of e.
2977 //
2978 // C++11 misses the 'began within the evaluation of e' check and
2979 // instead allows all temporaries, including things like:
2980 // int &&r = 1;
2981 // int x = ++r;
2982 // constexpr int k = r;
2983 // Therefore we use the C++1y rules in C++11 too.
2984 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2985 const ValueDecl *ED = MTE->getExtendingDecl();
2986 if (!(BaseType.isConstQualified() &&
2987 BaseType->isIntegralOrEnumerationType()) &&
2988 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002989 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00002990 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2991 return CompleteObject();
2992 }
2993
2994 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2995 assert(BaseVal && "got reference to unevaluated temporary");
2996 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002997 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00002998 return CompleteObject();
2999 }
3000 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003001 BaseVal = Frame->getTemporary(Base);
3002 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003003 }
Richard Smith3229b742013-05-05 21:17:10 +00003004
3005 // Volatile temporary objects cannot be accessed in constant expressions.
3006 if (BaseType.isVolatileQualified()) {
3007 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003008 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003009 << AK << 0;
3010 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3011 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003012 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003013 }
3014 return CompleteObject();
3015 }
3016 }
3017
Richard Smith7525ff62013-05-09 07:14:00 +00003018 // During the construction of an object, it is not yet 'const'.
3019 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3020 // and this doesn't do quite the right thing for const subobjects of the
3021 // object under construction.
3022 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3023 BaseType = Info.Ctx.getCanonicalType(BaseType);
3024 BaseType.removeLocalConst();
3025 }
3026
Richard Smith6d4c6582013-11-05 22:18:15 +00003027 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003028 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003029 //
3030 // FIXME: Not all local state is mutable. Allow local constant subobjects
3031 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003032 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3033 Info.EvalStatus.HasSideEffects) ||
3034 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003035 return CompleteObject();
3036
3037 return CompleteObject(BaseVal, BaseType);
3038}
3039
Richard Smith243ef902013-05-05 23:31:59 +00003040/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3041/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3042/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003043///
3044/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003045/// \param Conv - The expression for which we are performing the conversion.
3046/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003047/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3048/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003049/// \param LVal - The glvalue on which we are attempting to perform this action.
3050/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003051static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003052 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003053 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003054 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003055 return false;
3056
Richard Smith3229b742013-05-05 21:17:10 +00003057 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003058 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003059 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003060 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3061 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3062 // initializer until now for such expressions. Such an expression can't be
3063 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003064 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003065 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003066 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003067 }
Richard Smith3229b742013-05-05 21:17:10 +00003068 APValue Lit;
3069 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3070 return false;
3071 CompleteObject LitObj(&Lit, Base->getType());
3072 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003073 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003074 // We represent a string literal array as an lvalue pointing at the
3075 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003076 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003077 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3078 CompleteObject StrObj(&Str, Base->getType());
3079 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003080 }
Richard Smith11562c52011-10-28 17:51:58 +00003081 }
3082
Richard Smith3229b742013-05-05 21:17:10 +00003083 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3084 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003085}
3086
3087/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003088static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003089 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003090 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003091 return false;
3092
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003093 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003094 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003095 return false;
3096 }
3097
Richard Smith3229b742013-05-05 21:17:10 +00003098 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3099 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003100}
3101
Richard Smith243ef902013-05-05 23:31:59 +00003102static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3103 return T->isSignedIntegerType() &&
3104 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3105}
3106
3107namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003108struct CompoundAssignSubobjectHandler {
3109 EvalInfo &Info;
3110 const Expr *E;
3111 QualType PromotedLHSType;
3112 BinaryOperatorKind Opcode;
3113 const APValue &RHS;
3114
3115 static const AccessKinds AccessKind = AK_Assign;
3116
3117 typedef bool result_type;
3118
3119 bool checkConst(QualType QT) {
3120 // Assigning to a const object has undefined behavior.
3121 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003122 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003123 return false;
3124 }
3125 return true;
3126 }
3127
3128 bool failed() { return false; }
3129 bool found(APValue &Subobj, QualType SubobjType) {
3130 switch (Subobj.getKind()) {
3131 case APValue::Int:
3132 return found(Subobj.getInt(), SubobjType);
3133 case APValue::Float:
3134 return found(Subobj.getFloat(), SubobjType);
3135 case APValue::ComplexInt:
3136 case APValue::ComplexFloat:
3137 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003138 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003139 return false;
3140 case APValue::LValue:
3141 return foundPointer(Subobj, SubobjType);
3142 default:
3143 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003144 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003145 return false;
3146 }
3147 }
3148 bool found(APSInt &Value, QualType SubobjType) {
3149 if (!checkConst(SubobjType))
3150 return false;
3151
3152 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3153 // We don't support compound assignment on integer-cast-to-pointer
3154 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003155 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003156 return false;
3157 }
3158
3159 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3160 SubobjType, Value);
3161 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3162 return false;
3163 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3164 return true;
3165 }
3166 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003167 return checkConst(SubobjType) &&
3168 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3169 Value) &&
3170 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3171 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003172 }
3173 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3174 if (!checkConst(SubobjType))
3175 return false;
3176
3177 QualType PointeeType;
3178 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3179 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003180
3181 if (PointeeType.isNull() || !RHS.isInt() ||
3182 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003183 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003184 return false;
3185 }
3186
Richard Smith861b5b52013-05-07 23:34:45 +00003187 int64_t Offset = getExtValue(RHS.getInt());
3188 if (Opcode == BO_Sub)
3189 Offset = -Offset;
3190
3191 LValue LVal;
3192 LVal.setFrom(Info.Ctx, Subobj);
3193 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3194 return false;
3195 LVal.moveInto(Subobj);
3196 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003197 }
3198 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3199 llvm_unreachable("shouldn't encounter string elements here");
3200 }
3201};
3202} // end anonymous namespace
3203
3204const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3205
3206/// Perform a compound assignment of LVal <op>= RVal.
3207static bool handleCompoundAssignment(
3208 EvalInfo &Info, const Expr *E,
3209 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3210 BinaryOperatorKind Opcode, const APValue &RVal) {
3211 if (LVal.Designator.Invalid)
3212 return false;
3213
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003214 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003215 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003216 return false;
3217 }
3218
3219 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3220 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3221 RVal };
3222 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3223}
3224
3225namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003226struct IncDecSubobjectHandler {
3227 EvalInfo &Info;
3228 const Expr *E;
3229 AccessKinds AccessKind;
3230 APValue *Old;
3231
3232 typedef bool result_type;
3233
3234 bool checkConst(QualType QT) {
3235 // Assigning to a const object has undefined behavior.
3236 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003237 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003238 return false;
3239 }
3240 return true;
3241 }
3242
3243 bool failed() { return false; }
3244 bool found(APValue &Subobj, QualType SubobjType) {
3245 // Stash the old value. Also clear Old, so we don't clobber it later
3246 // if we're post-incrementing a complex.
3247 if (Old) {
3248 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003249 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003250 }
3251
3252 switch (Subobj.getKind()) {
3253 case APValue::Int:
3254 return found(Subobj.getInt(), SubobjType);
3255 case APValue::Float:
3256 return found(Subobj.getFloat(), SubobjType);
3257 case APValue::ComplexInt:
3258 return found(Subobj.getComplexIntReal(),
3259 SubobjType->castAs<ComplexType>()->getElementType()
3260 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3261 case APValue::ComplexFloat:
3262 return found(Subobj.getComplexFloatReal(),
3263 SubobjType->castAs<ComplexType>()->getElementType()
3264 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3265 case APValue::LValue:
3266 return foundPointer(Subobj, SubobjType);
3267 default:
3268 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003269 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003270 return false;
3271 }
3272 }
3273 bool found(APSInt &Value, QualType SubobjType) {
3274 if (!checkConst(SubobjType))
3275 return false;
3276
3277 if (!SubobjType->isIntegerType()) {
3278 // We don't support increment / decrement on integer-cast-to-pointer
3279 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003280 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003281 return false;
3282 }
3283
3284 if (Old) *Old = APValue(Value);
3285
3286 // bool arithmetic promotes to int, and the conversion back to bool
3287 // doesn't reduce mod 2^n, so special-case it.
3288 if (SubobjType->isBooleanType()) {
3289 if (AccessKind == AK_Increment)
3290 Value = 1;
3291 else
3292 Value = !Value;
3293 return true;
3294 }
3295
3296 bool WasNegative = Value.isNegative();
3297 if (AccessKind == AK_Increment) {
3298 ++Value;
3299
3300 if (!WasNegative && Value.isNegative() &&
3301 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3302 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003303 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003304 }
3305 } else {
3306 --Value;
3307
3308 if (WasNegative && !Value.isNegative() &&
3309 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3310 unsigned BitWidth = Value.getBitWidth();
3311 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3312 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003313 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003314 }
3315 }
3316 return true;
3317 }
3318 bool found(APFloat &Value, QualType SubobjType) {
3319 if (!checkConst(SubobjType))
3320 return false;
3321
3322 if (Old) *Old = APValue(Value);
3323
3324 APFloat One(Value.getSemantics(), 1);
3325 if (AccessKind == AK_Increment)
3326 Value.add(One, APFloat::rmNearestTiesToEven);
3327 else
3328 Value.subtract(One, APFloat::rmNearestTiesToEven);
3329 return true;
3330 }
3331 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3332 if (!checkConst(SubobjType))
3333 return false;
3334
3335 QualType PointeeType;
3336 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3337 PointeeType = PT->getPointeeType();
3338 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003339 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003340 return false;
3341 }
3342
3343 LValue LVal;
3344 LVal.setFrom(Info.Ctx, Subobj);
3345 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3346 AccessKind == AK_Increment ? 1 : -1))
3347 return false;
3348 LVal.moveInto(Subobj);
3349 return true;
3350 }
3351 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3352 llvm_unreachable("shouldn't encounter string elements here");
3353 }
3354};
3355} // end anonymous namespace
3356
3357/// Perform an increment or decrement on LVal.
3358static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3359 QualType LValType, bool IsIncrement, APValue *Old) {
3360 if (LVal.Designator.Invalid)
3361 return false;
3362
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003363 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003364 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003365 return false;
3366 }
3367
3368 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3369 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3370 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3371 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3372}
3373
Richard Smithe97cbd72011-11-11 04:05:33 +00003374/// Build an lvalue for the object argument of a member function call.
3375static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3376 LValue &This) {
3377 if (Object->getType()->isPointerType())
3378 return EvaluatePointer(Object, This, Info);
3379
3380 if (Object->isGLValue())
3381 return EvaluateLValue(Object, This, Info);
3382
Richard Smithd9f663b2013-04-22 15:31:51 +00003383 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003384 return EvaluateTemporary(Object, This, Info);
3385
Faisal Valie690b7a2016-07-02 22:34:24 +00003386 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003387 return false;
3388}
3389
3390/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3391/// lvalue referring to the result.
3392///
3393/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003394/// \param LV - An lvalue referring to the base of the member pointer.
3395/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003396/// \param IncludeMember - Specifies whether the member itself is included in
3397/// the resulting LValue subobject designator. This is not possible when
3398/// creating a bound member function.
3399/// \return The field or method declaration to which the member pointer refers,
3400/// or 0 if evaluation fails.
3401static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003402 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003403 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003404 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003405 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003406 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003407 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003408 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003409
3410 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3411 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003412 if (!MemPtr.getDecl()) {
3413 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003414 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003415 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003416 }
Richard Smith253c2a32012-01-27 01:14:48 +00003417
Richard Smith027bf112011-11-17 22:56:20 +00003418 if (MemPtr.isDerivedMember()) {
3419 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003420 // The end of the derived-to-base path for the base object must match the
3421 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003422 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003423 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003424 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003425 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003426 }
Richard Smith027bf112011-11-17 22:56:20 +00003427 unsigned PathLengthToMember =
3428 LV.Designator.Entries.size() - MemPtr.Path.size();
3429 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3430 const CXXRecordDecl *LVDecl = getAsBaseClass(
3431 LV.Designator.Entries[PathLengthToMember + I]);
3432 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003433 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003434 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003435 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003436 }
Richard Smith027bf112011-11-17 22:56:20 +00003437 }
3438
3439 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003440 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003441 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003442 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003443 } else if (!MemPtr.Path.empty()) {
3444 // Extend the LValue path with the member pointer's path.
3445 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3446 MemPtr.Path.size() + IncludeMember);
3447
3448 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003449 if (const PointerType *PT = LVType->getAs<PointerType>())
3450 LVType = PT->getPointeeType();
3451 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3452 assert(RD && "member pointer access on non-class-type expression");
3453 // The first class in the path is that of the lvalue.
3454 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3455 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003456 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003457 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003458 RD = Base;
3459 }
3460 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003461 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3462 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003463 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003464 }
3465
3466 // Add the member. Note that we cannot build bound member functions here.
3467 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003468 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003469 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003470 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003471 } else if (const IndirectFieldDecl *IFD =
3472 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003473 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003474 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003475 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003476 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003477 }
Richard Smith027bf112011-11-17 22:56:20 +00003478 }
3479
3480 return MemPtr.getDecl();
3481}
3482
Richard Smith84401042013-06-03 05:03:02 +00003483static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3484 const BinaryOperator *BO,
3485 LValue &LV,
3486 bool IncludeMember = true) {
3487 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3488
3489 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003490 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003491 MemberPtr MemPtr;
3492 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3493 }
Craig Topper36250ad2014-05-12 05:36:57 +00003494 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003495 }
3496
3497 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3498 BO->getRHS(), IncludeMember);
3499}
3500
Richard Smith027bf112011-11-17 22:56:20 +00003501/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3502/// the provided lvalue, which currently refers to the base object.
3503static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3504 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003505 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003506 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003507 return false;
3508
Richard Smitha8105bc2012-01-06 16:39:00 +00003509 QualType TargetQT = E->getType();
3510 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3511 TargetQT = PT->getPointeeType();
3512
3513 // Check this cast lands within the final derived-to-base subobject path.
3514 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003515 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003516 << D.MostDerivedType << TargetQT;
3517 return false;
3518 }
3519
Richard Smith027bf112011-11-17 22:56:20 +00003520 // Check the type of the final cast. We don't need to check the path,
3521 // since a cast can only be formed if the path is unique.
3522 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003523 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3524 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003525 if (NewEntriesSize == D.MostDerivedPathLength)
3526 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3527 else
Richard Smith027bf112011-11-17 22:56:20 +00003528 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003529 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003530 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003531 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003532 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003533 }
Richard Smith027bf112011-11-17 22:56:20 +00003534
3535 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003536 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003537}
3538
Mike Stump876387b2009-10-27 22:09:17 +00003539namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003540enum EvalStmtResult {
3541 /// Evaluation failed.
3542 ESR_Failed,
3543 /// Hit a 'return' statement.
3544 ESR_Returned,
3545 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003546 ESR_Succeeded,
3547 /// Hit a 'continue' statement.
3548 ESR_Continue,
3549 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003550 ESR_Break,
3551 /// Still scanning for 'case' or 'default' statement.
3552 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003553};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003554}
Richard Smith254a73d2011-10-28 22:34:42 +00003555
Richard Smith97fcf4b2016-08-14 23:15:52 +00003556static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3557 // We don't need to evaluate the initializer for a static local.
3558 if (!VD->hasLocalStorage())
3559 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003560
Richard Smith97fcf4b2016-08-14 23:15:52 +00003561 LValue Result;
3562 Result.set(VD, Info.CurrentCall->Index);
3563 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003564
Richard Smith97fcf4b2016-08-14 23:15:52 +00003565 const Expr *InitE = VD->getInit();
3566 if (!InitE) {
3567 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3568 << false << VD->getType();
3569 Val = APValue();
3570 return false;
3571 }
Richard Smith51f03172013-06-20 03:00:05 +00003572
Richard Smith97fcf4b2016-08-14 23:15:52 +00003573 if (InitE->isValueDependent())
3574 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003575
Richard Smith97fcf4b2016-08-14 23:15:52 +00003576 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3577 // Wipe out any partially-computed value, to allow tracking that this
3578 // evaluation failed.
3579 Val = APValue();
3580 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003581 }
3582
3583 return true;
3584}
3585
Richard Smith97fcf4b2016-08-14 23:15:52 +00003586static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3587 bool OK = true;
3588
3589 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3590 OK &= EvaluateVarDecl(Info, VD);
3591
3592 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3593 for (auto *BD : DD->bindings())
3594 if (auto *VD = BD->getHoldingVar())
3595 OK &= EvaluateDecl(Info, VD);
3596
3597 return OK;
3598}
3599
3600
Richard Smith4e18ca52013-05-06 05:56:11 +00003601/// Evaluate a condition (either a variable declaration or an expression).
3602static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3603 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003604 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003605 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3606 return false;
3607 return EvaluateAsBooleanCondition(Cond, Result, Info);
3608}
3609
Richard Smith89210072016-04-04 23:29:43 +00003610namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003611/// \brief A location where the result (returned value) of evaluating a
3612/// statement should be stored.
3613struct StmtResult {
3614 /// The APValue that should be filled in with the returned value.
3615 APValue &Value;
3616 /// The location containing the result, if any (used to support RVO).
3617 const LValue *Slot;
3618};
Richard Smith89210072016-04-04 23:29:43 +00003619}
Richard Smith52a980a2015-08-28 02:43:42 +00003620
3621static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003622 const Stmt *S,
3623 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003624
3625/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003626static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003627 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003628 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003629 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003630 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003631 case ESR_Break:
3632 return ESR_Succeeded;
3633 case ESR_Succeeded:
3634 case ESR_Continue:
3635 return ESR_Continue;
3636 case ESR_Failed:
3637 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003638 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003639 return ESR;
3640 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003641 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003642}
3643
Richard Smith496ddcf2013-05-12 17:32:42 +00003644/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003645static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003646 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003647 BlockScopeRAII Scope(Info);
3648
Richard Smith496ddcf2013-05-12 17:32:42 +00003649 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003650 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003651 {
3652 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003653 if (const Stmt *Init = SS->getInit()) {
3654 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3655 if (ESR != ESR_Succeeded)
3656 return ESR;
3657 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003658 if (SS->getConditionVariable() &&
3659 !EvaluateDecl(Info, SS->getConditionVariable()))
3660 return ESR_Failed;
3661 if (!EvaluateInteger(SS->getCond(), Value, Info))
3662 return ESR_Failed;
3663 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003664
3665 // Find the switch case corresponding to the value of the condition.
3666 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003667 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003668 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3669 SC = SC->getNextSwitchCase()) {
3670 if (isa<DefaultStmt>(SC)) {
3671 Found = SC;
3672 continue;
3673 }
3674
3675 const CaseStmt *CS = cast<CaseStmt>(SC);
3676 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3677 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3678 : LHS;
3679 if (LHS <= Value && Value <= RHS) {
3680 Found = SC;
3681 break;
3682 }
3683 }
3684
3685 if (!Found)
3686 return ESR_Succeeded;
3687
3688 // Search the switch body for the switch case and evaluate it from there.
3689 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3690 case ESR_Break:
3691 return ESR_Succeeded;
3692 case ESR_Succeeded:
3693 case ESR_Continue:
3694 case ESR_Failed:
3695 case ESR_Returned:
3696 return ESR;
3697 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003698 // This can only happen if the switch case is nested within a statement
3699 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003700 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003701 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003702 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003703 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003704}
3705
Richard Smith254a73d2011-10-28 22:34:42 +00003706// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003707static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003708 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003709 if (!Info.nextStep(S))
3710 return ESR_Failed;
3711
Richard Smith496ddcf2013-05-12 17:32:42 +00003712 // If we're hunting down a 'case' or 'default' label, recurse through
3713 // substatements until we hit the label.
3714 if (Case) {
3715 // FIXME: We don't start the lifetime of objects whose initialization we
3716 // jump over. However, such objects must be of class type with a trivial
3717 // default constructor that initialize all subobjects, so must be empty,
3718 // so this almost never matters.
3719 switch (S->getStmtClass()) {
3720 case Stmt::CompoundStmtClass:
3721 // FIXME: Precompute which substatement of a compound statement we
3722 // would jump to, and go straight there rather than performing a
3723 // linear scan each time.
3724 case Stmt::LabelStmtClass:
3725 case Stmt::AttributedStmtClass:
3726 case Stmt::DoStmtClass:
3727 break;
3728
3729 case Stmt::CaseStmtClass:
3730 case Stmt::DefaultStmtClass:
3731 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003732 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003733 break;
3734
3735 case Stmt::IfStmtClass: {
3736 // FIXME: Precompute which side of an 'if' we would jump to, and go
3737 // straight there rather than scanning both sides.
3738 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003739
3740 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3741 // preceded by our switch label.
3742 BlockScopeRAII Scope(Info);
3743
Richard Smith496ddcf2013-05-12 17:32:42 +00003744 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3745 if (ESR != ESR_CaseNotFound || !IS->getElse())
3746 return ESR;
3747 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3748 }
3749
3750 case Stmt::WhileStmtClass: {
3751 EvalStmtResult ESR =
3752 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3753 if (ESR != ESR_Continue)
3754 return ESR;
3755 break;
3756 }
3757
3758 case Stmt::ForStmtClass: {
3759 const ForStmt *FS = cast<ForStmt>(S);
3760 EvalStmtResult ESR =
3761 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3762 if (ESR != ESR_Continue)
3763 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003764 if (FS->getInc()) {
3765 FullExpressionRAII IncScope(Info);
3766 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3767 return ESR_Failed;
3768 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003769 break;
3770 }
3771
3772 case Stmt::DeclStmtClass:
3773 // FIXME: If the variable has initialization that can't be jumped over,
3774 // bail out of any immediately-surrounding compound-statement too.
3775 default:
3776 return ESR_CaseNotFound;
3777 }
3778 }
3779
Richard Smith254a73d2011-10-28 22:34:42 +00003780 switch (S->getStmtClass()) {
3781 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003782 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003783 // Don't bother evaluating beyond an expression-statement which couldn't
3784 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003785 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003786 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003787 return ESR_Failed;
3788 return ESR_Succeeded;
3789 }
3790
Faisal Valie690b7a2016-07-02 22:34:24 +00003791 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003792 return ESR_Failed;
3793
3794 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003795 return ESR_Succeeded;
3796
Richard Smithd9f663b2013-04-22 15:31:51 +00003797 case Stmt::DeclStmtClass: {
3798 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003799 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003800 // Each declaration initialization is its own full-expression.
3801 // FIXME: This isn't quite right; if we're performing aggregate
3802 // initialization, each braced subexpression is its own full-expression.
3803 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003804 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003805 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003806 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003807 return ESR_Succeeded;
3808 }
3809
Richard Smith357362d2011-12-13 06:39:58 +00003810 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003811 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003812 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003813 if (RetExpr &&
3814 !(Result.Slot
3815 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3816 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003817 return ESR_Failed;
3818 return ESR_Returned;
3819 }
Richard Smith254a73d2011-10-28 22:34:42 +00003820
3821 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003822 BlockScopeRAII Scope(Info);
3823
Richard Smith254a73d2011-10-28 22:34:42 +00003824 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003825 for (const auto *BI : CS->body()) {
3826 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003827 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003828 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003829 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003830 return ESR;
3831 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003832 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003833 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003834
3835 case Stmt::IfStmtClass: {
3836 const IfStmt *IS = cast<IfStmt>(S);
3837
3838 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003839 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003840 if (const Stmt *Init = IS->getInit()) {
3841 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3842 if (ESR != ESR_Succeeded)
3843 return ESR;
3844 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003845 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003846 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003847 return ESR_Failed;
3848
3849 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3850 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3851 if (ESR != ESR_Succeeded)
3852 return ESR;
3853 }
3854 return ESR_Succeeded;
3855 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003856
3857 case Stmt::WhileStmtClass: {
3858 const WhileStmt *WS = cast<WhileStmt>(S);
3859 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003860 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003861 bool Continue;
3862 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3863 Continue))
3864 return ESR_Failed;
3865 if (!Continue)
3866 break;
3867
3868 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3869 if (ESR != ESR_Continue)
3870 return ESR;
3871 }
3872 return ESR_Succeeded;
3873 }
3874
3875 case Stmt::DoStmtClass: {
3876 const DoStmt *DS = cast<DoStmt>(S);
3877 bool Continue;
3878 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003879 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003880 if (ESR != ESR_Continue)
3881 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003882 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003883
Richard Smith08d6a2c2013-07-24 07:11:57 +00003884 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003885 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3886 return ESR_Failed;
3887 } while (Continue);
3888 return ESR_Succeeded;
3889 }
3890
3891 case Stmt::ForStmtClass: {
3892 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003893 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003894 if (FS->getInit()) {
3895 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3896 if (ESR != ESR_Succeeded)
3897 return ESR;
3898 }
3899 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003900 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003901 bool Continue = true;
3902 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3903 FS->getCond(), Continue))
3904 return ESR_Failed;
3905 if (!Continue)
3906 break;
3907
3908 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3909 if (ESR != ESR_Continue)
3910 return ESR;
3911
Richard Smith08d6a2c2013-07-24 07:11:57 +00003912 if (FS->getInc()) {
3913 FullExpressionRAII IncScope(Info);
3914 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3915 return ESR_Failed;
3916 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003917 }
3918 return ESR_Succeeded;
3919 }
3920
Richard Smith896e0d72013-05-06 06:51:17 +00003921 case Stmt::CXXForRangeStmtClass: {
3922 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003923 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003924
3925 // Initialize the __range variable.
3926 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3927 if (ESR != ESR_Succeeded)
3928 return ESR;
3929
3930 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003931 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3932 if (ESR != ESR_Succeeded)
3933 return ESR;
3934 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003935 if (ESR != ESR_Succeeded)
3936 return ESR;
3937
3938 while (true) {
3939 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003940 {
3941 bool Continue = true;
3942 FullExpressionRAII CondExpr(Info);
3943 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3944 return ESR_Failed;
3945 if (!Continue)
3946 break;
3947 }
Richard Smith896e0d72013-05-06 06:51:17 +00003948
3949 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003950 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003951 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3952 if (ESR != ESR_Succeeded)
3953 return ESR;
3954
3955 // Loop body.
3956 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3957 if (ESR != ESR_Continue)
3958 return ESR;
3959
3960 // Increment: ++__begin
3961 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3962 return ESR_Failed;
3963 }
3964
3965 return ESR_Succeeded;
3966 }
3967
Richard Smith496ddcf2013-05-12 17:32:42 +00003968 case Stmt::SwitchStmtClass:
3969 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3970
Richard Smith4e18ca52013-05-06 05:56:11 +00003971 case Stmt::ContinueStmtClass:
3972 return ESR_Continue;
3973
3974 case Stmt::BreakStmtClass:
3975 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003976
3977 case Stmt::LabelStmtClass:
3978 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3979
3980 case Stmt::AttributedStmtClass:
3981 // As a general principle, C++11 attributes can be ignored without
3982 // any semantic impact.
3983 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3984 Case);
3985
3986 case Stmt::CaseStmtClass:
3987 case Stmt::DefaultStmtClass:
3988 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003989 }
3990}
3991
Richard Smithcc36f692011-12-22 02:22:31 +00003992/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3993/// default constructor. If so, we'll fold it whether or not it's marked as
3994/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3995/// so we need special handling.
3996static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003997 const CXXConstructorDecl *CD,
3998 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003999 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4000 return false;
4001
Richard Smith66e05fe2012-01-18 05:21:49 +00004002 // Value-initialization does not call a trivial default constructor, so such a
4003 // call is a core constant expression whether or not the constructor is
4004 // constexpr.
4005 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004006 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004007 // FIXME: If DiagDecl is an implicitly-declared special member function,
4008 // we should be much more explicit about why it's not constexpr.
4009 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4010 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4011 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004012 } else {
4013 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4014 }
4015 }
4016 return true;
4017}
4018
Richard Smith357362d2011-12-13 06:39:58 +00004019/// CheckConstexprFunction - Check that a function can be called in a constant
4020/// expression.
4021static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4022 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004023 const FunctionDecl *Definition,
4024 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004025 // Potential constant expressions can contain calls to declared, but not yet
4026 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004027 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004028 Declaration->isConstexpr())
4029 return false;
4030
Richard Smith0838f3a2013-05-14 05:18:44 +00004031 // Bail out with no diagnostic if the function declaration itself is invalid.
4032 // We will have produced a relevant diagnostic while parsing it.
4033 if (Declaration->isInvalidDecl())
4034 return false;
4035
Richard Smith357362d2011-12-13 06:39:58 +00004036 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004037 if (Definition && Definition->isConstexpr() &&
4038 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004039 return true;
4040
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004041 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004042 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00004043
Richard Smith5179eb72016-06-28 19:03:57 +00004044 // If this function is not constexpr because it is an inherited
4045 // non-constexpr constructor, diagnose that directly.
4046 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4047 if (CD && CD->isInheritingConstructor()) {
4048 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4049 if (!Inherited->isConstexpr())
4050 DiagDecl = CD = Inherited;
4051 }
4052
4053 // FIXME: If DiagDecl is an implicitly-declared special member function
4054 // or an inheriting constructor, we should be much more explicit about why
4055 // it's not constexpr.
4056 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004057 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004058 << CD->getInheritedConstructor().getConstructor()->getParent();
4059 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004060 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004061 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004062 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4063 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004064 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004065 }
4066 return false;
4067}
4068
Richard Smithbe6dd812014-11-19 21:27:17 +00004069/// Determine if a class has any fields that might need to be copied by a
4070/// trivial copy or move operation.
4071static bool hasFields(const CXXRecordDecl *RD) {
4072 if (!RD || RD->isEmpty())
4073 return false;
4074 for (auto *FD : RD->fields()) {
4075 if (FD->isUnnamedBitfield())
4076 continue;
4077 return true;
4078 }
4079 for (auto &Base : RD->bases())
4080 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4081 return true;
4082 return false;
4083}
4084
Richard Smithd62306a2011-11-10 06:34:14 +00004085namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004086typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004087}
4088
4089/// EvaluateArgs - Evaluate the arguments to a function call.
4090static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4091 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004092 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004093 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004094 I != E; ++I) {
4095 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4096 // If we're checking for a potential constant expression, evaluate all
4097 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004098 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004099 return false;
4100 Success = false;
4101 }
4102 }
4103 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004104}
4105
Richard Smith254a73d2011-10-28 22:34:42 +00004106/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004107static bool HandleFunctionCall(SourceLocation CallLoc,
4108 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004109 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004110 EvalInfo &Info, APValue &Result,
4111 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004112 ArgVector ArgValues(Args.size());
4113 if (!EvaluateArgs(Args, ArgValues, Info))
4114 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004115
Richard Smith253c2a32012-01-27 01:14:48 +00004116 if (!Info.CheckCallLimit(CallLoc))
4117 return false;
4118
4119 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004120
4121 // For a trivial copy or move assignment, perform an APValue copy. This is
4122 // essential for unions, where the operations performed by the assignment
4123 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004124 //
4125 // Skip this for non-union classes with no fields; in that case, the defaulted
4126 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004127 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004128 if (MD && MD->isDefaulted() &&
4129 (MD->getParent()->isUnion() ||
4130 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004131 assert(This &&
4132 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4133 LValue RHS;
4134 RHS.setFrom(Info.Ctx, ArgValues[0]);
4135 APValue RHSValue;
4136 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4137 RHS, RHSValue))
4138 return false;
4139 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4140 RHSValue))
4141 return false;
4142 This->moveInto(Result);
4143 return true;
4144 }
4145
Richard Smith52a980a2015-08-28 02:43:42 +00004146 StmtResult Ret = {Result, ResultSlot};
4147 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004148 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004149 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004150 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004151 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004152 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004153 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004154}
4155
Richard Smithd62306a2011-11-10 06:34:14 +00004156/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004157static bool HandleConstructorCall(const Expr *E, const LValue &This,
4158 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004159 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004160 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004161 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004162 if (!Info.CheckCallLimit(CallLoc))
4163 return false;
4164
Richard Smith3607ffe2012-02-13 03:54:03 +00004165 const CXXRecordDecl *RD = Definition->getParent();
4166 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004167 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004168 return false;
4169 }
4170
Richard Smith5179eb72016-06-28 19:03:57 +00004171 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004172
Richard Smith52a980a2015-08-28 02:43:42 +00004173 // FIXME: Creating an APValue just to hold a nonexistent return value is
4174 // wasteful.
4175 APValue RetVal;
4176 StmtResult Ret = {RetVal, nullptr};
4177
Richard Smith5179eb72016-06-28 19:03:57 +00004178 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004179 if (Definition->isDelegatingConstructor()) {
4180 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004181 {
4182 FullExpressionRAII InitScope(Info);
4183 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4184 return false;
4185 }
Richard Smith52a980a2015-08-28 02:43:42 +00004186 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004187 }
4188
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004189 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004190 // essential for unions (or classes with anonymous union members), where the
4191 // operations performed by the constructor cannot be represented by
4192 // ctor-initializers.
4193 //
4194 // Skip this for empty non-union classes; we should not perform an
4195 // lvalue-to-rvalue conversion on them because their copy constructor does not
4196 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004197 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004198 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004199 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004200 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004201 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004202 return handleLValueToRValueConversion(
4203 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4204 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004205 }
4206
4207 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004208 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004209 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004210 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004211
John McCalld7bca762012-05-01 00:38:49 +00004212 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004213 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4214
Richard Smith08d6a2c2013-07-24 07:11:57 +00004215 // A scope for temporaries lifetime-extended by reference members.
4216 BlockScopeRAII LifetimeExtendedScope(Info);
4217
Richard Smith253c2a32012-01-27 01:14:48 +00004218 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004219 unsigned BasesSeen = 0;
4220#ifndef NDEBUG
4221 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4222#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004223 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004224 LValue Subobject = This;
4225 APValue *Value = &Result;
4226
4227 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004228 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004229 if (I->isBaseInitializer()) {
4230 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004231#ifndef NDEBUG
4232 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004233 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004234 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4235 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4236 "base class initializers not in expected order");
4237 ++BaseIt;
4238#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004239 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004240 BaseType->getAsCXXRecordDecl(), &Layout))
4241 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004242 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004243 } else if ((FD = I->getMember())) {
4244 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004245 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004246 if (RD->isUnion()) {
4247 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004248 Value = &Result.getUnionValue();
4249 } else {
4250 Value = &Result.getStructField(FD->getFieldIndex());
4251 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004252 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004253 // Walk the indirect field decl's chain to find the object to initialize,
4254 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004255 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004256 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004257 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4258 // Switch the union field if it differs. This happens if we had
4259 // preceding zero-initialization, and we're now initializing a union
4260 // subobject other than the first.
4261 // FIXME: In this case, the values of the other subobjects are
4262 // specified, since zero-initialization sets all padding bits to zero.
4263 if (Value->isUninit() ||
4264 (Value->isUnion() && Value->getUnionField() != FD)) {
4265 if (CD->isUnion())
4266 *Value = APValue(FD);
4267 else
4268 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004269 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004270 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004271 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004272 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004273 if (CD->isUnion())
4274 Value = &Value->getUnionValue();
4275 else
4276 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004277 }
Richard Smithd62306a2011-11-10 06:34:14 +00004278 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004279 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004280 }
Richard Smith253c2a32012-01-27 01:14:48 +00004281
Richard Smith08d6a2c2013-07-24 07:11:57 +00004282 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004283 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4284 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004285 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004286 // If we're checking for a potential constant expression, evaluate all
4287 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004288 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004289 return false;
4290 Success = false;
4291 }
Richard Smithd62306a2011-11-10 06:34:14 +00004292 }
4293
Richard Smithd9f663b2013-04-22 15:31:51 +00004294 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004295 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004296}
4297
Richard Smith5179eb72016-06-28 19:03:57 +00004298static bool HandleConstructorCall(const Expr *E, const LValue &This,
4299 ArrayRef<const Expr*> Args,
4300 const CXXConstructorDecl *Definition,
4301 EvalInfo &Info, APValue &Result) {
4302 ArgVector ArgValues(Args.size());
4303 if (!EvaluateArgs(Args, ArgValues, Info))
4304 return false;
4305
4306 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4307 Info, Result);
4308}
4309
Eli Friedman9a156e52008-11-12 09:44:48 +00004310//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004311// Generic Evaluation
4312//===----------------------------------------------------------------------===//
4313namespace {
4314
Aaron Ballman68af21c2014-01-03 19:26:43 +00004315template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004316class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004317 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004318private:
Richard Smith52a980a2015-08-28 02:43:42 +00004319 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004320 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004321 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004322 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004323 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004324 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004325 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004326
Richard Smith17100ba2012-02-16 02:46:34 +00004327 // Check whether a conditional operator with a non-constant condition is a
4328 // potential constant expression. If neither arm is a potential constant
4329 // expression, then the conditional operator is not either.
4330 template<typename ConditionalOperator>
4331 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004332 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004333
4334 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004335 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004336 {
Richard Smith17100ba2012-02-16 02:46:34 +00004337 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004338 StmtVisitorTy::Visit(E->getFalseExpr());
4339 if (Diag.empty())
4340 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004341 }
Richard Smith17100ba2012-02-16 02:46:34 +00004342
George Burgess IV8c892b52016-05-25 22:31:54 +00004343 {
4344 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004345 Diag.clear();
4346 StmtVisitorTy::Visit(E->getTrueExpr());
4347 if (Diag.empty())
4348 return;
4349 }
4350
4351 Error(E, diag::note_constexpr_conditional_never_const);
4352 }
4353
4354
4355 template<typename ConditionalOperator>
4356 bool HandleConditionalOperator(const ConditionalOperator *E) {
4357 bool BoolResult;
4358 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004359 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004360 CheckPotentialConstantConditional(E);
4361 return false;
4362 }
4363
4364 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4365 return StmtVisitorTy::Visit(EvalExpr);
4366 }
4367
Peter Collingbournee9200682011-05-13 03:29:01 +00004368protected:
4369 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004370 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004371 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4372
Richard Smith92b1ce02011-12-12 09:28:41 +00004373 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004374 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004375 }
4376
Aaron Ballman68af21c2014-01-03 19:26:43 +00004377 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004378
4379public:
4380 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4381
4382 EvalInfo &getEvalInfo() { return Info; }
4383
Richard Smithf57d8cb2011-12-09 22:58:01 +00004384 /// Report an evaluation error. This should only be called when an error is
4385 /// first discovered. When propagating an error, just return false.
4386 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004387 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004388 return false;
4389 }
4390 bool Error(const Expr *E) {
4391 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4392 }
4393
Aaron Ballman68af21c2014-01-03 19:26:43 +00004394 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004395 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004396 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004397 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004398 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004399 }
4400
Aaron Ballman68af21c2014-01-03 19:26:43 +00004401 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004402 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004403 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004404 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004405 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004406 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004407 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004408 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004409 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004410 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004411 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004412 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004413 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004414 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004415 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004416 // The initializer may not have been parsed yet, or might be erroneous.
4417 if (!E->getExpr())
4418 return Error(E);
4419 return StmtVisitorTy::Visit(E->getExpr());
4420 }
Richard Smith5894a912011-12-19 22:12:41 +00004421 // We cannot create any objects for which cleanups are required, so there is
4422 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004423 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004424 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004425
Aaron Ballman68af21c2014-01-03 19:26:43 +00004426 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004427 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4428 return static_cast<Derived*>(this)->VisitCastExpr(E);
4429 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004430 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004431 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4432 return static_cast<Derived*>(this)->VisitCastExpr(E);
4433 }
4434
Aaron Ballman68af21c2014-01-03 19:26:43 +00004435 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004436 switch (E->getOpcode()) {
4437 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004438 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004439
4440 case BO_Comma:
4441 VisitIgnoredValue(E->getLHS());
4442 return StmtVisitorTy::Visit(E->getRHS());
4443
4444 case BO_PtrMemD:
4445 case BO_PtrMemI: {
4446 LValue Obj;
4447 if (!HandleMemberPointerAccess(Info, E, Obj))
4448 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004449 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004450 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004451 return false;
4452 return DerivedSuccess(Result, E);
4453 }
4454 }
4455 }
4456
Aaron Ballman68af21c2014-01-03 19:26:43 +00004457 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004458 // Evaluate and cache the common expression. We treat it as a temporary,
4459 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004460 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004461 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004462 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004463
Richard Smith17100ba2012-02-16 02:46:34 +00004464 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004465 }
4466
Aaron Ballman68af21c2014-01-03 19:26:43 +00004467 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004468 bool IsBcpCall = false;
4469 // If the condition (ignoring parens) is a __builtin_constant_p call,
4470 // the result is a constant expression if it can be folded without
4471 // side-effects. This is an important GNU extension. See GCC PR38377
4472 // for discussion.
4473 if (const CallExpr *CallCE =
4474 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004475 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004476 IsBcpCall = true;
4477
4478 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4479 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004480 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004481 return false;
4482
Richard Smith6d4c6582013-11-05 22:18:15 +00004483 FoldConstant Fold(Info, IsBcpCall);
4484 if (!HandleConditionalOperator(E)) {
4485 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004486 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004487 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004488
4489 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004490 }
4491
Aaron Ballman68af21c2014-01-03 19:26:43 +00004492 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004493 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4494 return DerivedSuccess(*Value, E);
4495
4496 const Expr *Source = E->getSourceExpr();
4497 if (!Source)
4498 return Error(E);
4499 if (Source == E) { // sanity checking.
4500 assert(0 && "OpaqueValueExpr recursively refers to itself");
4501 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004502 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004503 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004504 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004505
Aaron Ballman68af21c2014-01-03 19:26:43 +00004506 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004507 APValue Result;
4508 if (!handleCallExpr(E, Result, nullptr))
4509 return false;
4510 return DerivedSuccess(Result, E);
4511 }
4512
4513 bool handleCallExpr(const CallExpr *E, APValue &Result,
4514 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004515 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004516 QualType CalleeType = Callee->getType();
4517
Craig Topper36250ad2014-05-12 05:36:57 +00004518 const FunctionDecl *FD = nullptr;
4519 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004520 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004521 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004522
Richard Smithe97cbd72011-11-11 04:05:33 +00004523 // Extract function decl and 'this' pointer from the callee.
4524 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004525 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004526 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4527 // Explicit bound member calls, such as x.f() or p->g();
4528 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004529 return false;
4530 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004531 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004532 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004533 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4534 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004535 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4536 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004537 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004538 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004539 return Error(Callee);
4540
4541 FD = dyn_cast<FunctionDecl>(Member);
4542 if (!FD)
4543 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004544 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004545 LValue Call;
4546 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004547 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004548
Richard Smitha8105bc2012-01-06 16:39:00 +00004549 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004550 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004551 FD = dyn_cast_or_null<FunctionDecl>(
4552 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004553 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004554 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004555 // Don't call function pointers which have been cast to some other type.
4556 // Per DR (no number yet), the caller and callee can differ in noexcept.
4557 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4558 CalleeType->getPointeeType(), FD->getType())) {
4559 return Error(E);
4560 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004561
4562 // Overloaded operator calls to member functions are represented as normal
4563 // calls with '*this' as the first argument.
4564 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4565 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004566 // FIXME: When selecting an implicit conversion for an overloaded
4567 // operator delete, we sometimes try to evaluate calls to conversion
4568 // operators without a 'this' parameter!
4569 if (Args.empty())
4570 return Error(E);
4571
Richard Smithe97cbd72011-11-11 04:05:33 +00004572 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4573 return false;
4574 This = &ThisVal;
4575 Args = Args.slice(1);
Faisal Valid92e7492017-01-08 18:56:11 +00004576 } else if (MD && MD->isLambdaStaticInvoker()) {
4577 // Map the static invoker for the lambda back to the call operator.
4578 // Conveniently, we don't have to slice out the 'this' argument (as is
4579 // being done for the non-static case), since a static member function
4580 // doesn't have an implicit argument passed in.
4581 const CXXRecordDecl *ClosureClass = MD->getParent();
4582 assert(
4583 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4584 "Number of captures must be zero for conversion to function-ptr");
4585
4586 const CXXMethodDecl *LambdaCallOp =
4587 ClosureClass->getLambdaCallOperator();
4588
4589 // Set 'FD', the function that will be called below, to the call
4590 // operator. If the closure object represents a generic lambda, find
4591 // the corresponding specialization of the call operator.
4592
4593 if (ClosureClass->isGenericLambda()) {
4594 assert(MD->isFunctionTemplateSpecialization() &&
4595 "A generic lambda's static-invoker function must be a "
4596 "template specialization");
4597 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4598 FunctionTemplateDecl *CallOpTemplate =
4599 LambdaCallOp->getDescribedFunctionTemplate();
4600 void *InsertPos = nullptr;
4601 FunctionDecl *CorrespondingCallOpSpecialization =
4602 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4603 assert(CorrespondingCallOpSpecialization &&
4604 "We must always have a function call operator specialization "
4605 "that corresponds to our static invoker specialization");
4606 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4607 } else
4608 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004609 }
4610
Faisal Valid92e7492017-01-08 18:56:11 +00004611
Richard Smithe97cbd72011-11-11 04:05:33 +00004612 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004613 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004614
Richard Smith47b34932012-02-01 02:39:43 +00004615 if (This && !This->checkSubobject(Info, E, CSK_This))
4616 return false;
4617
Richard Smith3607ffe2012-02-13 03:54:03 +00004618 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4619 // calls to such functions in constant expressions.
4620 if (This && !HasQualifier &&
4621 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4622 return Error(E, diag::note_constexpr_virtual_call);
4623
Craig Topper36250ad2014-05-12 05:36:57 +00004624 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004625 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004626
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004627 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004628 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4629 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004630 return false;
4631
Richard Smith52a980a2015-08-28 02:43:42 +00004632 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004633 }
4634
Aaron Ballman68af21c2014-01-03 19:26:43 +00004635 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004636 return StmtVisitorTy::Visit(E->getInitializer());
4637 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004638 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004639 if (E->getNumInits() == 0)
4640 return DerivedZeroInitialization(E);
4641 if (E->getNumInits() == 1)
4642 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004643 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004644 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004645 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004646 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004647 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004648 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004649 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004650 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004651 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004652 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004653 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004654
Richard Smithd62306a2011-11-10 06:34:14 +00004655 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004656 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004657 assert(!E->isArrow() && "missing call to bound member function?");
4658
Richard Smith2e312c82012-03-03 22:46:17 +00004659 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004660 if (!Evaluate(Val, Info, E->getBase()))
4661 return false;
4662
4663 QualType BaseTy = E->getBase()->getType();
4664
4665 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004666 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004667 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004668 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004669 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4670
Richard Smith3229b742013-05-05 21:17:10 +00004671 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004672 SubobjectDesignator Designator(BaseTy);
4673 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004674
Richard Smith3229b742013-05-05 21:17:10 +00004675 APValue Result;
4676 return extractSubobject(Info, E, Obj, Designator, Result) &&
4677 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004678 }
4679
Aaron Ballman68af21c2014-01-03 19:26:43 +00004680 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004681 switch (E->getCastKind()) {
4682 default:
4683 break;
4684
Richard Smitha23ab512013-05-23 00:30:41 +00004685 case CK_AtomicToNonAtomic: {
4686 APValue AtomicVal;
4687 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4688 return false;
4689 return DerivedSuccess(AtomicVal, E);
4690 }
4691
Richard Smith11562c52011-10-28 17:51:58 +00004692 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004693 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004694 return StmtVisitorTy::Visit(E->getSubExpr());
4695
4696 case CK_LValueToRValue: {
4697 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004698 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4699 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004700 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004701 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004702 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004703 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004704 return false;
4705 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004706 }
4707 }
4708
Richard Smithf57d8cb2011-12-09 22:58:01 +00004709 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004710 }
4711
Aaron Ballman68af21c2014-01-03 19:26:43 +00004712 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004713 return VisitUnaryPostIncDec(UO);
4714 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004715 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004716 return VisitUnaryPostIncDec(UO);
4717 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004718 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004719 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004720 return Error(UO);
4721
4722 LValue LVal;
4723 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4724 return false;
4725 APValue RVal;
4726 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4727 UO->isIncrementOp(), &RVal))
4728 return false;
4729 return DerivedSuccess(RVal, UO);
4730 }
4731
Aaron Ballman68af21c2014-01-03 19:26:43 +00004732 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004733 // We will have checked the full-expressions inside the statement expression
4734 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004735 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004736 return Error(E);
4737
Richard Smith08d6a2c2013-07-24 07:11:57 +00004738 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004739 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004740 if (CS->body_empty())
4741 return true;
4742
Richard Smith51f03172013-06-20 03:00:05 +00004743 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4744 BE = CS->body_end();
4745 /**/; ++BI) {
4746 if (BI + 1 == BE) {
4747 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4748 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004749 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004750 diag::note_constexpr_stmt_expr_unsupported);
4751 return false;
4752 }
4753 return this->Visit(FinalExpr);
4754 }
4755
4756 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004757 StmtResult Result = { ReturnValue, nullptr };
4758 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004759 if (ESR != ESR_Succeeded) {
4760 // FIXME: If the statement-expression terminated due to 'return',
4761 // 'break', or 'continue', it would be nice to propagate that to
4762 // the outer statement evaluation rather than bailing out.
4763 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004764 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004765 diag::note_constexpr_stmt_expr_unsupported);
4766 return false;
4767 }
4768 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004769
4770 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004771 }
4772
Richard Smith4a678122011-10-24 18:44:57 +00004773 /// Visit a value which is evaluated, but whose value is ignored.
4774 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004775 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004776 }
David Majnemere9807b22016-02-26 04:23:19 +00004777
4778 /// Potentially visit a MemberExpr's base expression.
4779 void VisitIgnoredBaseExpression(const Expr *E) {
4780 // While MSVC doesn't evaluate the base expression, it does diagnose the
4781 // presence of side-effecting behavior.
4782 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4783 return;
4784 VisitIgnoredValue(E);
4785 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004786};
4787
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004788}
Peter Collingbournee9200682011-05-13 03:29:01 +00004789
4790//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004791// Common base class for lvalue and temporary evaluation.
4792//===----------------------------------------------------------------------===//
4793namespace {
4794template<class Derived>
4795class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004796 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004797protected:
4798 LValue &Result;
4799 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004800 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004801
4802 bool Success(APValue::LValueBase B) {
4803 Result.set(B);
4804 return true;
4805 }
4806
4807public:
4808 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4809 ExprEvaluatorBaseTy(Info), Result(Result) {}
4810
Richard Smith2e312c82012-03-03 22:46:17 +00004811 bool Success(const APValue &V, const Expr *E) {
4812 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004813 return true;
4814 }
Richard Smith027bf112011-11-17 22:56:20 +00004815
Richard Smith027bf112011-11-17 22:56:20 +00004816 bool VisitMemberExpr(const MemberExpr *E) {
4817 // Handle non-static data members.
4818 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004819 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004820 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004821 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004822 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004823 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004824 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004825 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004826 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004827 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004828 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004829 BaseTy = E->getBase()->getType();
4830 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004831 if (!EvalOK) {
4832 if (!this->Info.allowInvalidBaseExpr())
4833 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004834 Result.setInvalid(E);
4835 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004836 }
Richard Smith027bf112011-11-17 22:56:20 +00004837
Richard Smith1b78b3d2012-01-25 22:15:11 +00004838 const ValueDecl *MD = E->getMemberDecl();
4839 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4840 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4841 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4842 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004843 if (!HandleLValueMember(this->Info, E, Result, FD))
4844 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004845 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004846 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4847 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004848 } else
4849 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004850
Richard Smith1b78b3d2012-01-25 22:15:11 +00004851 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004852 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004853 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004854 RefValue))
4855 return false;
4856 return Success(RefValue, E);
4857 }
4858 return true;
4859 }
4860
4861 bool VisitBinaryOperator(const BinaryOperator *E) {
4862 switch (E->getOpcode()) {
4863 default:
4864 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4865
4866 case BO_PtrMemD:
4867 case BO_PtrMemI:
4868 return HandleMemberPointerAccess(this->Info, E, Result);
4869 }
4870 }
4871
4872 bool VisitCastExpr(const CastExpr *E) {
4873 switch (E->getCastKind()) {
4874 default:
4875 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4876
4877 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004878 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004879 if (!this->Visit(E->getSubExpr()))
4880 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004881
4882 // Now figure out the necessary offset to add to the base LV to get from
4883 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004884 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4885 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004886 }
4887 }
4888};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004889}
Richard Smith027bf112011-11-17 22:56:20 +00004890
4891//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004892// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004893//
4894// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4895// function designators (in C), decl references to void objects (in C), and
4896// temporaries (if building with -Wno-address-of-temporary).
4897//
4898// LValue evaluation produces values comprising a base expression of one of the
4899// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004900// - Declarations
4901// * VarDecl
4902// * FunctionDecl
4903// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00004904// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00004905// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004906// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004907// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004908// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004909// * ObjCEncodeExpr
4910// * AddrLabelExpr
4911// * BlockExpr
4912// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004913// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004914// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004915// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004916// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4917// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004918// * A MaterializeTemporaryExpr that has static storage duration, with no
4919// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004920// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004921//===----------------------------------------------------------------------===//
4922namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004923class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004924 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004925public:
Richard Smith027bf112011-11-17 22:56:20 +00004926 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4927 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004928
Richard Smith11562c52011-10-28 17:51:58 +00004929 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004930 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004931
Peter Collingbournee9200682011-05-13 03:29:01 +00004932 bool VisitDeclRefExpr(const DeclRefExpr *E);
4933 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004934 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004935 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4936 bool VisitMemberExpr(const MemberExpr *E);
4937 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4938 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004939 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004940 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004941 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4942 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004943 bool VisitUnaryReal(const UnaryOperator *E);
4944 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004945 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4946 return VisitUnaryPreIncDec(UO);
4947 }
4948 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4949 return VisitUnaryPreIncDec(UO);
4950 }
Richard Smith3229b742013-05-05 21:17:10 +00004951 bool VisitBinAssign(const BinaryOperator *BO);
4952 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004953
Peter Collingbournee9200682011-05-13 03:29:01 +00004954 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004955 switch (E->getCastKind()) {
4956 default:
Richard Smith027bf112011-11-17 22:56:20 +00004957 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004958
Eli Friedmance3e02a2011-10-11 00:13:24 +00004959 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004960 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004961 if (!Visit(E->getSubExpr()))
4962 return false;
4963 Result.Designator.setInvalid();
4964 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004965
Richard Smith027bf112011-11-17 22:56:20 +00004966 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004967 if (!Visit(E->getSubExpr()))
4968 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004969 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004970 }
4971 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004972};
4973} // end anonymous namespace
4974
Richard Smith11562c52011-10-28 17:51:58 +00004975/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004976/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004977/// * function designators in C, and
4978/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004979/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004980static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4981 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004982 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004983 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004984}
4985
Peter Collingbournee9200682011-05-13 03:29:01 +00004986bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004987 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004988 return Success(FD);
4989 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004990 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00004991 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00004992 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00004993 return Error(E);
4994}
Richard Smith733237d2011-10-24 23:14:33 +00004995
Faisal Vali0528a312016-11-13 06:09:16 +00004996
Richard Smith11562c52011-10-28 17:51:58 +00004997bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004998 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00004999 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5000 // Only if a local variable was declared in the function currently being
5001 // evaluated, do we expect to be able to find its value in the current
5002 // frame. (Otherwise it was likely declared in an enclosing context and
5003 // could either have a valid evaluatable value (for e.g. a constexpr
5004 // variable) or be ill-formed (and trigger an appropriate evaluation
5005 // diagnostic)).
5006 if (Info.CurrentCall->Callee &&
5007 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5008 Frame = Info.CurrentCall;
5009 }
5010 }
Richard Smith3229b742013-05-05 21:17:10 +00005011
Richard Smithfec09922011-11-01 16:57:24 +00005012 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005013 if (Frame) {
5014 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005015 return true;
5016 }
Richard Smithce40ad62011-11-12 22:28:03 +00005017 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005018 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005019
Richard Smith3229b742013-05-05 21:17:10 +00005020 APValue *V;
5021 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005022 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005023 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005024 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005025 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005026 return false;
5027 }
Richard Smith3229b742013-05-05 21:17:10 +00005028 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005029}
5030
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005031bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5032 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005033 // Walk through the expression to find the materialized temporary itself.
5034 SmallVector<const Expr *, 2> CommaLHSs;
5035 SmallVector<SubobjectAdjustment, 2> Adjustments;
5036 const Expr *Inner = E->GetTemporaryExpr()->
5037 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005038
Richard Smith84401042013-06-03 05:03:02 +00005039 // If we passed any comma operators, evaluate their LHSs.
5040 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5041 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5042 return false;
5043
Richard Smithe6c01442013-06-05 00:46:14 +00005044 // A materialized temporary with static storage duration can appear within the
5045 // result of a constant expression evaluation, so we need to preserve its
5046 // value for use outside this evaluation.
5047 APValue *Value;
5048 if (E->getStorageDuration() == SD_Static) {
5049 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005050 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005051 Result.set(E);
5052 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005053 Value = &Info.CurrentCall->
5054 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005055 Result.set(E, Info.CurrentCall->Index);
5056 }
5057
Richard Smithea4ad5d2013-06-06 08:19:16 +00005058 QualType Type = Inner->getType();
5059
Richard Smith84401042013-06-03 05:03:02 +00005060 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005061 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5062 (E->getStorageDuration() == SD_Static &&
5063 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5064 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005065 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005066 }
Richard Smith84401042013-06-03 05:03:02 +00005067
5068 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005069 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5070 --I;
5071 switch (Adjustments[I].Kind) {
5072 case SubobjectAdjustment::DerivedToBaseAdjustment:
5073 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5074 Type, Result))
5075 return false;
5076 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5077 break;
5078
5079 case SubobjectAdjustment::FieldAdjustment:
5080 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5081 return false;
5082 Type = Adjustments[I].Field->getType();
5083 break;
5084
5085 case SubobjectAdjustment::MemberPointerAdjustment:
5086 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5087 Adjustments[I].Ptr.RHS))
5088 return false;
5089 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5090 break;
5091 }
5092 }
5093
5094 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005095}
5096
Peter Collingbournee9200682011-05-13 03:29:01 +00005097bool
5098LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005099 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5100 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005101 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5102 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005103 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005104}
5105
Richard Smith6e525142011-12-27 12:18:28 +00005106bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005107 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005108 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005109
Faisal Valie690b7a2016-07-02 22:34:24 +00005110 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005111 << E->getExprOperand()->getType()
5112 << E->getExprOperand()->getSourceRange();
5113 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005114}
5115
Francois Pichet0066db92012-04-16 04:08:35 +00005116bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5117 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005118}
Francois Pichet0066db92012-04-16 04:08:35 +00005119
Peter Collingbournee9200682011-05-13 03:29:01 +00005120bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005121 // Handle static data members.
5122 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005123 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005124 return VisitVarDecl(E, VD);
5125 }
5126
Richard Smith254a73d2011-10-28 22:34:42 +00005127 // Handle static member functions.
5128 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5129 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005130 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005131 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005132 }
5133 }
5134
Richard Smithd62306a2011-11-10 06:34:14 +00005135 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005136 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005137}
5138
Peter Collingbournee9200682011-05-13 03:29:01 +00005139bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005140 // FIXME: Deal with vectors as array subscript bases.
5141 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005142 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005143
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005144 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00005145 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005146
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005147 APSInt Index;
5148 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005149 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005150
Richard Smith861b5b52013-05-07 23:34:45 +00005151 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
5152 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005153}
Eli Friedman9a156e52008-11-12 09:44:48 +00005154
Peter Collingbournee9200682011-05-13 03:29:01 +00005155bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00005156 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005157}
5158
Richard Smith66c96992012-02-18 22:04:06 +00005159bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5160 if (!Visit(E->getSubExpr()))
5161 return false;
5162 // __real is a no-op on scalar lvalues.
5163 if (E->getSubExpr()->getType()->isAnyComplexType())
5164 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5165 return true;
5166}
5167
5168bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5169 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5170 "lvalue __imag__ on scalar?");
5171 if (!Visit(E->getSubExpr()))
5172 return false;
5173 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5174 return true;
5175}
5176
Richard Smith243ef902013-05-05 23:31:59 +00005177bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005178 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005179 return Error(UO);
5180
5181 if (!this->Visit(UO->getSubExpr()))
5182 return false;
5183
Richard Smith243ef902013-05-05 23:31:59 +00005184 return handleIncDec(
5185 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005186 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005187}
5188
5189bool LValueExprEvaluator::VisitCompoundAssignOperator(
5190 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005191 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005192 return Error(CAO);
5193
Richard Smith3229b742013-05-05 21:17:10 +00005194 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005195
5196 // The overall lvalue result is the result of evaluating the LHS.
5197 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005198 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005199 Evaluate(RHS, this->Info, CAO->getRHS());
5200 return false;
5201 }
5202
Richard Smith3229b742013-05-05 21:17:10 +00005203 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5204 return false;
5205
Richard Smith43e77732013-05-07 04:50:00 +00005206 return handleCompoundAssignment(
5207 this->Info, CAO,
5208 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5209 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005210}
5211
5212bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005213 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005214 return Error(E);
5215
Richard Smith3229b742013-05-05 21:17:10 +00005216 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005217
5218 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005219 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005220 Evaluate(NewVal, this->Info, E->getRHS());
5221 return false;
5222 }
5223
Richard Smith3229b742013-05-05 21:17:10 +00005224 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5225 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005226
5227 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005228 NewVal);
5229}
5230
Eli Friedman9a156e52008-11-12 09:44:48 +00005231//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005232// Pointer Evaluation
5233//===----------------------------------------------------------------------===//
5234
George Burgess IVe3763372016-12-22 02:50:20 +00005235/// \brief Attempts to compute the number of bytes available at the pointer
5236/// returned by a function with the alloc_size attribute. Returns true if we
5237/// were successful. Places an unsigned number into `Result`.
5238///
5239/// This expects the given CallExpr to be a call to a function with an
5240/// alloc_size attribute.
5241static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5242 const CallExpr *Call,
5243 llvm::APInt &Result) {
5244 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5245
5246 // alloc_size args are 1-indexed, 0 means not present.
5247 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5248 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5249 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5250 if (Call->getNumArgs() <= SizeArgNo)
5251 return false;
5252
5253 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5254 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5255 return false;
5256 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5257 return false;
5258 Into = Into.zextOrSelf(BitsInSizeT);
5259 return true;
5260 };
5261
5262 APSInt SizeOfElem;
5263 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5264 return false;
5265
5266 if (!AllocSize->getNumElemsParam()) {
5267 Result = std::move(SizeOfElem);
5268 return true;
5269 }
5270
5271 APSInt NumberOfElems;
5272 // Argument numbers start at 1
5273 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5274 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5275 return false;
5276
5277 bool Overflow;
5278 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5279 if (Overflow)
5280 return false;
5281
5282 Result = std::move(BytesAvailable);
5283 return true;
5284}
5285
5286/// \brief Convenience function. LVal's base must be a call to an alloc_size
5287/// function.
5288static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5289 const LValue &LVal,
5290 llvm::APInt &Result) {
5291 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5292 "Can't get the size of a non alloc_size function");
5293 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5294 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5295 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5296}
5297
5298/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5299/// a function with the alloc_size attribute. If it was possible to do so, this
5300/// function will return true, make Result's Base point to said function call,
5301/// and mark Result's Base as invalid.
5302static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5303 LValue &Result) {
5304 if (!Info.allowInvalidBaseExpr() || Base.isNull())
5305 return false;
5306
5307 // Because we do no form of static analysis, we only support const variables.
5308 //
5309 // Additionally, we can't support parameters, nor can we support static
5310 // variables (in the latter case, use-before-assign isn't UB; in the former,
5311 // we have no clue what they'll be assigned to).
5312 const auto *VD =
5313 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5314 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5315 return false;
5316
5317 const Expr *Init = VD->getAnyInitializer();
5318 if (!Init)
5319 return false;
5320
5321 const Expr *E = Init->IgnoreParens();
5322 if (!tryUnwrapAllocSizeCall(E))
5323 return false;
5324
5325 // Store E instead of E unwrapped so that the type of the LValue's base is
5326 // what the user wanted.
5327 Result.setInvalid(E);
5328
5329 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5330 Result.addUnsizedArray(Info, Pointee);
5331 return true;
5332}
5333
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005334namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005335class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005336 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005337 LValue &Result;
5338
Peter Collingbournee9200682011-05-13 03:29:01 +00005339 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005340 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005341 return true;
5342 }
George Burgess IVe3763372016-12-22 02:50:20 +00005343
5344 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005345public:
Mike Stump11289f42009-09-09 15:08:12 +00005346
John McCall45d55e42010-05-07 21:00:08 +00005347 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005348 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005349
Richard Smith2e312c82012-03-03 22:46:17 +00005350 bool Success(const APValue &V, const Expr *E) {
5351 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005352 return true;
5353 }
Richard Smithfddd3842011-12-30 21:15:51 +00005354 bool ZeroInitialization(const Expr *E) {
Yaxun Liu402804b2016-12-15 08:09:08 +00005355 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5356 Result.set((Expr*)nullptr, 0, false, true, Offset);
5357 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005358 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005359
John McCall45d55e42010-05-07 21:00:08 +00005360 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005361 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005362 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005363 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005364 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005365 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005366 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005367 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005368 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005369 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005370 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005371 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005372 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005373 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005374 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005375 }
Richard Smithd62306a2011-11-10 06:34:14 +00005376 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005377 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005378 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005379 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005380 if (!Info.CurrentCall->This) {
5381 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005382 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005383 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005384 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005385 return false;
5386 }
Richard Smithd62306a2011-11-10 06:34:14 +00005387 Result = *Info.CurrentCall->This;
5388 return true;
5389 }
John McCallc07a0c72011-02-17 10:25:35 +00005390
Eli Friedman449fe542009-03-23 04:56:01 +00005391 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005392};
Chris Lattner05706e882008-07-11 18:11:29 +00005393} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005394
John McCall45d55e42010-05-07 21:00:08 +00005395static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005396 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005397 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005398}
5399
John McCall45d55e42010-05-07 21:00:08 +00005400bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005401 if (E->getOpcode() != BO_Add &&
5402 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005403 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005404
Chris Lattner05706e882008-07-11 18:11:29 +00005405 const Expr *PExp = E->getLHS();
5406 const Expr *IExp = E->getRHS();
5407 if (IExp->getType()->isPointerType())
5408 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005409
Richard Smith253c2a32012-01-27 01:14:48 +00005410 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005411 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005412 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005413
John McCall45d55e42010-05-07 21:00:08 +00005414 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005415 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005416 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005417
5418 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00005419 if (E->getOpcode() == BO_Sub)
5420 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00005421
Ted Kremenek28831752012-08-23 20:46:57 +00005422 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00005423 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5424 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00005425}
Eli Friedman9a156e52008-11-12 09:44:48 +00005426
John McCall45d55e42010-05-07 21:00:08 +00005427bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5428 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005429}
Mike Stump11289f42009-09-09 15:08:12 +00005430
Peter Collingbournee9200682011-05-13 03:29:01 +00005431bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5432 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005433
Eli Friedman847a2bc2009-12-27 05:43:15 +00005434 switch (E->getCastKind()) {
5435 default:
5436 break;
5437
John McCalle3027922010-08-25 11:45:40 +00005438 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005439 case CK_CPointerToObjCPointerCast:
5440 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005441 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005442 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005443 if (!Visit(SubExpr))
5444 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005445 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5446 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5447 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005448 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005449 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005450 if (SubExpr->getType()->isVoidPointerType())
5451 CCEDiag(E, diag::note_constexpr_invalid_cast)
5452 << 3 << SubExpr->getType();
5453 else
5454 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5455 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005456 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5457 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005458 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005459
Anders Carlsson18275092010-10-31 20:41:46 +00005460 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005461 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005462 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005463 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005464 if (!Result.Base && Result.Offset.isZero())
5465 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005466
Richard Smithd62306a2011-11-10 06:34:14 +00005467 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005468 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005469 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5470 castAs<PointerType>()->getPointeeType(),
5471 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005472
Richard Smith027bf112011-11-17 22:56:20 +00005473 case CK_BaseToDerived:
5474 if (!Visit(E->getSubExpr()))
5475 return false;
5476 if (!Result.Base && Result.Offset.isZero())
5477 return true;
5478 return HandleBaseToDerivedCast(Info, E, Result);
5479
Richard Smith0b0a0b62011-10-29 20:57:55 +00005480 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005481 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005482 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005483
John McCalle3027922010-08-25 11:45:40 +00005484 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005485 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5486
Richard Smith2e312c82012-03-03 22:46:17 +00005487 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005488 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005489 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005490
John McCall45d55e42010-05-07 21:00:08 +00005491 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005492 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5493 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005494 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005495 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005496 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005497 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005498 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005499 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005500 return true;
5501 } else {
5502 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005503 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005504 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005505 }
5506 }
John McCalle3027922010-08-25 11:45:40 +00005507 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005508 if (SubExpr->isGLValue()) {
5509 if (!EvaluateLValue(SubExpr, Result, Info))
5510 return false;
5511 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005512 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005513 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005514 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005515 return false;
5516 }
Richard Smith96e0c102011-11-04 02:25:55 +00005517 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005518 if (const ConstantArrayType *CAT
5519 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5520 Result.addArray(Info, E, CAT);
5521 else
5522 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005523 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005524
John McCalle3027922010-08-25 11:45:40 +00005525 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005526 return EvaluateLValue(SubExpr, Result, Info);
George Burgess IVe3763372016-12-22 02:50:20 +00005527
5528 case CK_LValueToRValue: {
5529 LValue LVal;
5530 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5531 return false;
5532
5533 APValue RVal;
5534 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5535 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5536 LVal, RVal))
5537 return evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5538 return Success(RVal, E);
5539 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005540 }
5541
Richard Smith11562c52011-10-28 17:51:58 +00005542 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005543}
Chris Lattner05706e882008-07-11 18:11:29 +00005544
Hal Finkel0dd05d42014-10-03 17:18:37 +00005545static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5546 // C++ [expr.alignof]p3:
5547 // When alignof is applied to a reference type, the result is the
5548 // alignment of the referenced type.
5549 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5550 T = Ref->getPointeeType();
5551
5552 // __alignof is defined to return the preferred alignment.
5553 return Info.Ctx.toCharUnitsFromBits(
5554 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5555}
5556
5557static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5558 E = E->IgnoreParens();
5559
5560 // The kinds of expressions that we have special-case logic here for
5561 // should be kept up to date with the special checks for those
5562 // expressions in Sema.
5563
5564 // alignof decl is always accepted, even if it doesn't make sense: we default
5565 // to 1 in those cases.
5566 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5567 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5568 /*RefAsPointee*/true);
5569
5570 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5571 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5572 /*RefAsPointee*/true);
5573
5574 return GetAlignOfType(Info, E->getType());
5575}
5576
George Burgess IVe3763372016-12-22 02:50:20 +00005577// To be clear: this happily visits unsupported builtins. Better name welcomed.
5578bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5579 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5580 return true;
5581
5582 if (!(Info.allowInvalidBaseExpr() && getAllocSizeAttr(E)))
5583 return false;
5584
5585 Result.setInvalid(E);
5586 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5587 Result.addUnsizedArray(Info, PointeeTy);
5588 return true;
5589}
5590
Peter Collingbournee9200682011-05-13 03:29:01 +00005591bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005592 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005593 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005594
Richard Smith6328cbd2016-11-16 00:57:23 +00005595 if (unsigned BuiltinOp = E->getBuiltinCallee())
5596 return VisitBuiltinCallExpr(E, BuiltinOp);
5597
George Burgess IVe3763372016-12-22 02:50:20 +00005598 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005599}
5600
5601bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5602 unsigned BuiltinOp) {
5603 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005604 case Builtin::BI__builtin_addressof:
5605 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005606 case Builtin::BI__builtin_assume_aligned: {
5607 // We need to be very careful here because: if the pointer does not have the
5608 // asserted alignment, then the behavior is undefined, and undefined
5609 // behavior is non-constant.
5610 if (!EvaluatePointer(E->getArg(0), Result, Info))
5611 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005612
Hal Finkel0dd05d42014-10-03 17:18:37 +00005613 LValue OffsetResult(Result);
5614 APSInt Alignment;
5615 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5616 return false;
5617 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5618
5619 if (E->getNumArgs() > 2) {
5620 APSInt Offset;
5621 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5622 return false;
5623
5624 int64_t AdditionalOffset = -getExtValue(Offset);
5625 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5626 }
5627
5628 // If there is a base object, then it must have the correct alignment.
5629 if (OffsetResult.Base) {
5630 CharUnits BaseAlignment;
5631 if (const ValueDecl *VD =
5632 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5633 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5634 } else {
5635 BaseAlignment =
5636 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5637 }
5638
5639 if (BaseAlignment < Align) {
5640 Result.Designator.setInvalid();
Yaron Kerene0bcdd42016-10-08 06:45:10 +00005641 // FIXME: Quantities here cast to integers because the plural modifier
5642 // does not work on APSInts yet.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005643 CCEDiag(E->getArg(0),
5644 diag::note_constexpr_baa_insufficient_alignment) << 0
5645 << (int) BaseAlignment.getQuantity()
5646 << (unsigned) getExtValue(Alignment);
5647 return false;
5648 }
5649 }
5650
5651 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005652 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005653 Result.Designator.setInvalid();
5654 APSInt Offset(64, false);
5655 Offset = OffsetResult.Offset.getQuantity();
5656
5657 if (OffsetResult.Base)
5658 CCEDiag(E->getArg(0),
5659 diag::note_constexpr_baa_insufficient_alignment) << 1
5660 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5661 else
5662 CCEDiag(E->getArg(0),
5663 diag::note_constexpr_baa_value_insufficient_alignment)
5664 << Offset << (unsigned) getExtValue(Alignment);
5665
5666 return false;
5667 }
5668
5669 return true;
5670 }
Richard Smithe9507952016-11-12 01:39:56 +00005671
5672 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005673 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005674 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005675 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005676 if (Info.getLangOpts().CPlusPlus11)
5677 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5678 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005679 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005680 else
5681 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5682 // Fall through.
5683 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005684 case Builtin::BI__builtin_wcschr:
5685 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005686 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005687 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005688 if (!Visit(E->getArg(0)))
5689 return false;
5690 APSInt Desired;
5691 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5692 return false;
5693 uint64_t MaxLength = uint64_t(-1);
5694 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005695 BuiltinOp != Builtin::BIwcschr &&
5696 BuiltinOp != Builtin::BI__builtin_strchr &&
5697 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005698 APSInt N;
5699 if (!EvaluateInteger(E->getArg(2), N, Info))
5700 return false;
5701 MaxLength = N.getExtValue();
5702 }
5703
Richard Smith8110c9d2016-11-29 19:45:17 +00005704 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005705
Richard Smith8110c9d2016-11-29 19:45:17 +00005706 // Figure out what value we're actually looking for (after converting to
5707 // the corresponding unsigned type if necessary).
5708 uint64_t DesiredVal;
5709 bool StopAtNull = false;
5710 switch (BuiltinOp) {
5711 case Builtin::BIstrchr:
5712 case Builtin::BI__builtin_strchr:
5713 // strchr compares directly to the passed integer, and therefore
5714 // always fails if given an int that is not a char.
5715 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5716 E->getArg(1)->getType(),
5717 Desired),
5718 Desired))
5719 return ZeroInitialization(E);
5720 StopAtNull = true;
5721 // Fall through.
5722 case Builtin::BImemchr:
5723 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005724 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005725 // memchr compares by converting both sides to unsigned char. That's also
5726 // correct for strchr if we get this far (to cope with plain char being
5727 // unsigned in the strchr case).
5728 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5729 break;
Richard Smithe9507952016-11-12 01:39:56 +00005730
Richard Smith8110c9d2016-11-29 19:45:17 +00005731 case Builtin::BIwcschr:
5732 case Builtin::BI__builtin_wcschr:
5733 StopAtNull = true;
5734 // Fall through.
5735 case Builtin::BIwmemchr:
5736 case Builtin::BI__builtin_wmemchr:
5737 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5738 DesiredVal = Desired.getZExtValue();
5739 break;
5740 }
Richard Smithe9507952016-11-12 01:39:56 +00005741
5742 for (; MaxLength; --MaxLength) {
5743 APValue Char;
5744 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5745 !Char.isInt())
5746 return false;
5747 if (Char.getInt().getZExtValue() == DesiredVal)
5748 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005749 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005750 break;
5751 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5752 return false;
5753 }
5754 // Not found: return nullptr.
5755 return ZeroInitialization(E);
5756 }
5757
Richard Smith6cbd65d2013-07-11 02:27:57 +00005758 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005759 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005760 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005761}
Chris Lattner05706e882008-07-11 18:11:29 +00005762
5763//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005764// Member Pointer Evaluation
5765//===----------------------------------------------------------------------===//
5766
5767namespace {
5768class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005769 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005770 MemberPtr &Result;
5771
5772 bool Success(const ValueDecl *D) {
5773 Result = MemberPtr(D);
5774 return true;
5775 }
5776public:
5777
5778 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5779 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5780
Richard Smith2e312c82012-03-03 22:46:17 +00005781 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005782 Result.setFrom(V);
5783 return true;
5784 }
Richard Smithfddd3842011-12-30 21:15:51 +00005785 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005786 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005787 }
5788
5789 bool VisitCastExpr(const CastExpr *E);
5790 bool VisitUnaryAddrOf(const UnaryOperator *E);
5791};
5792} // end anonymous namespace
5793
5794static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5795 EvalInfo &Info) {
5796 assert(E->isRValue() && E->getType()->isMemberPointerType());
5797 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5798}
5799
5800bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5801 switch (E->getCastKind()) {
5802 default:
5803 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5804
5805 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005806 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005807 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005808
5809 case CK_BaseToDerivedMemberPointer: {
5810 if (!Visit(E->getSubExpr()))
5811 return false;
5812 if (E->path_empty())
5813 return true;
5814 // Base-to-derived member pointer casts store the path in derived-to-base
5815 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5816 // the wrong end of the derived->base arc, so stagger the path by one class.
5817 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5818 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5819 PathI != PathE; ++PathI) {
5820 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5821 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5822 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005823 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005824 }
5825 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5826 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005827 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005828 return true;
5829 }
5830
5831 case CK_DerivedToBaseMemberPointer:
5832 if (!Visit(E->getSubExpr()))
5833 return false;
5834 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5835 PathE = E->path_end(); PathI != PathE; ++PathI) {
5836 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5837 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5838 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005839 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005840 }
5841 return true;
5842 }
5843}
5844
5845bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5846 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5847 // member can be formed.
5848 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5849}
5850
5851//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005852// Record Evaluation
5853//===----------------------------------------------------------------------===//
5854
5855namespace {
5856 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005857 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005858 const LValue &This;
5859 APValue &Result;
5860 public:
5861
5862 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5863 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5864
Richard Smith2e312c82012-03-03 22:46:17 +00005865 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005866 Result = V;
5867 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005868 }
Richard Smithb8348f52016-05-12 22:16:28 +00005869 bool ZeroInitialization(const Expr *E) {
5870 return ZeroInitialization(E, E->getType());
5871 }
5872 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005873
Richard Smith52a980a2015-08-28 02:43:42 +00005874 bool VisitCallExpr(const CallExpr *E) {
5875 return handleCallExpr(E, Result, &This);
5876 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005877 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005878 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005879 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5880 return VisitCXXConstructExpr(E, E->getType());
5881 }
Faisal Valic72a08c2017-01-09 03:02:53 +00005882 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00005883 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005884 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005885 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005886 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005887}
Richard Smithd62306a2011-11-10 06:34:14 +00005888
Richard Smithfddd3842011-12-30 21:15:51 +00005889/// Perform zero-initialization on an object of non-union class type.
5890/// C++11 [dcl.init]p5:
5891/// To zero-initialize an object or reference of type T means:
5892/// [...]
5893/// -- if T is a (possibly cv-qualified) non-union class type,
5894/// each non-static data member and each base-class subobject is
5895/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005896static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5897 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005898 const LValue &This, APValue &Result) {
5899 assert(!RD->isUnion() && "Expected non-union class type");
5900 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5901 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005902 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005903
John McCalld7bca762012-05-01 00:38:49 +00005904 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005905 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5906
5907 if (CD) {
5908 unsigned Index = 0;
5909 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005910 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005911 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5912 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005913 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5914 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005915 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005916 Result.getStructBase(Index)))
5917 return false;
5918 }
5919 }
5920
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005921 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005922 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005923 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005924 continue;
5925
5926 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005927 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005928 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005929
David Blaikie2d7c57e2012-04-30 02:36:29 +00005930 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005931 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005932 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005933 return false;
5934 }
5935
5936 return true;
5937}
5938
Richard Smithb8348f52016-05-12 22:16:28 +00005939bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5940 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005941 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005942 if (RD->isUnion()) {
5943 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5944 // object's first non-static named data member is zero-initialized
5945 RecordDecl::field_iterator I = RD->field_begin();
5946 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005947 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005948 return true;
5949 }
5950
5951 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005952 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005953 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005954 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005955 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005956 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005957 }
5958
Richard Smith5d108602012-02-17 00:44:16 +00005959 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005960 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005961 return false;
5962 }
5963
Richard Smitha8105bc2012-01-06 16:39:00 +00005964 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005965}
5966
Richard Smithe97cbd72011-11-11 04:05:33 +00005967bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5968 switch (E->getCastKind()) {
5969 default:
5970 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5971
5972 case CK_ConstructorConversion:
5973 return Visit(E->getSubExpr());
5974
5975 case CK_DerivedToBase:
5976 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005977 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005978 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005979 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005980 if (!DerivedObject.isStruct())
5981 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005982
5983 // Derived-to-base rvalue conversion: just slice off the derived part.
5984 APValue *Value = &DerivedObject;
5985 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5986 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5987 PathE = E->path_end(); PathI != PathE; ++PathI) {
5988 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5989 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5990 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5991 RD = Base;
5992 }
5993 Result = *Value;
5994 return true;
5995 }
5996 }
5997}
5998
Richard Smithd62306a2011-11-10 06:34:14 +00005999bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006000 if (E->isTransparent())
6001 return Visit(E->getInit(0));
6002
Richard Smithd62306a2011-11-10 06:34:14 +00006003 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006004 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006005 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6006
6007 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006008 const FieldDecl *Field = E->getInitializedFieldInUnion();
6009 Result = APValue(Field);
6010 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006011 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006012
6013 // If the initializer list for a union does not contain any elements, the
6014 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006015 // FIXME: The element should be initialized from an initializer list.
6016 // Is this difference ever observable for initializer lists which
6017 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006018 ImplicitValueInitExpr VIE(Field->getType());
6019 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6020
Richard Smithd62306a2011-11-10 06:34:14 +00006021 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006022 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6023 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006024
6025 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6026 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6027 isa<CXXDefaultInitExpr>(InitExpr));
6028
Richard Smithb228a862012-02-15 02:18:13 +00006029 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006030 }
6031
Richard Smith872307e2016-03-08 22:17:41 +00006032 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006033 if (Result.isUninit())
6034 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6035 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006036 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006037 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006038
6039 // Initialize base classes.
6040 if (CXXRD) {
6041 for (const auto &Base : CXXRD->bases()) {
6042 assert(ElementNo < E->getNumInits() && "missing init for base class");
6043 const Expr *Init = E->getInit(ElementNo);
6044
6045 LValue Subobject = This;
6046 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6047 return false;
6048
6049 APValue &FieldVal = Result.getStructBase(ElementNo);
6050 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006051 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006052 return false;
6053 Success = false;
6054 }
6055 ++ElementNo;
6056 }
6057 }
6058
6059 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006060 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006061 // Anonymous bit-fields are not considered members of the class for
6062 // purposes of aggregate initialization.
6063 if (Field->isUnnamedBitfield())
6064 continue;
6065
6066 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006067
Richard Smith253c2a32012-01-27 01:14:48 +00006068 bool HaveInit = ElementNo < E->getNumInits();
6069
6070 // FIXME: Diagnostics here should point to the end of the initializer
6071 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006072 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006073 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006074 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006075
6076 // Perform an implicit value-initialization for members beyond the end of
6077 // the initializer list.
6078 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006079 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006080
Richard Smith852c9db2013-04-20 22:23:05 +00006081 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6082 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6083 isa<CXXDefaultInitExpr>(Init));
6084
Richard Smith49ca8aa2013-08-06 07:09:20 +00006085 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6086 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6087 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006088 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006089 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006090 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006091 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006092 }
6093 }
6094
Richard Smith253c2a32012-01-27 01:14:48 +00006095 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006096}
6097
Richard Smithb8348f52016-05-12 22:16:28 +00006098bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6099 QualType T) {
6100 // Note that E's type is not necessarily the type of our class here; we might
6101 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006102 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006103 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6104
Richard Smithfddd3842011-12-30 21:15:51 +00006105 bool ZeroInit = E->requiresZeroInitialization();
6106 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006107 // If we've already performed zero-initialization, we're already done.
6108 if (!Result.isUninit())
6109 return true;
6110
Richard Smithda3f4fd2014-03-05 23:32:50 +00006111 // We can get here in two different ways:
6112 // 1) We're performing value-initialization, and should zero-initialize
6113 // the object, or
6114 // 2) We're performing default-initialization of an object with a trivial
6115 // constexpr default constructor, in which case we should start the
6116 // lifetimes of all the base subobjects (there can be no data member
6117 // subobjects in this case) per [basic.life]p1.
6118 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006119 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006120 }
6121
Craig Topper36250ad2014-05-12 05:36:57 +00006122 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006123 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006124
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006125 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006126 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006127
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006128 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006129 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006130 if (const MaterializeTemporaryExpr *ME
6131 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6132 return Visit(ME->GetTemporaryExpr());
6133
Richard Smithb8348f52016-05-12 22:16:28 +00006134 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006135 return false;
6136
Craig Topper5fc8fc22014-08-27 06:28:36 +00006137 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006138 return HandleConstructorCall(E, This, Args,
6139 cast<CXXConstructorDecl>(Definition), Info,
6140 Result);
6141}
6142
6143bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6144 const CXXInheritedCtorInitExpr *E) {
6145 if (!Info.CurrentCall) {
6146 assert(Info.checkingPotentialConstantExpression());
6147 return false;
6148 }
6149
6150 const CXXConstructorDecl *FD = E->getConstructor();
6151 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6152 return false;
6153
6154 const FunctionDecl *Definition = nullptr;
6155 auto Body = FD->getBody(Definition);
6156
6157 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6158 return false;
6159
6160 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006161 cast<CXXConstructorDecl>(Definition), Info,
6162 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006163}
6164
Richard Smithcc1b96d2013-06-12 22:31:48 +00006165bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6166 const CXXStdInitializerListExpr *E) {
6167 const ConstantArrayType *ArrayType =
6168 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6169
6170 LValue Array;
6171 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6172 return false;
6173
6174 // Get a pointer to the first element of the array.
6175 Array.addArray(Info, E, ArrayType);
6176
6177 // FIXME: Perform the checks on the field types in SemaInit.
6178 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6179 RecordDecl::field_iterator Field = Record->field_begin();
6180 if (Field == Record->field_end())
6181 return Error(E);
6182
6183 // Start pointer.
6184 if (!Field->getType()->isPointerType() ||
6185 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6186 ArrayType->getElementType()))
6187 return Error(E);
6188
6189 // FIXME: What if the initializer_list type has base classes, etc?
6190 Result = APValue(APValue::UninitStruct(), 0, 2);
6191 Array.moveInto(Result.getStructField(0));
6192
6193 if (++Field == Record->field_end())
6194 return Error(E);
6195
6196 if (Field->getType()->isPointerType() &&
6197 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6198 ArrayType->getElementType())) {
6199 // End pointer.
6200 if (!HandleLValueArrayAdjustment(Info, E, Array,
6201 ArrayType->getElementType(),
6202 ArrayType->getSize().getZExtValue()))
6203 return false;
6204 Array.moveInto(Result.getStructField(1));
6205 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6206 // Length.
6207 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6208 else
6209 return Error(E);
6210
6211 if (++Field != Record->field_end())
6212 return Error(E);
6213
6214 return true;
6215}
6216
Faisal Valic72a08c2017-01-09 03:02:53 +00006217bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6218 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6219 if (ClosureClass->isInvalidDecl()) return false;
6220
6221 if (Info.checkingPotentialConstantExpression()) return true;
6222 if (E->capture_size()) {
6223 Info.FFDiag(E, diag::note_unimplemented_constexpr_lambda_feature_ast)
6224 << "can not evaluate lambda expressions with captures";
6225 return false;
6226 }
6227 // FIXME: Implement captures.
6228 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, /*NumFields*/0);
6229 return true;
6230}
6231
Richard Smithd62306a2011-11-10 06:34:14 +00006232static bool EvaluateRecord(const Expr *E, const LValue &This,
6233 APValue &Result, EvalInfo &Info) {
6234 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006235 "can't evaluate expression as a record rvalue");
6236 return RecordExprEvaluator(Info, This, Result).Visit(E);
6237}
6238
6239//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006240// Temporary Evaluation
6241//
6242// Temporaries are represented in the AST as rvalues, but generally behave like
6243// lvalues. The full-object of which the temporary is a subobject is implicitly
6244// materialized so that a reference can bind to it.
6245//===----------------------------------------------------------------------===//
6246namespace {
6247class TemporaryExprEvaluator
6248 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6249public:
6250 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6251 LValueExprEvaluatorBaseTy(Info, Result) {}
6252
6253 /// Visit an expression which constructs the value of this temporary.
6254 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006255 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006256 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6257 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006258 }
6259
6260 bool VisitCastExpr(const CastExpr *E) {
6261 switch (E->getCastKind()) {
6262 default:
6263 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6264
6265 case CK_ConstructorConversion:
6266 return VisitConstructExpr(E->getSubExpr());
6267 }
6268 }
6269 bool VisitInitListExpr(const InitListExpr *E) {
6270 return VisitConstructExpr(E);
6271 }
6272 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6273 return VisitConstructExpr(E);
6274 }
6275 bool VisitCallExpr(const CallExpr *E) {
6276 return VisitConstructExpr(E);
6277 }
Richard Smith513955c2014-12-17 19:24:30 +00006278 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6279 return VisitConstructExpr(E);
6280 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006281 bool VisitLambdaExpr(const LambdaExpr *E) {
6282 return VisitConstructExpr(E);
6283 }
Richard Smith027bf112011-11-17 22:56:20 +00006284};
6285} // end anonymous namespace
6286
6287/// Evaluate an expression of record type as a temporary.
6288static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006289 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006290 return TemporaryExprEvaluator(Info, Result).Visit(E);
6291}
6292
6293//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006294// Vector Evaluation
6295//===----------------------------------------------------------------------===//
6296
6297namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006298 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006299 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006300 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006301 public:
Mike Stump11289f42009-09-09 15:08:12 +00006302
Richard Smith2d406342011-10-22 21:10:00 +00006303 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6304 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006305
Craig Topper9798b932015-09-29 04:30:05 +00006306 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006307 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6308 // FIXME: remove this APValue copy.
6309 Result = APValue(V.data(), V.size());
6310 return true;
6311 }
Richard Smith2e312c82012-03-03 22:46:17 +00006312 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006313 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006314 Result = V;
6315 return true;
6316 }
Richard Smithfddd3842011-12-30 21:15:51 +00006317 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006318
Richard Smith2d406342011-10-22 21:10:00 +00006319 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006320 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006321 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006322 bool VisitInitListExpr(const InitListExpr *E);
6323 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006324 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006325 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006326 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006327 };
6328} // end anonymous namespace
6329
6330static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006331 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006332 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006333}
6334
George Burgess IV533ff002015-12-11 00:23:35 +00006335bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006336 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006337 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006338
Richard Smith161f09a2011-12-06 22:44:34 +00006339 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006340 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006341
Eli Friedmanc757de22011-03-25 00:43:55 +00006342 switch (E->getCastKind()) {
6343 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006344 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006345 if (SETy->isIntegerType()) {
6346 APSInt IntResult;
6347 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006348 return false;
6349 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006350 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006351 APFloat FloatResult(0.0);
6352 if (!EvaluateFloat(SE, FloatResult, Info))
6353 return false;
6354 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006355 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006356 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006357 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006358
6359 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006360 SmallVector<APValue, 4> Elts(NElts, Val);
6361 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006362 }
Eli Friedman803acb32011-12-22 03:51:45 +00006363 case CK_BitCast: {
6364 // Evaluate the operand into an APInt we can extract from.
6365 llvm::APInt SValInt;
6366 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6367 return false;
6368 // Extract the elements
6369 QualType EltTy = VTy->getElementType();
6370 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6371 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6372 SmallVector<APValue, 4> Elts;
6373 if (EltTy->isRealFloatingType()) {
6374 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006375 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006376 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006377 FloatEltSize = 80;
6378 for (unsigned i = 0; i < NElts; i++) {
6379 llvm::APInt Elt;
6380 if (BigEndian)
6381 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6382 else
6383 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006384 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006385 }
6386 } else if (EltTy->isIntegerType()) {
6387 for (unsigned i = 0; i < NElts; i++) {
6388 llvm::APInt Elt;
6389 if (BigEndian)
6390 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6391 else
6392 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6393 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6394 }
6395 } else {
6396 return Error(E);
6397 }
6398 return Success(Elts, E);
6399 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006400 default:
Richard Smith11562c52011-10-28 17:51:58 +00006401 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006402 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006403}
6404
Richard Smith2d406342011-10-22 21:10:00 +00006405bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006406VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006407 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006408 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006409 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006410
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006411 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006412 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006413
Eli Friedmanb9c71292012-01-03 23:24:20 +00006414 // The number of initializers can be less than the number of
6415 // vector elements. For OpenCL, this can be due to nested vector
6416 // initialization. For GCC compatibility, missing trailing elements
6417 // should be initialized with zeroes.
6418 unsigned CountInits = 0, CountElts = 0;
6419 while (CountElts < NumElements) {
6420 // Handle nested vector initialization.
6421 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006422 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006423 APValue v;
6424 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6425 return Error(E);
6426 unsigned vlen = v.getVectorLength();
6427 for (unsigned j = 0; j < vlen; j++)
6428 Elements.push_back(v.getVectorElt(j));
6429 CountElts += vlen;
6430 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006431 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006432 if (CountInits < NumInits) {
6433 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006434 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006435 } else // trailing integer zero.
6436 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6437 Elements.push_back(APValue(sInt));
6438 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006439 } else {
6440 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006441 if (CountInits < NumInits) {
6442 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006443 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006444 } else // trailing float zero.
6445 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6446 Elements.push_back(APValue(f));
6447 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006448 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006449 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006450 }
Richard Smith2d406342011-10-22 21:10:00 +00006451 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006452}
6453
Richard Smith2d406342011-10-22 21:10:00 +00006454bool
Richard Smithfddd3842011-12-30 21:15:51 +00006455VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006456 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006457 QualType EltTy = VT->getElementType();
6458 APValue ZeroElement;
6459 if (EltTy->isIntegerType())
6460 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6461 else
6462 ZeroElement =
6463 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6464
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006465 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006466 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006467}
6468
Richard Smith2d406342011-10-22 21:10:00 +00006469bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006470 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006471 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006472}
6473
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006474//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006475// Array Evaluation
6476//===----------------------------------------------------------------------===//
6477
6478namespace {
6479 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006480 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006481 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006482 APValue &Result;
6483 public:
6484
Richard Smithd62306a2011-11-10 06:34:14 +00006485 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6486 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006487
6488 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006489 assert((V.isArray() || V.isLValue()) &&
6490 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006491 Result = V;
6492 return true;
6493 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006494
Richard Smithfddd3842011-12-30 21:15:51 +00006495 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006496 const ConstantArrayType *CAT =
6497 Info.Ctx.getAsConstantArrayType(E->getType());
6498 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006499 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006500
6501 Result = APValue(APValue::UninitArray(), 0,
6502 CAT->getSize().getZExtValue());
6503 if (!Result.hasArrayFiller()) return true;
6504
Richard Smithfddd3842011-12-30 21:15:51 +00006505 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006506 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006507 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006508 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006509 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006510 }
6511
Richard Smith52a980a2015-08-28 02:43:42 +00006512 bool VisitCallExpr(const CallExpr *E) {
6513 return handleCallExpr(E, Result, &This);
6514 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006515 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006516 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006517 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006518 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6519 const LValue &Subobject,
6520 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006521 };
6522} // end anonymous namespace
6523
Richard Smithd62306a2011-11-10 06:34:14 +00006524static bool EvaluateArray(const Expr *E, const LValue &This,
6525 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006526 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006527 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006528}
6529
6530bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6531 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6532 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006533 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006534
Richard Smithca2cfbf2011-12-22 01:07:19 +00006535 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6536 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006537 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006538 LValue LV;
6539 if (!EvaluateLValue(E->getInit(0), LV, Info))
6540 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006541 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006542 LV.moveInto(Val);
6543 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006544 }
6545
Richard Smith253c2a32012-01-27 01:14:48 +00006546 bool Success = true;
6547
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006548 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6549 "zero-initialized array shouldn't have any initialized elts");
6550 APValue Filler;
6551 if (Result.isArray() && Result.hasArrayFiller())
6552 Filler = Result.getArrayFiller();
6553
Richard Smith9543c5e2013-04-22 14:44:29 +00006554 unsigned NumEltsToInit = E->getNumInits();
6555 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006556 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006557
6558 // If the initializer might depend on the array index, run it for each
6559 // array element. For now, just whitelist non-class value-initialization.
6560 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6561 NumEltsToInit = NumElts;
6562
6563 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006564
6565 // If the array was previously zero-initialized, preserve the
6566 // zero-initialized values.
6567 if (!Filler.isUninit()) {
6568 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6569 Result.getArrayInitializedElt(I) = Filler;
6570 if (Result.hasArrayFiller())
6571 Result.getArrayFiller() = Filler;
6572 }
6573
Richard Smithd62306a2011-11-10 06:34:14 +00006574 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006575 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006576 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6577 const Expr *Init =
6578 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006579 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006580 Info, Subobject, Init) ||
6581 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006582 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006583 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006584 return false;
6585 Success = false;
6586 }
Richard Smithd62306a2011-11-10 06:34:14 +00006587 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006588
Richard Smith9543c5e2013-04-22 14:44:29 +00006589 if (!Result.hasArrayFiller())
6590 return Success;
6591
6592 // If we get here, we have a trivial filler, which we can just evaluate
6593 // once and splat over the rest of the array elements.
6594 assert(FillerExpr && "no array filler for incomplete init list");
6595 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6596 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006597}
6598
Richard Smith410306b2016-12-12 02:53:20 +00006599bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6600 if (E->getCommonExpr() &&
6601 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6602 Info, E->getCommonExpr()->getSourceExpr()))
6603 return false;
6604
6605 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6606
6607 uint64_t Elements = CAT->getSize().getZExtValue();
6608 Result = APValue(APValue::UninitArray(), Elements, Elements);
6609
6610 LValue Subobject = This;
6611 Subobject.addArray(Info, E, CAT);
6612
6613 bool Success = true;
6614 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6615 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6616 Info, Subobject, E->getSubExpr()) ||
6617 !HandleLValueArrayAdjustment(Info, E, Subobject,
6618 CAT->getElementType(), 1)) {
6619 if (!Info.noteFailure())
6620 return false;
6621 Success = false;
6622 }
6623 }
6624
6625 return Success;
6626}
6627
Richard Smith027bf112011-11-17 22:56:20 +00006628bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006629 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6630}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006631
Richard Smith9543c5e2013-04-22 14:44:29 +00006632bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6633 const LValue &Subobject,
6634 APValue *Value,
6635 QualType Type) {
6636 bool HadZeroInit = !Value->isUninit();
6637
6638 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6639 unsigned N = CAT->getSize().getZExtValue();
6640
6641 // Preserve the array filler if we had prior zero-initialization.
6642 APValue Filler =
6643 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6644 : APValue();
6645
6646 *Value = APValue(APValue::UninitArray(), N, N);
6647
6648 if (HadZeroInit)
6649 for (unsigned I = 0; I != N; ++I)
6650 Value->getArrayInitializedElt(I) = Filler;
6651
6652 // Initialize the elements.
6653 LValue ArrayElt = Subobject;
6654 ArrayElt.addArray(Info, E, CAT);
6655 for (unsigned I = 0; I != N; ++I)
6656 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6657 CAT->getElementType()) ||
6658 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6659 CAT->getElementType(), 1))
6660 return false;
6661
6662 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006663 }
Richard Smith027bf112011-11-17 22:56:20 +00006664
Richard Smith9543c5e2013-04-22 14:44:29 +00006665 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006666 return Error(E);
6667
Richard Smithb8348f52016-05-12 22:16:28 +00006668 return RecordExprEvaluator(Info, Subobject, *Value)
6669 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006670}
6671
Richard Smithf3e9e432011-11-07 09:22:26 +00006672//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006673// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006674//
6675// As a GNU extension, we support casting pointers to sufficiently-wide integer
6676// types and back in constant folding. Integer values are thus represented
6677// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006678//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006679
6680namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006681class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006682 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006683 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006684public:
Richard Smith2e312c82012-03-03 22:46:17 +00006685 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006686 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006687
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006688 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006689 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006690 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006691 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006692 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006693 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006694 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006695 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006696 return true;
6697 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006698 bool Success(const llvm::APSInt &SI, const Expr *E) {
6699 return Success(SI, E, Result);
6700 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006701
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006702 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006703 assert(E->getType()->isIntegralOrEnumerationType() &&
6704 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006705 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006706 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006707 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006708 Result.getInt().setIsUnsigned(
6709 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006710 return true;
6711 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006712 bool Success(const llvm::APInt &I, const Expr *E) {
6713 return Success(I, E, Result);
6714 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006715
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006716 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006717 assert(E->getType()->isIntegralOrEnumerationType() &&
6718 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006719 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006720 return true;
6721 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006722 bool Success(uint64_t Value, const Expr *E) {
6723 return Success(Value, E, Result);
6724 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006725
Ken Dyckdbc01912011-03-11 02:13:43 +00006726 bool Success(CharUnits Size, const Expr *E) {
6727 return Success(Size.getQuantity(), E);
6728 }
6729
Richard Smith2e312c82012-03-03 22:46:17 +00006730 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006731 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006732 Result = V;
6733 return true;
6734 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006735 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006736 }
Mike Stump11289f42009-09-09 15:08:12 +00006737
Richard Smithfddd3842011-12-30 21:15:51 +00006738 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006739
Peter Collingbournee9200682011-05-13 03:29:01 +00006740 //===--------------------------------------------------------------------===//
6741 // Visitor Methods
6742 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006743
Chris Lattner7174bf32008-07-12 00:38:25 +00006744 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006745 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006746 }
6747 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006748 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006749 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006750
6751 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6752 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006753 if (CheckReferencedDecl(E, E->getDecl()))
6754 return true;
6755
6756 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006757 }
6758 bool VisitMemberExpr(const MemberExpr *E) {
6759 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006760 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006761 return true;
6762 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006763
6764 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006765 }
6766
Peter Collingbournee9200682011-05-13 03:29:01 +00006767 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006768 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006769 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006770 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006771 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006772
Peter Collingbournee9200682011-05-13 03:29:01 +00006773 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006774 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006775
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006776 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006777 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006778 }
Mike Stump11289f42009-09-09 15:08:12 +00006779
Ted Kremeneke65b0862012-03-06 20:05:56 +00006780 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6781 return Success(E->getValue(), E);
6782 }
Richard Smith410306b2016-12-12 02:53:20 +00006783
6784 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6785 if (Info.ArrayInitIndex == uint64_t(-1)) {
6786 // We were asked to evaluate this subexpression independent of the
6787 // enclosing ArrayInitLoopExpr. We can't do that.
6788 Info.FFDiag(E);
6789 return false;
6790 }
6791 return Success(Info.ArrayInitIndex, E);
6792 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00006793
Richard Smith4ce706a2011-10-11 21:43:33 +00006794 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006795 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006796 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006797 }
6798
Douglas Gregor29c42f22012-02-24 07:38:34 +00006799 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6800 return Success(E->getValue(), E);
6801 }
6802
John Wiegley6242b6a2011-04-28 00:16:57 +00006803 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6804 return Success(E->getValue(), E);
6805 }
6806
John Wiegleyf9f65842011-04-25 06:54:41 +00006807 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6808 return Success(E->getValue(), E);
6809 }
6810
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006811 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006812 bool VisitUnaryImag(const UnaryOperator *E);
6813
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006814 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006815 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006816
Eli Friedman4e7a2412009-02-27 04:45:43 +00006817 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006818};
Chris Lattner05706e882008-07-11 18:11:29 +00006819} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006820
Richard Smith11562c52011-10-28 17:51:58 +00006821/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6822/// produce either the integer value or a pointer.
6823///
6824/// GCC has a heinous extension which folds casts between pointer types and
6825/// pointer-sized integral types. We support this by allowing the evaluation of
6826/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6827/// Some simple arithmetic on such values is supported (they are treated much
6828/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006829static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006830 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006831 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006832 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006833}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006834
Richard Smithf57d8cb2011-12-09 22:58:01 +00006835static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006836 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006837 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006838 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006839 if (!Val.isInt()) {
6840 // FIXME: It would be better to produce the diagnostic for casting
6841 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006842 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006843 return false;
6844 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006845 Result = Val.getInt();
6846 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006847}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006848
Richard Smithf57d8cb2011-12-09 22:58:01 +00006849/// Check whether the given declaration can be directly converted to an integral
6850/// rvalue. If not, no diagnostic is produced; there are other things we can
6851/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006852bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006853 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006854 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006855 // Check for signedness/width mismatches between E type and ECD value.
6856 bool SameSign = (ECD->getInitVal().isSigned()
6857 == E->getType()->isSignedIntegerOrEnumerationType());
6858 bool SameWidth = (ECD->getInitVal().getBitWidth()
6859 == Info.Ctx.getIntWidth(E->getType()));
6860 if (SameSign && SameWidth)
6861 return Success(ECD->getInitVal(), E);
6862 else {
6863 // Get rid of mismatch (otherwise Success assertions will fail)
6864 // by computing a new value matching the type of E.
6865 llvm::APSInt Val = ECD->getInitVal();
6866 if (!SameSign)
6867 Val.setIsSigned(!ECD->getInitVal().isSigned());
6868 if (!SameWidth)
6869 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6870 return Success(Val, E);
6871 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006872 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006873 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006874}
6875
Chris Lattner86ee2862008-10-06 06:40:35 +00006876/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6877/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006878static int EvaluateBuiltinClassifyType(const CallExpr *E,
6879 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006880 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006881 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006882 enum gcc_type_class {
6883 no_type_class = -1,
6884 void_type_class, integer_type_class, char_type_class,
6885 enumeral_type_class, boolean_type_class,
6886 pointer_type_class, reference_type_class, offset_type_class,
6887 real_type_class, complex_type_class,
6888 function_type_class, method_type_class,
6889 record_type_class, union_type_class,
6890 array_type_class, string_type_class,
6891 lang_type_class
6892 };
Mike Stump11289f42009-09-09 15:08:12 +00006893
6894 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006895 // ideal, however it is what gcc does.
6896 if (E->getNumArgs() == 0)
6897 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006898
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006899 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6900 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6901
6902 switch (CanTy->getTypeClass()) {
6903#define TYPE(ID, BASE)
6904#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6905#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6906#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6907#include "clang/AST/TypeNodes.def"
6908 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6909
6910 case Type::Builtin:
6911 switch (BT->getKind()) {
6912#define BUILTIN_TYPE(ID, SINGLETON_ID)
6913#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6914#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6915#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6916#include "clang/AST/BuiltinTypes.def"
6917 case BuiltinType::Void:
6918 return void_type_class;
6919
6920 case BuiltinType::Bool:
6921 return boolean_type_class;
6922
6923 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6924 case BuiltinType::UChar:
6925 case BuiltinType::UShort:
6926 case BuiltinType::UInt:
6927 case BuiltinType::ULong:
6928 case BuiltinType::ULongLong:
6929 case BuiltinType::UInt128:
6930 return integer_type_class;
6931
6932 case BuiltinType::NullPtr:
6933 return pointer_type_class;
6934
6935 case BuiltinType::WChar_U:
6936 case BuiltinType::Char16:
6937 case BuiltinType::Char32:
6938 case BuiltinType::ObjCId:
6939 case BuiltinType::ObjCClass:
6940 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006941#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6942 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006943#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006944 case BuiltinType::OCLSampler:
6945 case BuiltinType::OCLEvent:
6946 case BuiltinType::OCLClkEvent:
6947 case BuiltinType::OCLQueue:
6948 case BuiltinType::OCLNDRange:
6949 case BuiltinType::OCLReserveID:
6950 case BuiltinType::Dependent:
6951 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6952 };
6953
6954 case Type::Enum:
6955 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6956 break;
6957
6958 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006959 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006960 break;
6961
6962 case Type::MemberPointer:
6963 if (CanTy->isMemberDataPointerType())
6964 return offset_type_class;
6965 else {
6966 // We expect member pointers to be either data or function pointers,
6967 // nothing else.
6968 assert(CanTy->isMemberFunctionPointerType());
6969 return method_type_class;
6970 }
6971
6972 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006973 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006974
6975 case Type::FunctionNoProto:
6976 case Type::FunctionProto:
6977 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6978
6979 case Type::Record:
6980 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6981 switch (RT->getDecl()->getTagKind()) {
6982 case TagTypeKind::TTK_Struct:
6983 case TagTypeKind::TTK_Class:
6984 case TagTypeKind::TTK_Interface:
6985 return record_type_class;
6986
6987 case TagTypeKind::TTK_Enum:
6988 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6989
6990 case TagTypeKind::TTK_Union:
6991 return union_type_class;
6992 }
6993 }
David Blaikie83d382b2011-09-23 05:06:16 +00006994 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006995
6996 case Type::ConstantArray:
6997 case Type::VariableArray:
6998 case Type::IncompleteArray:
6999 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7000
7001 case Type::BlockPointer:
7002 case Type::LValueReference:
7003 case Type::RValueReference:
7004 case Type::Vector:
7005 case Type::ExtVector:
7006 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007007 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007008 case Type::ObjCObject:
7009 case Type::ObjCInterface:
7010 case Type::ObjCObjectPointer:
7011 case Type::Pipe:
7012 case Type::Atomic:
7013 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7014 }
7015
7016 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007017}
7018
Richard Smith5fab0c92011-12-28 19:48:30 +00007019/// EvaluateBuiltinConstantPForLValue - Determine the result of
7020/// __builtin_constant_p when applied to the given lvalue.
7021///
7022/// An lvalue is only "constant" if it is a pointer or reference to the first
7023/// character of a string literal.
7024template<typename LValue>
7025static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007026 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007027 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7028}
7029
7030/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7031/// GCC as we can manage.
7032static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7033 QualType ArgType = Arg->getType();
7034
7035 // __builtin_constant_p always has one operand. The rules which gcc follows
7036 // are not precisely documented, but are as follows:
7037 //
7038 // - If the operand is of integral, floating, complex or enumeration type,
7039 // and can be folded to a known value of that type, it returns 1.
7040 // - If the operand and can be folded to a pointer to the first character
7041 // of a string literal (or such a pointer cast to an integral type), it
7042 // returns 1.
7043 //
7044 // Otherwise, it returns 0.
7045 //
7046 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7047 // its support for this does not currently work.
7048 if (ArgType->isIntegralOrEnumerationType()) {
7049 Expr::EvalResult Result;
7050 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7051 return false;
7052
7053 APValue &V = Result.Val;
7054 if (V.getKind() == APValue::Int)
7055 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007056 if (V.getKind() == APValue::LValue)
7057 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007058 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7059 return Arg->isEvaluatable(Ctx);
7060 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7061 LValue LV;
7062 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007063 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007064 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7065 : EvaluatePointer(Arg, LV, Info)) &&
7066 !Status.HasSideEffects)
7067 return EvaluateBuiltinConstantPForLValue(LV);
7068 }
7069
7070 // Anything else isn't considered to be sufficiently constant.
7071 return false;
7072}
7073
John McCall95007602010-05-10 23:27:23 +00007074/// Retrieves the "underlying object type" of the given expression,
7075/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007076static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007077 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7078 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007079 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007080 } else if (const Expr *E = B.get<const Expr*>()) {
7081 if (isa<CompoundLiteralExpr>(E))
7082 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007083 }
7084
7085 return QualType();
7086}
7087
George Burgess IV3a03fab2015-09-04 21:28:13 +00007088/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007089/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007090/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007091/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7092///
7093/// Always returns an RValue with a pointer representation.
7094static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7095 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7096
7097 auto *NoParens = E->IgnoreParens();
7098 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007099 if (Cast == nullptr)
7100 return NoParens;
7101
7102 // We only conservatively allow a few kinds of casts, because this code is
7103 // inherently a simple solution that seeks to support the common case.
7104 auto CastKind = Cast->getCastKind();
7105 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7106 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007107 return NoParens;
7108
7109 auto *SubExpr = Cast->getSubExpr();
7110 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7111 return NoParens;
7112 return ignorePointerCastsAndParens(SubExpr);
7113}
7114
George Burgess IVa51c4072015-10-16 01:49:01 +00007115/// Checks to see if the given LValue's Designator is at the end of the LValue's
7116/// record layout. e.g.
7117/// struct { struct { int a, b; } fst, snd; } obj;
7118/// obj.fst // no
7119/// obj.snd // yes
7120/// obj.fst.a // no
7121/// obj.fst.b // no
7122/// obj.snd.a // no
7123/// obj.snd.b // yes
7124///
7125/// Please note: this function is specialized for how __builtin_object_size
7126/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007127///
7128/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007129static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7130 assert(!LVal.Designator.Invalid);
7131
George Burgess IV4168d752016-06-27 19:40:41 +00007132 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7133 const RecordDecl *Parent = FD->getParent();
7134 Invalid = Parent->isInvalidDecl();
7135 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007136 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007137 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007138 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7139 };
7140
7141 auto &Base = LVal.getLValueBase();
7142 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7143 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007144 bool Invalid;
7145 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7146 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007147 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007148 for (auto *FD : IFD->chain()) {
7149 bool Invalid;
7150 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7151 return Invalid;
7152 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007153 }
7154 }
7155
George Burgess IVe3763372016-12-22 02:50:20 +00007156 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007157 QualType BaseType = getType(Base);
George Burgess IVe3763372016-12-22 02:50:20 +00007158 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7159 assert(isBaseAnAllocSizeCall(Base) &&
7160 "Unsized array in non-alloc_size call?");
7161 // If this is an alloc_size base, we should ignore the initial array index
7162 ++I;
7163 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7164 }
7165
7166 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7167 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007168 if (BaseType->isArrayType()) {
7169 // Because __builtin_object_size treats arrays as objects, we can ignore
7170 // the index iff this is the last array in the Designator.
7171 if (I + 1 == E)
7172 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007173 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7174 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007175 if (Index + 1 != CAT->getSize())
7176 return false;
7177 BaseType = CAT->getElementType();
7178 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007179 const auto *CT = BaseType->castAs<ComplexType>();
7180 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007181 if (Index != 1)
7182 return false;
7183 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007184 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007185 bool Invalid;
7186 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7187 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007188 BaseType = FD->getType();
7189 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007190 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007191 return false;
7192 }
7193 }
7194 return true;
7195}
7196
George Burgess IVe3763372016-12-22 02:50:20 +00007197/// Tests to see if the LValue has a user-specified designator (that isn't
7198/// necessarily valid). Note that this always returns 'true' if the LValue has
7199/// an unsized array as its first designator entry, because there's currently no
7200/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007201static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007202 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007203 return false;
7204
George Burgess IVe3763372016-12-22 02:50:20 +00007205 if (!LVal.Designator.Entries.empty())
7206 return LVal.Designator.isMostDerivedAnUnsizedArray();
7207
George Burgess IVa51c4072015-10-16 01:49:01 +00007208 if (!LVal.InvalidBase)
7209 return true;
7210
George Burgess IVe3763372016-12-22 02:50:20 +00007211 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7212 // the LValueBase.
7213 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7214 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007215}
7216
George Burgess IVe3763372016-12-22 02:50:20 +00007217/// Attempts to detect a user writing into a piece of memory that's impossible
7218/// to figure out the size of by just using types.
7219static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7220 const SubobjectDesignator &Designator = LVal.Designator;
7221 // Notes:
7222 // - Users can only write off of the end when we have an invalid base. Invalid
7223 // bases imply we don't know where the memory came from.
7224 // - We used to be a bit more aggressive here; we'd only be conservative if
7225 // the array at the end was flexible, or if it had 0 or 1 elements. This
7226 // broke some common standard library extensions (PR30346), but was
7227 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7228 // with some sort of whitelist. OTOH, it seems that GCC is always
7229 // conservative with the last element in structs (if it's an array), so our
7230 // current behavior is more compatible than a whitelisting approach would
7231 // be.
7232 return LVal.InvalidBase &&
7233 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7234 Designator.MostDerivedIsArrayElement &&
7235 isDesignatorAtObjectEnd(Ctx, LVal);
7236}
7237
7238/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7239/// Fails if the conversion would cause loss of precision.
7240static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7241 CharUnits &Result) {
7242 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7243 if (Int.ugt(CharUnitsMax))
7244 return false;
7245 Result = CharUnits::fromQuantity(Int.getZExtValue());
7246 return true;
7247}
7248
7249/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7250/// determine how many bytes exist from the beginning of the object to either
7251/// the end of the current subobject, or the end of the object itself, depending
7252/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007253///
George Burgess IVe3763372016-12-22 02:50:20 +00007254/// If this returns false, the value of Result is undefined.
7255static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7256 unsigned Type, const LValue &LVal,
7257 CharUnits &EndOffset) {
7258 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007259
George Burgess IV7fb7e362017-01-03 23:35:19 +00007260 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7261 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7262 return false;
7263 return HandleSizeof(Info, ExprLoc, Ty, Result);
7264 };
7265
George Burgess IVe3763372016-12-22 02:50:20 +00007266 // We want to evaluate the size of the entire object. This is a valid fallback
7267 // for when Type=1 and the designator is invalid, because we're asked for an
7268 // upper-bound.
7269 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7270 // Type=3 wants a lower bound, so we can't fall back to this.
7271 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007272 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007273
7274 llvm::APInt APEndOffset;
7275 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7276 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7277 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7278
7279 if (LVal.InvalidBase)
7280 return false;
7281
7282 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007283 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007284 }
7285
George Burgess IVe3763372016-12-22 02:50:20 +00007286 // We want to evaluate the size of a subobject.
7287 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007288
7289 // The following is a moderately common idiom in C:
7290 //
7291 // struct Foo { int a; char c[1]; };
7292 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7293 // strcpy(&F->c[0], Bar);
7294 //
George Burgess IVe3763372016-12-22 02:50:20 +00007295 // In order to not break too much legacy code, we need to support it.
7296 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7297 // If we can resolve this to an alloc_size call, we can hand that back,
7298 // because we know for certain how many bytes there are to write to.
7299 llvm::APInt APEndOffset;
7300 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7301 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7302 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7303
7304 // If we cannot determine the size of the initial allocation, then we can't
7305 // given an accurate upper-bound. However, we are still able to give
7306 // conservative lower-bounds for Type=3.
7307 if (Type == 1)
7308 return false;
7309 }
7310
7311 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007312 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007313 return false;
7314
George Burgess IVe3763372016-12-22 02:50:20 +00007315 // According to the GCC documentation, we want the size of the subobject
7316 // denoted by the pointer. But that's not quite right -- what we actually
7317 // want is the size of the immediately-enclosing array, if there is one.
7318 int64_t ElemsRemaining;
7319 if (Designator.MostDerivedIsArrayElement &&
7320 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7321 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7322 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7323 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7324 } else {
7325 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7326 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007327
George Burgess IVe3763372016-12-22 02:50:20 +00007328 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7329 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007330}
7331
George Burgess IVe3763372016-12-22 02:50:20 +00007332/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7333/// returns true and stores the result in @p Size.
7334///
7335/// If @p WasError is non-null, this will report whether the failure to evaluate
7336/// is to be treated as an Error in IntExprEvaluator.
7337static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7338 EvalInfo &Info, uint64_t &Size) {
7339 // Determine the denoted object.
7340 LValue LVal;
7341 {
7342 // The operand of __builtin_object_size is never evaluated for side-effects.
7343 // If there are any, but we can determine the pointed-to object anyway, then
7344 // ignore the side-effects.
7345 SpeculativeEvaluationRAII SpeculativeEval(Info);
7346 FoldOffsetRAII Fold(Info);
7347
7348 if (E->isGLValue()) {
7349 // It's possible for us to be given GLValues if we're called via
7350 // Expr::tryEvaluateObjectSize.
7351 APValue RVal;
7352 if (!EvaluateAsRValue(Info, E, RVal))
7353 return false;
7354 LVal.setFrom(Info.Ctx, RVal);
7355 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info))
7356 return false;
7357 }
7358
7359 // If we point to before the start of the object, there are no accessible
7360 // bytes.
7361 if (LVal.getLValueOffset().isNegative()) {
7362 Size = 0;
7363 return true;
7364 }
7365
7366 CharUnits EndOffset;
7367 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7368 return false;
7369
7370 // If we've fallen outside of the end offset, just pretend there's nothing to
7371 // write to/read from.
7372 if (EndOffset <= LVal.getLValueOffset())
7373 Size = 0;
7374 else
7375 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7376 return true;
John McCall95007602010-05-10 23:27:23 +00007377}
7378
Peter Collingbournee9200682011-05-13 03:29:01 +00007379bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007380 if (unsigned BuiltinOp = E->getBuiltinCallee())
7381 return VisitBuiltinCallExpr(E, BuiltinOp);
7382
7383 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7384}
7385
7386bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7387 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007388 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007389 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007390 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007391
7392 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007393 // The type was checked when we built the expression.
7394 unsigned Type =
7395 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7396 assert(Type <= 3 && "unexpected type");
7397
George Burgess IVe3763372016-12-22 02:50:20 +00007398 uint64_t Size;
7399 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7400 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007401
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007402 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007403 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007404
Richard Smith01ade172012-05-23 04:13:20 +00007405 // Expression had no side effects, but we couldn't statically determine the
7406 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007407 switch (Info.EvalMode) {
7408 case EvalInfo::EM_ConstantExpression:
7409 case EvalInfo::EM_PotentialConstantExpression:
7410 case EvalInfo::EM_ConstantFold:
7411 case EvalInfo::EM_EvaluateForOverflow:
7412 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007413 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007414 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007415 return Error(E);
7416 case EvalInfo::EM_ConstantExpressionUnevaluated:
7417 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007418 // Reduce it to a constant now.
7419 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007420 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007421
7422 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007423 }
7424
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007425 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007426 case Builtin::BI__builtin_bswap32:
7427 case Builtin::BI__builtin_bswap64: {
7428 APSInt Val;
7429 if (!EvaluateInteger(E->getArg(0), Val, Info))
7430 return false;
7431
7432 return Success(Val.byteSwap(), E);
7433 }
7434
Richard Smith8889a3d2013-06-13 06:26:32 +00007435 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007436 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007437
7438 // FIXME: BI__builtin_clrsb
7439 // FIXME: BI__builtin_clrsbl
7440 // FIXME: BI__builtin_clrsbll
7441
Richard Smith80b3c8e2013-06-13 05:04:16 +00007442 case Builtin::BI__builtin_clz:
7443 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007444 case Builtin::BI__builtin_clzll:
7445 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007446 APSInt Val;
7447 if (!EvaluateInteger(E->getArg(0), Val, Info))
7448 return false;
7449 if (!Val)
7450 return Error(E);
7451
7452 return Success(Val.countLeadingZeros(), E);
7453 }
7454
Richard Smith8889a3d2013-06-13 06:26:32 +00007455 case Builtin::BI__builtin_constant_p:
7456 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7457
Richard Smith80b3c8e2013-06-13 05:04:16 +00007458 case Builtin::BI__builtin_ctz:
7459 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007460 case Builtin::BI__builtin_ctzll:
7461 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007462 APSInt Val;
7463 if (!EvaluateInteger(E->getArg(0), Val, Info))
7464 return false;
7465 if (!Val)
7466 return Error(E);
7467
7468 return Success(Val.countTrailingZeros(), E);
7469 }
7470
Richard Smith8889a3d2013-06-13 06:26:32 +00007471 case Builtin::BI__builtin_eh_return_data_regno: {
7472 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7473 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7474 return Success(Operand, E);
7475 }
7476
7477 case Builtin::BI__builtin_expect:
7478 return Visit(E->getArg(0));
7479
7480 case Builtin::BI__builtin_ffs:
7481 case Builtin::BI__builtin_ffsl:
7482 case Builtin::BI__builtin_ffsll: {
7483 APSInt Val;
7484 if (!EvaluateInteger(E->getArg(0), Val, Info))
7485 return false;
7486
7487 unsigned N = Val.countTrailingZeros();
7488 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7489 }
7490
7491 case Builtin::BI__builtin_fpclassify: {
7492 APFloat Val(0.0);
7493 if (!EvaluateFloat(E->getArg(5), Val, Info))
7494 return false;
7495 unsigned Arg;
7496 switch (Val.getCategory()) {
7497 case APFloat::fcNaN: Arg = 0; break;
7498 case APFloat::fcInfinity: Arg = 1; break;
7499 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7500 case APFloat::fcZero: Arg = 4; break;
7501 }
7502 return Visit(E->getArg(Arg));
7503 }
7504
7505 case Builtin::BI__builtin_isinf_sign: {
7506 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007507 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007508 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7509 }
7510
Richard Smithea3019d2013-10-15 19:07:14 +00007511 case Builtin::BI__builtin_isinf: {
7512 APFloat Val(0.0);
7513 return EvaluateFloat(E->getArg(0), Val, Info) &&
7514 Success(Val.isInfinity() ? 1 : 0, E);
7515 }
7516
7517 case Builtin::BI__builtin_isfinite: {
7518 APFloat Val(0.0);
7519 return EvaluateFloat(E->getArg(0), Val, Info) &&
7520 Success(Val.isFinite() ? 1 : 0, E);
7521 }
7522
7523 case Builtin::BI__builtin_isnan: {
7524 APFloat Val(0.0);
7525 return EvaluateFloat(E->getArg(0), Val, Info) &&
7526 Success(Val.isNaN() ? 1 : 0, E);
7527 }
7528
7529 case Builtin::BI__builtin_isnormal: {
7530 APFloat Val(0.0);
7531 return EvaluateFloat(E->getArg(0), Val, Info) &&
7532 Success(Val.isNormal() ? 1 : 0, E);
7533 }
7534
Richard Smith8889a3d2013-06-13 06:26:32 +00007535 case Builtin::BI__builtin_parity:
7536 case Builtin::BI__builtin_parityl:
7537 case Builtin::BI__builtin_parityll: {
7538 APSInt Val;
7539 if (!EvaluateInteger(E->getArg(0), Val, Info))
7540 return false;
7541
7542 return Success(Val.countPopulation() % 2, E);
7543 }
7544
Richard Smith80b3c8e2013-06-13 05:04:16 +00007545 case Builtin::BI__builtin_popcount:
7546 case Builtin::BI__builtin_popcountl:
7547 case Builtin::BI__builtin_popcountll: {
7548 APSInt Val;
7549 if (!EvaluateInteger(E->getArg(0), Val, Info))
7550 return false;
7551
7552 return Success(Val.countPopulation(), E);
7553 }
7554
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007555 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007556 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007557 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007558 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007559 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007560 << /*isConstexpr*/0 << /*isConstructor*/0
7561 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007562 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007563 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007564 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007565 case Builtin::BI__builtin_strlen:
7566 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007567 // As an extension, we support __builtin_strlen() as a constant expression,
7568 // and support folding strlen() to a constant.
7569 LValue String;
7570 if (!EvaluatePointer(E->getArg(0), String, Info))
7571 return false;
7572
Richard Smith8110c9d2016-11-29 19:45:17 +00007573 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7574
Richard Smithe6c19f22013-11-15 02:10:04 +00007575 // Fast path: if it's a string literal, search the string value.
7576 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7577 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007578 // The string literal may have embedded null characters. Find the first
7579 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007580 StringRef Str = S->getBytes();
7581 int64_t Off = String.Offset.getQuantity();
7582 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007583 S->getCharByteWidth() == 1 &&
7584 // FIXME: Add fast-path for wchar_t too.
7585 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007586 Str = Str.substr(Off);
7587
7588 StringRef::size_type Pos = Str.find(0);
7589 if (Pos != StringRef::npos)
7590 Str = Str.substr(0, Pos);
7591
7592 return Success(Str.size(), E);
7593 }
7594
7595 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007596 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007597
7598 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007599 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7600 APValue Char;
7601 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7602 !Char.isInt())
7603 return false;
7604 if (!Char.getInt())
7605 return Success(Strlen, E);
7606 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7607 return false;
7608 }
7609 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007610
Richard Smithe151bab2016-11-11 23:43:35 +00007611 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007612 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007613 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007614 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007615 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007616 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007617 // A call to strlen is not a constant expression.
7618 if (Info.getLangOpts().CPlusPlus11)
7619 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7620 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007621 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007622 else
7623 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7624 // Fall through.
7625 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007626 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007627 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007628 case Builtin::BI__builtin_wcsncmp:
7629 case Builtin::BI__builtin_memcmp:
7630 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007631 LValue String1, String2;
7632 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7633 !EvaluatePointer(E->getArg(1), String2, Info))
7634 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007635
7636 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7637
Richard Smithe151bab2016-11-11 23:43:35 +00007638 uint64_t MaxLength = uint64_t(-1);
7639 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007640 BuiltinOp != Builtin::BIwcscmp &&
7641 BuiltinOp != Builtin::BI__builtin_strcmp &&
7642 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007643 APSInt N;
7644 if (!EvaluateInteger(E->getArg(2), N, Info))
7645 return false;
7646 MaxLength = N.getExtValue();
7647 }
7648 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007649 BuiltinOp != Builtin::BIwmemcmp &&
7650 BuiltinOp != Builtin::BI__builtin_memcmp &&
7651 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007652 for (; MaxLength; --MaxLength) {
7653 APValue Char1, Char2;
7654 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7655 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7656 !Char1.isInt() || !Char2.isInt())
7657 return false;
7658 if (Char1.getInt() != Char2.getInt())
7659 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7660 if (StopAtNull && !Char1.getInt())
7661 return Success(0, E);
7662 assert(!(StopAtNull && !Char2.getInt()));
7663 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7664 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7665 return false;
7666 }
7667 // We hit the strncmp / memcmp limit.
7668 return Success(0, E);
7669 }
7670
Richard Smith01ba47d2012-04-13 00:45:38 +00007671 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007672 case Builtin::BI__atomic_is_lock_free:
7673 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007674 APSInt SizeVal;
7675 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7676 return false;
7677
7678 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7679 // of two less than the maximum inline atomic width, we know it is
7680 // lock-free. If the size isn't a power of two, or greater than the
7681 // maximum alignment where we promote atomics, we know it is not lock-free
7682 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7683 // the answer can only be determined at runtime; for example, 16-byte
7684 // atomics have lock-free implementations on some, but not all,
7685 // x86-64 processors.
7686
7687 // Check power-of-two.
7688 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007689 if (Size.isPowerOfTwo()) {
7690 // Check against inlining width.
7691 unsigned InlineWidthBits =
7692 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7693 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7694 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7695 Size == CharUnits::One() ||
7696 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7697 Expr::NPC_NeverValueDependent))
7698 // OK, we will inline appropriately-aligned operations of this size,
7699 // and _Atomic(T) is appropriately-aligned.
7700 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007701
Richard Smith01ba47d2012-04-13 00:45:38 +00007702 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7703 castAs<PointerType>()->getPointeeType();
7704 if (!PointeeType->isIncompleteType() &&
7705 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7706 // OK, we will inline operations on this object.
7707 return Success(1, E);
7708 }
7709 }
7710 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007711
Richard Smith01ba47d2012-04-13 00:45:38 +00007712 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7713 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007714 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007715 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007716}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007717
Richard Smith8b3497e2011-10-31 01:37:14 +00007718static bool HasSameBase(const LValue &A, const LValue &B) {
7719 if (!A.getLValueBase())
7720 return !B.getLValueBase();
7721 if (!B.getLValueBase())
7722 return false;
7723
Richard Smithce40ad62011-11-12 22:28:03 +00007724 if (A.getLValueBase().getOpaqueValue() !=
7725 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007726 const Decl *ADecl = GetLValueBaseDecl(A);
7727 if (!ADecl)
7728 return false;
7729 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007730 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007731 return false;
7732 }
7733
7734 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007735 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007736}
7737
Richard Smithd20f1e62014-10-21 23:01:04 +00007738/// \brief Determine whether this is a pointer past the end of the complete
7739/// object referred to by the lvalue.
7740static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7741 const LValue &LV) {
7742 // A null pointer can be viewed as being "past the end" but we don't
7743 // choose to look at it that way here.
7744 if (!LV.getLValueBase())
7745 return false;
7746
7747 // If the designator is valid and refers to a subobject, we're not pointing
7748 // past the end.
7749 if (!LV.getLValueDesignator().Invalid &&
7750 !LV.getLValueDesignator().isOnePastTheEnd())
7751 return false;
7752
David Majnemerc378ca52015-08-29 08:32:55 +00007753 // A pointer to an incomplete type might be past-the-end if the type's size is
7754 // zero. We cannot tell because the type is incomplete.
7755 QualType Ty = getType(LV.getLValueBase());
7756 if (Ty->isIncompleteType())
7757 return true;
7758
Richard Smithd20f1e62014-10-21 23:01:04 +00007759 // We're a past-the-end pointer if we point to the byte after the object,
7760 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007761 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007762 return LV.getLValueOffset() == Size;
7763}
7764
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007765namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007766
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007767/// \brief Data recursive integer evaluator of certain binary operators.
7768///
7769/// We use a data recursive algorithm for binary operators so that we are able
7770/// to handle extreme cases of chained binary operators without causing stack
7771/// overflow.
7772class DataRecursiveIntBinOpEvaluator {
7773 struct EvalResult {
7774 APValue Val;
7775 bool Failed;
7776
7777 EvalResult() : Failed(false) { }
7778
7779 void swap(EvalResult &RHS) {
7780 Val.swap(RHS.Val);
7781 Failed = RHS.Failed;
7782 RHS.Failed = false;
7783 }
7784 };
7785
7786 struct Job {
7787 const Expr *E;
7788 EvalResult LHSResult; // meaningful only for binary operator expression.
7789 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007790
David Blaikie73726062015-08-12 23:09:24 +00007791 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007792 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007793
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007794 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007795 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007796 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007797
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007798 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007799 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007800 };
7801
7802 SmallVector<Job, 16> Queue;
7803
7804 IntExprEvaluator &IntEval;
7805 EvalInfo &Info;
7806 APValue &FinalResult;
7807
7808public:
7809 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7810 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7811
7812 /// \brief True if \param E is a binary operator that we are going to handle
7813 /// data recursively.
7814 /// We handle binary operators that are comma, logical, or that have operands
7815 /// with integral or enumeration type.
7816 static bool shouldEnqueue(const BinaryOperator *E) {
7817 return E->getOpcode() == BO_Comma ||
7818 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007819 (E->isRValue() &&
7820 E->getType()->isIntegralOrEnumerationType() &&
7821 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007822 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007823 }
7824
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007825 bool Traverse(const BinaryOperator *E) {
7826 enqueue(E);
7827 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007828 while (!Queue.empty())
7829 process(PrevResult);
7830
7831 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007832
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007833 FinalResult.swap(PrevResult.Val);
7834 return true;
7835 }
7836
7837private:
7838 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7839 return IntEval.Success(Value, E, Result);
7840 }
7841 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7842 return IntEval.Success(Value, E, Result);
7843 }
7844 bool Error(const Expr *E) {
7845 return IntEval.Error(E);
7846 }
7847 bool Error(const Expr *E, diag::kind D) {
7848 return IntEval.Error(E, D);
7849 }
7850
7851 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7852 return Info.CCEDiag(E, D);
7853 }
7854
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007855 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7856 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007857 bool &SuppressRHSDiags);
7858
7859 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7860 const BinaryOperator *E, APValue &Result);
7861
7862 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7863 Result.Failed = !Evaluate(Result.Val, Info, E);
7864 if (Result.Failed)
7865 Result.Val = APValue();
7866 }
7867
Richard Trieuba4d0872012-03-21 23:30:30 +00007868 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007869
7870 void enqueue(const Expr *E) {
7871 E = E->IgnoreParens();
7872 Queue.resize(Queue.size()+1);
7873 Queue.back().E = E;
7874 Queue.back().Kind = Job::AnyExprKind;
7875 }
7876};
7877
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007878}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007879
7880bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007881 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007882 bool &SuppressRHSDiags) {
7883 if (E->getOpcode() == BO_Comma) {
7884 // Ignore LHS but note if we could not evaluate it.
7885 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007886 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007887 return true;
7888 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007889
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007890 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007891 bool LHSAsBool;
7892 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007893 // We were able to evaluate the LHS, see if we can get away with not
7894 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007895 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7896 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007897 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007898 }
7899 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007900 LHSResult.Failed = true;
7901
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007902 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007903 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007904 if (!Info.noteSideEffect())
7905 return false;
7906
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007907 // We can't evaluate the LHS; however, sometimes the result
7908 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7909 // Don't ignore RHS and suppress diagnostics from this arm.
7910 SuppressRHSDiags = true;
7911 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007912
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007913 return true;
7914 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007915
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007916 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7917 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007918
George Burgess IVa145e252016-05-25 22:38:36 +00007919 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007920 return false; // Ignore RHS;
7921
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007922 return true;
7923}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007924
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007925bool DataRecursiveIntBinOpEvaluator::
7926 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7927 const BinaryOperator *E, APValue &Result) {
7928 if (E->getOpcode() == BO_Comma) {
7929 if (RHSResult.Failed)
7930 return false;
7931 Result = RHSResult.Val;
7932 return true;
7933 }
7934
7935 if (E->isLogicalOp()) {
7936 bool lhsResult, rhsResult;
7937 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7938 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7939
7940 if (LHSIsOK) {
7941 if (RHSIsOK) {
7942 if (E->getOpcode() == BO_LOr)
7943 return Success(lhsResult || rhsResult, E, Result);
7944 else
7945 return Success(lhsResult && rhsResult, E, Result);
7946 }
7947 } else {
7948 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007949 // We can't evaluate the LHS; however, sometimes the result
7950 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7951 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007952 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007953 }
7954 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007955
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007956 return false;
7957 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007958
7959 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7960 E->getRHS()->getType()->isIntegralOrEnumerationType());
7961
7962 if (LHSResult.Failed || RHSResult.Failed)
7963 return false;
7964
7965 const APValue &LHSVal = LHSResult.Val;
7966 const APValue &RHSVal = RHSResult.Val;
7967
7968 // Handle cases like (unsigned long)&a + 4.
7969 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7970 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007971 CharUnits AdditionalOffset =
7972 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007973 if (E->getOpcode() == BO_Add)
7974 Result.getLValueOffset() += AdditionalOffset;
7975 else
7976 Result.getLValueOffset() -= AdditionalOffset;
7977 return true;
7978 }
7979
7980 // Handle cases like 4 + (unsigned long)&a
7981 if (E->getOpcode() == BO_Add &&
7982 RHSVal.isLValue() && LHSVal.isInt()) {
7983 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007984 Result.getLValueOffset() +=
7985 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007986 return true;
7987 }
7988
7989 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7990 // Handle (intptr_t)&&A - (intptr_t)&&B.
7991 if (!LHSVal.getLValueOffset().isZero() ||
7992 !RHSVal.getLValueOffset().isZero())
7993 return false;
7994 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7995 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7996 if (!LHSExpr || !RHSExpr)
7997 return false;
7998 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7999 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8000 if (!LHSAddrExpr || !RHSAddrExpr)
8001 return false;
8002 // Make sure both labels come from the same function.
8003 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8004 RHSAddrExpr->getLabel()->getDeclContext())
8005 return false;
8006 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8007 return true;
8008 }
Richard Smith43e77732013-05-07 04:50:00 +00008009
8010 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008011 if (!LHSVal.isInt() || !RHSVal.isInt())
8012 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008013
8014 // Set up the width and signedness manually, in case it can't be deduced
8015 // from the operation we're performing.
8016 // FIXME: Don't do this in the cases where we can deduce it.
8017 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8018 E->getType()->isUnsignedIntegerOrEnumerationType());
8019 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8020 RHSVal.getInt(), Value))
8021 return false;
8022 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008023}
8024
Richard Trieuba4d0872012-03-21 23:30:30 +00008025void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008026 Job &job = Queue.back();
8027
8028 switch (job.Kind) {
8029 case Job::AnyExprKind: {
8030 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8031 if (shouldEnqueue(Bop)) {
8032 job.Kind = Job::BinOpKind;
8033 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008034 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008035 }
8036 }
8037
8038 EvaluateExpr(job.E, Result);
8039 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008040 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008041 }
8042
8043 case Job::BinOpKind: {
8044 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008045 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008046 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008047 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008048 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008049 }
8050 if (SuppressRHSDiags)
8051 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008052 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008053 job.Kind = Job::BinOpVisitedLHSKind;
8054 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008055 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008056 }
8057
8058 case Job::BinOpVisitedLHSKind: {
8059 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8060 EvalResult RHS;
8061 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008062 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008063 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008064 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008065 }
8066 }
8067
8068 llvm_unreachable("Invalid Job::Kind!");
8069}
8070
George Burgess IV8c892b52016-05-25 22:31:54 +00008071namespace {
8072/// Used when we determine that we should fail, but can keep evaluating prior to
8073/// noting that we had a failure.
8074class DelayedNoteFailureRAII {
8075 EvalInfo &Info;
8076 bool NoteFailure;
8077
8078public:
8079 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8080 : Info(Info), NoteFailure(NoteFailure) {}
8081 ~DelayedNoteFailureRAII() {
8082 if (NoteFailure) {
8083 bool ContinueAfterFailure = Info.noteFailure();
8084 (void)ContinueAfterFailure;
8085 assert(ContinueAfterFailure &&
8086 "Shouldn't have kept evaluating on failure.");
8087 }
8088 }
8089};
8090}
8091
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008092bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008093 // We don't call noteFailure immediately because the assignment happens after
8094 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008095 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008096 return Error(E);
8097
George Burgess IV8c892b52016-05-25 22:31:54 +00008098 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008099 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8100 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008101
Anders Carlssonacc79812008-11-16 07:17:21 +00008102 QualType LHSTy = E->getLHS()->getType();
8103 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008104
Chandler Carruthb29a7432014-10-11 11:03:30 +00008105 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008106 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008107 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008108 if (E->isAssignmentOp()) {
8109 LValue LV;
8110 EvaluateLValue(E->getLHS(), LV, Info);
8111 LHSOK = false;
8112 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008113 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8114 if (LHSOK) {
8115 LHS.makeComplexFloat();
8116 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8117 }
8118 } else {
8119 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8120 }
George Burgess IVa145e252016-05-25 22:38:36 +00008121 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008122 return false;
8123
Chandler Carruthb29a7432014-10-11 11:03:30 +00008124 if (E->getRHS()->getType()->isRealFloatingType()) {
8125 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8126 return false;
8127 RHS.makeComplexFloat();
8128 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8129 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008130 return false;
8131
8132 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008133 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008134 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008135 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008136 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8137
John McCalle3027922010-08-25 11:45:40 +00008138 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008139 return Success((CR_r == APFloat::cmpEqual &&
8140 CR_i == APFloat::cmpEqual), E);
8141 else {
John McCalle3027922010-08-25 11:45:40 +00008142 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008143 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008144 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008145 CR_r == APFloat::cmpLessThan ||
8146 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008147 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008148 CR_i == APFloat::cmpLessThan ||
8149 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008150 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008151 } else {
John McCalle3027922010-08-25 11:45:40 +00008152 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008153 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8154 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8155 else {
John McCalle3027922010-08-25 11:45:40 +00008156 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008157 "Invalid compex comparison.");
8158 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8159 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8160 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008161 }
8162 }
Mike Stump11289f42009-09-09 15:08:12 +00008163
Anders Carlssonacc79812008-11-16 07:17:21 +00008164 if (LHSTy->isRealFloatingType() &&
8165 RHSTy->isRealFloatingType()) {
8166 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008167
Richard Smith253c2a32012-01-27 01:14:48 +00008168 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008169 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008170 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008171
Richard Smith253c2a32012-01-27 01:14:48 +00008172 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008173 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008174
Anders Carlssonacc79812008-11-16 07:17:21 +00008175 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008176
Anders Carlssonacc79812008-11-16 07:17:21 +00008177 switch (E->getOpcode()) {
8178 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008179 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008180 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008181 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008182 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008183 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008184 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008185 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008186 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008187 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008188 E);
John McCalle3027922010-08-25 11:45:40 +00008189 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008190 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008191 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008192 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008193 || CR == APFloat::cmpLessThan
8194 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008195 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008196 }
Mike Stump11289f42009-09-09 15:08:12 +00008197
Eli Friedmana38da572009-04-28 19:17:36 +00008198 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008199 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008200 LValue LHSValue, RHSValue;
8201
8202 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008203 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008204 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008205
Richard Smith253c2a32012-01-27 01:14:48 +00008206 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008207 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008208
Richard Smith8b3497e2011-10-31 01:37:14 +00008209 // Reject differing bases from the normal codepath; we special-case
8210 // comparisons to null.
8211 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008212 if (E->getOpcode() == BO_Sub) {
8213 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008214 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008215 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008216 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008217 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008218 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008219 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008220 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8221 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8222 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008223 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008224 // Make sure both labels come from the same function.
8225 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8226 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008227 return Error(E);
8228 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008229 }
Richard Smith83c68212011-10-31 05:11:32 +00008230 // Inequalities and subtractions between unrelated pointers have
8231 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008232 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008233 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008234 // A constant address may compare equal to the address of a symbol.
8235 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008236 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008237 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8238 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008239 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008240 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008241 // distinct addresses. In clang, the result of such a comparison is
8242 // unspecified, so it is not a constant expression. However, we do know
8243 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008244 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8245 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008246 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008247 // We can't tell whether weak symbols will end up pointing to the same
8248 // object.
8249 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008250 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008251 // We can't compare the address of the start of one object with the
8252 // past-the-end address of another object, per C++ DR1652.
8253 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8254 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8255 (RHSValue.Base && RHSValue.Offset.isZero() &&
8256 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8257 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008258 // We can't tell whether an object is at the same address as another
8259 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008260 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8261 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008262 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008263 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008264 // (Note that clang defaults to -fmerge-all-constants, which can
8265 // lead to inconsistent results for comparisons involving the address
8266 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008267 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008268 }
Eli Friedman64004332009-03-23 04:38:34 +00008269
Richard Smith1b470412012-02-01 08:10:20 +00008270 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8271 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8272
Richard Smith84f6dcf2012-02-02 01:16:57 +00008273 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8274 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8275
John McCalle3027922010-08-25 11:45:40 +00008276 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008277 // C++11 [expr.add]p6:
8278 // Unless both pointers point to elements of the same array object, or
8279 // one past the last element of the array object, the behavior is
8280 // undefined.
8281 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8282 !AreElementsOfSameArray(getType(LHSValue.Base),
8283 LHSDesignator, RHSDesignator))
8284 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8285
Chris Lattner882bdf22010-04-20 17:13:14 +00008286 QualType Type = E->getLHS()->getType();
8287 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008288
Richard Smithd62306a2011-11-10 06:34:14 +00008289 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008290 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008291 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008292
Richard Smith84c6b3d2013-09-10 21:34:14 +00008293 // As an extension, a type may have zero size (empty struct or union in
8294 // C, array of zero length). Pointer subtraction in such cases has
8295 // undefined behavior, so is not constant.
8296 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008297 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008298 << ElementType;
8299 return false;
8300 }
8301
Richard Smith1b470412012-02-01 08:10:20 +00008302 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8303 // and produce incorrect results when it overflows. Such behavior
8304 // appears to be non-conforming, but is common, so perhaps we should
8305 // assume the standard intended for such cases to be undefined behavior
8306 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008307
Richard Smith1b470412012-02-01 08:10:20 +00008308 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8309 // overflow in the final conversion to ptrdiff_t.
8310 APSInt LHS(
8311 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8312 APSInt RHS(
8313 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8314 APSInt ElemSize(
8315 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8316 APSInt TrueResult = (LHS - RHS) / ElemSize;
8317 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8318
Richard Smith0c6124b2015-12-03 01:36:22 +00008319 if (Result.extend(65) != TrueResult &&
8320 !HandleOverflow(Info, E, TrueResult, E->getType()))
8321 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008322 return Success(Result, E);
8323 }
Richard Smithde21b242012-01-31 06:41:30 +00008324
8325 // C++11 [expr.rel]p3:
8326 // Pointers to void (after pointer conversions) can be compared, with a
8327 // result defined as follows: If both pointers represent the same
8328 // address or are both the null pointer value, the result is true if the
8329 // operator is <= or >= and false otherwise; otherwise the result is
8330 // unspecified.
8331 // We interpret this as applying to pointers to *cv* void.
8332 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008333 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008334 CCEDiag(E, diag::note_constexpr_void_comparison);
8335
Richard Smith84f6dcf2012-02-02 01:16:57 +00008336 // C++11 [expr.rel]p2:
8337 // - If two pointers point to non-static data members of the same object,
8338 // or to subobjects or array elements fo such members, recursively, the
8339 // pointer to the later declared member compares greater provided the
8340 // two members have the same access control and provided their class is
8341 // not a union.
8342 // [...]
8343 // - Otherwise pointer comparisons are unspecified.
8344 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8345 E->isRelationalOp()) {
8346 bool WasArrayIndex;
8347 unsigned Mismatch =
8348 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8349 RHSDesignator, WasArrayIndex);
8350 // At the point where the designators diverge, the comparison has a
8351 // specified value if:
8352 // - we are comparing array indices
8353 // - we are comparing fields of a union, or fields with the same access
8354 // Otherwise, the result is unspecified and thus the comparison is not a
8355 // constant expression.
8356 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8357 Mismatch < RHSDesignator.Entries.size()) {
8358 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8359 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8360 if (!LF && !RF)
8361 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8362 else if (!LF)
8363 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8364 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8365 << RF->getParent() << RF;
8366 else if (!RF)
8367 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8368 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8369 << LF->getParent() << LF;
8370 else if (!LF->getParent()->isUnion() &&
8371 LF->getAccess() != RF->getAccess())
8372 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8373 << LF << LF->getAccess() << RF << RF->getAccess()
8374 << LF->getParent();
8375 }
8376 }
8377
Eli Friedman6c31cb42012-04-16 04:30:08 +00008378 // The comparison here must be unsigned, and performed with the same
8379 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008380 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8381 uint64_t CompareLHS = LHSOffset.getQuantity();
8382 uint64_t CompareRHS = RHSOffset.getQuantity();
8383 assert(PtrSize <= 64 && "Unexpected pointer width");
8384 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8385 CompareLHS &= Mask;
8386 CompareRHS &= Mask;
8387
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008388 // If there is a base and this is a relational operator, we can only
8389 // compare pointers within the object in question; otherwise, the result
8390 // depends on where the object is located in memory.
8391 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8392 QualType BaseTy = getType(LHSValue.Base);
8393 if (BaseTy->isIncompleteType())
8394 return Error(E);
8395 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8396 uint64_t OffsetLimit = Size.getQuantity();
8397 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8398 return Error(E);
8399 }
8400
Richard Smith8b3497e2011-10-31 01:37:14 +00008401 switch (E->getOpcode()) {
8402 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008403 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8404 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8405 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8406 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8407 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8408 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008409 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008410 }
8411 }
Richard Smith7bb00672012-02-01 01:42:44 +00008412
8413 if (LHSTy->isMemberPointerType()) {
8414 assert(E->isEqualityOp() && "unexpected member pointer operation");
8415 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8416
8417 MemberPtr LHSValue, RHSValue;
8418
8419 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008420 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008421 return false;
8422
8423 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8424 return false;
8425
8426 // C++11 [expr.eq]p2:
8427 // If both operands are null, they compare equal. Otherwise if only one is
8428 // null, they compare unequal.
8429 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8430 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8431 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8432 }
8433
8434 // Otherwise if either is a pointer to a virtual member function, the
8435 // result is unspecified.
8436 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8437 if (MD->isVirtual())
8438 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8439 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8440 if (MD->isVirtual())
8441 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8442
8443 // Otherwise they compare equal if and only if they would refer to the
8444 // same member of the same most derived object or the same subobject if
8445 // they were dereferenced with a hypothetical object of the associated
8446 // class type.
8447 bool Equal = LHSValue == RHSValue;
8448 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8449 }
8450
Richard Smithab44d9b2012-02-14 22:35:28 +00008451 if (LHSTy->isNullPtrType()) {
8452 assert(E->isComparisonOp() && "unexpected nullptr operation");
8453 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8454 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8455 // are compared, the result is true of the operator is <=, >= or ==, and
8456 // false otherwise.
8457 BinaryOperator::Opcode Opcode = E->getOpcode();
8458 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8459 }
8460
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008461 assert((!LHSTy->isIntegralOrEnumerationType() ||
8462 !RHSTy->isIntegralOrEnumerationType()) &&
8463 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8464 // We can't continue from here for non-integral types.
8465 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008466}
8467
Peter Collingbournee190dee2011-03-11 19:24:49 +00008468/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8469/// a result as the expression's type.
8470bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8471 const UnaryExprOrTypeTraitExpr *E) {
8472 switch(E->getKind()) {
8473 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008474 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008475 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008476 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008477 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008478 }
Eli Friedman64004332009-03-23 04:38:34 +00008479
Peter Collingbournee190dee2011-03-11 19:24:49 +00008480 case UETT_VecStep: {
8481 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008482
Peter Collingbournee190dee2011-03-11 19:24:49 +00008483 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008484 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008485
Peter Collingbournee190dee2011-03-11 19:24:49 +00008486 // The vec_step built-in functions that take a 3-component
8487 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8488 if (n == 3)
8489 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008490
Peter Collingbournee190dee2011-03-11 19:24:49 +00008491 return Success(n, E);
8492 } else
8493 return Success(1, E);
8494 }
8495
8496 case UETT_SizeOf: {
8497 QualType SrcTy = E->getTypeOfArgument();
8498 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8499 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008500 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8501 SrcTy = Ref->getPointeeType();
8502
Richard Smithd62306a2011-11-10 06:34:14 +00008503 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008504 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008505 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008506 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008507 }
Alexey Bataev00396512015-07-02 03:40:19 +00008508 case UETT_OpenMPRequiredSimdAlign:
8509 assert(E->isArgumentType());
8510 return Success(
8511 Info.Ctx.toCharUnitsFromBits(
8512 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8513 .getQuantity(),
8514 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008515 }
8516
8517 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008518}
8519
Peter Collingbournee9200682011-05-13 03:29:01 +00008520bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008521 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008522 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008523 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008524 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008525 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008526 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008527 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008528 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008529 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008530 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008531 APSInt IdxResult;
8532 if (!EvaluateInteger(Idx, IdxResult, Info))
8533 return false;
8534 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8535 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008536 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008537 CurrentType = AT->getElementType();
8538 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8539 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008540 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008541 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008542
James Y Knight7281c352015-12-29 22:31:18 +00008543 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008544 FieldDecl *MemberDecl = ON.getField();
8545 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008546 if (!RT)
8547 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008548 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008549 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008550 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008551 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008552 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008553 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008554 CurrentType = MemberDecl->getType().getNonReferenceType();
8555 break;
8556 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008557
James Y Knight7281c352015-12-29 22:31:18 +00008558 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008559 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008560
James Y Knight7281c352015-12-29 22:31:18 +00008561 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008562 CXXBaseSpecifier *BaseSpec = ON.getBase();
8563 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008564 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008565
8566 // Find the layout of the class whose base we are looking into.
8567 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008568 if (!RT)
8569 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008570 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008571 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008572 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8573
8574 // Find the base class itself.
8575 CurrentType = BaseSpec->getType();
8576 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8577 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008578 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008579
8580 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008581 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008582 break;
8583 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008584 }
8585 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008586 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008587}
8588
Chris Lattnere13042c2008-07-11 19:10:17 +00008589bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008590 switch (E->getOpcode()) {
8591 default:
8592 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8593 // See C99 6.6p3.
8594 return Error(E);
8595 case UO_Extension:
8596 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8597 // If so, we could clear the diagnostic ID.
8598 return Visit(E->getSubExpr());
8599 case UO_Plus:
8600 // The result is just the value.
8601 return Visit(E->getSubExpr());
8602 case UO_Minus: {
8603 if (!Visit(E->getSubExpr()))
8604 return false;
8605 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008606 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008607 if (Value.isSigned() && Value.isMinSignedValue() &&
8608 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8609 E->getType()))
8610 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008611 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008612 }
8613 case UO_Not: {
8614 if (!Visit(E->getSubExpr()))
8615 return false;
8616 if (!Result.isInt()) return Error(E);
8617 return Success(~Result.getInt(), E);
8618 }
8619 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008620 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008621 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008622 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008623 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008624 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008625 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008626}
Mike Stump11289f42009-09-09 15:08:12 +00008627
Chris Lattner477c4be2008-07-12 01:15:53 +00008628/// HandleCast - This is used to evaluate implicit or explicit casts where the
8629/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008630bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8631 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008632 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008633 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008634
Eli Friedmanc757de22011-03-25 00:43:55 +00008635 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008636 case CK_BaseToDerived:
8637 case CK_DerivedToBase:
8638 case CK_UncheckedDerivedToBase:
8639 case CK_Dynamic:
8640 case CK_ToUnion:
8641 case CK_ArrayToPointerDecay:
8642 case CK_FunctionToPointerDecay:
8643 case CK_NullToPointer:
8644 case CK_NullToMemberPointer:
8645 case CK_BaseToDerivedMemberPointer:
8646 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008647 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008648 case CK_ConstructorConversion:
8649 case CK_IntegralToPointer:
8650 case CK_ToVoid:
8651 case CK_VectorSplat:
8652 case CK_IntegralToFloating:
8653 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008654 case CK_CPointerToObjCPointerCast:
8655 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008656 case CK_AnyPointerToBlockPointerCast:
8657 case CK_ObjCObjectLValueCast:
8658 case CK_FloatingRealToComplex:
8659 case CK_FloatingComplexToReal:
8660 case CK_FloatingComplexCast:
8661 case CK_FloatingComplexToIntegralComplex:
8662 case CK_IntegralRealToComplex:
8663 case CK_IntegralComplexCast:
8664 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008665 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008666 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008667 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008668 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008669 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008670 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008671 llvm_unreachable("invalid cast kind for integral value");
8672
Eli Friedman9faf2f92011-03-25 19:07:11 +00008673 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008674 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008675 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008676 case CK_ARCProduceObject:
8677 case CK_ARCConsumeObject:
8678 case CK_ARCReclaimReturnedObject:
8679 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008680 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008681 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008682
Richard Smith4ef685b2012-01-17 21:17:26 +00008683 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008684 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008685 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008686 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008687 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008688
8689 case CK_MemberPointerToBoolean:
8690 case CK_PointerToBoolean:
8691 case CK_IntegralToBoolean:
8692 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008693 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008694 case CK_FloatingComplexToBoolean:
8695 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008696 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008697 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008698 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008699 uint64_t IntResult = BoolResult;
8700 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8701 IntResult = (uint64_t)-1;
8702 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008703 }
8704
Eli Friedmanc757de22011-03-25 00:43:55 +00008705 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008706 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008707 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008708
Eli Friedman742421e2009-02-20 01:15:07 +00008709 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008710 // Allow casts of address-of-label differences if they are no-ops
8711 // or narrowing. (The narrowing case isn't actually guaranteed to
8712 // be constant-evaluatable except in some narrow cases which are hard
8713 // to detect here. We let it through on the assumption the user knows
8714 // what they are doing.)
8715 if (Result.isAddrLabelDiff())
8716 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008717 // Only allow casts of lvalues if they are lossless.
8718 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8719 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008720
Richard Smith911e1422012-01-30 22:27:01 +00008721 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8722 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008723 }
Mike Stump11289f42009-09-09 15:08:12 +00008724
Eli Friedmanc757de22011-03-25 00:43:55 +00008725 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008726 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8727
John McCall45d55e42010-05-07 21:00:08 +00008728 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008729 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008730 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008731
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008732 if (LV.getLValueBase()) {
8733 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008734 // FIXME: Allow a larger integer size than the pointer size, and allow
8735 // narrowing back down to pointer width in subsequent integral casts.
8736 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008737 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008738 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008739
Richard Smithcf74da72011-11-16 07:18:12 +00008740 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008741 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008742 return true;
8743 }
8744
Yaxun Liu402804b2016-12-15 08:09:08 +00008745 uint64_t V;
8746 if (LV.isNullPointer())
8747 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8748 else
8749 V = LV.getLValueOffset().getQuantity();
8750
8751 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008752 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008753 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008754
Eli Friedmanc757de22011-03-25 00:43:55 +00008755 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008756 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008757 if (!EvaluateComplex(SubExpr, C, Info))
8758 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008759 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008760 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008761
Eli Friedmanc757de22011-03-25 00:43:55 +00008762 case CK_FloatingToIntegral: {
8763 APFloat F(0.0);
8764 if (!EvaluateFloat(SubExpr, F, Info))
8765 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008766
Richard Smith357362d2011-12-13 06:39:58 +00008767 APSInt Value;
8768 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8769 return false;
8770 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008771 }
8772 }
Mike Stump11289f42009-09-09 15:08:12 +00008773
Eli Friedmanc757de22011-03-25 00:43:55 +00008774 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008775}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008776
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008777bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8778 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008779 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008780 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8781 return false;
8782 if (!LV.isComplexInt())
8783 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008784 return Success(LV.getComplexIntReal(), E);
8785 }
8786
8787 return Visit(E->getSubExpr());
8788}
8789
Eli Friedman4e7a2412009-02-27 04:45:43 +00008790bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008791 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008792 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008793 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8794 return false;
8795 if (!LV.isComplexInt())
8796 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008797 return Success(LV.getComplexIntImag(), E);
8798 }
8799
Richard Smith4a678122011-10-24 18:44:57 +00008800 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008801 return Success(0, E);
8802}
8803
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008804bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8805 return Success(E->getPackLength(), E);
8806}
8807
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008808bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8809 return Success(E->getValue(), E);
8810}
8811
Chris Lattner05706e882008-07-11 18:11:29 +00008812//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008813// Float Evaluation
8814//===----------------------------------------------------------------------===//
8815
8816namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008817class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008818 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008819 APFloat &Result;
8820public:
8821 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008822 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008823
Richard Smith2e312c82012-03-03 22:46:17 +00008824 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008825 Result = V.getFloat();
8826 return true;
8827 }
Eli Friedman24c01542008-08-22 00:06:13 +00008828
Richard Smithfddd3842011-12-30 21:15:51 +00008829 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008830 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8831 return true;
8832 }
8833
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008834 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008835
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008836 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008837 bool VisitBinaryOperator(const BinaryOperator *E);
8838 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008839 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008840
John McCallb1fb0d32010-05-07 22:08:54 +00008841 bool VisitUnaryReal(const UnaryOperator *E);
8842 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008843
Richard Smithfddd3842011-12-30 21:15:51 +00008844 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008845};
8846} // end anonymous namespace
8847
8848static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008849 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008850 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008851}
8852
Jay Foad39c79802011-01-12 09:06:06 +00008853static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008854 QualType ResultTy,
8855 const Expr *Arg,
8856 bool SNaN,
8857 llvm::APFloat &Result) {
8858 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8859 if (!S) return false;
8860
8861 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8862
8863 llvm::APInt fill;
8864
8865 // Treat empty strings as if they were zero.
8866 if (S->getString().empty())
8867 fill = llvm::APInt(32, 0);
8868 else if (S->getString().getAsInteger(0, fill))
8869 return false;
8870
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008871 if (Context.getTargetInfo().isNan2008()) {
8872 if (SNaN)
8873 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8874 else
8875 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8876 } else {
8877 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8878 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8879 // a different encoding to what became a standard in 2008, and for pre-
8880 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8881 // sNaN. This is now known as "legacy NaN" encoding.
8882 if (SNaN)
8883 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8884 else
8885 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8886 }
8887
John McCall16291492010-02-28 13:00:19 +00008888 return true;
8889}
8890
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008891bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008892 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008893 default:
8894 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8895
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008896 case Builtin::BI__builtin_huge_val:
8897 case Builtin::BI__builtin_huge_valf:
8898 case Builtin::BI__builtin_huge_vall:
8899 case Builtin::BI__builtin_inf:
8900 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008901 case Builtin::BI__builtin_infl: {
8902 const llvm::fltSemantics &Sem =
8903 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008904 Result = llvm::APFloat::getInf(Sem);
8905 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008906 }
Mike Stump11289f42009-09-09 15:08:12 +00008907
John McCall16291492010-02-28 13:00:19 +00008908 case Builtin::BI__builtin_nans:
8909 case Builtin::BI__builtin_nansf:
8910 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008911 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8912 true, Result))
8913 return Error(E);
8914 return true;
John McCall16291492010-02-28 13:00:19 +00008915
Chris Lattner0b7282e2008-10-06 06:31:58 +00008916 case Builtin::BI__builtin_nan:
8917 case Builtin::BI__builtin_nanf:
8918 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008919 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008920 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008921 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8922 false, Result))
8923 return Error(E);
8924 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008925
8926 case Builtin::BI__builtin_fabs:
8927 case Builtin::BI__builtin_fabsf:
8928 case Builtin::BI__builtin_fabsl:
8929 if (!EvaluateFloat(E->getArg(0), Result, Info))
8930 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008931
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008932 if (Result.isNegative())
8933 Result.changeSign();
8934 return true;
8935
Richard Smith8889a3d2013-06-13 06:26:32 +00008936 // FIXME: Builtin::BI__builtin_powi
8937 // FIXME: Builtin::BI__builtin_powif
8938 // FIXME: Builtin::BI__builtin_powil
8939
Mike Stump11289f42009-09-09 15:08:12 +00008940 case Builtin::BI__builtin_copysign:
8941 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008942 case Builtin::BI__builtin_copysignl: {
8943 APFloat RHS(0.);
8944 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8945 !EvaluateFloat(E->getArg(1), RHS, Info))
8946 return false;
8947 Result.copySign(RHS);
8948 return true;
8949 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008950 }
8951}
8952
John McCallb1fb0d32010-05-07 22:08:54 +00008953bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008954 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8955 ComplexValue CV;
8956 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8957 return false;
8958 Result = CV.FloatReal;
8959 return true;
8960 }
8961
8962 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008963}
8964
8965bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008966 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8967 ComplexValue CV;
8968 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8969 return false;
8970 Result = CV.FloatImag;
8971 return true;
8972 }
8973
Richard Smith4a678122011-10-24 18:44:57 +00008974 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008975 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8976 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008977 return true;
8978}
8979
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008980bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008981 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008982 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008983 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008984 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008985 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008986 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8987 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008988 Result.changeSign();
8989 return true;
8990 }
8991}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008992
Eli Friedman24c01542008-08-22 00:06:13 +00008993bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008994 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8995 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008996
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008997 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008998 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008999 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009000 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009001 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9002 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009003}
9004
9005bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9006 Result = E->getValue();
9007 return true;
9008}
9009
Peter Collingbournee9200682011-05-13 03:29:01 +00009010bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9011 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009012
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009013 switch (E->getCastKind()) {
9014 default:
Richard Smith11562c52011-10-28 17:51:58 +00009015 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009016
9017 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009018 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009019 return EvaluateInteger(SubExpr, IntResult, Info) &&
9020 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9021 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009022 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009023
9024 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009025 if (!Visit(SubExpr))
9026 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009027 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9028 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009029 }
John McCalld7646252010-11-14 08:17:51 +00009030
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009031 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009032 ComplexValue V;
9033 if (!EvaluateComplex(SubExpr, V, Info))
9034 return false;
9035 Result = V.getComplexFloatReal();
9036 return true;
9037 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009038 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009039}
9040
Eli Friedman24c01542008-08-22 00:06:13 +00009041//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009042// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009043//===----------------------------------------------------------------------===//
9044
9045namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009046class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009047 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009048 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009049
Anders Carlsson537969c2008-11-16 20:27:53 +00009050public:
John McCall93d91dc2010-05-07 17:22:02 +00009051 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009052 : ExprEvaluatorBaseTy(info), Result(Result) {}
9053
Richard Smith2e312c82012-03-03 22:46:17 +00009054 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009055 Result.setFrom(V);
9056 return true;
9057 }
Mike Stump11289f42009-09-09 15:08:12 +00009058
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009059 bool ZeroInitialization(const Expr *E);
9060
Anders Carlsson537969c2008-11-16 20:27:53 +00009061 //===--------------------------------------------------------------------===//
9062 // Visitor Methods
9063 //===--------------------------------------------------------------------===//
9064
Peter Collingbournee9200682011-05-13 03:29:01 +00009065 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009066 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009067 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009068 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009069 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009070};
9071} // end anonymous namespace
9072
John McCall93d91dc2010-05-07 17:22:02 +00009073static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9074 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009075 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009076 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009077}
9078
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009079bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009080 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009081 if (ElemTy->isRealFloatingType()) {
9082 Result.makeComplexFloat();
9083 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9084 Result.FloatReal = Zero;
9085 Result.FloatImag = Zero;
9086 } else {
9087 Result.makeComplexInt();
9088 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9089 Result.IntReal = Zero;
9090 Result.IntImag = Zero;
9091 }
9092 return true;
9093}
9094
Peter Collingbournee9200682011-05-13 03:29:01 +00009095bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9096 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009097
9098 if (SubExpr->getType()->isRealFloatingType()) {
9099 Result.makeComplexFloat();
9100 APFloat &Imag = Result.FloatImag;
9101 if (!EvaluateFloat(SubExpr, Imag, Info))
9102 return false;
9103
9104 Result.FloatReal = APFloat(Imag.getSemantics());
9105 return true;
9106 } else {
9107 assert(SubExpr->getType()->isIntegerType() &&
9108 "Unexpected imaginary literal.");
9109
9110 Result.makeComplexInt();
9111 APSInt &Imag = Result.IntImag;
9112 if (!EvaluateInteger(SubExpr, Imag, Info))
9113 return false;
9114
9115 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9116 return true;
9117 }
9118}
9119
Peter Collingbournee9200682011-05-13 03:29:01 +00009120bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009121
John McCallfcef3cf2010-12-14 17:51:41 +00009122 switch (E->getCastKind()) {
9123 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009124 case CK_BaseToDerived:
9125 case CK_DerivedToBase:
9126 case CK_UncheckedDerivedToBase:
9127 case CK_Dynamic:
9128 case CK_ToUnion:
9129 case CK_ArrayToPointerDecay:
9130 case CK_FunctionToPointerDecay:
9131 case CK_NullToPointer:
9132 case CK_NullToMemberPointer:
9133 case CK_BaseToDerivedMemberPointer:
9134 case CK_DerivedToBaseMemberPointer:
9135 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009136 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009137 case CK_ConstructorConversion:
9138 case CK_IntegralToPointer:
9139 case CK_PointerToIntegral:
9140 case CK_PointerToBoolean:
9141 case CK_ToVoid:
9142 case CK_VectorSplat:
9143 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009144 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009145 case CK_IntegralToBoolean:
9146 case CK_IntegralToFloating:
9147 case CK_FloatingToIntegral:
9148 case CK_FloatingToBoolean:
9149 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009150 case CK_CPointerToObjCPointerCast:
9151 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009152 case CK_AnyPointerToBlockPointerCast:
9153 case CK_ObjCObjectLValueCast:
9154 case CK_FloatingComplexToReal:
9155 case CK_FloatingComplexToBoolean:
9156 case CK_IntegralComplexToReal:
9157 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009158 case CK_ARCProduceObject:
9159 case CK_ARCConsumeObject:
9160 case CK_ARCReclaimReturnedObject:
9161 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009162 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009163 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009164 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009165 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009166 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009167 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009168 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009169 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009170
John McCallfcef3cf2010-12-14 17:51:41 +00009171 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009172 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009173 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009174 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009175
9176 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009177 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009178 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009179 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009180
9181 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009182 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009183 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009184 return false;
9185
John McCallfcef3cf2010-12-14 17:51:41 +00009186 Result.makeComplexFloat();
9187 Result.FloatImag = APFloat(Real.getSemantics());
9188 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009189 }
9190
John McCallfcef3cf2010-12-14 17:51:41 +00009191 case CK_FloatingComplexCast: {
9192 if (!Visit(E->getSubExpr()))
9193 return false;
9194
9195 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9196 QualType From
9197 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9198
Richard Smith357362d2011-12-13 06:39:58 +00009199 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9200 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009201 }
9202
9203 case CK_FloatingComplexToIntegralComplex: {
9204 if (!Visit(E->getSubExpr()))
9205 return false;
9206
9207 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9208 QualType From
9209 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9210 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009211 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9212 To, Result.IntReal) &&
9213 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9214 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009215 }
9216
9217 case CK_IntegralRealToComplex: {
9218 APSInt &Real = Result.IntReal;
9219 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9220 return false;
9221
9222 Result.makeComplexInt();
9223 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9224 return true;
9225 }
9226
9227 case CK_IntegralComplexCast: {
9228 if (!Visit(E->getSubExpr()))
9229 return false;
9230
9231 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9232 QualType From
9233 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9234
Richard Smith911e1422012-01-30 22:27:01 +00009235 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9236 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009237 return true;
9238 }
9239
9240 case CK_IntegralComplexToFloatingComplex: {
9241 if (!Visit(E->getSubExpr()))
9242 return false;
9243
Ted Kremenek28831752012-08-23 20:46:57 +00009244 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009245 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009246 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009247 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009248 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9249 To, Result.FloatReal) &&
9250 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9251 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009252 }
9253 }
9254
9255 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009256}
9257
John McCall93d91dc2010-05-07 17:22:02 +00009258bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009259 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009260 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9261
Chandler Carrutha216cad2014-10-11 00:57:18 +00009262 // Track whether the LHS or RHS is real at the type system level. When this is
9263 // the case we can simplify our evaluation strategy.
9264 bool LHSReal = false, RHSReal = false;
9265
9266 bool LHSOK;
9267 if (E->getLHS()->getType()->isRealFloatingType()) {
9268 LHSReal = true;
9269 APFloat &Real = Result.FloatReal;
9270 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9271 if (LHSOK) {
9272 Result.makeComplexFloat();
9273 Result.FloatImag = APFloat(Real.getSemantics());
9274 }
9275 } else {
9276 LHSOK = Visit(E->getLHS());
9277 }
George Burgess IVa145e252016-05-25 22:38:36 +00009278 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009279 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009280
John McCall93d91dc2010-05-07 17:22:02 +00009281 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009282 if (E->getRHS()->getType()->isRealFloatingType()) {
9283 RHSReal = true;
9284 APFloat &Real = RHS.FloatReal;
9285 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9286 return false;
9287 RHS.makeComplexFloat();
9288 RHS.FloatImag = APFloat(Real.getSemantics());
9289 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009290 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009291
Chandler Carrutha216cad2014-10-11 00:57:18 +00009292 assert(!(LHSReal && RHSReal) &&
9293 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009294 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009295 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009296 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009297 if (Result.isComplexFloat()) {
9298 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9299 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009300 if (LHSReal)
9301 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9302 else if (!RHSReal)
9303 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9304 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009305 } else {
9306 Result.getComplexIntReal() += RHS.getComplexIntReal();
9307 Result.getComplexIntImag() += RHS.getComplexIntImag();
9308 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009309 break;
John McCalle3027922010-08-25 11:45:40 +00009310 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009311 if (Result.isComplexFloat()) {
9312 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9313 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009314 if (LHSReal) {
9315 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9316 Result.getComplexFloatImag().changeSign();
9317 } else if (!RHSReal) {
9318 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9319 APFloat::rmNearestTiesToEven);
9320 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009321 } else {
9322 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9323 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9324 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009325 break;
John McCalle3027922010-08-25 11:45:40 +00009326 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009327 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009328 // This is an implementation of complex multiplication according to the
9329 // constraints laid out in C11 Annex G. The implemantion uses the
9330 // following naming scheme:
9331 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009332 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009333 APFloat &A = LHS.getComplexFloatReal();
9334 APFloat &B = LHS.getComplexFloatImag();
9335 APFloat &C = RHS.getComplexFloatReal();
9336 APFloat &D = RHS.getComplexFloatImag();
9337 APFloat &ResR = Result.getComplexFloatReal();
9338 APFloat &ResI = Result.getComplexFloatImag();
9339 if (LHSReal) {
9340 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9341 ResR = A * C;
9342 ResI = A * D;
9343 } else if (RHSReal) {
9344 ResR = C * A;
9345 ResI = C * B;
9346 } else {
9347 // In the fully general case, we need to handle NaNs and infinities
9348 // robustly.
9349 APFloat AC = A * C;
9350 APFloat BD = B * D;
9351 APFloat AD = A * D;
9352 APFloat BC = B * C;
9353 ResR = AC - BD;
9354 ResI = AD + BC;
9355 if (ResR.isNaN() && ResI.isNaN()) {
9356 bool Recalc = false;
9357 if (A.isInfinity() || B.isInfinity()) {
9358 A = APFloat::copySign(
9359 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9360 B = APFloat::copySign(
9361 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9362 if (C.isNaN())
9363 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9364 if (D.isNaN())
9365 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9366 Recalc = true;
9367 }
9368 if (C.isInfinity() || D.isInfinity()) {
9369 C = APFloat::copySign(
9370 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9371 D = APFloat::copySign(
9372 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9373 if (A.isNaN())
9374 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9375 if (B.isNaN())
9376 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9377 Recalc = true;
9378 }
9379 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9380 AD.isInfinity() || BC.isInfinity())) {
9381 if (A.isNaN())
9382 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9383 if (B.isNaN())
9384 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9385 if (C.isNaN())
9386 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9387 if (D.isNaN())
9388 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9389 Recalc = true;
9390 }
9391 if (Recalc) {
9392 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9393 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9394 }
9395 }
9396 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009397 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009398 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009399 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009400 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9401 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009402 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009403 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9404 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9405 }
9406 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009407 case BO_Div:
9408 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009409 // This is an implementation of complex division according to the
9410 // constraints laid out in C11 Annex G. The implemantion uses the
9411 // following naming scheme:
9412 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009413 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009414 APFloat &A = LHS.getComplexFloatReal();
9415 APFloat &B = LHS.getComplexFloatImag();
9416 APFloat &C = RHS.getComplexFloatReal();
9417 APFloat &D = RHS.getComplexFloatImag();
9418 APFloat &ResR = Result.getComplexFloatReal();
9419 APFloat &ResI = Result.getComplexFloatImag();
9420 if (RHSReal) {
9421 ResR = A / C;
9422 ResI = B / C;
9423 } else {
9424 if (LHSReal) {
9425 // No real optimizations we can do here, stub out with zero.
9426 B = APFloat::getZero(A.getSemantics());
9427 }
9428 int DenomLogB = 0;
9429 APFloat MaxCD = maxnum(abs(C), abs(D));
9430 if (MaxCD.isFinite()) {
9431 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009432 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9433 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009434 }
9435 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009436 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9437 APFloat::rmNearestTiesToEven);
9438 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9439 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009440 if (ResR.isNaN() && ResI.isNaN()) {
9441 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9442 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9443 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9444 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9445 D.isFinite()) {
9446 A = APFloat::copySign(
9447 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9448 B = APFloat::copySign(
9449 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9450 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9451 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9452 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9453 C = APFloat::copySign(
9454 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9455 D = APFloat::copySign(
9456 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9457 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9458 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9459 }
9460 }
9461 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009462 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009463 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9464 return Error(E, diag::note_expr_divide_by_zero);
9465
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009466 ComplexValue LHS = Result;
9467 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9468 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9469 Result.getComplexIntReal() =
9470 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9471 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9472 Result.getComplexIntImag() =
9473 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9474 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9475 }
9476 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009477 }
9478
John McCall93d91dc2010-05-07 17:22:02 +00009479 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009480}
9481
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009482bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9483 // Get the operand value into 'Result'.
9484 if (!Visit(E->getSubExpr()))
9485 return false;
9486
9487 switch (E->getOpcode()) {
9488 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009489 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009490 case UO_Extension:
9491 return true;
9492 case UO_Plus:
9493 // The result is always just the subexpr.
9494 return true;
9495 case UO_Minus:
9496 if (Result.isComplexFloat()) {
9497 Result.getComplexFloatReal().changeSign();
9498 Result.getComplexFloatImag().changeSign();
9499 }
9500 else {
9501 Result.getComplexIntReal() = -Result.getComplexIntReal();
9502 Result.getComplexIntImag() = -Result.getComplexIntImag();
9503 }
9504 return true;
9505 case UO_Not:
9506 if (Result.isComplexFloat())
9507 Result.getComplexFloatImag().changeSign();
9508 else
9509 Result.getComplexIntImag() = -Result.getComplexIntImag();
9510 return true;
9511 }
9512}
9513
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009514bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9515 if (E->getNumInits() == 2) {
9516 if (E->getType()->isComplexType()) {
9517 Result.makeComplexFloat();
9518 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9519 return false;
9520 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9521 return false;
9522 } else {
9523 Result.makeComplexInt();
9524 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9525 return false;
9526 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9527 return false;
9528 }
9529 return true;
9530 }
9531 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9532}
9533
Anders Carlsson537969c2008-11-16 20:27:53 +00009534//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009535// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9536// implicit conversion.
9537//===----------------------------------------------------------------------===//
9538
9539namespace {
9540class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009541 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00009542 APValue &Result;
9543public:
9544 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9545 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9546
9547 bool Success(const APValue &V, const Expr *E) {
9548 Result = V;
9549 return true;
9550 }
9551
9552 bool ZeroInitialization(const Expr *E) {
9553 ImplicitValueInitExpr VIE(
9554 E->getType()->castAs<AtomicType>()->getValueType());
9555 return Evaluate(Result, Info, &VIE);
9556 }
9557
9558 bool VisitCastExpr(const CastExpr *E) {
9559 switch (E->getCastKind()) {
9560 default:
9561 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9562 case CK_NonAtomicToAtomic:
9563 return Evaluate(Result, Info, E->getSubExpr());
9564 }
9565 }
9566};
9567} // end anonymous namespace
9568
9569static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9570 assert(E->isRValue() && E->getType()->isAtomicType());
9571 return AtomicExprEvaluator(Info, Result).Visit(E);
9572}
9573
9574//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009575// Void expression evaluation, primarily for a cast to void on the LHS of a
9576// comma operator
9577//===----------------------------------------------------------------------===//
9578
9579namespace {
9580class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009581 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009582public:
9583 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9584
Richard Smith2e312c82012-03-03 22:46:17 +00009585 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009586
9587 bool VisitCastExpr(const CastExpr *E) {
9588 switch (E->getCastKind()) {
9589 default:
9590 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9591 case CK_ToVoid:
9592 VisitIgnoredValue(E->getSubExpr());
9593 return true;
9594 }
9595 }
Hal Finkela8443c32014-07-17 14:49:58 +00009596
9597 bool VisitCallExpr(const CallExpr *E) {
9598 switch (E->getBuiltinCallee()) {
9599 default:
9600 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9601 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009602 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009603 // The argument is not evaluated!
9604 return true;
9605 }
9606 }
Richard Smith42d3af92011-12-07 00:43:50 +00009607};
9608} // end anonymous namespace
9609
9610static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9611 assert(E->isRValue() && E->getType()->isVoidType());
9612 return VoidExprEvaluator(Info).Visit(E);
9613}
9614
9615//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009616// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009617//===----------------------------------------------------------------------===//
9618
Richard Smith2e312c82012-03-03 22:46:17 +00009619static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009620 // In C, function designators are not lvalues, but we evaluate them as if they
9621 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009622 QualType T = E->getType();
9623 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009624 LValue LV;
9625 if (!EvaluateLValue(E, LV, Info))
9626 return false;
9627 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009628 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009629 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009630 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009631 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009632 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009633 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009634 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009635 LValue LV;
9636 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009637 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009638 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009639 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009640 llvm::APFloat F(0.0);
9641 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009642 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009643 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009644 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009645 ComplexValue C;
9646 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009647 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009648 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009649 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009650 MemberPtr P;
9651 if (!EvaluateMemberPointer(E, P, Info))
9652 return false;
9653 P.moveInto(Result);
9654 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009655 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009656 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009657 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009658 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9659 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009660 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009661 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009662 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009663 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009664 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009665 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9666 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009667 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009668 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009669 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009670 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009671 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009672 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009673 if (!EvaluateVoid(E, Info))
9674 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009675 } else if (T->isAtomicType()) {
9676 if (!EvaluateAtomic(E, Result, Info))
9677 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009678 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009679 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009680 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009681 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009682 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009683 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009684 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009685
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009686 return true;
9687}
9688
Richard Smithb228a862012-02-15 02:18:13 +00009689/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9690/// cases, the in-place evaluation is essential, since later initializers for
9691/// an object can indirectly refer to subobjects which were initialized earlier.
9692static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009693 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009694 assert(!E->isValueDependent());
9695
Richard Smith7525ff62013-05-09 07:14:00 +00009696 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009697 return false;
9698
9699 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009700 // Evaluate arrays and record types in-place, so that later initializers can
9701 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009702 if (E->getType()->isArrayType())
9703 return EvaluateArray(E, This, Result, Info);
9704 else if (E->getType()->isRecordType())
9705 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009706 }
9707
9708 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009709 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009710}
9711
Richard Smithf57d8cb2011-12-09 22:58:01 +00009712/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9713/// lvalue-to-rvalue cast if it is an lvalue.
9714static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009715 if (E->getType().isNull())
9716 return false;
9717
Richard Smithfddd3842011-12-30 21:15:51 +00009718 if (!CheckLiteralType(Info, E))
9719 return false;
9720
Richard Smith2e312c82012-03-03 22:46:17 +00009721 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009722 return false;
9723
9724 if (E->isGLValue()) {
9725 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009726 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009727 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009728 return false;
9729 }
9730
Richard Smith2e312c82012-03-03 22:46:17 +00009731 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009732 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009733}
Richard Smith11562c52011-10-28 17:51:58 +00009734
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009735static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9736 const ASTContext &Ctx, bool &IsConst) {
9737 // Fast-path evaluations of integer literals, since we sometimes see files
9738 // containing vast quantities of these.
9739 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9740 Result.Val = APValue(APSInt(L->getValue(),
9741 L->getType()->isUnsignedIntegerType()));
9742 IsConst = true;
9743 return true;
9744 }
James Dennett0492ef02014-03-14 17:44:10 +00009745
9746 // This case should be rare, but we need to check it before we check on
9747 // the type below.
9748 if (Exp->getType().isNull()) {
9749 IsConst = false;
9750 return true;
9751 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009752
9753 // FIXME: Evaluating values of large array and record types can cause
9754 // performance problems. Only do so in C++11 for now.
9755 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9756 Exp->getType()->isRecordType()) &&
9757 !Ctx.getLangOpts().CPlusPlus11) {
9758 IsConst = false;
9759 return true;
9760 }
9761 return false;
9762}
9763
9764
Richard Smith7b553f12011-10-29 00:50:52 +00009765/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009766/// any crazy technique (that has nothing to do with language standards) that
9767/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009768/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9769/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009770bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009771 bool IsConst;
9772 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9773 return IsConst;
9774
Richard Smith6d4c6582013-11-05 22:18:15 +00009775 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009776 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009777}
9778
Jay Foad39c79802011-01-12 09:06:06 +00009779bool Expr::EvaluateAsBooleanCondition(bool &Result,
9780 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009781 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009782 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009783 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009784}
9785
Richard Smithce8eca52015-12-08 03:21:47 +00009786static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9787 Expr::SideEffectsKind SEK) {
9788 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9789 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9790}
9791
Richard Smith5fab0c92011-12-28 19:48:30 +00009792bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9793 SideEffectsKind AllowSideEffects) const {
9794 if (!getType()->isIntegralOrEnumerationType())
9795 return false;
9796
Richard Smith11562c52011-10-28 17:51:58 +00009797 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009798 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009799 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009800 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009801
Richard Smith11562c52011-10-28 17:51:58 +00009802 Result = ExprResult.Val.getInt();
9803 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009804}
9805
Richard Trieube234c32016-04-21 21:04:55 +00009806bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9807 SideEffectsKind AllowSideEffects) const {
9808 if (!getType()->isRealFloatingType())
9809 return false;
9810
9811 EvalResult ExprResult;
9812 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9813 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9814 return false;
9815
9816 Result = ExprResult.Val.getFloat();
9817 return true;
9818}
9819
Jay Foad39c79802011-01-12 09:06:06 +00009820bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009821 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009822
John McCall45d55e42010-05-07 21:00:08 +00009823 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009824 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9825 !CheckLValueConstantExpression(Info, getExprLoc(),
9826 Ctx.getLValueReferenceType(getType()), LV))
9827 return false;
9828
Richard Smith2e312c82012-03-03 22:46:17 +00009829 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009830 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009831}
9832
Richard Smithd0b4dd62011-12-19 06:19:21 +00009833bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9834 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009835 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009836 // FIXME: Evaluating initializers for large array and record types can cause
9837 // performance problems. Only do so in C++11 for now.
9838 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009839 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009840 return false;
9841
Richard Smithd0b4dd62011-12-19 06:19:21 +00009842 Expr::EvalStatus EStatus;
9843 EStatus.Diag = &Notes;
9844
Richard Smith0c6124b2015-12-03 01:36:22 +00009845 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9846 ? EvalInfo::EM_ConstantExpression
9847 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009848 InitInfo.setEvaluatingDecl(VD, Value);
9849
9850 LValue LVal;
9851 LVal.set(VD);
9852
Richard Smithfddd3842011-12-30 21:15:51 +00009853 // C++11 [basic.start.init]p2:
9854 // Variables with static storage duration or thread storage duration shall be
9855 // zero-initialized before any other initialization takes place.
9856 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009857 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009858 !VD->getType()->isReferenceType()) {
9859 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009860 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009861 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009862 return false;
9863 }
9864
Richard Smith7525ff62013-05-09 07:14:00 +00009865 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9866 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009867 EStatus.HasSideEffects)
9868 return false;
9869
9870 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9871 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009872}
9873
Richard Smith7b553f12011-10-29 00:50:52 +00009874/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9875/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009876bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009877 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009878 return EvaluateAsRValue(Result, Ctx) &&
9879 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009880}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009881
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009882APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009883 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009884 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009885 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009886 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009887 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009888 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009889 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009890
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009891 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009892}
John McCall864e3962010-05-07 05:32:02 +00009893
Richard Smithe9ff7702013-11-05 22:23:30 +00009894void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009895 bool IsConst;
9896 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009897 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009898 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009899 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9900 }
9901}
9902
Richard Smithe6c01442013-06-05 00:46:14 +00009903bool Expr::EvalResult::isGlobalLValue() const {
9904 assert(Val.isLValue());
9905 return IsGlobalLValue(Val.getLValueBase());
9906}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009907
9908
John McCall864e3962010-05-07 05:32:02 +00009909/// isIntegerConstantExpr - this recursive routine will test if an expression is
9910/// an integer constant expression.
9911
9912/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9913/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009914
9915// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009916// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9917// and a (possibly null) SourceLocation indicating the location of the problem.
9918//
John McCall864e3962010-05-07 05:32:02 +00009919// Note that to reduce code duplication, this helper does no evaluation
9920// itself; the caller checks whether the expression is evaluatable, and
9921// in the rare cases where CheckICE actually cares about the evaluated
9922// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009923
Dan Gohman28ade552010-07-26 21:25:24 +00009924namespace {
9925
Richard Smith9e575da2012-12-28 13:25:52 +00009926enum ICEKind {
9927 /// This expression is an ICE.
9928 IK_ICE,
9929 /// This expression is not an ICE, but if it isn't evaluated, it's
9930 /// a legal subexpression for an ICE. This return value is used to handle
9931 /// the comma operator in C99 mode, and non-constant subexpressions.
9932 IK_ICEIfUnevaluated,
9933 /// This expression is not an ICE, and is not a legal subexpression for one.
9934 IK_NotICE
9935};
9936
John McCall864e3962010-05-07 05:32:02 +00009937struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009938 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009939 SourceLocation Loc;
9940
Richard Smith9e575da2012-12-28 13:25:52 +00009941 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009942};
9943
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009944}
Dan Gohman28ade552010-07-26 21:25:24 +00009945
Richard Smith9e575da2012-12-28 13:25:52 +00009946static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9947
9948static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009949
Craig Toppera31a8822013-08-22 07:09:37 +00009950static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009951 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009952 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009953 !EVResult.Val.isInt())
9954 return ICEDiag(IK_NotICE, E->getLocStart());
9955
John McCall864e3962010-05-07 05:32:02 +00009956 return NoDiag();
9957}
9958
Craig Toppera31a8822013-08-22 07:09:37 +00009959static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009960 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009961 if (!E->getType()->isIntegralOrEnumerationType())
9962 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009963
9964 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009965#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009966#define STMT(Node, Base) case Expr::Node##Class:
9967#define EXPR(Node, Base)
9968#include "clang/AST/StmtNodes.inc"
9969 case Expr::PredefinedExprClass:
9970 case Expr::FloatingLiteralClass:
9971 case Expr::ImaginaryLiteralClass:
9972 case Expr::StringLiteralClass:
9973 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009974 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009975 case Expr::MemberExprClass:
9976 case Expr::CompoundAssignOperatorClass:
9977 case Expr::CompoundLiteralExprClass:
9978 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009979 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00009980 case Expr::ArrayInitLoopExprClass:
9981 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009982 case Expr::NoInitExprClass:
9983 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009984 case Expr::ImplicitValueInitExprClass:
9985 case Expr::ParenListExprClass:
9986 case Expr::VAArgExprClass:
9987 case Expr::AddrLabelExprClass:
9988 case Expr::StmtExprClass:
9989 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009990 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009991 case Expr::CXXDynamicCastExprClass:
9992 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009993 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009994 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009995 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009996 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009997 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009998 case Expr::CXXThisExprClass:
9999 case Expr::CXXThrowExprClass:
10000 case Expr::CXXNewExprClass:
10001 case Expr::CXXDeleteExprClass:
10002 case Expr::CXXPseudoDestructorExprClass:
10003 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010004 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010005 case Expr::DependentScopeDeclRefExprClass:
10006 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010007 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010008 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010009 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010010 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010011 case Expr::CXXTemporaryObjectExprClass:
10012 case Expr::CXXUnresolvedConstructExprClass:
10013 case Expr::CXXDependentScopeMemberExprClass:
10014 case Expr::UnresolvedMemberExprClass:
10015 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010016 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010017 case Expr::ObjCArrayLiteralClass:
10018 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010019 case Expr::ObjCEncodeExprClass:
10020 case Expr::ObjCMessageExprClass:
10021 case Expr::ObjCSelectorExprClass:
10022 case Expr::ObjCProtocolExprClass:
10023 case Expr::ObjCIvarRefExprClass:
10024 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010025 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010026 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010027 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010028 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010029 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010030 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010031 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010032 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010033 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010034 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010035 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010036 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010037 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010038 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010039 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010040 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010041 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010042 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010043 case Expr::CoawaitExprClass:
10044 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010045 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010046
Richard Smithf137f932014-01-25 20:50:08 +000010047 case Expr::InitListExprClass: {
10048 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10049 // form "T x = { a };" is equivalent to "T x = a;".
10050 // Unless we're initializing a reference, T is a scalar as it is known to be
10051 // of integral or enumeration type.
10052 if (E->isRValue())
10053 if (cast<InitListExpr>(E)->getNumInits() == 1)
10054 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10055 return ICEDiag(IK_NotICE, E->getLocStart());
10056 }
10057
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010058 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010059 case Expr::GNUNullExprClass:
10060 // GCC considers the GNU __null value to be an integral constant expression.
10061 return NoDiag();
10062
John McCall7c454bb2011-07-15 05:09:51 +000010063 case Expr::SubstNonTypeTemplateParmExprClass:
10064 return
10065 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10066
John McCall864e3962010-05-07 05:32:02 +000010067 case Expr::ParenExprClass:
10068 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010069 case Expr::GenericSelectionExprClass:
10070 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010071 case Expr::IntegerLiteralClass:
10072 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010073 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010074 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010075 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010076 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010077 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010078 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010079 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010080 return NoDiag();
10081 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010082 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010083 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10084 // constant expressions, but they can never be ICEs because an ICE cannot
10085 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010086 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010087 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010088 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010089 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010090 }
Richard Smith6365c912012-02-24 22:12:32 +000010091 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010092 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10093 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010094 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010095 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010096 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010097 // Parameter variables are never constants. Without this check,
10098 // getAnyInitializer() can find a default argument, which leads
10099 // to chaos.
10100 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010101 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010102
10103 // C++ 7.1.5.1p2
10104 // A variable of non-volatile const-qualified integral or enumeration
10105 // type initialized by an ICE can be used in ICEs.
10106 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010107 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010108 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010109
Richard Smithd0b4dd62011-12-19 06:19:21 +000010110 const VarDecl *VD;
10111 // Look for a declaration of this variable that has an initializer, and
10112 // check whether it is an ICE.
10113 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10114 return NoDiag();
10115 else
Richard Smith9e575da2012-12-28 13:25:52 +000010116 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010117 }
10118 }
Richard Smith9e575da2012-12-28 13:25:52 +000010119 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010120 }
John McCall864e3962010-05-07 05:32:02 +000010121 case Expr::UnaryOperatorClass: {
10122 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10123 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010124 case UO_PostInc:
10125 case UO_PostDec:
10126 case UO_PreInc:
10127 case UO_PreDec:
10128 case UO_AddrOf:
10129 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010130 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010131 // C99 6.6/3 allows increment and decrement within unevaluated
10132 // subexpressions of constant expressions, but they can never be ICEs
10133 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010134 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010135 case UO_Extension:
10136 case UO_LNot:
10137 case UO_Plus:
10138 case UO_Minus:
10139 case UO_Not:
10140 case UO_Real:
10141 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010142 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010143 }
Richard Smith9e575da2012-12-28 13:25:52 +000010144
John McCall864e3962010-05-07 05:32:02 +000010145 // OffsetOf falls through here.
10146 }
10147 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010148 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10149 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10150 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10151 // compliance: we should warn earlier for offsetof expressions with
10152 // array subscripts that aren't ICEs, and if the array subscripts
10153 // are ICEs, the value of the offsetof must be an integer constant.
10154 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010155 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010156 case Expr::UnaryExprOrTypeTraitExprClass: {
10157 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10158 if ((Exp->getKind() == UETT_SizeOf) &&
10159 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010160 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010161 return NoDiag();
10162 }
10163 case Expr::BinaryOperatorClass: {
10164 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10165 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010166 case BO_PtrMemD:
10167 case BO_PtrMemI:
10168 case BO_Assign:
10169 case BO_MulAssign:
10170 case BO_DivAssign:
10171 case BO_RemAssign:
10172 case BO_AddAssign:
10173 case BO_SubAssign:
10174 case BO_ShlAssign:
10175 case BO_ShrAssign:
10176 case BO_AndAssign:
10177 case BO_XorAssign:
10178 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010179 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10180 // constant expressions, but they can never be ICEs because an ICE cannot
10181 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010182 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010183
John McCalle3027922010-08-25 11:45:40 +000010184 case BO_Mul:
10185 case BO_Div:
10186 case BO_Rem:
10187 case BO_Add:
10188 case BO_Sub:
10189 case BO_Shl:
10190 case BO_Shr:
10191 case BO_LT:
10192 case BO_GT:
10193 case BO_LE:
10194 case BO_GE:
10195 case BO_EQ:
10196 case BO_NE:
10197 case BO_And:
10198 case BO_Xor:
10199 case BO_Or:
10200 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010201 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10202 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010203 if (Exp->getOpcode() == BO_Div ||
10204 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010205 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010206 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010207 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010208 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010209 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010210 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010211 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010212 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010213 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010214 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010215 }
10216 }
10217 }
John McCalle3027922010-08-25 11:45:40 +000010218 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010219 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010220 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10221 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010222 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10223 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010224 } else {
10225 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010226 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010227 }
10228 }
Richard Smith9e575da2012-12-28 13:25:52 +000010229 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010230 }
John McCalle3027922010-08-25 11:45:40 +000010231 case BO_LAnd:
10232 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010233 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10234 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010235 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010236 // Rare case where the RHS has a comma "side-effect"; we need
10237 // to actually check the condition to see whether the side
10238 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010239 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010240 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010241 return RHSResult;
10242 return NoDiag();
10243 }
10244
Richard Smith9e575da2012-12-28 13:25:52 +000010245 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010246 }
10247 }
10248 }
10249 case Expr::ImplicitCastExprClass:
10250 case Expr::CStyleCastExprClass:
10251 case Expr::CXXFunctionalCastExprClass:
10252 case Expr::CXXStaticCastExprClass:
10253 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010254 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010255 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010256 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010257 if (isa<ExplicitCastExpr>(E)) {
10258 if (const FloatingLiteral *FL
10259 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10260 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10261 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10262 APSInt IgnoredVal(DestWidth, !DestSigned);
10263 bool Ignored;
10264 // If the value does not fit in the destination type, the behavior is
10265 // undefined, so we are not required to treat it as a constant
10266 // expression.
10267 if (FL->getValue().convertToInteger(IgnoredVal,
10268 llvm::APFloat::rmTowardZero,
10269 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010270 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010271 return NoDiag();
10272 }
10273 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010274 switch (cast<CastExpr>(E)->getCastKind()) {
10275 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010276 case CK_AtomicToNonAtomic:
10277 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010278 case CK_NoOp:
10279 case CK_IntegralToBoolean:
10280 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010281 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010282 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010283 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010284 }
John McCall864e3962010-05-07 05:32:02 +000010285 }
John McCallc07a0c72011-02-17 10:25:35 +000010286 case Expr::BinaryConditionalOperatorClass: {
10287 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10288 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010289 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010290 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010291 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10292 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10293 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010294 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010295 return FalseResult;
10296 }
John McCall864e3962010-05-07 05:32:02 +000010297 case Expr::ConditionalOperatorClass: {
10298 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10299 // If the condition (ignoring parens) is a __builtin_constant_p call,
10300 // then only the true side is actually considered in an integer constant
10301 // expression, and it is fully evaluated. This is an important GNU
10302 // extension. See GCC PR38377 for discussion.
10303 if (const CallExpr *CallCE
10304 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010305 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010306 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010307 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010308 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010309 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010310
Richard Smithf57d8cb2011-12-09 22:58:01 +000010311 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10312 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010313
Richard Smith9e575da2012-12-28 13:25:52 +000010314 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010315 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010316 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010317 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010318 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010319 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010320 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010321 return NoDiag();
10322 // Rare case where the diagnostics depend on which side is evaluated
10323 // Note that if we get here, CondResult is 0, and at least one of
10324 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010325 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010326 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010327 return TrueResult;
10328 }
10329 case Expr::CXXDefaultArgExprClass:
10330 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010331 case Expr::CXXDefaultInitExprClass:
10332 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010333 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010334 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010335 }
10336 }
10337
David Blaikiee4d798f2012-01-20 21:50:17 +000010338 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010339}
10340
Richard Smithf57d8cb2011-12-09 22:58:01 +000010341/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010342static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010343 const Expr *E,
10344 llvm::APSInt *Value,
10345 SourceLocation *Loc) {
10346 if (!E->getType()->isIntegralOrEnumerationType()) {
10347 if (Loc) *Loc = E->getExprLoc();
10348 return false;
10349 }
10350
Richard Smith66e05fe2012-01-18 05:21:49 +000010351 APValue Result;
10352 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010353 return false;
10354
Richard Smith98710fc2014-11-13 23:03:19 +000010355 if (!Result.isInt()) {
10356 if (Loc) *Loc = E->getExprLoc();
10357 return false;
10358 }
10359
Richard Smith66e05fe2012-01-18 05:21:49 +000010360 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010361 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010362}
10363
Craig Toppera31a8822013-08-22 07:09:37 +000010364bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10365 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010366 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010367 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010368
Richard Smith9e575da2012-12-28 13:25:52 +000010369 ICEDiag D = CheckICE(this, Ctx);
10370 if (D.Kind != IK_ICE) {
10371 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010372 return false;
10373 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010374 return true;
10375}
10376
Craig Toppera31a8822013-08-22 07:09:37 +000010377bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010378 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010379 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010380 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10381
10382 if (!isIntegerConstantExpr(Ctx, Loc))
10383 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010384 // The only possible side-effects here are due to UB discovered in the
10385 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10386 // required to treat the expression as an ICE, so we produce the folded
10387 // value.
10388 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010389 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010390 return true;
10391}
Richard Smith66e05fe2012-01-18 05:21:49 +000010392
Craig Toppera31a8822013-08-22 07:09:37 +000010393bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010394 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010395}
10396
Craig Toppera31a8822013-08-22 07:09:37 +000010397bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010398 SourceLocation *Loc) const {
10399 // We support this checking in C++98 mode in order to diagnose compatibility
10400 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010401 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010402
Richard Smith98a0a492012-02-14 21:38:30 +000010403 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010404 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010405 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010406 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010407 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010408
10409 APValue Scratch;
10410 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10411
10412 if (!Diags.empty()) {
10413 IsConstExpr = false;
10414 if (Loc) *Loc = Diags[0].first;
10415 } else if (!IsConstExpr) {
10416 // FIXME: This shouldn't happen.
10417 if (Loc) *Loc = getExprLoc();
10418 }
10419
10420 return IsConstExpr;
10421}
Richard Smith253c2a32012-01-27 01:14:48 +000010422
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010423bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10424 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010425 ArrayRef<const Expr*> Args,
10426 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010427 Expr::EvalStatus Status;
10428 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10429
George Burgess IV177399e2017-01-09 04:12:14 +000010430 LValue ThisVal;
10431 const LValue *ThisPtr = nullptr;
10432 if (This) {
10433#ifndef NDEBUG
10434 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10435 assert(MD && "Don't provide `this` for non-methods.");
10436 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10437#endif
10438 if (EvaluateObjectArgument(Info, This, ThisVal))
10439 ThisPtr = &ThisVal;
10440 if (Info.EvalStatus.HasSideEffects)
10441 return false;
10442 }
10443
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010444 ArgVector ArgValues(Args.size());
10445 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10446 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010447 if ((*I)->isValueDependent() ||
10448 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010449 // If evaluation fails, throw away the argument entirely.
10450 ArgValues[I - Args.begin()] = APValue();
10451 if (Info.EvalStatus.HasSideEffects)
10452 return false;
10453 }
10454
10455 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010456 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010457 ArgValues.data());
10458 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10459}
10460
Richard Smith253c2a32012-01-27 01:14:48 +000010461bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010462 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010463 PartialDiagnosticAt> &Diags) {
10464 // FIXME: It would be useful to check constexpr function templates, but at the
10465 // moment the constant expression evaluator cannot cope with the non-rigorous
10466 // ASTs which we build for dependent expressions.
10467 if (FD->isDependentContext())
10468 return true;
10469
10470 Expr::EvalStatus Status;
10471 Status.Diag = &Diags;
10472
Richard Smith6d4c6582013-11-05 22:18:15 +000010473 EvalInfo Info(FD->getASTContext(), Status,
10474 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010475
10476 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010477 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010478
Richard Smith7525ff62013-05-09 07:14:00 +000010479 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010480 // is a temporary being used as the 'this' pointer.
10481 LValue This;
10482 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010483 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010484
Richard Smith253c2a32012-01-27 01:14:48 +000010485 ArrayRef<const Expr*> Args;
10486
Richard Smith2e312c82012-03-03 22:46:17 +000010487 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010488 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10489 // Evaluate the call as a constant initializer, to allow the construction
10490 // of objects of non-literal types.
10491 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010492 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10493 } else {
10494 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010495 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010496 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010497 }
Richard Smith253c2a32012-01-27 01:14:48 +000010498
10499 return Diags.empty();
10500}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010501
10502bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10503 const FunctionDecl *FD,
10504 SmallVectorImpl<
10505 PartialDiagnosticAt> &Diags) {
10506 Expr::EvalStatus Status;
10507 Status.Diag = &Diags;
10508
10509 EvalInfo Info(FD->getASTContext(), Status,
10510 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10511
10512 // Fabricate a call stack frame to give the arguments a plausible cover story.
10513 ArrayRef<const Expr*> Args;
10514 ArgVector ArgValues(0);
10515 bool Success = EvaluateArgs(Args, ArgValues, Info);
10516 (void)Success;
10517 assert(Success &&
10518 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010519 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010520
10521 APValue ResultScratch;
10522 Evaluate(ResultScratch, Info, E);
10523 return Diags.empty();
10524}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010525
10526bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10527 unsigned Type) const {
10528 if (!getType()->isPointerType())
10529 return false;
10530
10531 Expr::EvalStatus Status;
10532 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010533 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010534}