blob: b3f8925b64643ae6552592ac2134e3b1f34a6b5a [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.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001630 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001631 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001632 return true;
1633
Richard Smithfddd3842011-12-30 21:15:51 +00001634 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001635 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001636 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001637 << E->getType();
1638 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001639 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001640 return false;
1641}
1642
Richard Smith0b0a0b62011-10-29 20:57:55 +00001643/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001644/// constant expression. If not, report an appropriate diagnostic. Does not
1645/// check that the expression is of literal type.
1646static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1647 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001648 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001649 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001650 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001651 return false;
1652 }
1653
Richard Smith77be48a2014-07-31 06:31:19 +00001654 // We allow _Atomic(T) to be initialized from anything that T can be
1655 // initialized from.
1656 if (const AtomicType *AT = Type->getAs<AtomicType>())
1657 Type = AT->getValueType();
1658
Richard Smithb228a862012-02-15 02:18:13 +00001659 // Core issue 1454: For a literal constant expression of array or class type,
1660 // each subobject of its value shall have been initialized by a constant
1661 // expression.
1662 if (Value.isArray()) {
1663 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1664 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1665 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1666 Value.getArrayInitializedElt(I)))
1667 return false;
1668 }
1669 if (!Value.hasArrayFiller())
1670 return true;
1671 return CheckConstantExpression(Info, DiagLoc, EltTy,
1672 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001673 }
Richard Smithb228a862012-02-15 02:18:13 +00001674 if (Value.isUnion() && Value.getUnionField()) {
1675 return CheckConstantExpression(Info, DiagLoc,
1676 Value.getUnionField()->getType(),
1677 Value.getUnionValue());
1678 }
1679 if (Value.isStruct()) {
1680 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1681 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1682 unsigned BaseIndex = 0;
1683 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1684 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1685 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1686 Value.getStructBase(BaseIndex)))
1687 return false;
1688 }
1689 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001690 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001691 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1692 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001693 return false;
1694 }
1695 }
1696
1697 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001698 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001699 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001700 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1701 }
1702
1703 // Everything else is fine.
1704 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001705}
1706
Benjamin Kramer8407df72015-03-09 16:47:52 +00001707static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001708 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001709}
1710
1711static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001712 if (Value.CallIndex)
1713 return false;
1714 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1715 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001716}
1717
Richard Smithcecf1842011-11-01 21:06:14 +00001718static bool IsWeakLValue(const LValue &Value) {
1719 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001720 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001721}
1722
David Majnemerb5116032014-12-09 23:32:34 +00001723static bool isZeroSized(const LValue &Value) {
1724 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001725 if (Decl && isa<VarDecl>(Decl)) {
1726 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001727 if (Ty->isArrayType())
1728 return Ty->isIncompleteType() ||
1729 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001730 }
1731 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001732}
1733
Richard Smith2e312c82012-03-03 22:46:17 +00001734static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001735 // A null base expression indicates a null pointer. These are always
1736 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001737 if (!Value.getLValueBase()) {
1738 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001739 return true;
1740 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001741
Richard Smith027bf112011-11-17 22:56:20 +00001742 // We have a non-null base. These are generally known to be true, but if it's
1743 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001744 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001745 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001746 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001747}
1748
Richard Smith2e312c82012-03-03 22:46:17 +00001749static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001750 switch (Val.getKind()) {
1751 case APValue::Uninitialized:
1752 return false;
1753 case APValue::Int:
1754 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001755 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001756 case APValue::Float:
1757 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001758 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001759 case APValue::ComplexInt:
1760 Result = Val.getComplexIntReal().getBoolValue() ||
1761 Val.getComplexIntImag().getBoolValue();
1762 return true;
1763 case APValue::ComplexFloat:
1764 Result = !Val.getComplexFloatReal().isZero() ||
1765 !Val.getComplexFloatImag().isZero();
1766 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001767 case APValue::LValue:
1768 return EvalPointerValueAsBool(Val, Result);
1769 case APValue::MemberPointer:
1770 Result = Val.getMemberPointerDecl();
1771 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001772 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001773 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001774 case APValue::Struct:
1775 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001776 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001777 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001778 }
1779
Richard Smith11562c52011-10-28 17:51:58 +00001780 llvm_unreachable("unknown APValue kind");
1781}
1782
1783static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1784 EvalInfo &Info) {
1785 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001786 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001787 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001788 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001789 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001790}
1791
Richard Smith357362d2011-12-13 06:39:58 +00001792template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001793static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001794 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001795 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001796 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001797 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001798}
1799
1800static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1801 QualType SrcType, const APFloat &Value,
1802 QualType DestType, APSInt &Result) {
1803 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001804 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001805 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001806
Richard Smith357362d2011-12-13 06:39:58 +00001807 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001808 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001809 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1810 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001811 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001812 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001813}
1814
Richard Smith357362d2011-12-13 06:39:58 +00001815static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1816 QualType SrcType, QualType DestType,
1817 APFloat &Result) {
1818 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001819 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001820 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1821 APFloat::rmNearestTiesToEven, &ignored)
1822 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001823 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001824 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001825}
1826
Richard Smith911e1422012-01-30 22:27:01 +00001827static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1828 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001829 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001830 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001831 APSInt Result = Value;
1832 // Figure out if this is a truncate, extend or noop cast.
1833 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001834 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001835 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001836 return Result;
1837}
1838
Richard Smith357362d2011-12-13 06:39:58 +00001839static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1840 QualType SrcType, const APSInt &Value,
1841 QualType DestType, APFloat &Result) {
1842 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1843 if (Result.convertFromAPInt(Value, Value.isSigned(),
1844 APFloat::rmNearestTiesToEven)
1845 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001846 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001847 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001848}
1849
Richard Smith49ca8aa2013-08-06 07:09:20 +00001850static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1851 APValue &Value, const FieldDecl *FD) {
1852 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1853
1854 if (!Value.isInt()) {
1855 // Trying to store a pointer-cast-to-integer into a bitfield.
1856 // FIXME: In this case, we should provide the diagnostic for casting
1857 // a pointer to an integer.
1858 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001859 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001860 return false;
1861 }
1862
1863 APSInt &Int = Value.getInt();
1864 unsigned OldBitWidth = Int.getBitWidth();
1865 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1866 if (NewBitWidth < OldBitWidth)
1867 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1868 return true;
1869}
1870
Eli Friedman803acb32011-12-22 03:51:45 +00001871static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1872 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001873 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001874 if (!Evaluate(SVal, Info, E))
1875 return false;
1876 if (SVal.isInt()) {
1877 Res = SVal.getInt();
1878 return true;
1879 }
1880 if (SVal.isFloat()) {
1881 Res = SVal.getFloat().bitcastToAPInt();
1882 return true;
1883 }
1884 if (SVal.isVector()) {
1885 QualType VecTy = E->getType();
1886 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1887 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1888 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1889 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1890 Res = llvm::APInt::getNullValue(VecSize);
1891 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1892 APValue &Elt = SVal.getVectorElt(i);
1893 llvm::APInt EltAsInt;
1894 if (Elt.isInt()) {
1895 EltAsInt = Elt.getInt();
1896 } else if (Elt.isFloat()) {
1897 EltAsInt = Elt.getFloat().bitcastToAPInt();
1898 } else {
1899 // Don't try to handle vectors of anything other than int or float
1900 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001901 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001902 return false;
1903 }
1904 unsigned BaseEltSize = EltAsInt.getBitWidth();
1905 if (BigEndian)
1906 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1907 else
1908 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1909 }
1910 return true;
1911 }
1912 // Give up if the input isn't an int, float, or vector. For example, we
1913 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001914 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001915 return false;
1916}
1917
Richard Smith43e77732013-05-07 04:50:00 +00001918/// Perform the given integer operation, which is known to need at most BitWidth
1919/// bits, and check for overflow in the original type (if that type was not an
1920/// unsigned type).
1921template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001922static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1923 const APSInt &LHS, const APSInt &RHS,
1924 unsigned BitWidth, Operation Op,
1925 APSInt &Result) {
1926 if (LHS.isUnsigned()) {
1927 Result = Op(LHS, RHS);
1928 return true;
1929 }
Richard Smith43e77732013-05-07 04:50:00 +00001930
1931 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001932 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001933 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001934 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001935 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001936 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001937 << Result.toString(10) << E->getType();
1938 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001939 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001940 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001941 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001942}
1943
1944/// Perform the given binary integer operation.
1945static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1946 BinaryOperatorKind Opcode, APSInt RHS,
1947 APSInt &Result) {
1948 switch (Opcode) {
1949 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001950 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001951 return false;
1952 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001953 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1954 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001955 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001956 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1957 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001958 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001959 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1960 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001961 case BO_And: Result = LHS & RHS; return true;
1962 case BO_Xor: Result = LHS ^ RHS; return true;
1963 case BO_Or: Result = LHS | RHS; return true;
1964 case BO_Div:
1965 case BO_Rem:
1966 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001967 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00001968 return false;
1969 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001970 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1971 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1972 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001973 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1974 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001975 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1976 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001977 return true;
1978 case BO_Shl: {
1979 if (Info.getLangOpts().OpenCL)
1980 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1981 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1982 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1983 RHS.isUnsigned());
1984 else if (RHS.isSigned() && RHS.isNegative()) {
1985 // During constant-folding, a negative shift is an opposite shift. Such
1986 // a shift is not a constant expression.
1987 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1988 RHS = -RHS;
1989 goto shift_right;
1990 }
1991 shift_left:
1992 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1993 // the shifted type.
1994 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1995 if (SA != RHS) {
1996 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1997 << RHS << E->getType() << LHS.getBitWidth();
1998 } else if (LHS.isSigned()) {
1999 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2000 // operand, and must not overflow the corresponding unsigned type.
2001 if (LHS.isNegative())
2002 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2003 else if (LHS.countLeadingZeros() < SA)
2004 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2005 }
2006 Result = LHS << SA;
2007 return true;
2008 }
2009 case BO_Shr: {
2010 if (Info.getLangOpts().OpenCL)
2011 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2012 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2013 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2014 RHS.isUnsigned());
2015 else if (RHS.isSigned() && RHS.isNegative()) {
2016 // During constant-folding, a negative shift is an opposite shift. Such a
2017 // shift is not a constant expression.
2018 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2019 RHS = -RHS;
2020 goto shift_left;
2021 }
2022 shift_right:
2023 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2024 // shifted type.
2025 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2026 if (SA != RHS)
2027 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2028 << RHS << E->getType() << LHS.getBitWidth();
2029 Result = LHS >> SA;
2030 return true;
2031 }
2032
2033 case BO_LT: Result = LHS < RHS; return true;
2034 case BO_GT: Result = LHS > RHS; return true;
2035 case BO_LE: Result = LHS <= RHS; return true;
2036 case BO_GE: Result = LHS >= RHS; return true;
2037 case BO_EQ: Result = LHS == RHS; return true;
2038 case BO_NE: Result = LHS != RHS; return true;
2039 }
2040}
2041
Richard Smith861b5b52013-05-07 23:34:45 +00002042/// Perform the given binary floating-point operation, in-place, on LHS.
2043static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2044 APFloat &LHS, BinaryOperatorKind Opcode,
2045 const APFloat &RHS) {
2046 switch (Opcode) {
2047 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002048 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002049 return false;
2050 case BO_Mul:
2051 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2052 break;
2053 case BO_Add:
2054 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2055 break;
2056 case BO_Sub:
2057 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2058 break;
2059 case BO_Div:
2060 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2061 break;
2062 }
2063
Richard Smith0c6124b2015-12-03 01:36:22 +00002064 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002065 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002066 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002067 }
Richard Smith861b5b52013-05-07 23:34:45 +00002068 return true;
2069}
2070
Richard Smitha8105bc2012-01-06 16:39:00 +00002071/// Cast an lvalue referring to a base subobject to a derived class, by
2072/// truncating the lvalue's path to the given length.
2073static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2074 const RecordDecl *TruncatedType,
2075 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002076 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002077
2078 // Check we actually point to a derived class object.
2079 if (TruncatedElements == D.Entries.size())
2080 return true;
2081 assert(TruncatedElements >= D.MostDerivedPathLength &&
2082 "not casting to a derived class");
2083 if (!Result.checkSubobject(Info, E, CSK_Derived))
2084 return false;
2085
2086 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002087 const RecordDecl *RD = TruncatedType;
2088 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002089 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002090 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2091 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002092 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002093 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002094 else
Richard Smithd62306a2011-11-10 06:34:14 +00002095 Result.Offset -= Layout.getBaseClassOffset(Base);
2096 RD = Base;
2097 }
Richard Smith027bf112011-11-17 22:56:20 +00002098 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002099 return true;
2100}
2101
John McCalld7bca762012-05-01 00:38:49 +00002102static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002103 const CXXRecordDecl *Derived,
2104 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002105 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002106 if (!RL) {
2107 if (Derived->isInvalidDecl()) return false;
2108 RL = &Info.Ctx.getASTRecordLayout(Derived);
2109 }
2110
Richard Smithd62306a2011-11-10 06:34:14 +00002111 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002112 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002113 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002114}
2115
Richard Smitha8105bc2012-01-06 16:39:00 +00002116static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002117 const CXXRecordDecl *DerivedDecl,
2118 const CXXBaseSpecifier *Base) {
2119 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2120
John McCalld7bca762012-05-01 00:38:49 +00002121 if (!Base->isVirtual())
2122 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002123
Richard Smitha8105bc2012-01-06 16:39:00 +00002124 SubobjectDesignator &D = Obj.Designator;
2125 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002126 return false;
2127
Richard Smitha8105bc2012-01-06 16:39:00 +00002128 // Extract most-derived object and corresponding type.
2129 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2130 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2131 return false;
2132
2133 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002134 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002135 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2136 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002137 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002138 return true;
2139}
2140
Richard Smith84401042013-06-03 05:03:02 +00002141static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2142 QualType Type, LValue &Result) {
2143 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2144 PathE = E->path_end();
2145 PathI != PathE; ++PathI) {
2146 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2147 *PathI))
2148 return false;
2149 Type = (*PathI)->getType();
2150 }
2151 return true;
2152}
2153
Richard Smithd62306a2011-11-10 06:34:14 +00002154/// Update LVal to refer to the given field, which must be a member of the type
2155/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002156static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002157 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002158 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002159 if (!RL) {
2160 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002161 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002162 }
Richard Smithd62306a2011-11-10 06:34:14 +00002163
2164 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002165 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002166 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002167 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002168}
2169
Richard Smith1b78b3d2012-01-25 22:15:11 +00002170/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002171static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002172 LValue &LVal,
2173 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002174 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002175 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002176 return false;
2177 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002178}
2179
Richard Smithd62306a2011-11-10 06:34:14 +00002180/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002181static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2182 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002183 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2184 // extension.
2185 if (Type->isVoidType() || Type->isFunctionType()) {
2186 Size = CharUnits::One();
2187 return true;
2188 }
2189
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002190 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002191 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002192 return false;
2193 }
2194
Richard Smithd62306a2011-11-10 06:34:14 +00002195 if (!Type->isConstantSizeType()) {
2196 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002197 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002198 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002199 return false;
2200 }
2201
2202 Size = Info.Ctx.getTypeSizeInChars(Type);
2203 return true;
2204}
2205
2206/// Update a pointer value to model pointer arithmetic.
2207/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002208/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002209/// \param LVal - The pointer value to be updated.
2210/// \param EltTy - The pointee type represented by LVal.
2211/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002212static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2213 LValue &LVal, QualType EltTy,
2214 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002215 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002216 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002217 return false;
2218
Yaxun Liu402804b2016-12-15 08:09:08 +00002219 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002220 return true;
2221}
2222
Richard Smith66c96992012-02-18 22:04:06 +00002223/// Update an lvalue to refer to a component of a complex number.
2224/// \param Info - Information about the ongoing evaluation.
2225/// \param LVal - The lvalue to be updated.
2226/// \param EltTy - The complex number's component type.
2227/// \param Imag - False for the real component, true for the imaginary.
2228static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2229 LValue &LVal, QualType EltTy,
2230 bool Imag) {
2231 if (Imag) {
2232 CharUnits SizeOfComponent;
2233 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2234 return false;
2235 LVal.Offset += SizeOfComponent;
2236 }
2237 LVal.addComplex(Info, E, EltTy, Imag);
2238 return true;
2239}
2240
Richard Smith27908702011-10-24 17:54:18 +00002241/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002242///
2243/// \param Info Information about the ongoing evaluation.
2244/// \param E An expression to be used when printing diagnostics.
2245/// \param VD The variable whose initializer should be obtained.
2246/// \param Frame The frame in which the variable was created. Must be null
2247/// if this variable is not local to the evaluation.
2248/// \param Result Filled in with a pointer to the value of the variable.
2249static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2250 const VarDecl *VD, CallStackFrame *Frame,
2251 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002252 // If this is a parameter to an active constexpr function call, perform
2253 // argument substitution.
2254 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002255 // Assume arguments of a potential constant expression are unknown
2256 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002257 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002258 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002259 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002260 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002261 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002262 }
Richard Smith3229b742013-05-05 21:17:10 +00002263 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002264 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002265 }
Richard Smith27908702011-10-24 17:54:18 +00002266
Richard Smithd9f663b2013-04-22 15:31:51 +00002267 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002268 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002269 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002270 if (!Result) {
2271 // Assume variables referenced within a lambda's call operator that were
2272 // not declared within the call operator are captures and during checking
2273 // of a potential constant expression, assume they are unknown constant
2274 // expressions.
2275 assert(isLambdaCallOperator(Frame->Callee) &&
2276 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2277 "missing value for local variable");
2278 if (Info.checkingPotentialConstantExpression())
2279 return false;
2280 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002281 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002282 diag::note_unimplemented_constexpr_lambda_feature_ast)
2283 << "captures not currently allowed";
2284 return false;
2285 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002286 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002287 }
2288
Richard Smithd0b4dd62011-12-19 06:19:21 +00002289 // Dig out the initializer, and use the declaration which it's attached to.
2290 const Expr *Init = VD->getAnyInitializer(VD);
2291 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002292 // If we're checking a potential constant expression, the variable could be
2293 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002294 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002295 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002296 return false;
2297 }
2298
Richard Smithd62306a2011-11-10 06:34:14 +00002299 // If we're currently evaluating the initializer of this declaration, use that
2300 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002301 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002302 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002303 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002304 }
2305
Richard Smithcecf1842011-11-01 21:06:14 +00002306 // Never evaluate the initializer of a weak variable. We can't be sure that
2307 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002308 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002309 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002310 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002311 }
Richard Smithcecf1842011-11-01 21:06:14 +00002312
Richard Smithd0b4dd62011-12-19 06:19:21 +00002313 // Check that we can fold the initializer. In C++, we will have already done
2314 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002315 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002316 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002317 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002318 Notes.size() + 1) << VD;
2319 Info.Note(VD->getLocation(), diag::note_declared_at);
2320 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002321 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002322 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002323 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002324 Notes.size() + 1) << VD;
2325 Info.Note(VD->getLocation(), diag::note_declared_at);
2326 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002327 }
Richard Smith27908702011-10-24 17:54:18 +00002328
Richard Smith3229b742013-05-05 21:17:10 +00002329 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002330 return true;
Richard Smith27908702011-10-24 17:54:18 +00002331}
2332
Richard Smith11562c52011-10-28 17:51:58 +00002333static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002334 Qualifiers Quals = T.getQualifiers();
2335 return Quals.hasConst() && !Quals.hasVolatile();
2336}
2337
Richard Smithe97cbd72011-11-11 04:05:33 +00002338/// Get the base index of the given base class within an APValue representing
2339/// the given derived class.
2340static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2341 const CXXRecordDecl *Base) {
2342 Base = Base->getCanonicalDecl();
2343 unsigned Index = 0;
2344 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2345 E = Derived->bases_end(); I != E; ++I, ++Index) {
2346 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2347 return Index;
2348 }
2349
2350 llvm_unreachable("base class missing from derived class's bases list");
2351}
2352
Richard Smith3da88fa2013-04-26 14:36:30 +00002353/// Extract the value of a character from a string literal.
2354static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2355 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002356 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2357 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2358 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002359 const StringLiteral *S = cast<StringLiteral>(Lit);
2360 const ConstantArrayType *CAT =
2361 Info.Ctx.getAsConstantArrayType(S->getType());
2362 assert(CAT && "string literal isn't an array");
2363 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002364 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002365
2366 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002367 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002368 if (Index < S->getLength())
2369 Value = S->getCodeUnit(Index);
2370 return Value;
2371}
2372
Richard Smith3da88fa2013-04-26 14:36:30 +00002373// Expand a string literal into an array of characters.
2374static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2375 APValue &Result) {
2376 const StringLiteral *S = cast<StringLiteral>(Lit);
2377 const ConstantArrayType *CAT =
2378 Info.Ctx.getAsConstantArrayType(S->getType());
2379 assert(CAT && "string literal isn't an array");
2380 QualType CharType = CAT->getElementType();
2381 assert(CharType->isIntegerType() && "unexpected character type");
2382
2383 unsigned Elts = CAT->getSize().getZExtValue();
2384 Result = APValue(APValue::UninitArray(),
2385 std::min(S->getLength(), Elts), Elts);
2386 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2387 CharType->isUnsignedIntegerType());
2388 if (Result.hasArrayFiller())
2389 Result.getArrayFiller() = APValue(Value);
2390 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2391 Value = S->getCodeUnit(I);
2392 Result.getArrayInitializedElt(I) = APValue(Value);
2393 }
2394}
2395
2396// Expand an array so that it has more than Index filled elements.
2397static void expandArray(APValue &Array, unsigned Index) {
2398 unsigned Size = Array.getArraySize();
2399 assert(Index < Size);
2400
2401 // Always at least double the number of elements for which we store a value.
2402 unsigned OldElts = Array.getArrayInitializedElts();
2403 unsigned NewElts = std::max(Index+1, OldElts * 2);
2404 NewElts = std::min(Size, std::max(NewElts, 8u));
2405
2406 // Copy the data across.
2407 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2408 for (unsigned I = 0; I != OldElts; ++I)
2409 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2410 for (unsigned I = OldElts; I != NewElts; ++I)
2411 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2412 if (NewValue.hasArrayFiller())
2413 NewValue.getArrayFiller() = Array.getArrayFiller();
2414 Array.swap(NewValue);
2415}
2416
Richard Smithb01fe402014-09-16 01:24:02 +00002417/// Determine whether a type would actually be read by an lvalue-to-rvalue
2418/// conversion. If it's of class type, we may assume that the copy operation
2419/// is trivial. Note that this is never true for a union type with fields
2420/// (because the copy always "reads" the active member) and always true for
2421/// a non-class type.
2422static bool isReadByLvalueToRvalueConversion(QualType T) {
2423 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2424 if (!RD || (RD->isUnion() && !RD->field_empty()))
2425 return true;
2426 if (RD->isEmpty())
2427 return false;
2428
2429 for (auto *Field : RD->fields())
2430 if (isReadByLvalueToRvalueConversion(Field->getType()))
2431 return true;
2432
2433 for (auto &BaseSpec : RD->bases())
2434 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2435 return true;
2436
2437 return false;
2438}
2439
2440/// Diagnose an attempt to read from any unreadable field within the specified
2441/// type, which might be a class type.
2442static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2443 QualType T) {
2444 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2445 if (!RD)
2446 return false;
2447
2448 if (!RD->hasMutableFields())
2449 return false;
2450
2451 for (auto *Field : RD->fields()) {
2452 // If we're actually going to read this field in some way, then it can't
2453 // be mutable. If we're in a union, then assigning to a mutable field
2454 // (even an empty one) can change the active member, so that's not OK.
2455 // FIXME: Add core issue number for the union case.
2456 if (Field->isMutable() &&
2457 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002458 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002459 Info.Note(Field->getLocation(), diag::note_declared_at);
2460 return true;
2461 }
2462
2463 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2464 return true;
2465 }
2466
2467 for (auto &BaseSpec : RD->bases())
2468 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2469 return true;
2470
2471 // All mutable fields were empty, and thus not actually read.
2472 return false;
2473}
2474
Richard Smith861b5b52013-05-07 23:34:45 +00002475/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002476enum AccessKinds {
2477 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002478 AK_Assign,
2479 AK_Increment,
2480 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002481};
2482
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002483namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002484/// A handle to a complete object (an object that is not a subobject of
2485/// another object).
2486struct CompleteObject {
2487 /// The value of the complete object.
2488 APValue *Value;
2489 /// The type of the complete object.
2490 QualType Type;
2491
Craig Topper36250ad2014-05-12 05:36:57 +00002492 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002493 CompleteObject(APValue *Value, QualType Type)
2494 : Value(Value), Type(Type) {
2495 assert(Value && "missing value for complete object");
2496 }
2497
Aaron Ballman67347662015-02-15 22:00:28 +00002498 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002499};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002500} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002501
Richard Smith3da88fa2013-04-26 14:36:30 +00002502/// Find the designated sub-object of an rvalue.
2503template<typename SubobjectHandler>
2504typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002505findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002506 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002507 if (Sub.Invalid)
2508 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002509 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002510 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002511 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002512 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002513 << handler.AccessKind;
2514 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002515 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002516 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002517 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002518
Richard Smith3229b742013-05-05 21:17:10 +00002519 APValue *O = Obj.Value;
2520 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002521 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002522
Richard Smithd62306a2011-11-10 06:34:14 +00002523 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002524 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2525 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002526 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002527 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002528 return handler.failed();
2529 }
2530
Richard Smith49ca8aa2013-08-06 07:09:20 +00002531 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002532 // If we are reading an object of class type, there may still be more
2533 // things we need to check: if there are any mutable subobjects, we
2534 // cannot perform this read. (This only happens when performing a trivial
2535 // copy or assignment.)
2536 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2537 diagnoseUnreadableFields(Info, E, ObjType))
2538 return handler.failed();
2539
Richard Smith49ca8aa2013-08-06 07:09:20 +00002540 if (!handler.found(*O, ObjType))
2541 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002542
Richard Smith49ca8aa2013-08-06 07:09:20 +00002543 // If we modified a bit-field, truncate it to the right width.
2544 if (handler.AccessKind != AK_Read &&
2545 LastField && LastField->isBitField() &&
2546 !truncateBitfieldValue(Info, E, *O, LastField))
2547 return false;
2548
2549 return true;
2550 }
2551
Craig Topper36250ad2014-05-12 05:36:57 +00002552 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002553 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002554 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002555 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002556 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002557 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002558 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002559 // Note, it should not be possible to form a pointer with a valid
2560 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002561 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002562 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002563 << handler.AccessKind;
2564 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002565 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002566 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002567 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002568
2569 ObjType = CAT->getElementType();
2570
Richard Smith14a94132012-02-17 03:35:37 +00002571 // An array object is represented as either an Array APValue or as an
2572 // LValue which refers to a string literal.
2573 if (O->isLValue()) {
2574 assert(I == N - 1 && "extracting subobject of character?");
2575 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002576 if (handler.AccessKind != AK_Read)
2577 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2578 *O);
2579 else
2580 return handler.foundString(*O, ObjType, Index);
2581 }
2582
2583 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002584 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002585 else if (handler.AccessKind != AK_Read) {
2586 expandArray(*O, Index);
2587 O = &O->getArrayInitializedElt(Index);
2588 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002589 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002590 } else if (ObjType->isAnyComplexType()) {
2591 // Next subobject is a complex number.
2592 uint64_t Index = Sub.Entries[I].ArrayIndex;
2593 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002594 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002595 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002596 << handler.AccessKind;
2597 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002598 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002599 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002600 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002601
2602 bool WasConstQualified = ObjType.isConstQualified();
2603 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2604 if (WasConstQualified)
2605 ObjType.addConst();
2606
Richard Smith66c96992012-02-18 22:04:06 +00002607 assert(I == N - 1 && "extracting subobject of scalar?");
2608 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002609 return handler.found(Index ? O->getComplexIntImag()
2610 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002611 } else {
2612 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002613 return handler.found(Index ? O->getComplexFloatImag()
2614 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002615 }
Richard Smithd62306a2011-11-10 06:34:14 +00002616 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002617 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002618 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002619 << Field;
2620 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002621 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002622 }
2623
Richard Smithd62306a2011-11-10 06:34:14 +00002624 // Next subobject is a class, struct or union field.
2625 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2626 if (RD->isUnion()) {
2627 const FieldDecl *UnionField = O->getUnionField();
2628 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002629 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002630 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002631 << handler.AccessKind << Field << !UnionField << UnionField;
2632 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002633 }
Richard Smithd62306a2011-11-10 06:34:14 +00002634 O = &O->getUnionValue();
2635 } else
2636 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002637
2638 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002639 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002640 if (WasConstQualified && !Field->isMutable())
2641 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002642
2643 if (ObjType.isVolatileQualified()) {
2644 if (Info.getLangOpts().CPlusPlus) {
2645 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002646 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002647 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002648 Info.Note(Field->getLocation(), diag::note_declared_at);
2649 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002650 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002651 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002652 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002653 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002654
2655 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002656 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002657 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002658 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2659 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2660 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002661
2662 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002663 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002664 if (WasConstQualified)
2665 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002666 }
2667 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002668}
2669
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002670namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002671struct ExtractSubobjectHandler {
2672 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002673 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002674
2675 static const AccessKinds AccessKind = AK_Read;
2676
2677 typedef bool result_type;
2678 bool failed() { return false; }
2679 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002680 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002681 return true;
2682 }
2683 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002684 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002685 return true;
2686 }
2687 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002688 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002689 return true;
2690 }
2691 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002692 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002693 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2694 return true;
2695 }
2696};
Richard Smith3229b742013-05-05 21:17:10 +00002697} // end anonymous namespace
2698
Richard Smith3da88fa2013-04-26 14:36:30 +00002699const AccessKinds ExtractSubobjectHandler::AccessKind;
2700
2701/// Extract the designated sub-object of an rvalue.
2702static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002703 const CompleteObject &Obj,
2704 const SubobjectDesignator &Sub,
2705 APValue &Result) {
2706 ExtractSubobjectHandler Handler = { Info, Result };
2707 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002708}
2709
Richard Smith3229b742013-05-05 21:17:10 +00002710namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002711struct ModifySubobjectHandler {
2712 EvalInfo &Info;
2713 APValue &NewVal;
2714 const Expr *E;
2715
2716 typedef bool result_type;
2717 static const AccessKinds AccessKind = AK_Assign;
2718
2719 bool checkConst(QualType QT) {
2720 // Assigning to a const object has undefined behavior.
2721 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002722 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002723 return false;
2724 }
2725 return true;
2726 }
2727
2728 bool failed() { return false; }
2729 bool found(APValue &Subobj, QualType SubobjType) {
2730 if (!checkConst(SubobjType))
2731 return false;
2732 // We've been given ownership of NewVal, so just swap it in.
2733 Subobj.swap(NewVal);
2734 return true;
2735 }
2736 bool found(APSInt &Value, QualType SubobjType) {
2737 if (!checkConst(SubobjType))
2738 return false;
2739 if (!NewVal.isInt()) {
2740 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002741 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002742 return false;
2743 }
2744 Value = NewVal.getInt();
2745 return true;
2746 }
2747 bool found(APFloat &Value, QualType SubobjType) {
2748 if (!checkConst(SubobjType))
2749 return false;
2750 Value = NewVal.getFloat();
2751 return true;
2752 }
2753 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2754 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2755 }
2756};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002757} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002758
Richard Smith3229b742013-05-05 21:17:10 +00002759const AccessKinds ModifySubobjectHandler::AccessKind;
2760
Richard Smith3da88fa2013-04-26 14:36:30 +00002761/// Update the designated sub-object of an rvalue to the given value.
2762static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002763 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002764 const SubobjectDesignator &Sub,
2765 APValue &NewVal) {
2766 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002767 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002768}
2769
Richard Smith84f6dcf2012-02-02 01:16:57 +00002770/// Find the position where two subobject designators diverge, or equivalently
2771/// the length of the common initial subsequence.
2772static unsigned FindDesignatorMismatch(QualType ObjType,
2773 const SubobjectDesignator &A,
2774 const SubobjectDesignator &B,
2775 bool &WasArrayIndex) {
2776 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2777 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002778 if (!ObjType.isNull() &&
2779 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002780 // Next subobject is an array element.
2781 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2782 WasArrayIndex = true;
2783 return I;
2784 }
Richard Smith66c96992012-02-18 22:04:06 +00002785 if (ObjType->isAnyComplexType())
2786 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2787 else
2788 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002789 } else {
2790 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2791 WasArrayIndex = false;
2792 return I;
2793 }
2794 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2795 // Next subobject is a field.
2796 ObjType = FD->getType();
2797 else
2798 // Next subobject is a base class.
2799 ObjType = QualType();
2800 }
2801 }
2802 WasArrayIndex = false;
2803 return I;
2804}
2805
2806/// Determine whether the given subobject designators refer to elements of the
2807/// same array object.
2808static bool AreElementsOfSameArray(QualType ObjType,
2809 const SubobjectDesignator &A,
2810 const SubobjectDesignator &B) {
2811 if (A.Entries.size() != B.Entries.size())
2812 return false;
2813
George Burgess IVa51c4072015-10-16 01:49:01 +00002814 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002815 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2816 // A is a subobject of the array element.
2817 return false;
2818
2819 // If A (and B) designates an array element, the last entry will be the array
2820 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2821 // of length 1' case, and the entire path must match.
2822 bool WasArrayIndex;
2823 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2824 return CommonLength >= A.Entries.size() - IsArray;
2825}
2826
Richard Smith3229b742013-05-05 21:17:10 +00002827/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002828static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2829 AccessKinds AK, const LValue &LVal,
2830 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002831 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002832 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002833 return CompleteObject();
2834 }
2835
Craig Topper36250ad2014-05-12 05:36:57 +00002836 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002837 if (LVal.CallIndex) {
2838 Frame = Info.getCallFrame(LVal.CallIndex);
2839 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002840 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002841 << AK << LVal.Base.is<const ValueDecl*>();
2842 NoteLValueLocation(Info, LVal.Base);
2843 return CompleteObject();
2844 }
Richard Smith3229b742013-05-05 21:17:10 +00002845 }
2846
2847 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2848 // is not a constant expression (even if the object is non-volatile). We also
2849 // apply this rule to C++98, in order to conform to the expected 'volatile'
2850 // semantics.
2851 if (LValType.isVolatileQualified()) {
2852 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002853 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002854 << AK << LValType;
2855 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002856 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002857 return CompleteObject();
2858 }
2859
2860 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002861 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002862 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002863
2864 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2865 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2866 // In C++11, constexpr, non-volatile variables initialized with constant
2867 // expressions are constant expressions too. Inside constexpr functions,
2868 // parameters are constant expressions even if they're non-const.
2869 // In C++1y, objects local to a constant expression (those with a Frame) are
2870 // both readable and writable inside constant expressions.
2871 // In C, such things can also be folded, although they are not ICEs.
2872 const VarDecl *VD = dyn_cast<VarDecl>(D);
2873 if (VD) {
2874 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2875 VD = VDef;
2876 }
2877 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002878 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002879 return CompleteObject();
2880 }
2881
2882 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002883 if (BaseType.isVolatileQualified()) {
2884 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002885 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002886 << AK << 1 << VD;
2887 Info.Note(VD->getLocation(), diag::note_declared_at);
2888 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002889 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002890 }
2891 return CompleteObject();
2892 }
2893
2894 // Unless we're looking at a local variable or argument in a constexpr call,
2895 // the variable we're reading must be const.
2896 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002897 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002898 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2899 // OK, we can read and modify an object if we're in the process of
2900 // evaluating its initializer, because its lifetime began in this
2901 // evaluation.
2902 } else if (AK != AK_Read) {
2903 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002904 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002905 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00002906 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002907 // OK, we can read this variable.
2908 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002909 // In OpenCL if a variable is in constant address space it is a const value.
2910 if (!(BaseType.isConstQualified() ||
2911 (Info.getLangOpts().OpenCL &&
2912 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002913 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002914 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002915 Info.Note(VD->getLocation(), diag::note_declared_at);
2916 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002917 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002918 }
2919 return CompleteObject();
2920 }
2921 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2922 // We support folding of const floating-point types, in order to make
2923 // static const data members of such types (supported as an extension)
2924 // more useful.
2925 if (Info.getLangOpts().CPlusPlus11) {
2926 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2927 Info.Note(VD->getLocation(), diag::note_declared_at);
2928 } else {
2929 Info.CCEDiag(E);
2930 }
George Burgess IVb5316982016-12-27 05:33:20 +00002931 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
2932 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
2933 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00002934 } else {
2935 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002936 if (Info.checkingPotentialConstantExpression() &&
2937 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2938 // The definition of this variable could be constexpr. We can't
2939 // access it right now, but may be able to in future.
2940 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002941 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002942 Info.Note(VD->getLocation(), diag::note_declared_at);
2943 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002944 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002945 }
2946 return CompleteObject();
2947 }
2948 }
2949
2950 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2951 return CompleteObject();
2952 } else {
2953 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2954
2955 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002956 if (const MaterializeTemporaryExpr *MTE =
2957 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2958 assert(MTE->getStorageDuration() == SD_Static &&
2959 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002960
Richard Smithe6c01442013-06-05 00:46:14 +00002961 // Per C++1y [expr.const]p2:
2962 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2963 // - a [...] glvalue of integral or enumeration type that refers to
2964 // a non-volatile const object [...]
2965 // [...]
2966 // - a [...] glvalue of literal type that refers to a non-volatile
2967 // object whose lifetime began within the evaluation of e.
2968 //
2969 // C++11 misses the 'began within the evaluation of e' check and
2970 // instead allows all temporaries, including things like:
2971 // int &&r = 1;
2972 // int x = ++r;
2973 // constexpr int k = r;
2974 // Therefore we use the C++1y rules in C++11 too.
2975 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2976 const ValueDecl *ED = MTE->getExtendingDecl();
2977 if (!(BaseType.isConstQualified() &&
2978 BaseType->isIntegralOrEnumerationType()) &&
2979 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002980 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00002981 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2982 return CompleteObject();
2983 }
2984
2985 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2986 assert(BaseVal && "got reference to unevaluated temporary");
2987 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002988 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00002989 return CompleteObject();
2990 }
2991 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002992 BaseVal = Frame->getTemporary(Base);
2993 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002994 }
Richard Smith3229b742013-05-05 21:17:10 +00002995
2996 // Volatile temporary objects cannot be accessed in constant expressions.
2997 if (BaseType.isVolatileQualified()) {
2998 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002999 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003000 << AK << 0;
3001 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3002 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003003 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003004 }
3005 return CompleteObject();
3006 }
3007 }
3008
Richard Smith7525ff62013-05-09 07:14:00 +00003009 // During the construction of an object, it is not yet 'const'.
3010 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3011 // and this doesn't do quite the right thing for const subobjects of the
3012 // object under construction.
3013 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3014 BaseType = Info.Ctx.getCanonicalType(BaseType);
3015 BaseType.removeLocalConst();
3016 }
3017
Richard Smith6d4c6582013-11-05 22:18:15 +00003018 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003019 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003020 //
3021 // FIXME: Not all local state is mutable. Allow local constant subobjects
3022 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003023 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3024 Info.EvalStatus.HasSideEffects) ||
3025 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003026 return CompleteObject();
3027
3028 return CompleteObject(BaseVal, BaseType);
3029}
3030
Richard Smith243ef902013-05-05 23:31:59 +00003031/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3032/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3033/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003034///
3035/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003036/// \param Conv - The expression for which we are performing the conversion.
3037/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003038/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3039/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003040/// \param LVal - The glvalue on which we are attempting to perform this action.
3041/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003042static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003043 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003044 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003045 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003046 return false;
3047
Richard Smith3229b742013-05-05 21:17:10 +00003048 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003049 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003050 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003051 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3052 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3053 // initializer until now for such expressions. Such an expression can't be
3054 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003055 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003056 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003057 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003058 }
Richard Smith3229b742013-05-05 21:17:10 +00003059 APValue Lit;
3060 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3061 return false;
3062 CompleteObject LitObj(&Lit, Base->getType());
3063 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003064 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003065 // We represent a string literal array as an lvalue pointing at the
3066 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003067 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003068 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3069 CompleteObject StrObj(&Str, Base->getType());
3070 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003071 }
Richard Smith11562c52011-10-28 17:51:58 +00003072 }
3073
Richard Smith3229b742013-05-05 21:17:10 +00003074 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3075 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003076}
3077
3078/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003079static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003080 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003081 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003082 return false;
3083
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003084 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003085 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003086 return false;
3087 }
3088
Richard Smith3229b742013-05-05 21:17:10 +00003089 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3090 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003091}
3092
Richard Smith243ef902013-05-05 23:31:59 +00003093static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3094 return T->isSignedIntegerType() &&
3095 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3096}
3097
3098namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003099struct CompoundAssignSubobjectHandler {
3100 EvalInfo &Info;
3101 const Expr *E;
3102 QualType PromotedLHSType;
3103 BinaryOperatorKind Opcode;
3104 const APValue &RHS;
3105
3106 static const AccessKinds AccessKind = AK_Assign;
3107
3108 typedef bool result_type;
3109
3110 bool checkConst(QualType QT) {
3111 // Assigning to a const object has undefined behavior.
3112 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003113 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003114 return false;
3115 }
3116 return true;
3117 }
3118
3119 bool failed() { return false; }
3120 bool found(APValue &Subobj, QualType SubobjType) {
3121 switch (Subobj.getKind()) {
3122 case APValue::Int:
3123 return found(Subobj.getInt(), SubobjType);
3124 case APValue::Float:
3125 return found(Subobj.getFloat(), SubobjType);
3126 case APValue::ComplexInt:
3127 case APValue::ComplexFloat:
3128 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003129 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003130 return false;
3131 case APValue::LValue:
3132 return foundPointer(Subobj, SubobjType);
3133 default:
3134 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003135 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003136 return false;
3137 }
3138 }
3139 bool found(APSInt &Value, QualType SubobjType) {
3140 if (!checkConst(SubobjType))
3141 return false;
3142
3143 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3144 // We don't support compound assignment on integer-cast-to-pointer
3145 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003146 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003147 return false;
3148 }
3149
3150 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3151 SubobjType, Value);
3152 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3153 return false;
3154 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3155 return true;
3156 }
3157 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003158 return checkConst(SubobjType) &&
3159 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3160 Value) &&
3161 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3162 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003163 }
3164 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3165 if (!checkConst(SubobjType))
3166 return false;
3167
3168 QualType PointeeType;
3169 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3170 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003171
3172 if (PointeeType.isNull() || !RHS.isInt() ||
3173 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003174 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003175 return false;
3176 }
3177
Richard Smith861b5b52013-05-07 23:34:45 +00003178 int64_t Offset = getExtValue(RHS.getInt());
3179 if (Opcode == BO_Sub)
3180 Offset = -Offset;
3181
3182 LValue LVal;
3183 LVal.setFrom(Info.Ctx, Subobj);
3184 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3185 return false;
3186 LVal.moveInto(Subobj);
3187 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003188 }
3189 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3190 llvm_unreachable("shouldn't encounter string elements here");
3191 }
3192};
3193} // end anonymous namespace
3194
3195const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3196
3197/// Perform a compound assignment of LVal <op>= RVal.
3198static bool handleCompoundAssignment(
3199 EvalInfo &Info, const Expr *E,
3200 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3201 BinaryOperatorKind Opcode, const APValue &RVal) {
3202 if (LVal.Designator.Invalid)
3203 return false;
3204
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003205 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003206 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003207 return false;
3208 }
3209
3210 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3211 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3212 RVal };
3213 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3214}
3215
3216namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003217struct IncDecSubobjectHandler {
3218 EvalInfo &Info;
3219 const Expr *E;
3220 AccessKinds AccessKind;
3221 APValue *Old;
3222
3223 typedef bool result_type;
3224
3225 bool checkConst(QualType QT) {
3226 // Assigning to a const object has undefined behavior.
3227 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003228 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003229 return false;
3230 }
3231 return true;
3232 }
3233
3234 bool failed() { return false; }
3235 bool found(APValue &Subobj, QualType SubobjType) {
3236 // Stash the old value. Also clear Old, so we don't clobber it later
3237 // if we're post-incrementing a complex.
3238 if (Old) {
3239 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003240 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003241 }
3242
3243 switch (Subobj.getKind()) {
3244 case APValue::Int:
3245 return found(Subobj.getInt(), SubobjType);
3246 case APValue::Float:
3247 return found(Subobj.getFloat(), SubobjType);
3248 case APValue::ComplexInt:
3249 return found(Subobj.getComplexIntReal(),
3250 SubobjType->castAs<ComplexType>()->getElementType()
3251 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3252 case APValue::ComplexFloat:
3253 return found(Subobj.getComplexFloatReal(),
3254 SubobjType->castAs<ComplexType>()->getElementType()
3255 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3256 case APValue::LValue:
3257 return foundPointer(Subobj, SubobjType);
3258 default:
3259 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003260 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003261 return false;
3262 }
3263 }
3264 bool found(APSInt &Value, QualType SubobjType) {
3265 if (!checkConst(SubobjType))
3266 return false;
3267
3268 if (!SubobjType->isIntegerType()) {
3269 // We don't support increment / decrement on integer-cast-to-pointer
3270 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003271 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003272 return false;
3273 }
3274
3275 if (Old) *Old = APValue(Value);
3276
3277 // bool arithmetic promotes to int, and the conversion back to bool
3278 // doesn't reduce mod 2^n, so special-case it.
3279 if (SubobjType->isBooleanType()) {
3280 if (AccessKind == AK_Increment)
3281 Value = 1;
3282 else
3283 Value = !Value;
3284 return true;
3285 }
3286
3287 bool WasNegative = Value.isNegative();
3288 if (AccessKind == AK_Increment) {
3289 ++Value;
3290
3291 if (!WasNegative && Value.isNegative() &&
3292 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3293 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003294 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003295 }
3296 } else {
3297 --Value;
3298
3299 if (WasNegative && !Value.isNegative() &&
3300 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3301 unsigned BitWidth = Value.getBitWidth();
3302 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3303 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003304 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003305 }
3306 }
3307 return true;
3308 }
3309 bool found(APFloat &Value, QualType SubobjType) {
3310 if (!checkConst(SubobjType))
3311 return false;
3312
3313 if (Old) *Old = APValue(Value);
3314
3315 APFloat One(Value.getSemantics(), 1);
3316 if (AccessKind == AK_Increment)
3317 Value.add(One, APFloat::rmNearestTiesToEven);
3318 else
3319 Value.subtract(One, APFloat::rmNearestTiesToEven);
3320 return true;
3321 }
3322 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3323 if (!checkConst(SubobjType))
3324 return false;
3325
3326 QualType PointeeType;
3327 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3328 PointeeType = PT->getPointeeType();
3329 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003330 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003331 return false;
3332 }
3333
3334 LValue LVal;
3335 LVal.setFrom(Info.Ctx, Subobj);
3336 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3337 AccessKind == AK_Increment ? 1 : -1))
3338 return false;
3339 LVal.moveInto(Subobj);
3340 return true;
3341 }
3342 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3343 llvm_unreachable("shouldn't encounter string elements here");
3344 }
3345};
3346} // end anonymous namespace
3347
3348/// Perform an increment or decrement on LVal.
3349static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3350 QualType LValType, bool IsIncrement, APValue *Old) {
3351 if (LVal.Designator.Invalid)
3352 return false;
3353
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003354 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003355 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003356 return false;
3357 }
3358
3359 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3360 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3361 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3362 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3363}
3364
Richard Smithe97cbd72011-11-11 04:05:33 +00003365/// Build an lvalue for the object argument of a member function call.
3366static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3367 LValue &This) {
3368 if (Object->getType()->isPointerType())
3369 return EvaluatePointer(Object, This, Info);
3370
3371 if (Object->isGLValue())
3372 return EvaluateLValue(Object, This, Info);
3373
Richard Smithd9f663b2013-04-22 15:31:51 +00003374 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003375 return EvaluateTemporary(Object, This, Info);
3376
Faisal Valie690b7a2016-07-02 22:34:24 +00003377 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003378 return false;
3379}
3380
3381/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3382/// lvalue referring to the result.
3383///
3384/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003385/// \param LV - An lvalue referring to the base of the member pointer.
3386/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003387/// \param IncludeMember - Specifies whether the member itself is included in
3388/// the resulting LValue subobject designator. This is not possible when
3389/// creating a bound member function.
3390/// \return The field or method declaration to which the member pointer refers,
3391/// or 0 if evaluation fails.
3392static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003393 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003394 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003395 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003396 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003397 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003398 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003399 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003400
3401 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3402 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003403 if (!MemPtr.getDecl()) {
3404 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003405 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003406 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003407 }
Richard Smith253c2a32012-01-27 01:14:48 +00003408
Richard Smith027bf112011-11-17 22:56:20 +00003409 if (MemPtr.isDerivedMember()) {
3410 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003411 // The end of the derived-to-base path for the base object must match the
3412 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003413 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003414 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003415 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003416 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003417 }
Richard Smith027bf112011-11-17 22:56:20 +00003418 unsigned PathLengthToMember =
3419 LV.Designator.Entries.size() - MemPtr.Path.size();
3420 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3421 const CXXRecordDecl *LVDecl = getAsBaseClass(
3422 LV.Designator.Entries[PathLengthToMember + I]);
3423 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003424 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003425 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003426 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003427 }
Richard Smith027bf112011-11-17 22:56:20 +00003428 }
3429
3430 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003431 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003432 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003433 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003434 } else if (!MemPtr.Path.empty()) {
3435 // Extend the LValue path with the member pointer's path.
3436 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3437 MemPtr.Path.size() + IncludeMember);
3438
3439 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003440 if (const PointerType *PT = LVType->getAs<PointerType>())
3441 LVType = PT->getPointeeType();
3442 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3443 assert(RD && "member pointer access on non-class-type expression");
3444 // The first class in the path is that of the lvalue.
3445 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3446 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003447 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003448 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003449 RD = Base;
3450 }
3451 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003452 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3453 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003454 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003455 }
3456
3457 // Add the member. Note that we cannot build bound member functions here.
3458 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003459 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003460 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003461 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003462 } else if (const IndirectFieldDecl *IFD =
3463 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003464 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003465 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003466 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003467 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003468 }
Richard Smith027bf112011-11-17 22:56:20 +00003469 }
3470
3471 return MemPtr.getDecl();
3472}
3473
Richard Smith84401042013-06-03 05:03:02 +00003474static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3475 const BinaryOperator *BO,
3476 LValue &LV,
3477 bool IncludeMember = true) {
3478 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3479
3480 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003481 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003482 MemberPtr MemPtr;
3483 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3484 }
Craig Topper36250ad2014-05-12 05:36:57 +00003485 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003486 }
3487
3488 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3489 BO->getRHS(), IncludeMember);
3490}
3491
Richard Smith027bf112011-11-17 22:56:20 +00003492/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3493/// the provided lvalue, which currently refers to the base object.
3494static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3495 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003496 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003497 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003498 return false;
3499
Richard Smitha8105bc2012-01-06 16:39:00 +00003500 QualType TargetQT = E->getType();
3501 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3502 TargetQT = PT->getPointeeType();
3503
3504 // Check this cast lands within the final derived-to-base subobject path.
3505 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003506 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003507 << D.MostDerivedType << TargetQT;
3508 return false;
3509 }
3510
Richard Smith027bf112011-11-17 22:56:20 +00003511 // Check the type of the final cast. We don't need to check the path,
3512 // since a cast can only be formed if the path is unique.
3513 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003514 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3515 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003516 if (NewEntriesSize == D.MostDerivedPathLength)
3517 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3518 else
Richard Smith027bf112011-11-17 22:56:20 +00003519 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003520 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003521 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003522 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003523 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003524 }
Richard Smith027bf112011-11-17 22:56:20 +00003525
3526 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003527 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003528}
3529
Mike Stump876387b2009-10-27 22:09:17 +00003530namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003531enum EvalStmtResult {
3532 /// Evaluation failed.
3533 ESR_Failed,
3534 /// Hit a 'return' statement.
3535 ESR_Returned,
3536 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003537 ESR_Succeeded,
3538 /// Hit a 'continue' statement.
3539 ESR_Continue,
3540 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003541 ESR_Break,
3542 /// Still scanning for 'case' or 'default' statement.
3543 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003544};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003545}
Richard Smith254a73d2011-10-28 22:34:42 +00003546
Richard Smith97fcf4b2016-08-14 23:15:52 +00003547static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3548 // We don't need to evaluate the initializer for a static local.
3549 if (!VD->hasLocalStorage())
3550 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003551
Richard Smith97fcf4b2016-08-14 23:15:52 +00003552 LValue Result;
3553 Result.set(VD, Info.CurrentCall->Index);
3554 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003555
Richard Smith97fcf4b2016-08-14 23:15:52 +00003556 const Expr *InitE = VD->getInit();
3557 if (!InitE) {
3558 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3559 << false << VD->getType();
3560 Val = APValue();
3561 return false;
3562 }
Richard Smith51f03172013-06-20 03:00:05 +00003563
Richard Smith97fcf4b2016-08-14 23:15:52 +00003564 if (InitE->isValueDependent())
3565 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003566
Richard Smith97fcf4b2016-08-14 23:15:52 +00003567 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3568 // Wipe out any partially-computed value, to allow tracking that this
3569 // evaluation failed.
3570 Val = APValue();
3571 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003572 }
3573
3574 return true;
3575}
3576
Richard Smith97fcf4b2016-08-14 23:15:52 +00003577static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3578 bool OK = true;
3579
3580 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3581 OK &= EvaluateVarDecl(Info, VD);
3582
3583 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3584 for (auto *BD : DD->bindings())
3585 if (auto *VD = BD->getHoldingVar())
3586 OK &= EvaluateDecl(Info, VD);
3587
3588 return OK;
3589}
3590
3591
Richard Smith4e18ca52013-05-06 05:56:11 +00003592/// Evaluate a condition (either a variable declaration or an expression).
3593static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3594 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003595 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003596 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3597 return false;
3598 return EvaluateAsBooleanCondition(Cond, Result, Info);
3599}
3600
Richard Smith89210072016-04-04 23:29:43 +00003601namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003602/// \brief A location where the result (returned value) of evaluating a
3603/// statement should be stored.
3604struct StmtResult {
3605 /// The APValue that should be filled in with the returned value.
3606 APValue &Value;
3607 /// The location containing the result, if any (used to support RVO).
3608 const LValue *Slot;
3609};
Richard Smith89210072016-04-04 23:29:43 +00003610}
Richard Smith52a980a2015-08-28 02:43:42 +00003611
3612static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003613 const Stmt *S,
3614 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003615
3616/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003617static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003618 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003619 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003620 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003621 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003622 case ESR_Break:
3623 return ESR_Succeeded;
3624 case ESR_Succeeded:
3625 case ESR_Continue:
3626 return ESR_Continue;
3627 case ESR_Failed:
3628 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003629 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003630 return ESR;
3631 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003632 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003633}
3634
Richard Smith496ddcf2013-05-12 17:32:42 +00003635/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003636static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003637 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003638 BlockScopeRAII Scope(Info);
3639
Richard Smith496ddcf2013-05-12 17:32:42 +00003640 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003641 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003642 {
3643 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003644 if (const Stmt *Init = SS->getInit()) {
3645 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3646 if (ESR != ESR_Succeeded)
3647 return ESR;
3648 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003649 if (SS->getConditionVariable() &&
3650 !EvaluateDecl(Info, SS->getConditionVariable()))
3651 return ESR_Failed;
3652 if (!EvaluateInteger(SS->getCond(), Value, Info))
3653 return ESR_Failed;
3654 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003655
3656 // Find the switch case corresponding to the value of the condition.
3657 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003658 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003659 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3660 SC = SC->getNextSwitchCase()) {
3661 if (isa<DefaultStmt>(SC)) {
3662 Found = SC;
3663 continue;
3664 }
3665
3666 const CaseStmt *CS = cast<CaseStmt>(SC);
3667 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3668 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3669 : LHS;
3670 if (LHS <= Value && Value <= RHS) {
3671 Found = SC;
3672 break;
3673 }
3674 }
3675
3676 if (!Found)
3677 return ESR_Succeeded;
3678
3679 // Search the switch body for the switch case and evaluate it from there.
3680 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3681 case ESR_Break:
3682 return ESR_Succeeded;
3683 case ESR_Succeeded:
3684 case ESR_Continue:
3685 case ESR_Failed:
3686 case ESR_Returned:
3687 return ESR;
3688 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003689 // This can only happen if the switch case is nested within a statement
3690 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003691 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003692 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003693 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003694 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003695}
3696
Richard Smith254a73d2011-10-28 22:34:42 +00003697// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003698static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003699 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003700 if (!Info.nextStep(S))
3701 return ESR_Failed;
3702
Richard Smith496ddcf2013-05-12 17:32:42 +00003703 // If we're hunting down a 'case' or 'default' label, recurse through
3704 // substatements until we hit the label.
3705 if (Case) {
3706 // FIXME: We don't start the lifetime of objects whose initialization we
3707 // jump over. However, such objects must be of class type with a trivial
3708 // default constructor that initialize all subobjects, so must be empty,
3709 // so this almost never matters.
3710 switch (S->getStmtClass()) {
3711 case Stmt::CompoundStmtClass:
3712 // FIXME: Precompute which substatement of a compound statement we
3713 // would jump to, and go straight there rather than performing a
3714 // linear scan each time.
3715 case Stmt::LabelStmtClass:
3716 case Stmt::AttributedStmtClass:
3717 case Stmt::DoStmtClass:
3718 break;
3719
3720 case Stmt::CaseStmtClass:
3721 case Stmt::DefaultStmtClass:
3722 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003723 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003724 break;
3725
3726 case Stmt::IfStmtClass: {
3727 // FIXME: Precompute which side of an 'if' we would jump to, and go
3728 // straight there rather than scanning both sides.
3729 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003730
3731 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3732 // preceded by our switch label.
3733 BlockScopeRAII Scope(Info);
3734
Richard Smith496ddcf2013-05-12 17:32:42 +00003735 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3736 if (ESR != ESR_CaseNotFound || !IS->getElse())
3737 return ESR;
3738 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3739 }
3740
3741 case Stmt::WhileStmtClass: {
3742 EvalStmtResult ESR =
3743 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3744 if (ESR != ESR_Continue)
3745 return ESR;
3746 break;
3747 }
3748
3749 case Stmt::ForStmtClass: {
3750 const ForStmt *FS = cast<ForStmt>(S);
3751 EvalStmtResult ESR =
3752 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3753 if (ESR != ESR_Continue)
3754 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003755 if (FS->getInc()) {
3756 FullExpressionRAII IncScope(Info);
3757 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3758 return ESR_Failed;
3759 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003760 break;
3761 }
3762
3763 case Stmt::DeclStmtClass:
3764 // FIXME: If the variable has initialization that can't be jumped over,
3765 // bail out of any immediately-surrounding compound-statement too.
3766 default:
3767 return ESR_CaseNotFound;
3768 }
3769 }
3770
Richard Smith254a73d2011-10-28 22:34:42 +00003771 switch (S->getStmtClass()) {
3772 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003773 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003774 // Don't bother evaluating beyond an expression-statement which couldn't
3775 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003776 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003777 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003778 return ESR_Failed;
3779 return ESR_Succeeded;
3780 }
3781
Faisal Valie690b7a2016-07-02 22:34:24 +00003782 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003783 return ESR_Failed;
3784
3785 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003786 return ESR_Succeeded;
3787
Richard Smithd9f663b2013-04-22 15:31:51 +00003788 case Stmt::DeclStmtClass: {
3789 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003790 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003791 // Each declaration initialization is its own full-expression.
3792 // FIXME: This isn't quite right; if we're performing aggregate
3793 // initialization, each braced subexpression is its own full-expression.
3794 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003795 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003796 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003797 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003798 return ESR_Succeeded;
3799 }
3800
Richard Smith357362d2011-12-13 06:39:58 +00003801 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003802 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003803 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003804 if (RetExpr &&
3805 !(Result.Slot
3806 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3807 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003808 return ESR_Failed;
3809 return ESR_Returned;
3810 }
Richard Smith254a73d2011-10-28 22:34:42 +00003811
3812 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003813 BlockScopeRAII Scope(Info);
3814
Richard Smith254a73d2011-10-28 22:34:42 +00003815 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003816 for (const auto *BI : CS->body()) {
3817 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003818 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003819 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003820 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003821 return ESR;
3822 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003823 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003824 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003825
3826 case Stmt::IfStmtClass: {
3827 const IfStmt *IS = cast<IfStmt>(S);
3828
3829 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003830 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003831 if (const Stmt *Init = IS->getInit()) {
3832 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3833 if (ESR != ESR_Succeeded)
3834 return ESR;
3835 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003836 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003837 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003838 return ESR_Failed;
3839
3840 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3841 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3842 if (ESR != ESR_Succeeded)
3843 return ESR;
3844 }
3845 return ESR_Succeeded;
3846 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003847
3848 case Stmt::WhileStmtClass: {
3849 const WhileStmt *WS = cast<WhileStmt>(S);
3850 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003851 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003852 bool Continue;
3853 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3854 Continue))
3855 return ESR_Failed;
3856 if (!Continue)
3857 break;
3858
3859 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3860 if (ESR != ESR_Continue)
3861 return ESR;
3862 }
3863 return ESR_Succeeded;
3864 }
3865
3866 case Stmt::DoStmtClass: {
3867 const DoStmt *DS = cast<DoStmt>(S);
3868 bool Continue;
3869 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003870 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003871 if (ESR != ESR_Continue)
3872 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003873 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003874
Richard Smith08d6a2c2013-07-24 07:11:57 +00003875 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003876 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3877 return ESR_Failed;
3878 } while (Continue);
3879 return ESR_Succeeded;
3880 }
3881
3882 case Stmt::ForStmtClass: {
3883 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003884 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003885 if (FS->getInit()) {
3886 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3887 if (ESR != ESR_Succeeded)
3888 return ESR;
3889 }
3890 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003891 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003892 bool Continue = true;
3893 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3894 FS->getCond(), Continue))
3895 return ESR_Failed;
3896 if (!Continue)
3897 break;
3898
3899 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3900 if (ESR != ESR_Continue)
3901 return ESR;
3902
Richard Smith08d6a2c2013-07-24 07:11:57 +00003903 if (FS->getInc()) {
3904 FullExpressionRAII IncScope(Info);
3905 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3906 return ESR_Failed;
3907 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003908 }
3909 return ESR_Succeeded;
3910 }
3911
Richard Smith896e0d72013-05-06 06:51:17 +00003912 case Stmt::CXXForRangeStmtClass: {
3913 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003914 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003915
3916 // Initialize the __range variable.
3917 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3918 if (ESR != ESR_Succeeded)
3919 return ESR;
3920
3921 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003922 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3923 if (ESR != ESR_Succeeded)
3924 return ESR;
3925 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003926 if (ESR != ESR_Succeeded)
3927 return ESR;
3928
3929 while (true) {
3930 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003931 {
3932 bool Continue = true;
3933 FullExpressionRAII CondExpr(Info);
3934 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3935 return ESR_Failed;
3936 if (!Continue)
3937 break;
3938 }
Richard Smith896e0d72013-05-06 06:51:17 +00003939
3940 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003941 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003942 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3943 if (ESR != ESR_Succeeded)
3944 return ESR;
3945
3946 // Loop body.
3947 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3948 if (ESR != ESR_Continue)
3949 return ESR;
3950
3951 // Increment: ++__begin
3952 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3953 return ESR_Failed;
3954 }
3955
3956 return ESR_Succeeded;
3957 }
3958
Richard Smith496ddcf2013-05-12 17:32:42 +00003959 case Stmt::SwitchStmtClass:
3960 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3961
Richard Smith4e18ca52013-05-06 05:56:11 +00003962 case Stmt::ContinueStmtClass:
3963 return ESR_Continue;
3964
3965 case Stmt::BreakStmtClass:
3966 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003967
3968 case Stmt::LabelStmtClass:
3969 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3970
3971 case Stmt::AttributedStmtClass:
3972 // As a general principle, C++11 attributes can be ignored without
3973 // any semantic impact.
3974 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3975 Case);
3976
3977 case Stmt::CaseStmtClass:
3978 case Stmt::DefaultStmtClass:
3979 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003980 }
3981}
3982
Richard Smithcc36f692011-12-22 02:22:31 +00003983/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3984/// default constructor. If so, we'll fold it whether or not it's marked as
3985/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3986/// so we need special handling.
3987static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003988 const CXXConstructorDecl *CD,
3989 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003990 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3991 return false;
3992
Richard Smith66e05fe2012-01-18 05:21:49 +00003993 // Value-initialization does not call a trivial default constructor, so such a
3994 // call is a core constant expression whether or not the constructor is
3995 // constexpr.
3996 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003997 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003998 // FIXME: If DiagDecl is an implicitly-declared special member function,
3999 // we should be much more explicit about why it's not constexpr.
4000 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4001 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4002 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004003 } else {
4004 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4005 }
4006 }
4007 return true;
4008}
4009
Richard Smith357362d2011-12-13 06:39:58 +00004010/// CheckConstexprFunction - Check that a function can be called in a constant
4011/// expression.
4012static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4013 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004014 const FunctionDecl *Definition,
4015 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004016 // Potential constant expressions can contain calls to declared, but not yet
4017 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004018 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004019 Declaration->isConstexpr())
4020 return false;
4021
Richard Smith0838f3a2013-05-14 05:18:44 +00004022 // Bail out with no diagnostic if the function declaration itself is invalid.
4023 // We will have produced a relevant diagnostic while parsing it.
4024 if (Declaration->isInvalidDecl())
4025 return false;
4026
Richard Smith357362d2011-12-13 06:39:58 +00004027 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004028 if (Definition && Definition->isConstexpr() &&
4029 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004030 return true;
4031
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004032 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004033 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00004034
Richard Smith5179eb72016-06-28 19:03:57 +00004035 // If this function is not constexpr because it is an inherited
4036 // non-constexpr constructor, diagnose that directly.
4037 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4038 if (CD && CD->isInheritingConstructor()) {
4039 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4040 if (!Inherited->isConstexpr())
4041 DiagDecl = CD = Inherited;
4042 }
4043
4044 // FIXME: If DiagDecl is an implicitly-declared special member function
4045 // or an inheriting constructor, we should be much more explicit about why
4046 // it's not constexpr.
4047 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004048 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004049 << CD->getInheritedConstructor().getConstructor()->getParent();
4050 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004051 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004052 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004053 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4054 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004055 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004056 }
4057 return false;
4058}
4059
Richard Smithbe6dd812014-11-19 21:27:17 +00004060/// Determine if a class has any fields that might need to be copied by a
4061/// trivial copy or move operation.
4062static bool hasFields(const CXXRecordDecl *RD) {
4063 if (!RD || RD->isEmpty())
4064 return false;
4065 for (auto *FD : RD->fields()) {
4066 if (FD->isUnnamedBitfield())
4067 continue;
4068 return true;
4069 }
4070 for (auto &Base : RD->bases())
4071 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4072 return true;
4073 return false;
4074}
4075
Richard Smithd62306a2011-11-10 06:34:14 +00004076namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004077typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004078}
4079
4080/// EvaluateArgs - Evaluate the arguments to a function call.
4081static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4082 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004083 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004084 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004085 I != E; ++I) {
4086 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4087 // If we're checking for a potential constant expression, evaluate all
4088 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004089 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004090 return false;
4091 Success = false;
4092 }
4093 }
4094 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004095}
4096
Richard Smith254a73d2011-10-28 22:34:42 +00004097/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004098static bool HandleFunctionCall(SourceLocation CallLoc,
4099 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004100 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004101 EvalInfo &Info, APValue &Result,
4102 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004103 ArgVector ArgValues(Args.size());
4104 if (!EvaluateArgs(Args, ArgValues, Info))
4105 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004106
Richard Smith253c2a32012-01-27 01:14:48 +00004107 if (!Info.CheckCallLimit(CallLoc))
4108 return false;
4109
4110 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004111
4112 // For a trivial copy or move assignment, perform an APValue copy. This is
4113 // essential for unions, where the operations performed by the assignment
4114 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004115 //
4116 // Skip this for non-union classes with no fields; in that case, the defaulted
4117 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004118 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004119 if (MD && MD->isDefaulted() &&
4120 (MD->getParent()->isUnion() ||
4121 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004122 assert(This &&
4123 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4124 LValue RHS;
4125 RHS.setFrom(Info.Ctx, ArgValues[0]);
4126 APValue RHSValue;
4127 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4128 RHS, RHSValue))
4129 return false;
4130 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4131 RHSValue))
4132 return false;
4133 This->moveInto(Result);
4134 return true;
4135 }
4136
Richard Smith52a980a2015-08-28 02:43:42 +00004137 StmtResult Ret = {Result, ResultSlot};
4138 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004139 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004140 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004141 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004142 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004143 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004144 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004145}
4146
Richard Smithd62306a2011-11-10 06:34:14 +00004147/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004148static bool HandleConstructorCall(const Expr *E, const LValue &This,
4149 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004150 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004151 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004152 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004153 if (!Info.CheckCallLimit(CallLoc))
4154 return false;
4155
Richard Smith3607ffe2012-02-13 03:54:03 +00004156 const CXXRecordDecl *RD = Definition->getParent();
4157 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004158 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004159 return false;
4160 }
4161
Richard Smith5179eb72016-06-28 19:03:57 +00004162 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004163
Richard Smith52a980a2015-08-28 02:43:42 +00004164 // FIXME: Creating an APValue just to hold a nonexistent return value is
4165 // wasteful.
4166 APValue RetVal;
4167 StmtResult Ret = {RetVal, nullptr};
4168
Richard Smith5179eb72016-06-28 19:03:57 +00004169 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004170 if (Definition->isDelegatingConstructor()) {
4171 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004172 {
4173 FullExpressionRAII InitScope(Info);
4174 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4175 return false;
4176 }
Richard Smith52a980a2015-08-28 02:43:42 +00004177 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004178 }
4179
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004180 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004181 // essential for unions (or classes with anonymous union members), where the
4182 // operations performed by the constructor cannot be represented by
4183 // ctor-initializers.
4184 //
4185 // Skip this for empty non-union classes; we should not perform an
4186 // lvalue-to-rvalue conversion on them because their copy constructor does not
4187 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004188 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004189 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004190 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004191 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004192 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004193 return handleLValueToRValueConversion(
4194 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4195 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004196 }
4197
4198 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004199 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004200 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004201 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004202
John McCalld7bca762012-05-01 00:38:49 +00004203 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004204 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4205
Richard Smith08d6a2c2013-07-24 07:11:57 +00004206 // A scope for temporaries lifetime-extended by reference members.
4207 BlockScopeRAII LifetimeExtendedScope(Info);
4208
Richard Smith253c2a32012-01-27 01:14:48 +00004209 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004210 unsigned BasesSeen = 0;
4211#ifndef NDEBUG
4212 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4213#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004214 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004215 LValue Subobject = This;
4216 APValue *Value = &Result;
4217
4218 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004219 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004220 if (I->isBaseInitializer()) {
4221 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004222#ifndef NDEBUG
4223 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004224 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004225 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4226 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4227 "base class initializers not in expected order");
4228 ++BaseIt;
4229#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004230 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004231 BaseType->getAsCXXRecordDecl(), &Layout))
4232 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004233 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004234 } else if ((FD = I->getMember())) {
4235 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004236 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004237 if (RD->isUnion()) {
4238 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004239 Value = &Result.getUnionValue();
4240 } else {
4241 Value = &Result.getStructField(FD->getFieldIndex());
4242 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004243 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004244 // Walk the indirect field decl's chain to find the object to initialize,
4245 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004246 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004247 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004248 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4249 // Switch the union field if it differs. This happens if we had
4250 // preceding zero-initialization, and we're now initializing a union
4251 // subobject other than the first.
4252 // FIXME: In this case, the values of the other subobjects are
4253 // specified, since zero-initialization sets all padding bits to zero.
4254 if (Value->isUninit() ||
4255 (Value->isUnion() && Value->getUnionField() != FD)) {
4256 if (CD->isUnion())
4257 *Value = APValue(FD);
4258 else
4259 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004260 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004261 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004262 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004263 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004264 if (CD->isUnion())
4265 Value = &Value->getUnionValue();
4266 else
4267 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004268 }
Richard Smithd62306a2011-11-10 06:34:14 +00004269 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004270 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004271 }
Richard Smith253c2a32012-01-27 01:14:48 +00004272
Richard Smith08d6a2c2013-07-24 07:11:57 +00004273 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004274 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4275 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004276 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004277 // If we're checking for a potential constant expression, evaluate all
4278 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004279 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004280 return false;
4281 Success = false;
4282 }
Richard Smithd62306a2011-11-10 06:34:14 +00004283 }
4284
Richard Smithd9f663b2013-04-22 15:31:51 +00004285 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004286 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004287}
4288
Richard Smith5179eb72016-06-28 19:03:57 +00004289static bool HandleConstructorCall(const Expr *E, const LValue &This,
4290 ArrayRef<const Expr*> Args,
4291 const CXXConstructorDecl *Definition,
4292 EvalInfo &Info, APValue &Result) {
4293 ArgVector ArgValues(Args.size());
4294 if (!EvaluateArgs(Args, ArgValues, Info))
4295 return false;
4296
4297 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4298 Info, Result);
4299}
4300
Eli Friedman9a156e52008-11-12 09:44:48 +00004301//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004302// Generic Evaluation
4303//===----------------------------------------------------------------------===//
4304namespace {
4305
Aaron Ballman68af21c2014-01-03 19:26:43 +00004306template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004307class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004308 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004309private:
Richard Smith52a980a2015-08-28 02:43:42 +00004310 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004311 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004312 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004313 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004314 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004315 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004316 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004317
Richard Smith17100ba2012-02-16 02:46:34 +00004318 // Check whether a conditional operator with a non-constant condition is a
4319 // potential constant expression. If neither arm is a potential constant
4320 // expression, then the conditional operator is not either.
4321 template<typename ConditionalOperator>
4322 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004323 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004324
4325 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004326 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004327 {
Richard Smith17100ba2012-02-16 02:46:34 +00004328 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004329 StmtVisitorTy::Visit(E->getFalseExpr());
4330 if (Diag.empty())
4331 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004332 }
Richard Smith17100ba2012-02-16 02:46:34 +00004333
George Burgess IV8c892b52016-05-25 22:31:54 +00004334 {
4335 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004336 Diag.clear();
4337 StmtVisitorTy::Visit(E->getTrueExpr());
4338 if (Diag.empty())
4339 return;
4340 }
4341
4342 Error(E, diag::note_constexpr_conditional_never_const);
4343 }
4344
4345
4346 template<typename ConditionalOperator>
4347 bool HandleConditionalOperator(const ConditionalOperator *E) {
4348 bool BoolResult;
4349 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004350 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004351 CheckPotentialConstantConditional(E);
4352 return false;
4353 }
4354
4355 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4356 return StmtVisitorTy::Visit(EvalExpr);
4357 }
4358
Peter Collingbournee9200682011-05-13 03:29:01 +00004359protected:
4360 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004361 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004362 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4363
Richard Smith92b1ce02011-12-12 09:28:41 +00004364 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004365 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004366 }
4367
Aaron Ballman68af21c2014-01-03 19:26:43 +00004368 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004369
4370public:
4371 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4372
4373 EvalInfo &getEvalInfo() { return Info; }
4374
Richard Smithf57d8cb2011-12-09 22:58:01 +00004375 /// Report an evaluation error. This should only be called when an error is
4376 /// first discovered. When propagating an error, just return false.
4377 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004378 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004379 return false;
4380 }
4381 bool Error(const Expr *E) {
4382 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4383 }
4384
Aaron Ballman68af21c2014-01-03 19:26:43 +00004385 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004386 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004387 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004388 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004389 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004390 }
4391
Aaron Ballman68af21c2014-01-03 19:26:43 +00004392 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004393 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004394 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004395 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004396 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004397 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004398 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004399 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004400 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004401 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004402 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004403 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004404 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004405 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004406 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004407 // The initializer may not have been parsed yet, or might be erroneous.
4408 if (!E->getExpr())
4409 return Error(E);
4410 return StmtVisitorTy::Visit(E->getExpr());
4411 }
Richard Smith5894a912011-12-19 22:12:41 +00004412 // We cannot create any objects for which cleanups are required, so there is
4413 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004414 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004415 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004416
Aaron Ballman68af21c2014-01-03 19:26:43 +00004417 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004418 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4419 return static_cast<Derived*>(this)->VisitCastExpr(E);
4420 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004421 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004422 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4423 return static_cast<Derived*>(this)->VisitCastExpr(E);
4424 }
4425
Aaron Ballman68af21c2014-01-03 19:26:43 +00004426 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004427 switch (E->getOpcode()) {
4428 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004429 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004430
4431 case BO_Comma:
4432 VisitIgnoredValue(E->getLHS());
4433 return StmtVisitorTy::Visit(E->getRHS());
4434
4435 case BO_PtrMemD:
4436 case BO_PtrMemI: {
4437 LValue Obj;
4438 if (!HandleMemberPointerAccess(Info, E, Obj))
4439 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004440 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004441 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004442 return false;
4443 return DerivedSuccess(Result, E);
4444 }
4445 }
4446 }
4447
Aaron Ballman68af21c2014-01-03 19:26:43 +00004448 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004449 // Evaluate and cache the common expression. We treat it as a temporary,
4450 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004451 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004452 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004453 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004454
Richard Smith17100ba2012-02-16 02:46:34 +00004455 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004456 }
4457
Aaron Ballman68af21c2014-01-03 19:26:43 +00004458 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004459 bool IsBcpCall = false;
4460 // If the condition (ignoring parens) is a __builtin_constant_p call,
4461 // the result is a constant expression if it can be folded without
4462 // side-effects. This is an important GNU extension. See GCC PR38377
4463 // for discussion.
4464 if (const CallExpr *CallCE =
4465 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004466 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004467 IsBcpCall = true;
4468
4469 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4470 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004471 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004472 return false;
4473
Richard Smith6d4c6582013-11-05 22:18:15 +00004474 FoldConstant Fold(Info, IsBcpCall);
4475 if (!HandleConditionalOperator(E)) {
4476 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004477 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004478 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004479
4480 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004481 }
4482
Aaron Ballman68af21c2014-01-03 19:26:43 +00004483 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004484 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4485 return DerivedSuccess(*Value, E);
4486
4487 const Expr *Source = E->getSourceExpr();
4488 if (!Source)
4489 return Error(E);
4490 if (Source == E) { // sanity checking.
4491 assert(0 && "OpaqueValueExpr recursively refers to itself");
4492 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004493 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004494 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004495 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004496
Aaron Ballman68af21c2014-01-03 19:26:43 +00004497 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004498 APValue Result;
4499 if (!handleCallExpr(E, Result, nullptr))
4500 return false;
4501 return DerivedSuccess(Result, E);
4502 }
4503
4504 bool handleCallExpr(const CallExpr *E, APValue &Result,
4505 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004506 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004507 QualType CalleeType = Callee->getType();
4508
Craig Topper36250ad2014-05-12 05:36:57 +00004509 const FunctionDecl *FD = nullptr;
4510 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004511 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004512 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004513
Richard Smithe97cbd72011-11-11 04:05:33 +00004514 // Extract function decl and 'this' pointer from the callee.
4515 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004516 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004517 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4518 // Explicit bound member calls, such as x.f() or p->g();
4519 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004520 return false;
4521 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004522 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004523 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004524 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4525 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004526 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4527 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004528 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004529 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004530 return Error(Callee);
4531
4532 FD = dyn_cast<FunctionDecl>(Member);
4533 if (!FD)
4534 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004535 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004536 LValue Call;
4537 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004538 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004539
Richard Smitha8105bc2012-01-06 16:39:00 +00004540 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004541 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004542 FD = dyn_cast_or_null<FunctionDecl>(
4543 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004544 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004545 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004546
4547 // Overloaded operator calls to member functions are represented as normal
4548 // calls with '*this' as the first argument.
4549 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4550 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004551 // FIXME: When selecting an implicit conversion for an overloaded
4552 // operator delete, we sometimes try to evaluate calls to conversion
4553 // operators without a 'this' parameter!
4554 if (Args.empty())
4555 return Error(E);
4556
Richard Smithe97cbd72011-11-11 04:05:33 +00004557 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4558 return false;
4559 This = &ThisVal;
4560 Args = Args.slice(1);
4561 }
4562
4563 // Don't call function pointers which have been cast to some other type.
Richard Smithdfe85e22016-12-15 02:35:39 +00004564 // Per DR (no number yet), the caller and callee can differ in noexcept.
4565 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4566 CalleeType->getPointeeType(), FD->getType())) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004567 return Error(E);
Richard Smithdfe85e22016-12-15 02:35:39 +00004568 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004569 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004570 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004571
Richard Smith47b34932012-02-01 02:39:43 +00004572 if (This && !This->checkSubobject(Info, E, CSK_This))
4573 return false;
4574
Richard Smith3607ffe2012-02-13 03:54:03 +00004575 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4576 // calls to such functions in constant expressions.
4577 if (This && !HasQualifier &&
4578 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4579 return Error(E, diag::note_constexpr_virtual_call);
4580
Craig Topper36250ad2014-05-12 05:36:57 +00004581 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004582 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004583
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004584 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004585 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4586 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004587 return false;
4588
Richard Smith52a980a2015-08-28 02:43:42 +00004589 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004590 }
4591
Aaron Ballman68af21c2014-01-03 19:26:43 +00004592 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004593 return StmtVisitorTy::Visit(E->getInitializer());
4594 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004595 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004596 if (E->getNumInits() == 0)
4597 return DerivedZeroInitialization(E);
4598 if (E->getNumInits() == 1)
4599 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004600 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004601 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004602 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004603 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004604 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004605 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004606 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004607 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004608 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004609 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004610 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004611
Richard Smithd62306a2011-11-10 06:34:14 +00004612 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004613 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004614 assert(!E->isArrow() && "missing call to bound member function?");
4615
Richard Smith2e312c82012-03-03 22:46:17 +00004616 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004617 if (!Evaluate(Val, Info, E->getBase()))
4618 return false;
4619
4620 QualType BaseTy = E->getBase()->getType();
4621
4622 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004623 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004624 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004625 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004626 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4627
Richard Smith3229b742013-05-05 21:17:10 +00004628 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004629 SubobjectDesignator Designator(BaseTy);
4630 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004631
Richard Smith3229b742013-05-05 21:17:10 +00004632 APValue Result;
4633 return extractSubobject(Info, E, Obj, Designator, Result) &&
4634 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004635 }
4636
Aaron Ballman68af21c2014-01-03 19:26:43 +00004637 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004638 switch (E->getCastKind()) {
4639 default:
4640 break;
4641
Richard Smitha23ab512013-05-23 00:30:41 +00004642 case CK_AtomicToNonAtomic: {
4643 APValue AtomicVal;
4644 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4645 return false;
4646 return DerivedSuccess(AtomicVal, E);
4647 }
4648
Richard Smith11562c52011-10-28 17:51:58 +00004649 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004650 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004651 return StmtVisitorTy::Visit(E->getSubExpr());
4652
4653 case CK_LValueToRValue: {
4654 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004655 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4656 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004657 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004658 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004659 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004660 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004661 return false;
4662 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004663 }
4664 }
4665
Richard Smithf57d8cb2011-12-09 22:58:01 +00004666 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004667 }
4668
Aaron Ballman68af21c2014-01-03 19:26:43 +00004669 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004670 return VisitUnaryPostIncDec(UO);
4671 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004672 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004673 return VisitUnaryPostIncDec(UO);
4674 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004675 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004676 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004677 return Error(UO);
4678
4679 LValue LVal;
4680 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4681 return false;
4682 APValue RVal;
4683 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4684 UO->isIncrementOp(), &RVal))
4685 return false;
4686 return DerivedSuccess(RVal, UO);
4687 }
4688
Aaron Ballman68af21c2014-01-03 19:26:43 +00004689 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004690 // We will have checked the full-expressions inside the statement expression
4691 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004692 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004693 return Error(E);
4694
Richard Smith08d6a2c2013-07-24 07:11:57 +00004695 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004696 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004697 if (CS->body_empty())
4698 return true;
4699
Richard Smith51f03172013-06-20 03:00:05 +00004700 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4701 BE = CS->body_end();
4702 /**/; ++BI) {
4703 if (BI + 1 == BE) {
4704 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4705 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004706 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004707 diag::note_constexpr_stmt_expr_unsupported);
4708 return false;
4709 }
4710 return this->Visit(FinalExpr);
4711 }
4712
4713 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004714 StmtResult Result = { ReturnValue, nullptr };
4715 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004716 if (ESR != ESR_Succeeded) {
4717 // FIXME: If the statement-expression terminated due to 'return',
4718 // 'break', or 'continue', it would be nice to propagate that to
4719 // the outer statement evaluation rather than bailing out.
4720 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004721 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004722 diag::note_constexpr_stmt_expr_unsupported);
4723 return false;
4724 }
4725 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004726
4727 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004728 }
4729
Richard Smith4a678122011-10-24 18:44:57 +00004730 /// Visit a value which is evaluated, but whose value is ignored.
4731 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004732 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004733 }
David Majnemere9807b22016-02-26 04:23:19 +00004734
4735 /// Potentially visit a MemberExpr's base expression.
4736 void VisitIgnoredBaseExpression(const Expr *E) {
4737 // While MSVC doesn't evaluate the base expression, it does diagnose the
4738 // presence of side-effecting behavior.
4739 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4740 return;
4741 VisitIgnoredValue(E);
4742 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004743};
4744
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004745}
Peter Collingbournee9200682011-05-13 03:29:01 +00004746
4747//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004748// Common base class for lvalue and temporary evaluation.
4749//===----------------------------------------------------------------------===//
4750namespace {
4751template<class Derived>
4752class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004753 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004754protected:
4755 LValue &Result;
4756 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004757 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004758
4759 bool Success(APValue::LValueBase B) {
4760 Result.set(B);
4761 return true;
4762 }
4763
4764public:
4765 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4766 ExprEvaluatorBaseTy(Info), Result(Result) {}
4767
Richard Smith2e312c82012-03-03 22:46:17 +00004768 bool Success(const APValue &V, const Expr *E) {
4769 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004770 return true;
4771 }
Richard Smith027bf112011-11-17 22:56:20 +00004772
Richard Smith027bf112011-11-17 22:56:20 +00004773 bool VisitMemberExpr(const MemberExpr *E) {
4774 // Handle non-static data members.
4775 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004776 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004777 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004778 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004779 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004780 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004781 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004782 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004783 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004784 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004785 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004786 BaseTy = E->getBase()->getType();
4787 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004788 if (!EvalOK) {
4789 if (!this->Info.allowInvalidBaseExpr())
4790 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004791 Result.setInvalid(E);
4792 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004793 }
Richard Smith027bf112011-11-17 22:56:20 +00004794
Richard Smith1b78b3d2012-01-25 22:15:11 +00004795 const ValueDecl *MD = E->getMemberDecl();
4796 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4797 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4798 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4799 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004800 if (!HandleLValueMember(this->Info, E, Result, FD))
4801 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004802 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004803 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4804 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004805 } else
4806 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004807
Richard Smith1b78b3d2012-01-25 22:15:11 +00004808 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004809 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004810 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004811 RefValue))
4812 return false;
4813 return Success(RefValue, E);
4814 }
4815 return true;
4816 }
4817
4818 bool VisitBinaryOperator(const BinaryOperator *E) {
4819 switch (E->getOpcode()) {
4820 default:
4821 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4822
4823 case BO_PtrMemD:
4824 case BO_PtrMemI:
4825 return HandleMemberPointerAccess(this->Info, E, Result);
4826 }
4827 }
4828
4829 bool VisitCastExpr(const CastExpr *E) {
4830 switch (E->getCastKind()) {
4831 default:
4832 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4833
4834 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004835 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004836 if (!this->Visit(E->getSubExpr()))
4837 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004838
4839 // Now figure out the necessary offset to add to the base LV to get from
4840 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004841 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4842 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004843 }
4844 }
4845};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004846}
Richard Smith027bf112011-11-17 22:56:20 +00004847
4848//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004849// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004850//
4851// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4852// function designators (in C), decl references to void objects (in C), and
4853// temporaries (if building with -Wno-address-of-temporary).
4854//
4855// LValue evaluation produces values comprising a base expression of one of the
4856// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004857// - Declarations
4858// * VarDecl
4859// * FunctionDecl
4860// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00004861// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00004862// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004863// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004864// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004865// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004866// * ObjCEncodeExpr
4867// * AddrLabelExpr
4868// * BlockExpr
4869// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004870// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004871// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004872// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004873// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4874// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004875// * A MaterializeTemporaryExpr that has static storage duration, with no
4876// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004877// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004878//===----------------------------------------------------------------------===//
4879namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004880class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004881 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004882public:
Richard Smith027bf112011-11-17 22:56:20 +00004883 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4884 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004885
Richard Smith11562c52011-10-28 17:51:58 +00004886 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004887 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004888
Peter Collingbournee9200682011-05-13 03:29:01 +00004889 bool VisitDeclRefExpr(const DeclRefExpr *E);
4890 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004891 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004892 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4893 bool VisitMemberExpr(const MemberExpr *E);
4894 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4895 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004896 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004897 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004898 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4899 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004900 bool VisitUnaryReal(const UnaryOperator *E);
4901 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004902 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4903 return VisitUnaryPreIncDec(UO);
4904 }
4905 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4906 return VisitUnaryPreIncDec(UO);
4907 }
Richard Smith3229b742013-05-05 21:17:10 +00004908 bool VisitBinAssign(const BinaryOperator *BO);
4909 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004910
Peter Collingbournee9200682011-05-13 03:29:01 +00004911 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004912 switch (E->getCastKind()) {
4913 default:
Richard Smith027bf112011-11-17 22:56:20 +00004914 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004915
Eli Friedmance3e02a2011-10-11 00:13:24 +00004916 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004917 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004918 if (!Visit(E->getSubExpr()))
4919 return false;
4920 Result.Designator.setInvalid();
4921 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004922
Richard Smith027bf112011-11-17 22:56:20 +00004923 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004924 if (!Visit(E->getSubExpr()))
4925 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004926 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004927 }
4928 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004929};
4930} // end anonymous namespace
4931
Richard Smith11562c52011-10-28 17:51:58 +00004932/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004933/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004934/// * function designators in C, and
4935/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004936/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004937static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4938 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004939 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004940 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004941}
4942
Peter Collingbournee9200682011-05-13 03:29:01 +00004943bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004944 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004945 return Success(FD);
4946 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004947 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00004948 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00004949 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00004950 return Error(E);
4951}
Richard Smith733237d2011-10-24 23:14:33 +00004952
Faisal Vali0528a312016-11-13 06:09:16 +00004953
Richard Smith11562c52011-10-28 17:51:58 +00004954bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004955 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00004956 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
4957 // Only if a local variable was declared in the function currently being
4958 // evaluated, do we expect to be able to find its value in the current
4959 // frame. (Otherwise it was likely declared in an enclosing context and
4960 // could either have a valid evaluatable value (for e.g. a constexpr
4961 // variable) or be ill-formed (and trigger an appropriate evaluation
4962 // diagnostic)).
4963 if (Info.CurrentCall->Callee &&
4964 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
4965 Frame = Info.CurrentCall;
4966 }
4967 }
Richard Smith3229b742013-05-05 21:17:10 +00004968
Richard Smithfec09922011-11-01 16:57:24 +00004969 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004970 if (Frame) {
4971 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004972 return true;
4973 }
Richard Smithce40ad62011-11-12 22:28:03 +00004974 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004975 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004976
Richard Smith3229b742013-05-05 21:17:10 +00004977 APValue *V;
4978 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004979 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004980 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004981 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00004982 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004983 return false;
4984 }
Richard Smith3229b742013-05-05 21:17:10 +00004985 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004986}
4987
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004988bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4989 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004990 // Walk through the expression to find the materialized temporary itself.
4991 SmallVector<const Expr *, 2> CommaLHSs;
4992 SmallVector<SubobjectAdjustment, 2> Adjustments;
4993 const Expr *Inner = E->GetTemporaryExpr()->
4994 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004995
Richard Smith84401042013-06-03 05:03:02 +00004996 // If we passed any comma operators, evaluate their LHSs.
4997 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4998 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4999 return false;
5000
Richard Smithe6c01442013-06-05 00:46:14 +00005001 // A materialized temporary with static storage duration can appear within the
5002 // result of a constant expression evaluation, so we need to preserve its
5003 // value for use outside this evaluation.
5004 APValue *Value;
5005 if (E->getStorageDuration() == SD_Static) {
5006 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005007 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005008 Result.set(E);
5009 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005010 Value = &Info.CurrentCall->
5011 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005012 Result.set(E, Info.CurrentCall->Index);
5013 }
5014
Richard Smithea4ad5d2013-06-06 08:19:16 +00005015 QualType Type = Inner->getType();
5016
Richard Smith84401042013-06-03 05:03:02 +00005017 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005018 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5019 (E->getStorageDuration() == SD_Static &&
5020 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5021 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005022 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005023 }
Richard Smith84401042013-06-03 05:03:02 +00005024
5025 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005026 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5027 --I;
5028 switch (Adjustments[I].Kind) {
5029 case SubobjectAdjustment::DerivedToBaseAdjustment:
5030 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5031 Type, Result))
5032 return false;
5033 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5034 break;
5035
5036 case SubobjectAdjustment::FieldAdjustment:
5037 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5038 return false;
5039 Type = Adjustments[I].Field->getType();
5040 break;
5041
5042 case SubobjectAdjustment::MemberPointerAdjustment:
5043 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5044 Adjustments[I].Ptr.RHS))
5045 return false;
5046 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5047 break;
5048 }
5049 }
5050
5051 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005052}
5053
Peter Collingbournee9200682011-05-13 03:29:01 +00005054bool
5055LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005056 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5057 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005058 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5059 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005060 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005061}
5062
Richard Smith6e525142011-12-27 12:18:28 +00005063bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005064 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005065 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005066
Faisal Valie690b7a2016-07-02 22:34:24 +00005067 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005068 << E->getExprOperand()->getType()
5069 << E->getExprOperand()->getSourceRange();
5070 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005071}
5072
Francois Pichet0066db92012-04-16 04:08:35 +00005073bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5074 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005075}
Francois Pichet0066db92012-04-16 04:08:35 +00005076
Peter Collingbournee9200682011-05-13 03:29:01 +00005077bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005078 // Handle static data members.
5079 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005080 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005081 return VisitVarDecl(E, VD);
5082 }
5083
Richard Smith254a73d2011-10-28 22:34:42 +00005084 // Handle static member functions.
5085 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5086 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005087 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005088 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005089 }
5090 }
5091
Richard Smithd62306a2011-11-10 06:34:14 +00005092 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005093 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005094}
5095
Peter Collingbournee9200682011-05-13 03:29:01 +00005096bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005097 // FIXME: Deal with vectors as array subscript bases.
5098 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005099 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005100
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005101 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00005102 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005103
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005104 APSInt Index;
5105 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005106 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005107
Richard Smith861b5b52013-05-07 23:34:45 +00005108 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
5109 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005110}
Eli Friedman9a156e52008-11-12 09:44:48 +00005111
Peter Collingbournee9200682011-05-13 03:29:01 +00005112bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00005113 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005114}
5115
Richard Smith66c96992012-02-18 22:04:06 +00005116bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5117 if (!Visit(E->getSubExpr()))
5118 return false;
5119 // __real is a no-op on scalar lvalues.
5120 if (E->getSubExpr()->getType()->isAnyComplexType())
5121 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5122 return true;
5123}
5124
5125bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5126 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5127 "lvalue __imag__ on scalar?");
5128 if (!Visit(E->getSubExpr()))
5129 return false;
5130 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5131 return true;
5132}
5133
Richard Smith243ef902013-05-05 23:31:59 +00005134bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005135 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005136 return Error(UO);
5137
5138 if (!this->Visit(UO->getSubExpr()))
5139 return false;
5140
Richard Smith243ef902013-05-05 23:31:59 +00005141 return handleIncDec(
5142 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005143 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005144}
5145
5146bool LValueExprEvaluator::VisitCompoundAssignOperator(
5147 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005148 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005149 return Error(CAO);
5150
Richard Smith3229b742013-05-05 21:17:10 +00005151 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005152
5153 // The overall lvalue result is the result of evaluating the LHS.
5154 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005155 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005156 Evaluate(RHS, this->Info, CAO->getRHS());
5157 return false;
5158 }
5159
Richard Smith3229b742013-05-05 21:17:10 +00005160 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5161 return false;
5162
Richard Smith43e77732013-05-07 04:50:00 +00005163 return handleCompoundAssignment(
5164 this->Info, CAO,
5165 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5166 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005167}
5168
5169bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005170 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005171 return Error(E);
5172
Richard Smith3229b742013-05-05 21:17:10 +00005173 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005174
5175 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005176 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005177 Evaluate(NewVal, this->Info, E->getRHS());
5178 return false;
5179 }
5180
Richard Smith3229b742013-05-05 21:17:10 +00005181 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5182 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005183
5184 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005185 NewVal);
5186}
5187
Eli Friedman9a156e52008-11-12 09:44:48 +00005188//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005189// Pointer Evaluation
5190//===----------------------------------------------------------------------===//
5191
George Burgess IVe3763372016-12-22 02:50:20 +00005192/// \brief Attempts to compute the number of bytes available at the pointer
5193/// returned by a function with the alloc_size attribute. Returns true if we
5194/// were successful. Places an unsigned number into `Result`.
5195///
5196/// This expects the given CallExpr to be a call to a function with an
5197/// alloc_size attribute.
5198static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5199 const CallExpr *Call,
5200 llvm::APInt &Result) {
5201 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5202
5203 // alloc_size args are 1-indexed, 0 means not present.
5204 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5205 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5206 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5207 if (Call->getNumArgs() <= SizeArgNo)
5208 return false;
5209
5210 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5211 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5212 return false;
5213 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5214 return false;
5215 Into = Into.zextOrSelf(BitsInSizeT);
5216 return true;
5217 };
5218
5219 APSInt SizeOfElem;
5220 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5221 return false;
5222
5223 if (!AllocSize->getNumElemsParam()) {
5224 Result = std::move(SizeOfElem);
5225 return true;
5226 }
5227
5228 APSInt NumberOfElems;
5229 // Argument numbers start at 1
5230 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5231 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5232 return false;
5233
5234 bool Overflow;
5235 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5236 if (Overflow)
5237 return false;
5238
5239 Result = std::move(BytesAvailable);
5240 return true;
5241}
5242
5243/// \brief Convenience function. LVal's base must be a call to an alloc_size
5244/// function.
5245static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5246 const LValue &LVal,
5247 llvm::APInt &Result) {
5248 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5249 "Can't get the size of a non alloc_size function");
5250 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5251 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5252 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5253}
5254
5255/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5256/// a function with the alloc_size attribute. If it was possible to do so, this
5257/// function will return true, make Result's Base point to said function call,
5258/// and mark Result's Base as invalid.
5259static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5260 LValue &Result) {
5261 if (!Info.allowInvalidBaseExpr() || Base.isNull())
5262 return false;
5263
5264 // Because we do no form of static analysis, we only support const variables.
5265 //
5266 // Additionally, we can't support parameters, nor can we support static
5267 // variables (in the latter case, use-before-assign isn't UB; in the former,
5268 // we have no clue what they'll be assigned to).
5269 const auto *VD =
5270 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5271 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5272 return false;
5273
5274 const Expr *Init = VD->getAnyInitializer();
5275 if (!Init)
5276 return false;
5277
5278 const Expr *E = Init->IgnoreParens();
5279 if (!tryUnwrapAllocSizeCall(E))
5280 return false;
5281
5282 // Store E instead of E unwrapped so that the type of the LValue's base is
5283 // what the user wanted.
5284 Result.setInvalid(E);
5285
5286 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5287 Result.addUnsizedArray(Info, Pointee);
5288 return true;
5289}
5290
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005291namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005292class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005293 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005294 LValue &Result;
5295
Peter Collingbournee9200682011-05-13 03:29:01 +00005296 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005297 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005298 return true;
5299 }
George Burgess IVe3763372016-12-22 02:50:20 +00005300
5301 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005302public:
Mike Stump11289f42009-09-09 15:08:12 +00005303
John McCall45d55e42010-05-07 21:00:08 +00005304 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005305 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005306
Richard Smith2e312c82012-03-03 22:46:17 +00005307 bool Success(const APValue &V, const Expr *E) {
5308 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005309 return true;
5310 }
Richard Smithfddd3842011-12-30 21:15:51 +00005311 bool ZeroInitialization(const Expr *E) {
Yaxun Liu402804b2016-12-15 08:09:08 +00005312 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5313 Result.set((Expr*)nullptr, 0, false, true, Offset);
5314 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005315 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005316
John McCall45d55e42010-05-07 21:00:08 +00005317 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005318 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005319 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005320 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005321 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005322 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005323 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005324 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005325 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005326 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005327 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005328 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005329 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005330 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005331 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005332 }
Richard Smithd62306a2011-11-10 06:34:14 +00005333 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005334 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005335 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005336 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005337 if (!Info.CurrentCall->This) {
5338 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005339 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005340 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005341 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005342 return false;
5343 }
Richard Smithd62306a2011-11-10 06:34:14 +00005344 Result = *Info.CurrentCall->This;
5345 return true;
5346 }
John McCallc07a0c72011-02-17 10:25:35 +00005347
Eli Friedman449fe542009-03-23 04:56:01 +00005348 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005349};
Chris Lattner05706e882008-07-11 18:11:29 +00005350} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005351
John McCall45d55e42010-05-07 21:00:08 +00005352static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005353 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005354 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005355}
5356
John McCall45d55e42010-05-07 21:00:08 +00005357bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005358 if (E->getOpcode() != BO_Add &&
5359 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005360 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005361
Chris Lattner05706e882008-07-11 18:11:29 +00005362 const Expr *PExp = E->getLHS();
5363 const Expr *IExp = E->getRHS();
5364 if (IExp->getType()->isPointerType())
5365 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005366
Richard Smith253c2a32012-01-27 01:14:48 +00005367 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005368 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005369 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005370
John McCall45d55e42010-05-07 21:00:08 +00005371 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005372 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005373 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005374
5375 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00005376 if (E->getOpcode() == BO_Sub)
5377 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00005378
Ted Kremenek28831752012-08-23 20:46:57 +00005379 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00005380 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5381 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00005382}
Eli Friedman9a156e52008-11-12 09:44:48 +00005383
John McCall45d55e42010-05-07 21:00:08 +00005384bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5385 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005386}
Mike Stump11289f42009-09-09 15:08:12 +00005387
Peter Collingbournee9200682011-05-13 03:29:01 +00005388bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5389 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005390
Eli Friedman847a2bc2009-12-27 05:43:15 +00005391 switch (E->getCastKind()) {
5392 default:
5393 break;
5394
John McCalle3027922010-08-25 11:45:40 +00005395 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005396 case CK_CPointerToObjCPointerCast:
5397 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005398 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005399 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005400 if (!Visit(SubExpr))
5401 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005402 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5403 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5404 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005405 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005406 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005407 if (SubExpr->getType()->isVoidPointerType())
5408 CCEDiag(E, diag::note_constexpr_invalid_cast)
5409 << 3 << SubExpr->getType();
5410 else
5411 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5412 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005413 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5414 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005415 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005416
Anders Carlsson18275092010-10-31 20:41:46 +00005417 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005418 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005419 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005420 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005421 if (!Result.Base && Result.Offset.isZero())
5422 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005423
Richard Smithd62306a2011-11-10 06:34:14 +00005424 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005425 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005426 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5427 castAs<PointerType>()->getPointeeType(),
5428 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005429
Richard Smith027bf112011-11-17 22:56:20 +00005430 case CK_BaseToDerived:
5431 if (!Visit(E->getSubExpr()))
5432 return false;
5433 if (!Result.Base && Result.Offset.isZero())
5434 return true;
5435 return HandleBaseToDerivedCast(Info, E, Result);
5436
Richard Smith0b0a0b62011-10-29 20:57:55 +00005437 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005438 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005439 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005440
John McCalle3027922010-08-25 11:45:40 +00005441 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005442 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5443
Richard Smith2e312c82012-03-03 22:46:17 +00005444 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005445 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005446 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005447
John McCall45d55e42010-05-07 21:00:08 +00005448 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005449 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5450 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005451 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005452 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005453 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005454 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005455 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005456 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005457 return true;
5458 } else {
5459 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005460 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005461 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005462 }
5463 }
John McCalle3027922010-08-25 11:45:40 +00005464 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005465 if (SubExpr->isGLValue()) {
5466 if (!EvaluateLValue(SubExpr, Result, Info))
5467 return false;
5468 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005469 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005470 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005471 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005472 return false;
5473 }
Richard Smith96e0c102011-11-04 02:25:55 +00005474 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005475 if (const ConstantArrayType *CAT
5476 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5477 Result.addArray(Info, E, CAT);
5478 else
5479 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005480 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005481
John McCalle3027922010-08-25 11:45:40 +00005482 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005483 return EvaluateLValue(SubExpr, Result, Info);
George Burgess IVe3763372016-12-22 02:50:20 +00005484
5485 case CK_LValueToRValue: {
5486 LValue LVal;
5487 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5488 return false;
5489
5490 APValue RVal;
5491 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5492 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5493 LVal, RVal))
5494 return evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5495 return Success(RVal, E);
5496 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005497 }
5498
Richard Smith11562c52011-10-28 17:51:58 +00005499 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005500}
Chris Lattner05706e882008-07-11 18:11:29 +00005501
Hal Finkel0dd05d42014-10-03 17:18:37 +00005502static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5503 // C++ [expr.alignof]p3:
5504 // When alignof is applied to a reference type, the result is the
5505 // alignment of the referenced type.
5506 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5507 T = Ref->getPointeeType();
5508
5509 // __alignof is defined to return the preferred alignment.
5510 return Info.Ctx.toCharUnitsFromBits(
5511 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5512}
5513
5514static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5515 E = E->IgnoreParens();
5516
5517 // The kinds of expressions that we have special-case logic here for
5518 // should be kept up to date with the special checks for those
5519 // expressions in Sema.
5520
5521 // alignof decl is always accepted, even if it doesn't make sense: we default
5522 // to 1 in those cases.
5523 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5524 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5525 /*RefAsPointee*/true);
5526
5527 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5528 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5529 /*RefAsPointee*/true);
5530
5531 return GetAlignOfType(Info, E->getType());
5532}
5533
George Burgess IVe3763372016-12-22 02:50:20 +00005534// To be clear: this happily visits unsupported builtins. Better name welcomed.
5535bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5536 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5537 return true;
5538
5539 if (!(Info.allowInvalidBaseExpr() && getAllocSizeAttr(E)))
5540 return false;
5541
5542 Result.setInvalid(E);
5543 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5544 Result.addUnsizedArray(Info, PointeeTy);
5545 return true;
5546}
5547
Peter Collingbournee9200682011-05-13 03:29:01 +00005548bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005549 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005550 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005551
Richard Smith6328cbd2016-11-16 00:57:23 +00005552 if (unsigned BuiltinOp = E->getBuiltinCallee())
5553 return VisitBuiltinCallExpr(E, BuiltinOp);
5554
George Burgess IVe3763372016-12-22 02:50:20 +00005555 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005556}
5557
5558bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5559 unsigned BuiltinOp) {
5560 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005561 case Builtin::BI__builtin_addressof:
5562 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005563 case Builtin::BI__builtin_assume_aligned: {
5564 // We need to be very careful here because: if the pointer does not have the
5565 // asserted alignment, then the behavior is undefined, and undefined
5566 // behavior is non-constant.
5567 if (!EvaluatePointer(E->getArg(0), Result, Info))
5568 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005569
Hal Finkel0dd05d42014-10-03 17:18:37 +00005570 LValue OffsetResult(Result);
5571 APSInt Alignment;
5572 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5573 return false;
5574 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5575
5576 if (E->getNumArgs() > 2) {
5577 APSInt Offset;
5578 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5579 return false;
5580
5581 int64_t AdditionalOffset = -getExtValue(Offset);
5582 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5583 }
5584
5585 // If there is a base object, then it must have the correct alignment.
5586 if (OffsetResult.Base) {
5587 CharUnits BaseAlignment;
5588 if (const ValueDecl *VD =
5589 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5590 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5591 } else {
5592 BaseAlignment =
5593 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5594 }
5595
5596 if (BaseAlignment < Align) {
5597 Result.Designator.setInvalid();
Yaron Kerene0bcdd42016-10-08 06:45:10 +00005598 // FIXME: Quantities here cast to integers because the plural modifier
5599 // does not work on APSInts yet.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005600 CCEDiag(E->getArg(0),
5601 diag::note_constexpr_baa_insufficient_alignment) << 0
5602 << (int) BaseAlignment.getQuantity()
5603 << (unsigned) getExtValue(Alignment);
5604 return false;
5605 }
5606 }
5607
5608 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005609 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005610 Result.Designator.setInvalid();
5611 APSInt Offset(64, false);
5612 Offset = OffsetResult.Offset.getQuantity();
5613
5614 if (OffsetResult.Base)
5615 CCEDiag(E->getArg(0),
5616 diag::note_constexpr_baa_insufficient_alignment) << 1
5617 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5618 else
5619 CCEDiag(E->getArg(0),
5620 diag::note_constexpr_baa_value_insufficient_alignment)
5621 << Offset << (unsigned) getExtValue(Alignment);
5622
5623 return false;
5624 }
5625
5626 return true;
5627 }
Richard Smithe9507952016-11-12 01:39:56 +00005628
5629 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005630 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005631 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005632 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005633 if (Info.getLangOpts().CPlusPlus11)
5634 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5635 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005636 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005637 else
5638 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5639 // Fall through.
5640 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005641 case Builtin::BI__builtin_wcschr:
5642 case Builtin::BI__builtin_memchr:
5643 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005644 if (!Visit(E->getArg(0)))
5645 return false;
5646 APSInt Desired;
5647 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5648 return false;
5649 uint64_t MaxLength = uint64_t(-1);
5650 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005651 BuiltinOp != Builtin::BIwcschr &&
5652 BuiltinOp != Builtin::BI__builtin_strchr &&
5653 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005654 APSInt N;
5655 if (!EvaluateInteger(E->getArg(2), N, Info))
5656 return false;
5657 MaxLength = N.getExtValue();
5658 }
5659
Richard Smith8110c9d2016-11-29 19:45:17 +00005660 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005661
Richard Smith8110c9d2016-11-29 19:45:17 +00005662 // Figure out what value we're actually looking for (after converting to
5663 // the corresponding unsigned type if necessary).
5664 uint64_t DesiredVal;
5665 bool StopAtNull = false;
5666 switch (BuiltinOp) {
5667 case Builtin::BIstrchr:
5668 case Builtin::BI__builtin_strchr:
5669 // strchr compares directly to the passed integer, and therefore
5670 // always fails if given an int that is not a char.
5671 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5672 E->getArg(1)->getType(),
5673 Desired),
5674 Desired))
5675 return ZeroInitialization(E);
5676 StopAtNull = true;
5677 // Fall through.
5678 case Builtin::BImemchr:
5679 case Builtin::BI__builtin_memchr:
5680 // memchr compares by converting both sides to unsigned char. That's also
5681 // correct for strchr if we get this far (to cope with plain char being
5682 // unsigned in the strchr case).
5683 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5684 break;
Richard Smithe9507952016-11-12 01:39:56 +00005685
Richard Smith8110c9d2016-11-29 19:45:17 +00005686 case Builtin::BIwcschr:
5687 case Builtin::BI__builtin_wcschr:
5688 StopAtNull = true;
5689 // Fall through.
5690 case Builtin::BIwmemchr:
5691 case Builtin::BI__builtin_wmemchr:
5692 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5693 DesiredVal = Desired.getZExtValue();
5694 break;
5695 }
Richard Smithe9507952016-11-12 01:39:56 +00005696
5697 for (; MaxLength; --MaxLength) {
5698 APValue Char;
5699 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5700 !Char.isInt())
5701 return false;
5702 if (Char.getInt().getZExtValue() == DesiredVal)
5703 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005704 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005705 break;
5706 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5707 return false;
5708 }
5709 // Not found: return nullptr.
5710 return ZeroInitialization(E);
5711 }
5712
Richard Smith6cbd65d2013-07-11 02:27:57 +00005713 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005714 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005715 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005716}
Chris Lattner05706e882008-07-11 18:11:29 +00005717
5718//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005719// Member Pointer Evaluation
5720//===----------------------------------------------------------------------===//
5721
5722namespace {
5723class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005724 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005725 MemberPtr &Result;
5726
5727 bool Success(const ValueDecl *D) {
5728 Result = MemberPtr(D);
5729 return true;
5730 }
5731public:
5732
5733 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5734 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5735
Richard Smith2e312c82012-03-03 22:46:17 +00005736 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005737 Result.setFrom(V);
5738 return true;
5739 }
Richard Smithfddd3842011-12-30 21:15:51 +00005740 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005741 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005742 }
5743
5744 bool VisitCastExpr(const CastExpr *E);
5745 bool VisitUnaryAddrOf(const UnaryOperator *E);
5746};
5747} // end anonymous namespace
5748
5749static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5750 EvalInfo &Info) {
5751 assert(E->isRValue() && E->getType()->isMemberPointerType());
5752 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5753}
5754
5755bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5756 switch (E->getCastKind()) {
5757 default:
5758 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5759
5760 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005761 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005762 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005763
5764 case CK_BaseToDerivedMemberPointer: {
5765 if (!Visit(E->getSubExpr()))
5766 return false;
5767 if (E->path_empty())
5768 return true;
5769 // Base-to-derived member pointer casts store the path in derived-to-base
5770 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5771 // the wrong end of the derived->base arc, so stagger the path by one class.
5772 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5773 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5774 PathI != PathE; ++PathI) {
5775 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5776 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5777 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005778 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005779 }
5780 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5781 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005782 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005783 return true;
5784 }
5785
5786 case CK_DerivedToBaseMemberPointer:
5787 if (!Visit(E->getSubExpr()))
5788 return false;
5789 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5790 PathE = E->path_end(); PathI != PathE; ++PathI) {
5791 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5792 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5793 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005794 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005795 }
5796 return true;
5797 }
5798}
5799
5800bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5801 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5802 // member can be formed.
5803 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5804}
5805
5806//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005807// Record Evaluation
5808//===----------------------------------------------------------------------===//
5809
5810namespace {
5811 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005812 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005813 const LValue &This;
5814 APValue &Result;
5815 public:
5816
5817 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5818 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5819
Richard Smith2e312c82012-03-03 22:46:17 +00005820 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005821 Result = V;
5822 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005823 }
Richard Smithb8348f52016-05-12 22:16:28 +00005824 bool ZeroInitialization(const Expr *E) {
5825 return ZeroInitialization(E, E->getType());
5826 }
5827 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005828
Richard Smith52a980a2015-08-28 02:43:42 +00005829 bool VisitCallExpr(const CallExpr *E) {
5830 return handleCallExpr(E, Result, &This);
5831 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005832 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005833 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005834 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5835 return VisitCXXConstructExpr(E, E->getType());
5836 }
Richard Smith5179eb72016-06-28 19:03:57 +00005837 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005838 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005839 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005840 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005841}
Richard Smithd62306a2011-11-10 06:34:14 +00005842
Richard Smithfddd3842011-12-30 21:15:51 +00005843/// Perform zero-initialization on an object of non-union class type.
5844/// C++11 [dcl.init]p5:
5845/// To zero-initialize an object or reference of type T means:
5846/// [...]
5847/// -- if T is a (possibly cv-qualified) non-union class type,
5848/// each non-static data member and each base-class subobject is
5849/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005850static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5851 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005852 const LValue &This, APValue &Result) {
5853 assert(!RD->isUnion() && "Expected non-union class type");
5854 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5855 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005856 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005857
John McCalld7bca762012-05-01 00:38:49 +00005858 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005859 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5860
5861 if (CD) {
5862 unsigned Index = 0;
5863 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005864 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005865 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5866 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005867 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5868 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005869 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005870 Result.getStructBase(Index)))
5871 return false;
5872 }
5873 }
5874
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005875 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005876 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005877 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005878 continue;
5879
5880 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005881 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005882 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005883
David Blaikie2d7c57e2012-04-30 02:36:29 +00005884 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005885 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005886 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005887 return false;
5888 }
5889
5890 return true;
5891}
5892
Richard Smithb8348f52016-05-12 22:16:28 +00005893bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5894 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005895 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005896 if (RD->isUnion()) {
5897 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5898 // object's first non-static named data member is zero-initialized
5899 RecordDecl::field_iterator I = RD->field_begin();
5900 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005901 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005902 return true;
5903 }
5904
5905 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005906 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005907 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005908 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005909 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005910 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005911 }
5912
Richard Smith5d108602012-02-17 00:44:16 +00005913 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005914 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005915 return false;
5916 }
5917
Richard Smitha8105bc2012-01-06 16:39:00 +00005918 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005919}
5920
Richard Smithe97cbd72011-11-11 04:05:33 +00005921bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5922 switch (E->getCastKind()) {
5923 default:
5924 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5925
5926 case CK_ConstructorConversion:
5927 return Visit(E->getSubExpr());
5928
5929 case CK_DerivedToBase:
5930 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005931 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005932 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005933 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005934 if (!DerivedObject.isStruct())
5935 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005936
5937 // Derived-to-base rvalue conversion: just slice off the derived part.
5938 APValue *Value = &DerivedObject;
5939 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5940 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5941 PathE = E->path_end(); PathI != PathE; ++PathI) {
5942 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5943 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5944 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5945 RD = Base;
5946 }
5947 Result = *Value;
5948 return true;
5949 }
5950 }
5951}
5952
Richard Smithd62306a2011-11-10 06:34:14 +00005953bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00005954 if (E->isTransparent())
5955 return Visit(E->getInit(0));
5956
Richard Smithd62306a2011-11-10 06:34:14 +00005957 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005958 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005959 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5960
5961 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005962 const FieldDecl *Field = E->getInitializedFieldInUnion();
5963 Result = APValue(Field);
5964 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005965 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005966
5967 // If the initializer list for a union does not contain any elements, the
5968 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005969 // FIXME: The element should be initialized from an initializer list.
5970 // Is this difference ever observable for initializer lists which
5971 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005972 ImplicitValueInitExpr VIE(Field->getType());
5973 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5974
Richard Smithd62306a2011-11-10 06:34:14 +00005975 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005976 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5977 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005978
5979 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5980 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5981 isa<CXXDefaultInitExpr>(InitExpr));
5982
Richard Smithb228a862012-02-15 02:18:13 +00005983 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005984 }
5985
Richard Smith872307e2016-03-08 22:17:41 +00005986 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00005987 if (Result.isUninit())
5988 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5989 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005990 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005991 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00005992
5993 // Initialize base classes.
5994 if (CXXRD) {
5995 for (const auto &Base : CXXRD->bases()) {
5996 assert(ElementNo < E->getNumInits() && "missing init for base class");
5997 const Expr *Init = E->getInit(ElementNo);
5998
5999 LValue Subobject = This;
6000 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6001 return false;
6002
6003 APValue &FieldVal = Result.getStructBase(ElementNo);
6004 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006005 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006006 return false;
6007 Success = false;
6008 }
6009 ++ElementNo;
6010 }
6011 }
6012
6013 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006014 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006015 // Anonymous bit-fields are not considered members of the class for
6016 // purposes of aggregate initialization.
6017 if (Field->isUnnamedBitfield())
6018 continue;
6019
6020 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006021
Richard Smith253c2a32012-01-27 01:14:48 +00006022 bool HaveInit = ElementNo < E->getNumInits();
6023
6024 // FIXME: Diagnostics here should point to the end of the initializer
6025 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006026 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006027 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006028 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006029
6030 // Perform an implicit value-initialization for members beyond the end of
6031 // the initializer list.
6032 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006033 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006034
Richard Smith852c9db2013-04-20 22:23:05 +00006035 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6036 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6037 isa<CXXDefaultInitExpr>(Init));
6038
Richard Smith49ca8aa2013-08-06 07:09:20 +00006039 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6040 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6041 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006042 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006043 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006044 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006045 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006046 }
6047 }
6048
Richard Smith253c2a32012-01-27 01:14:48 +00006049 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006050}
6051
Richard Smithb8348f52016-05-12 22:16:28 +00006052bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6053 QualType T) {
6054 // Note that E's type is not necessarily the type of our class here; we might
6055 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006056 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006057 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6058
Richard Smithfddd3842011-12-30 21:15:51 +00006059 bool ZeroInit = E->requiresZeroInitialization();
6060 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006061 // If we've already performed zero-initialization, we're already done.
6062 if (!Result.isUninit())
6063 return true;
6064
Richard Smithda3f4fd2014-03-05 23:32:50 +00006065 // We can get here in two different ways:
6066 // 1) We're performing value-initialization, and should zero-initialize
6067 // the object, or
6068 // 2) We're performing default-initialization of an object with a trivial
6069 // constexpr default constructor, in which case we should start the
6070 // lifetimes of all the base subobjects (there can be no data member
6071 // subobjects in this case) per [basic.life]p1.
6072 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006073 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006074 }
6075
Craig Topper36250ad2014-05-12 05:36:57 +00006076 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006077 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006078
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006079 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006080 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006081
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006082 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006083 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006084 if (const MaterializeTemporaryExpr *ME
6085 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6086 return Visit(ME->GetTemporaryExpr());
6087
Richard Smithb8348f52016-05-12 22:16:28 +00006088 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006089 return false;
6090
Craig Topper5fc8fc22014-08-27 06:28:36 +00006091 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006092 return HandleConstructorCall(E, This, Args,
6093 cast<CXXConstructorDecl>(Definition), Info,
6094 Result);
6095}
6096
6097bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6098 const CXXInheritedCtorInitExpr *E) {
6099 if (!Info.CurrentCall) {
6100 assert(Info.checkingPotentialConstantExpression());
6101 return false;
6102 }
6103
6104 const CXXConstructorDecl *FD = E->getConstructor();
6105 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6106 return false;
6107
6108 const FunctionDecl *Definition = nullptr;
6109 auto Body = FD->getBody(Definition);
6110
6111 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6112 return false;
6113
6114 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006115 cast<CXXConstructorDecl>(Definition), Info,
6116 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006117}
6118
Richard Smithcc1b96d2013-06-12 22:31:48 +00006119bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6120 const CXXStdInitializerListExpr *E) {
6121 const ConstantArrayType *ArrayType =
6122 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6123
6124 LValue Array;
6125 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6126 return false;
6127
6128 // Get a pointer to the first element of the array.
6129 Array.addArray(Info, E, ArrayType);
6130
6131 // FIXME: Perform the checks on the field types in SemaInit.
6132 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6133 RecordDecl::field_iterator Field = Record->field_begin();
6134 if (Field == Record->field_end())
6135 return Error(E);
6136
6137 // Start pointer.
6138 if (!Field->getType()->isPointerType() ||
6139 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6140 ArrayType->getElementType()))
6141 return Error(E);
6142
6143 // FIXME: What if the initializer_list type has base classes, etc?
6144 Result = APValue(APValue::UninitStruct(), 0, 2);
6145 Array.moveInto(Result.getStructField(0));
6146
6147 if (++Field == Record->field_end())
6148 return Error(E);
6149
6150 if (Field->getType()->isPointerType() &&
6151 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6152 ArrayType->getElementType())) {
6153 // End pointer.
6154 if (!HandleLValueArrayAdjustment(Info, E, Array,
6155 ArrayType->getElementType(),
6156 ArrayType->getSize().getZExtValue()))
6157 return false;
6158 Array.moveInto(Result.getStructField(1));
6159 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6160 // Length.
6161 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6162 else
6163 return Error(E);
6164
6165 if (++Field != Record->field_end())
6166 return Error(E);
6167
6168 return true;
6169}
6170
Richard Smithd62306a2011-11-10 06:34:14 +00006171static bool EvaluateRecord(const Expr *E, const LValue &This,
6172 APValue &Result, EvalInfo &Info) {
6173 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006174 "can't evaluate expression as a record rvalue");
6175 return RecordExprEvaluator(Info, This, Result).Visit(E);
6176}
6177
6178//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006179// Temporary Evaluation
6180//
6181// Temporaries are represented in the AST as rvalues, but generally behave like
6182// lvalues. The full-object of which the temporary is a subobject is implicitly
6183// materialized so that a reference can bind to it.
6184//===----------------------------------------------------------------------===//
6185namespace {
6186class TemporaryExprEvaluator
6187 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6188public:
6189 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6190 LValueExprEvaluatorBaseTy(Info, Result) {}
6191
6192 /// Visit an expression which constructs the value of this temporary.
6193 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006194 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006195 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6196 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006197 }
6198
6199 bool VisitCastExpr(const CastExpr *E) {
6200 switch (E->getCastKind()) {
6201 default:
6202 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6203
6204 case CK_ConstructorConversion:
6205 return VisitConstructExpr(E->getSubExpr());
6206 }
6207 }
6208 bool VisitInitListExpr(const InitListExpr *E) {
6209 return VisitConstructExpr(E);
6210 }
6211 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6212 return VisitConstructExpr(E);
6213 }
6214 bool VisitCallExpr(const CallExpr *E) {
6215 return VisitConstructExpr(E);
6216 }
Richard Smith513955c2014-12-17 19:24:30 +00006217 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6218 return VisitConstructExpr(E);
6219 }
Richard Smith027bf112011-11-17 22:56:20 +00006220};
6221} // end anonymous namespace
6222
6223/// Evaluate an expression of record type as a temporary.
6224static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006225 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006226 return TemporaryExprEvaluator(Info, Result).Visit(E);
6227}
6228
6229//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006230// Vector Evaluation
6231//===----------------------------------------------------------------------===//
6232
6233namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006234 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006235 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006236 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006237 public:
Mike Stump11289f42009-09-09 15:08:12 +00006238
Richard Smith2d406342011-10-22 21:10:00 +00006239 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6240 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006241
Craig Topper9798b932015-09-29 04:30:05 +00006242 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006243 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6244 // FIXME: remove this APValue copy.
6245 Result = APValue(V.data(), V.size());
6246 return true;
6247 }
Richard Smith2e312c82012-03-03 22:46:17 +00006248 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006249 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006250 Result = V;
6251 return true;
6252 }
Richard Smithfddd3842011-12-30 21:15:51 +00006253 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006254
Richard Smith2d406342011-10-22 21:10:00 +00006255 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006256 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006257 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006258 bool VisitInitListExpr(const InitListExpr *E);
6259 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006260 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006261 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006262 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006263 };
6264} // end anonymous namespace
6265
6266static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006267 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006268 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006269}
6270
George Burgess IV533ff002015-12-11 00:23:35 +00006271bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006272 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006273 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006274
Richard Smith161f09a2011-12-06 22:44:34 +00006275 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006276 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006277
Eli Friedmanc757de22011-03-25 00:43:55 +00006278 switch (E->getCastKind()) {
6279 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006280 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006281 if (SETy->isIntegerType()) {
6282 APSInt IntResult;
6283 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006284 return false;
6285 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006286 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006287 APFloat FloatResult(0.0);
6288 if (!EvaluateFloat(SE, FloatResult, Info))
6289 return false;
6290 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006291 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006292 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006293 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006294
6295 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006296 SmallVector<APValue, 4> Elts(NElts, Val);
6297 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006298 }
Eli Friedman803acb32011-12-22 03:51:45 +00006299 case CK_BitCast: {
6300 // Evaluate the operand into an APInt we can extract from.
6301 llvm::APInt SValInt;
6302 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6303 return false;
6304 // Extract the elements
6305 QualType EltTy = VTy->getElementType();
6306 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6307 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6308 SmallVector<APValue, 4> Elts;
6309 if (EltTy->isRealFloatingType()) {
6310 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006311 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006312 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006313 FloatEltSize = 80;
6314 for (unsigned i = 0; i < NElts; i++) {
6315 llvm::APInt Elt;
6316 if (BigEndian)
6317 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6318 else
6319 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006320 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006321 }
6322 } else if (EltTy->isIntegerType()) {
6323 for (unsigned i = 0; i < NElts; i++) {
6324 llvm::APInt Elt;
6325 if (BigEndian)
6326 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6327 else
6328 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6329 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6330 }
6331 } else {
6332 return Error(E);
6333 }
6334 return Success(Elts, E);
6335 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006336 default:
Richard Smith11562c52011-10-28 17:51:58 +00006337 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006338 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006339}
6340
Richard Smith2d406342011-10-22 21:10:00 +00006341bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006342VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006343 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006344 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006345 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006346
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006347 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006348 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006349
Eli Friedmanb9c71292012-01-03 23:24:20 +00006350 // The number of initializers can be less than the number of
6351 // vector elements. For OpenCL, this can be due to nested vector
6352 // initialization. For GCC compatibility, missing trailing elements
6353 // should be initialized with zeroes.
6354 unsigned CountInits = 0, CountElts = 0;
6355 while (CountElts < NumElements) {
6356 // Handle nested vector initialization.
6357 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006358 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006359 APValue v;
6360 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6361 return Error(E);
6362 unsigned vlen = v.getVectorLength();
6363 for (unsigned j = 0; j < vlen; j++)
6364 Elements.push_back(v.getVectorElt(j));
6365 CountElts += vlen;
6366 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006367 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006368 if (CountInits < NumInits) {
6369 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006370 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006371 } else // trailing integer zero.
6372 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6373 Elements.push_back(APValue(sInt));
6374 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006375 } else {
6376 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006377 if (CountInits < NumInits) {
6378 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006379 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006380 } else // trailing float zero.
6381 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6382 Elements.push_back(APValue(f));
6383 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006384 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006385 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006386 }
Richard Smith2d406342011-10-22 21:10:00 +00006387 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006388}
6389
Richard Smith2d406342011-10-22 21:10:00 +00006390bool
Richard Smithfddd3842011-12-30 21:15:51 +00006391VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006392 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006393 QualType EltTy = VT->getElementType();
6394 APValue ZeroElement;
6395 if (EltTy->isIntegerType())
6396 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6397 else
6398 ZeroElement =
6399 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6400
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006401 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006402 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006403}
6404
Richard Smith2d406342011-10-22 21:10:00 +00006405bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006406 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006407 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006408}
6409
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006410//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006411// Array Evaluation
6412//===----------------------------------------------------------------------===//
6413
6414namespace {
6415 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006416 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006417 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006418 APValue &Result;
6419 public:
6420
Richard Smithd62306a2011-11-10 06:34:14 +00006421 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6422 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006423
6424 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006425 assert((V.isArray() || V.isLValue()) &&
6426 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006427 Result = V;
6428 return true;
6429 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006430
Richard Smithfddd3842011-12-30 21:15:51 +00006431 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006432 const ConstantArrayType *CAT =
6433 Info.Ctx.getAsConstantArrayType(E->getType());
6434 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006435 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006436
6437 Result = APValue(APValue::UninitArray(), 0,
6438 CAT->getSize().getZExtValue());
6439 if (!Result.hasArrayFiller()) return true;
6440
Richard Smithfddd3842011-12-30 21:15:51 +00006441 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006442 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006443 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006444 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006445 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006446 }
6447
Richard Smith52a980a2015-08-28 02:43:42 +00006448 bool VisitCallExpr(const CallExpr *E) {
6449 return handleCallExpr(E, Result, &This);
6450 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006451 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006452 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006453 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006454 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6455 const LValue &Subobject,
6456 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006457 };
6458} // end anonymous namespace
6459
Richard Smithd62306a2011-11-10 06:34:14 +00006460static bool EvaluateArray(const Expr *E, const LValue &This,
6461 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006462 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006463 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006464}
6465
6466bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6467 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6468 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006469 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006470
Richard Smithca2cfbf2011-12-22 01:07:19 +00006471 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6472 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006473 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006474 LValue LV;
6475 if (!EvaluateLValue(E->getInit(0), LV, Info))
6476 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006477 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006478 LV.moveInto(Val);
6479 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006480 }
6481
Richard Smith253c2a32012-01-27 01:14:48 +00006482 bool Success = true;
6483
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006484 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6485 "zero-initialized array shouldn't have any initialized elts");
6486 APValue Filler;
6487 if (Result.isArray() && Result.hasArrayFiller())
6488 Filler = Result.getArrayFiller();
6489
Richard Smith9543c5e2013-04-22 14:44:29 +00006490 unsigned NumEltsToInit = E->getNumInits();
6491 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006492 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006493
6494 // If the initializer might depend on the array index, run it for each
6495 // array element. For now, just whitelist non-class value-initialization.
6496 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6497 NumEltsToInit = NumElts;
6498
6499 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006500
6501 // If the array was previously zero-initialized, preserve the
6502 // zero-initialized values.
6503 if (!Filler.isUninit()) {
6504 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6505 Result.getArrayInitializedElt(I) = Filler;
6506 if (Result.hasArrayFiller())
6507 Result.getArrayFiller() = Filler;
6508 }
6509
Richard Smithd62306a2011-11-10 06:34:14 +00006510 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006511 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006512 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6513 const Expr *Init =
6514 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006515 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006516 Info, Subobject, Init) ||
6517 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006518 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006519 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006520 return false;
6521 Success = false;
6522 }
Richard Smithd62306a2011-11-10 06:34:14 +00006523 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006524
Richard Smith9543c5e2013-04-22 14:44:29 +00006525 if (!Result.hasArrayFiller())
6526 return Success;
6527
6528 // If we get here, we have a trivial filler, which we can just evaluate
6529 // once and splat over the rest of the array elements.
6530 assert(FillerExpr && "no array filler for incomplete init list");
6531 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6532 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006533}
6534
Richard Smith410306b2016-12-12 02:53:20 +00006535bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6536 if (E->getCommonExpr() &&
6537 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6538 Info, E->getCommonExpr()->getSourceExpr()))
6539 return false;
6540
6541 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6542
6543 uint64_t Elements = CAT->getSize().getZExtValue();
6544 Result = APValue(APValue::UninitArray(), Elements, Elements);
6545
6546 LValue Subobject = This;
6547 Subobject.addArray(Info, E, CAT);
6548
6549 bool Success = true;
6550 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6551 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6552 Info, Subobject, E->getSubExpr()) ||
6553 !HandleLValueArrayAdjustment(Info, E, Subobject,
6554 CAT->getElementType(), 1)) {
6555 if (!Info.noteFailure())
6556 return false;
6557 Success = false;
6558 }
6559 }
6560
6561 return Success;
6562}
6563
Richard Smith027bf112011-11-17 22:56:20 +00006564bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006565 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6566}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006567
Richard Smith9543c5e2013-04-22 14:44:29 +00006568bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6569 const LValue &Subobject,
6570 APValue *Value,
6571 QualType Type) {
6572 bool HadZeroInit = !Value->isUninit();
6573
6574 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6575 unsigned N = CAT->getSize().getZExtValue();
6576
6577 // Preserve the array filler if we had prior zero-initialization.
6578 APValue Filler =
6579 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6580 : APValue();
6581
6582 *Value = APValue(APValue::UninitArray(), N, N);
6583
6584 if (HadZeroInit)
6585 for (unsigned I = 0; I != N; ++I)
6586 Value->getArrayInitializedElt(I) = Filler;
6587
6588 // Initialize the elements.
6589 LValue ArrayElt = Subobject;
6590 ArrayElt.addArray(Info, E, CAT);
6591 for (unsigned I = 0; I != N; ++I)
6592 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6593 CAT->getElementType()) ||
6594 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6595 CAT->getElementType(), 1))
6596 return false;
6597
6598 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006599 }
Richard Smith027bf112011-11-17 22:56:20 +00006600
Richard Smith9543c5e2013-04-22 14:44:29 +00006601 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006602 return Error(E);
6603
Richard Smithb8348f52016-05-12 22:16:28 +00006604 return RecordExprEvaluator(Info, Subobject, *Value)
6605 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006606}
6607
Richard Smithf3e9e432011-11-07 09:22:26 +00006608//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006609// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006610//
6611// As a GNU extension, we support casting pointers to sufficiently-wide integer
6612// types and back in constant folding. Integer values are thus represented
6613// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006614//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006615
6616namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006617class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006618 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006619 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006620public:
Richard Smith2e312c82012-03-03 22:46:17 +00006621 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006622 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006623
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006624 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006625 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006626 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006627 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006628 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006629 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006630 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006631 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006632 return true;
6633 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006634 bool Success(const llvm::APSInt &SI, const Expr *E) {
6635 return Success(SI, E, Result);
6636 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006637
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006638 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006639 assert(E->getType()->isIntegralOrEnumerationType() &&
6640 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006641 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006642 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006643 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006644 Result.getInt().setIsUnsigned(
6645 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006646 return true;
6647 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006648 bool Success(const llvm::APInt &I, const Expr *E) {
6649 return Success(I, E, Result);
6650 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006651
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006652 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006653 assert(E->getType()->isIntegralOrEnumerationType() &&
6654 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006655 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006656 return true;
6657 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006658 bool Success(uint64_t Value, const Expr *E) {
6659 return Success(Value, E, Result);
6660 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006661
Ken Dyckdbc01912011-03-11 02:13:43 +00006662 bool Success(CharUnits Size, const Expr *E) {
6663 return Success(Size.getQuantity(), E);
6664 }
6665
Richard Smith2e312c82012-03-03 22:46:17 +00006666 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006667 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006668 Result = V;
6669 return true;
6670 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006671 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006672 }
Mike Stump11289f42009-09-09 15:08:12 +00006673
Richard Smithfddd3842011-12-30 21:15:51 +00006674 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006675
Peter Collingbournee9200682011-05-13 03:29:01 +00006676 //===--------------------------------------------------------------------===//
6677 // Visitor Methods
6678 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006679
Chris Lattner7174bf32008-07-12 00:38:25 +00006680 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006681 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006682 }
6683 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006684 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006685 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006686
6687 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6688 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006689 if (CheckReferencedDecl(E, E->getDecl()))
6690 return true;
6691
6692 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006693 }
6694 bool VisitMemberExpr(const MemberExpr *E) {
6695 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006696 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006697 return true;
6698 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006699
6700 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006701 }
6702
Peter Collingbournee9200682011-05-13 03:29:01 +00006703 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006704 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006705 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006706 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006707 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006708
Peter Collingbournee9200682011-05-13 03:29:01 +00006709 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006710 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006711
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006712 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006713 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006714 }
Mike Stump11289f42009-09-09 15:08:12 +00006715
Ted Kremeneke65b0862012-03-06 20:05:56 +00006716 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6717 return Success(E->getValue(), E);
6718 }
Richard Smith410306b2016-12-12 02:53:20 +00006719
6720 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6721 if (Info.ArrayInitIndex == uint64_t(-1)) {
6722 // We were asked to evaluate this subexpression independent of the
6723 // enclosing ArrayInitLoopExpr. We can't do that.
6724 Info.FFDiag(E);
6725 return false;
6726 }
6727 return Success(Info.ArrayInitIndex, E);
6728 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00006729
Richard Smith4ce706a2011-10-11 21:43:33 +00006730 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006731 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006732 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006733 }
6734
Douglas Gregor29c42f22012-02-24 07:38:34 +00006735 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6736 return Success(E->getValue(), E);
6737 }
6738
John Wiegley6242b6a2011-04-28 00:16:57 +00006739 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6740 return Success(E->getValue(), E);
6741 }
6742
John Wiegleyf9f65842011-04-25 06:54:41 +00006743 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6744 return Success(E->getValue(), E);
6745 }
6746
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006747 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006748 bool VisitUnaryImag(const UnaryOperator *E);
6749
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006750 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006751 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006752
Eli Friedman4e7a2412009-02-27 04:45:43 +00006753 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006754};
Chris Lattner05706e882008-07-11 18:11:29 +00006755} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006756
Richard Smith11562c52011-10-28 17:51:58 +00006757/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6758/// produce either the integer value or a pointer.
6759///
6760/// GCC has a heinous extension which folds casts between pointer types and
6761/// pointer-sized integral types. We support this by allowing the evaluation of
6762/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6763/// Some simple arithmetic on such values is supported (they are treated much
6764/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006765static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006766 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006767 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006768 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006769}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006770
Richard Smithf57d8cb2011-12-09 22:58:01 +00006771static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006772 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006773 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006774 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006775 if (!Val.isInt()) {
6776 // FIXME: It would be better to produce the diagnostic for casting
6777 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006778 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006779 return false;
6780 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006781 Result = Val.getInt();
6782 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006783}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006784
Richard Smithf57d8cb2011-12-09 22:58:01 +00006785/// Check whether the given declaration can be directly converted to an integral
6786/// rvalue. If not, no diagnostic is produced; there are other things we can
6787/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006788bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006789 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006790 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006791 // Check for signedness/width mismatches between E type and ECD value.
6792 bool SameSign = (ECD->getInitVal().isSigned()
6793 == E->getType()->isSignedIntegerOrEnumerationType());
6794 bool SameWidth = (ECD->getInitVal().getBitWidth()
6795 == Info.Ctx.getIntWidth(E->getType()));
6796 if (SameSign && SameWidth)
6797 return Success(ECD->getInitVal(), E);
6798 else {
6799 // Get rid of mismatch (otherwise Success assertions will fail)
6800 // by computing a new value matching the type of E.
6801 llvm::APSInt Val = ECD->getInitVal();
6802 if (!SameSign)
6803 Val.setIsSigned(!ECD->getInitVal().isSigned());
6804 if (!SameWidth)
6805 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6806 return Success(Val, E);
6807 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006808 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006809 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006810}
6811
Chris Lattner86ee2862008-10-06 06:40:35 +00006812/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6813/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006814static int EvaluateBuiltinClassifyType(const CallExpr *E,
6815 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006816 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006817 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006818 enum gcc_type_class {
6819 no_type_class = -1,
6820 void_type_class, integer_type_class, char_type_class,
6821 enumeral_type_class, boolean_type_class,
6822 pointer_type_class, reference_type_class, offset_type_class,
6823 real_type_class, complex_type_class,
6824 function_type_class, method_type_class,
6825 record_type_class, union_type_class,
6826 array_type_class, string_type_class,
6827 lang_type_class
6828 };
Mike Stump11289f42009-09-09 15:08:12 +00006829
6830 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006831 // ideal, however it is what gcc does.
6832 if (E->getNumArgs() == 0)
6833 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006834
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006835 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6836 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6837
6838 switch (CanTy->getTypeClass()) {
6839#define TYPE(ID, BASE)
6840#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6841#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6842#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6843#include "clang/AST/TypeNodes.def"
6844 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6845
6846 case Type::Builtin:
6847 switch (BT->getKind()) {
6848#define BUILTIN_TYPE(ID, SINGLETON_ID)
6849#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6850#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6851#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6852#include "clang/AST/BuiltinTypes.def"
6853 case BuiltinType::Void:
6854 return void_type_class;
6855
6856 case BuiltinType::Bool:
6857 return boolean_type_class;
6858
6859 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6860 case BuiltinType::UChar:
6861 case BuiltinType::UShort:
6862 case BuiltinType::UInt:
6863 case BuiltinType::ULong:
6864 case BuiltinType::ULongLong:
6865 case BuiltinType::UInt128:
6866 return integer_type_class;
6867
6868 case BuiltinType::NullPtr:
6869 return pointer_type_class;
6870
6871 case BuiltinType::WChar_U:
6872 case BuiltinType::Char16:
6873 case BuiltinType::Char32:
6874 case BuiltinType::ObjCId:
6875 case BuiltinType::ObjCClass:
6876 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006877#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6878 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006879#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006880 case BuiltinType::OCLSampler:
6881 case BuiltinType::OCLEvent:
6882 case BuiltinType::OCLClkEvent:
6883 case BuiltinType::OCLQueue:
6884 case BuiltinType::OCLNDRange:
6885 case BuiltinType::OCLReserveID:
6886 case BuiltinType::Dependent:
6887 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6888 };
6889
6890 case Type::Enum:
6891 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6892 break;
6893
6894 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006895 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006896 break;
6897
6898 case Type::MemberPointer:
6899 if (CanTy->isMemberDataPointerType())
6900 return offset_type_class;
6901 else {
6902 // We expect member pointers to be either data or function pointers,
6903 // nothing else.
6904 assert(CanTy->isMemberFunctionPointerType());
6905 return method_type_class;
6906 }
6907
6908 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006909 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006910
6911 case Type::FunctionNoProto:
6912 case Type::FunctionProto:
6913 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6914
6915 case Type::Record:
6916 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6917 switch (RT->getDecl()->getTagKind()) {
6918 case TagTypeKind::TTK_Struct:
6919 case TagTypeKind::TTK_Class:
6920 case TagTypeKind::TTK_Interface:
6921 return record_type_class;
6922
6923 case TagTypeKind::TTK_Enum:
6924 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6925
6926 case TagTypeKind::TTK_Union:
6927 return union_type_class;
6928 }
6929 }
David Blaikie83d382b2011-09-23 05:06:16 +00006930 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006931
6932 case Type::ConstantArray:
6933 case Type::VariableArray:
6934 case Type::IncompleteArray:
6935 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6936
6937 case Type::BlockPointer:
6938 case Type::LValueReference:
6939 case Type::RValueReference:
6940 case Type::Vector:
6941 case Type::ExtVector:
6942 case Type::Auto:
6943 case Type::ObjCObject:
6944 case Type::ObjCInterface:
6945 case Type::ObjCObjectPointer:
6946 case Type::Pipe:
6947 case Type::Atomic:
6948 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6949 }
6950
6951 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006952}
6953
Richard Smith5fab0c92011-12-28 19:48:30 +00006954/// EvaluateBuiltinConstantPForLValue - Determine the result of
6955/// __builtin_constant_p when applied to the given lvalue.
6956///
6957/// An lvalue is only "constant" if it is a pointer or reference to the first
6958/// character of a string literal.
6959template<typename LValue>
6960static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006961 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006962 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6963}
6964
6965/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6966/// GCC as we can manage.
6967static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6968 QualType ArgType = Arg->getType();
6969
6970 // __builtin_constant_p always has one operand. The rules which gcc follows
6971 // are not precisely documented, but are as follows:
6972 //
6973 // - If the operand is of integral, floating, complex or enumeration type,
6974 // and can be folded to a known value of that type, it returns 1.
6975 // - If the operand and can be folded to a pointer to the first character
6976 // of a string literal (or such a pointer cast to an integral type), it
6977 // returns 1.
6978 //
6979 // Otherwise, it returns 0.
6980 //
6981 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6982 // its support for this does not currently work.
6983 if (ArgType->isIntegralOrEnumerationType()) {
6984 Expr::EvalResult Result;
6985 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6986 return false;
6987
6988 APValue &V = Result.Val;
6989 if (V.getKind() == APValue::Int)
6990 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006991 if (V.getKind() == APValue::LValue)
6992 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006993 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6994 return Arg->isEvaluatable(Ctx);
6995 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6996 LValue LV;
6997 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006998 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006999 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7000 : EvaluatePointer(Arg, LV, Info)) &&
7001 !Status.HasSideEffects)
7002 return EvaluateBuiltinConstantPForLValue(LV);
7003 }
7004
7005 // Anything else isn't considered to be sufficiently constant.
7006 return false;
7007}
7008
John McCall95007602010-05-10 23:27:23 +00007009/// Retrieves the "underlying object type" of the given expression,
7010/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007011static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007012 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7013 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007014 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007015 } else if (const Expr *E = B.get<const Expr*>()) {
7016 if (isa<CompoundLiteralExpr>(E))
7017 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007018 }
7019
7020 return QualType();
7021}
7022
George Burgess IV3a03fab2015-09-04 21:28:13 +00007023/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007024/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007025/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007026/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7027///
7028/// Always returns an RValue with a pointer representation.
7029static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7030 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7031
7032 auto *NoParens = E->IgnoreParens();
7033 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007034 if (Cast == nullptr)
7035 return NoParens;
7036
7037 // We only conservatively allow a few kinds of casts, because this code is
7038 // inherently a simple solution that seeks to support the common case.
7039 auto CastKind = Cast->getCastKind();
7040 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7041 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007042 return NoParens;
7043
7044 auto *SubExpr = Cast->getSubExpr();
7045 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7046 return NoParens;
7047 return ignorePointerCastsAndParens(SubExpr);
7048}
7049
George Burgess IVa51c4072015-10-16 01:49:01 +00007050/// Checks to see if the given LValue's Designator is at the end of the LValue's
7051/// record layout. e.g.
7052/// struct { struct { int a, b; } fst, snd; } obj;
7053/// obj.fst // no
7054/// obj.snd // yes
7055/// obj.fst.a // no
7056/// obj.fst.b // no
7057/// obj.snd.a // no
7058/// obj.snd.b // yes
7059///
7060/// Please note: this function is specialized for how __builtin_object_size
7061/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007062///
7063/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007064static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7065 assert(!LVal.Designator.Invalid);
7066
George Burgess IV4168d752016-06-27 19:40:41 +00007067 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7068 const RecordDecl *Parent = FD->getParent();
7069 Invalid = Parent->isInvalidDecl();
7070 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007071 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007072 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007073 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7074 };
7075
7076 auto &Base = LVal.getLValueBase();
7077 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7078 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007079 bool Invalid;
7080 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7081 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007082 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007083 for (auto *FD : IFD->chain()) {
7084 bool Invalid;
7085 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7086 return Invalid;
7087 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007088 }
7089 }
7090
George Burgess IVe3763372016-12-22 02:50:20 +00007091 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007092 QualType BaseType = getType(Base);
George Burgess IVe3763372016-12-22 02:50:20 +00007093 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7094 assert(isBaseAnAllocSizeCall(Base) &&
7095 "Unsized array in non-alloc_size call?");
7096 // If this is an alloc_size base, we should ignore the initial array index
7097 ++I;
7098 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7099 }
7100
7101 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7102 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007103 if (BaseType->isArrayType()) {
7104 // Because __builtin_object_size treats arrays as objects, we can ignore
7105 // the index iff this is the last array in the Designator.
7106 if (I + 1 == E)
7107 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007108 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7109 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007110 if (Index + 1 != CAT->getSize())
7111 return false;
7112 BaseType = CAT->getElementType();
7113 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007114 const auto *CT = BaseType->castAs<ComplexType>();
7115 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007116 if (Index != 1)
7117 return false;
7118 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007119 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007120 bool Invalid;
7121 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7122 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007123 BaseType = FD->getType();
7124 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007125 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007126 return false;
7127 }
7128 }
7129 return true;
7130}
7131
George Burgess IVe3763372016-12-22 02:50:20 +00007132/// Tests to see if the LValue has a user-specified designator (that isn't
7133/// necessarily valid). Note that this always returns 'true' if the LValue has
7134/// an unsized array as its first designator entry, because there's currently no
7135/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007136static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007137 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007138 return false;
7139
George Burgess IVe3763372016-12-22 02:50:20 +00007140 if (!LVal.Designator.Entries.empty())
7141 return LVal.Designator.isMostDerivedAnUnsizedArray();
7142
George Burgess IVa51c4072015-10-16 01:49:01 +00007143 if (!LVal.InvalidBase)
7144 return true;
7145
George Burgess IVe3763372016-12-22 02:50:20 +00007146 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7147 // the LValueBase.
7148 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7149 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007150}
7151
George Burgess IVe3763372016-12-22 02:50:20 +00007152/// Attempts to detect a user writing into a piece of memory that's impossible
7153/// to figure out the size of by just using types.
7154static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7155 const SubobjectDesignator &Designator = LVal.Designator;
7156 // Notes:
7157 // - Users can only write off of the end when we have an invalid base. Invalid
7158 // bases imply we don't know where the memory came from.
7159 // - We used to be a bit more aggressive here; we'd only be conservative if
7160 // the array at the end was flexible, or if it had 0 or 1 elements. This
7161 // broke some common standard library extensions (PR30346), but was
7162 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7163 // with some sort of whitelist. OTOH, it seems that GCC is always
7164 // conservative with the last element in structs (if it's an array), so our
7165 // current behavior is more compatible than a whitelisting approach would
7166 // be.
7167 return LVal.InvalidBase &&
7168 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7169 Designator.MostDerivedIsArrayElement &&
7170 isDesignatorAtObjectEnd(Ctx, LVal);
7171}
7172
7173/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7174/// Fails if the conversion would cause loss of precision.
7175static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7176 CharUnits &Result) {
7177 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7178 if (Int.ugt(CharUnitsMax))
7179 return false;
7180 Result = CharUnits::fromQuantity(Int.getZExtValue());
7181 return true;
7182}
7183
7184/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7185/// determine how many bytes exist from the beginning of the object to either
7186/// the end of the current subobject, or the end of the object itself, depending
7187/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007188///
George Burgess IVe3763372016-12-22 02:50:20 +00007189/// If this returns false, the value of Result is undefined.
7190static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7191 unsigned Type, const LValue &LVal,
7192 CharUnits &EndOffset) {
7193 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007194
George Burgess IVe3763372016-12-22 02:50:20 +00007195 // We want to evaluate the size of the entire object. This is a valid fallback
7196 // for when Type=1 and the designator is invalid, because we're asked for an
7197 // upper-bound.
7198 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7199 // Type=3 wants a lower bound, so we can't fall back to this.
7200 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007201 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007202
7203 llvm::APInt APEndOffset;
7204 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7205 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7206 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7207
7208 if (LVal.InvalidBase)
7209 return false;
7210
7211 QualType BaseTy = getObjectType(LVal.getLValueBase());
7212 return !BaseTy.isNull() && HandleSizeof(Info, ExprLoc, BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007213 }
7214
George Burgess IVe3763372016-12-22 02:50:20 +00007215 // We want to evaluate the size of a subobject.
7216 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007217
7218 // The following is a moderately common idiom in C:
7219 //
7220 // struct Foo { int a; char c[1]; };
7221 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7222 // strcpy(&F->c[0], Bar);
7223 //
George Burgess IVe3763372016-12-22 02:50:20 +00007224 // In order to not break too much legacy code, we need to support it.
7225 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7226 // If we can resolve this to an alloc_size call, we can hand that back,
7227 // because we know for certain how many bytes there are to write to.
7228 llvm::APInt APEndOffset;
7229 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7230 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7231 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7232
7233 // If we cannot determine the size of the initial allocation, then we can't
7234 // given an accurate upper-bound. However, we are still able to give
7235 // conservative lower-bounds for Type=3.
7236 if (Type == 1)
7237 return false;
7238 }
7239
7240 CharUnits BytesPerElem;
7241 if (!HandleSizeof(Info, ExprLoc, Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007242 return false;
7243
George Burgess IVe3763372016-12-22 02:50:20 +00007244 // According to the GCC documentation, we want the size of the subobject
7245 // denoted by the pointer. But that's not quite right -- what we actually
7246 // want is the size of the immediately-enclosing array, if there is one.
7247 int64_t ElemsRemaining;
7248 if (Designator.MostDerivedIsArrayElement &&
7249 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7250 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7251 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7252 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7253 } else {
7254 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7255 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007256
George Burgess IVe3763372016-12-22 02:50:20 +00007257 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7258 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007259}
7260
George Burgess IVe3763372016-12-22 02:50:20 +00007261/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7262/// returns true and stores the result in @p Size.
7263///
7264/// If @p WasError is non-null, this will report whether the failure to evaluate
7265/// is to be treated as an Error in IntExprEvaluator.
7266static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7267 EvalInfo &Info, uint64_t &Size) {
7268 // Determine the denoted object.
7269 LValue LVal;
7270 {
7271 // The operand of __builtin_object_size is never evaluated for side-effects.
7272 // If there are any, but we can determine the pointed-to object anyway, then
7273 // ignore the side-effects.
7274 SpeculativeEvaluationRAII SpeculativeEval(Info);
7275 FoldOffsetRAII Fold(Info);
7276
7277 if (E->isGLValue()) {
7278 // It's possible for us to be given GLValues if we're called via
7279 // Expr::tryEvaluateObjectSize.
7280 APValue RVal;
7281 if (!EvaluateAsRValue(Info, E, RVal))
7282 return false;
7283 LVal.setFrom(Info.Ctx, RVal);
7284 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info))
7285 return false;
7286 }
7287
7288 // If we point to before the start of the object, there are no accessible
7289 // bytes.
7290 if (LVal.getLValueOffset().isNegative()) {
7291 Size = 0;
7292 return true;
7293 }
7294
7295 CharUnits EndOffset;
7296 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7297 return false;
7298
7299 // If we've fallen outside of the end offset, just pretend there's nothing to
7300 // write to/read from.
7301 if (EndOffset <= LVal.getLValueOffset())
7302 Size = 0;
7303 else
7304 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7305 return true;
John McCall95007602010-05-10 23:27:23 +00007306}
7307
Peter Collingbournee9200682011-05-13 03:29:01 +00007308bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007309 if (unsigned BuiltinOp = E->getBuiltinCallee())
7310 return VisitBuiltinCallExpr(E, BuiltinOp);
7311
7312 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7313}
7314
7315bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7316 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007317 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007318 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007319 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007320
7321 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007322 // The type was checked when we built the expression.
7323 unsigned Type =
7324 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7325 assert(Type <= 3 && "unexpected type");
7326
George Burgess IVe3763372016-12-22 02:50:20 +00007327 uint64_t Size;
7328 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7329 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007330
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007331 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007332 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007333
Richard Smith01ade172012-05-23 04:13:20 +00007334 // Expression had no side effects, but we couldn't statically determine the
7335 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007336 switch (Info.EvalMode) {
7337 case EvalInfo::EM_ConstantExpression:
7338 case EvalInfo::EM_PotentialConstantExpression:
7339 case EvalInfo::EM_ConstantFold:
7340 case EvalInfo::EM_EvaluateForOverflow:
7341 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007342 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007343 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007344 return Error(E);
7345 case EvalInfo::EM_ConstantExpressionUnevaluated:
7346 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007347 // Reduce it to a constant now.
7348 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007349 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007350
7351 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007352 }
7353
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007354 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007355 case Builtin::BI__builtin_bswap32:
7356 case Builtin::BI__builtin_bswap64: {
7357 APSInt Val;
7358 if (!EvaluateInteger(E->getArg(0), Val, Info))
7359 return false;
7360
7361 return Success(Val.byteSwap(), E);
7362 }
7363
Richard Smith8889a3d2013-06-13 06:26:32 +00007364 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007365 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007366
7367 // FIXME: BI__builtin_clrsb
7368 // FIXME: BI__builtin_clrsbl
7369 // FIXME: BI__builtin_clrsbll
7370
Richard Smith80b3c8e2013-06-13 05:04:16 +00007371 case Builtin::BI__builtin_clz:
7372 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007373 case Builtin::BI__builtin_clzll:
7374 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007375 APSInt Val;
7376 if (!EvaluateInteger(E->getArg(0), Val, Info))
7377 return false;
7378 if (!Val)
7379 return Error(E);
7380
7381 return Success(Val.countLeadingZeros(), E);
7382 }
7383
Richard Smith8889a3d2013-06-13 06:26:32 +00007384 case Builtin::BI__builtin_constant_p:
7385 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7386
Richard Smith80b3c8e2013-06-13 05:04:16 +00007387 case Builtin::BI__builtin_ctz:
7388 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007389 case Builtin::BI__builtin_ctzll:
7390 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007391 APSInt Val;
7392 if (!EvaluateInteger(E->getArg(0), Val, Info))
7393 return false;
7394 if (!Val)
7395 return Error(E);
7396
7397 return Success(Val.countTrailingZeros(), E);
7398 }
7399
Richard Smith8889a3d2013-06-13 06:26:32 +00007400 case Builtin::BI__builtin_eh_return_data_regno: {
7401 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7402 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7403 return Success(Operand, E);
7404 }
7405
7406 case Builtin::BI__builtin_expect:
7407 return Visit(E->getArg(0));
7408
7409 case Builtin::BI__builtin_ffs:
7410 case Builtin::BI__builtin_ffsl:
7411 case Builtin::BI__builtin_ffsll: {
7412 APSInt Val;
7413 if (!EvaluateInteger(E->getArg(0), Val, Info))
7414 return false;
7415
7416 unsigned N = Val.countTrailingZeros();
7417 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7418 }
7419
7420 case Builtin::BI__builtin_fpclassify: {
7421 APFloat Val(0.0);
7422 if (!EvaluateFloat(E->getArg(5), Val, Info))
7423 return false;
7424 unsigned Arg;
7425 switch (Val.getCategory()) {
7426 case APFloat::fcNaN: Arg = 0; break;
7427 case APFloat::fcInfinity: Arg = 1; break;
7428 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7429 case APFloat::fcZero: Arg = 4; break;
7430 }
7431 return Visit(E->getArg(Arg));
7432 }
7433
7434 case Builtin::BI__builtin_isinf_sign: {
7435 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007436 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007437 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7438 }
7439
Richard Smithea3019d2013-10-15 19:07:14 +00007440 case Builtin::BI__builtin_isinf: {
7441 APFloat Val(0.0);
7442 return EvaluateFloat(E->getArg(0), Val, Info) &&
7443 Success(Val.isInfinity() ? 1 : 0, E);
7444 }
7445
7446 case Builtin::BI__builtin_isfinite: {
7447 APFloat Val(0.0);
7448 return EvaluateFloat(E->getArg(0), Val, Info) &&
7449 Success(Val.isFinite() ? 1 : 0, E);
7450 }
7451
7452 case Builtin::BI__builtin_isnan: {
7453 APFloat Val(0.0);
7454 return EvaluateFloat(E->getArg(0), Val, Info) &&
7455 Success(Val.isNaN() ? 1 : 0, E);
7456 }
7457
7458 case Builtin::BI__builtin_isnormal: {
7459 APFloat Val(0.0);
7460 return EvaluateFloat(E->getArg(0), Val, Info) &&
7461 Success(Val.isNormal() ? 1 : 0, E);
7462 }
7463
Richard Smith8889a3d2013-06-13 06:26:32 +00007464 case Builtin::BI__builtin_parity:
7465 case Builtin::BI__builtin_parityl:
7466 case Builtin::BI__builtin_parityll: {
7467 APSInt Val;
7468 if (!EvaluateInteger(E->getArg(0), Val, Info))
7469 return false;
7470
7471 return Success(Val.countPopulation() % 2, E);
7472 }
7473
Richard Smith80b3c8e2013-06-13 05:04:16 +00007474 case Builtin::BI__builtin_popcount:
7475 case Builtin::BI__builtin_popcountl:
7476 case Builtin::BI__builtin_popcountll: {
7477 APSInt Val;
7478 if (!EvaluateInteger(E->getArg(0), Val, Info))
7479 return false;
7480
7481 return Success(Val.countPopulation(), E);
7482 }
7483
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007484 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007485 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007486 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007487 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007488 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007489 << /*isConstexpr*/0 << /*isConstructor*/0
7490 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007491 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007492 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007493 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007494 case Builtin::BI__builtin_strlen:
7495 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007496 // As an extension, we support __builtin_strlen() as a constant expression,
7497 // and support folding strlen() to a constant.
7498 LValue String;
7499 if (!EvaluatePointer(E->getArg(0), String, Info))
7500 return false;
7501
Richard Smith8110c9d2016-11-29 19:45:17 +00007502 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7503
Richard Smithe6c19f22013-11-15 02:10:04 +00007504 // Fast path: if it's a string literal, search the string value.
7505 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7506 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007507 // The string literal may have embedded null characters. Find the first
7508 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007509 StringRef Str = S->getBytes();
7510 int64_t Off = String.Offset.getQuantity();
7511 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007512 S->getCharByteWidth() == 1 &&
7513 // FIXME: Add fast-path for wchar_t too.
7514 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007515 Str = Str.substr(Off);
7516
7517 StringRef::size_type Pos = Str.find(0);
7518 if (Pos != StringRef::npos)
7519 Str = Str.substr(0, Pos);
7520
7521 return Success(Str.size(), E);
7522 }
7523
7524 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007525 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007526
7527 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007528 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7529 APValue Char;
7530 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7531 !Char.isInt())
7532 return false;
7533 if (!Char.getInt())
7534 return Success(Strlen, E);
7535 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7536 return false;
7537 }
7538 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007539
Richard Smithe151bab2016-11-11 23:43:35 +00007540 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007541 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007542 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007543 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007544 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007545 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007546 // A call to strlen is not a constant expression.
7547 if (Info.getLangOpts().CPlusPlus11)
7548 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7549 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007550 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007551 else
7552 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7553 // Fall through.
7554 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007555 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007556 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007557 case Builtin::BI__builtin_wcsncmp:
7558 case Builtin::BI__builtin_memcmp:
7559 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007560 LValue String1, String2;
7561 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7562 !EvaluatePointer(E->getArg(1), String2, Info))
7563 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007564
7565 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7566
Richard Smithe151bab2016-11-11 23:43:35 +00007567 uint64_t MaxLength = uint64_t(-1);
7568 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007569 BuiltinOp != Builtin::BIwcscmp &&
7570 BuiltinOp != Builtin::BI__builtin_strcmp &&
7571 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007572 APSInt N;
7573 if (!EvaluateInteger(E->getArg(2), N, Info))
7574 return false;
7575 MaxLength = N.getExtValue();
7576 }
7577 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007578 BuiltinOp != Builtin::BIwmemcmp &&
7579 BuiltinOp != Builtin::BI__builtin_memcmp &&
7580 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007581 for (; MaxLength; --MaxLength) {
7582 APValue Char1, Char2;
7583 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7584 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7585 !Char1.isInt() || !Char2.isInt())
7586 return false;
7587 if (Char1.getInt() != Char2.getInt())
7588 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7589 if (StopAtNull && !Char1.getInt())
7590 return Success(0, E);
7591 assert(!(StopAtNull && !Char2.getInt()));
7592 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7593 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7594 return false;
7595 }
7596 // We hit the strncmp / memcmp limit.
7597 return Success(0, E);
7598 }
7599
Richard Smith01ba47d2012-04-13 00:45:38 +00007600 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007601 case Builtin::BI__atomic_is_lock_free:
7602 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007603 APSInt SizeVal;
7604 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7605 return false;
7606
7607 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7608 // of two less than the maximum inline atomic width, we know it is
7609 // lock-free. If the size isn't a power of two, or greater than the
7610 // maximum alignment where we promote atomics, we know it is not lock-free
7611 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7612 // the answer can only be determined at runtime; for example, 16-byte
7613 // atomics have lock-free implementations on some, but not all,
7614 // x86-64 processors.
7615
7616 // Check power-of-two.
7617 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007618 if (Size.isPowerOfTwo()) {
7619 // Check against inlining width.
7620 unsigned InlineWidthBits =
7621 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7622 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7623 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7624 Size == CharUnits::One() ||
7625 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7626 Expr::NPC_NeverValueDependent))
7627 // OK, we will inline appropriately-aligned operations of this size,
7628 // and _Atomic(T) is appropriately-aligned.
7629 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007630
Richard Smith01ba47d2012-04-13 00:45:38 +00007631 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7632 castAs<PointerType>()->getPointeeType();
7633 if (!PointeeType->isIncompleteType() &&
7634 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7635 // OK, we will inline operations on this object.
7636 return Success(1, E);
7637 }
7638 }
7639 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007640
Richard Smith01ba47d2012-04-13 00:45:38 +00007641 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7642 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007643 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007644 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007645}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007646
Richard Smith8b3497e2011-10-31 01:37:14 +00007647static bool HasSameBase(const LValue &A, const LValue &B) {
7648 if (!A.getLValueBase())
7649 return !B.getLValueBase();
7650 if (!B.getLValueBase())
7651 return false;
7652
Richard Smithce40ad62011-11-12 22:28:03 +00007653 if (A.getLValueBase().getOpaqueValue() !=
7654 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007655 const Decl *ADecl = GetLValueBaseDecl(A);
7656 if (!ADecl)
7657 return false;
7658 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007659 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007660 return false;
7661 }
7662
7663 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007664 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007665}
7666
Richard Smithd20f1e62014-10-21 23:01:04 +00007667/// \brief Determine whether this is a pointer past the end of the complete
7668/// object referred to by the lvalue.
7669static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7670 const LValue &LV) {
7671 // A null pointer can be viewed as being "past the end" but we don't
7672 // choose to look at it that way here.
7673 if (!LV.getLValueBase())
7674 return false;
7675
7676 // If the designator is valid and refers to a subobject, we're not pointing
7677 // past the end.
7678 if (!LV.getLValueDesignator().Invalid &&
7679 !LV.getLValueDesignator().isOnePastTheEnd())
7680 return false;
7681
David Majnemerc378ca52015-08-29 08:32:55 +00007682 // A pointer to an incomplete type might be past-the-end if the type's size is
7683 // zero. We cannot tell because the type is incomplete.
7684 QualType Ty = getType(LV.getLValueBase());
7685 if (Ty->isIncompleteType())
7686 return true;
7687
Richard Smithd20f1e62014-10-21 23:01:04 +00007688 // We're a past-the-end pointer if we point to the byte after the object,
7689 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007690 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007691 return LV.getLValueOffset() == Size;
7692}
7693
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007694namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007695
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007696/// \brief Data recursive integer evaluator of certain binary operators.
7697///
7698/// We use a data recursive algorithm for binary operators so that we are able
7699/// to handle extreme cases of chained binary operators without causing stack
7700/// overflow.
7701class DataRecursiveIntBinOpEvaluator {
7702 struct EvalResult {
7703 APValue Val;
7704 bool Failed;
7705
7706 EvalResult() : Failed(false) { }
7707
7708 void swap(EvalResult &RHS) {
7709 Val.swap(RHS.Val);
7710 Failed = RHS.Failed;
7711 RHS.Failed = false;
7712 }
7713 };
7714
7715 struct Job {
7716 const Expr *E;
7717 EvalResult LHSResult; // meaningful only for binary operator expression.
7718 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007719
David Blaikie73726062015-08-12 23:09:24 +00007720 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007721 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007722
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007723 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007724 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007725 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007726
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007727 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007728 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007729 };
7730
7731 SmallVector<Job, 16> Queue;
7732
7733 IntExprEvaluator &IntEval;
7734 EvalInfo &Info;
7735 APValue &FinalResult;
7736
7737public:
7738 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7739 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7740
7741 /// \brief True if \param E is a binary operator that we are going to handle
7742 /// data recursively.
7743 /// We handle binary operators that are comma, logical, or that have operands
7744 /// with integral or enumeration type.
7745 static bool shouldEnqueue(const BinaryOperator *E) {
7746 return E->getOpcode() == BO_Comma ||
7747 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007748 (E->isRValue() &&
7749 E->getType()->isIntegralOrEnumerationType() &&
7750 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007751 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007752 }
7753
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007754 bool Traverse(const BinaryOperator *E) {
7755 enqueue(E);
7756 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007757 while (!Queue.empty())
7758 process(PrevResult);
7759
7760 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007761
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007762 FinalResult.swap(PrevResult.Val);
7763 return true;
7764 }
7765
7766private:
7767 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7768 return IntEval.Success(Value, E, Result);
7769 }
7770 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7771 return IntEval.Success(Value, E, Result);
7772 }
7773 bool Error(const Expr *E) {
7774 return IntEval.Error(E);
7775 }
7776 bool Error(const Expr *E, diag::kind D) {
7777 return IntEval.Error(E, D);
7778 }
7779
7780 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7781 return Info.CCEDiag(E, D);
7782 }
7783
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007784 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7785 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007786 bool &SuppressRHSDiags);
7787
7788 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7789 const BinaryOperator *E, APValue &Result);
7790
7791 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7792 Result.Failed = !Evaluate(Result.Val, Info, E);
7793 if (Result.Failed)
7794 Result.Val = APValue();
7795 }
7796
Richard Trieuba4d0872012-03-21 23:30:30 +00007797 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007798
7799 void enqueue(const Expr *E) {
7800 E = E->IgnoreParens();
7801 Queue.resize(Queue.size()+1);
7802 Queue.back().E = E;
7803 Queue.back().Kind = Job::AnyExprKind;
7804 }
7805};
7806
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007807}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007808
7809bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007810 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007811 bool &SuppressRHSDiags) {
7812 if (E->getOpcode() == BO_Comma) {
7813 // Ignore LHS but note if we could not evaluate it.
7814 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007815 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007816 return true;
7817 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007818
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007819 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007820 bool LHSAsBool;
7821 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007822 // We were able to evaluate the LHS, see if we can get away with not
7823 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007824 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7825 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007826 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007827 }
7828 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007829 LHSResult.Failed = true;
7830
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007831 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007832 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007833 if (!Info.noteSideEffect())
7834 return false;
7835
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007836 // We can't evaluate the LHS; however, sometimes the result
7837 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7838 // Don't ignore RHS and suppress diagnostics from this arm.
7839 SuppressRHSDiags = true;
7840 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007841
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007842 return true;
7843 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007844
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007845 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7846 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007847
George Burgess IVa145e252016-05-25 22:38:36 +00007848 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007849 return false; // Ignore RHS;
7850
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007851 return true;
7852}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007853
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007854bool DataRecursiveIntBinOpEvaluator::
7855 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7856 const BinaryOperator *E, APValue &Result) {
7857 if (E->getOpcode() == BO_Comma) {
7858 if (RHSResult.Failed)
7859 return false;
7860 Result = RHSResult.Val;
7861 return true;
7862 }
7863
7864 if (E->isLogicalOp()) {
7865 bool lhsResult, rhsResult;
7866 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7867 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7868
7869 if (LHSIsOK) {
7870 if (RHSIsOK) {
7871 if (E->getOpcode() == BO_LOr)
7872 return Success(lhsResult || rhsResult, E, Result);
7873 else
7874 return Success(lhsResult && rhsResult, E, Result);
7875 }
7876 } else {
7877 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007878 // We can't evaluate the LHS; however, sometimes the result
7879 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7880 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007881 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007882 }
7883 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007884
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007885 return false;
7886 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007887
7888 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7889 E->getRHS()->getType()->isIntegralOrEnumerationType());
7890
7891 if (LHSResult.Failed || RHSResult.Failed)
7892 return false;
7893
7894 const APValue &LHSVal = LHSResult.Val;
7895 const APValue &RHSVal = RHSResult.Val;
7896
7897 // Handle cases like (unsigned long)&a + 4.
7898 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7899 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007900 CharUnits AdditionalOffset =
7901 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007902 if (E->getOpcode() == BO_Add)
7903 Result.getLValueOffset() += AdditionalOffset;
7904 else
7905 Result.getLValueOffset() -= AdditionalOffset;
7906 return true;
7907 }
7908
7909 // Handle cases like 4 + (unsigned long)&a
7910 if (E->getOpcode() == BO_Add &&
7911 RHSVal.isLValue() && LHSVal.isInt()) {
7912 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007913 Result.getLValueOffset() +=
7914 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007915 return true;
7916 }
7917
7918 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7919 // Handle (intptr_t)&&A - (intptr_t)&&B.
7920 if (!LHSVal.getLValueOffset().isZero() ||
7921 !RHSVal.getLValueOffset().isZero())
7922 return false;
7923 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7924 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7925 if (!LHSExpr || !RHSExpr)
7926 return false;
7927 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7928 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7929 if (!LHSAddrExpr || !RHSAddrExpr)
7930 return false;
7931 // Make sure both labels come from the same function.
7932 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7933 RHSAddrExpr->getLabel()->getDeclContext())
7934 return false;
7935 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7936 return true;
7937 }
Richard Smith43e77732013-05-07 04:50:00 +00007938
7939 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007940 if (!LHSVal.isInt() || !RHSVal.isInt())
7941 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007942
7943 // Set up the width and signedness manually, in case it can't be deduced
7944 // from the operation we're performing.
7945 // FIXME: Don't do this in the cases where we can deduce it.
7946 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7947 E->getType()->isUnsignedIntegerOrEnumerationType());
7948 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7949 RHSVal.getInt(), Value))
7950 return false;
7951 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007952}
7953
Richard Trieuba4d0872012-03-21 23:30:30 +00007954void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007955 Job &job = Queue.back();
7956
7957 switch (job.Kind) {
7958 case Job::AnyExprKind: {
7959 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7960 if (shouldEnqueue(Bop)) {
7961 job.Kind = Job::BinOpKind;
7962 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007963 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007964 }
7965 }
7966
7967 EvaluateExpr(job.E, Result);
7968 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007969 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007970 }
7971
7972 case Job::BinOpKind: {
7973 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007974 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007975 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007976 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007977 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007978 }
7979 if (SuppressRHSDiags)
7980 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007981 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007982 job.Kind = Job::BinOpVisitedLHSKind;
7983 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007984 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007985 }
7986
7987 case Job::BinOpVisitedLHSKind: {
7988 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7989 EvalResult RHS;
7990 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007991 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007992 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007993 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007994 }
7995 }
7996
7997 llvm_unreachable("Invalid Job::Kind!");
7998}
7999
George Burgess IV8c892b52016-05-25 22:31:54 +00008000namespace {
8001/// Used when we determine that we should fail, but can keep evaluating prior to
8002/// noting that we had a failure.
8003class DelayedNoteFailureRAII {
8004 EvalInfo &Info;
8005 bool NoteFailure;
8006
8007public:
8008 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8009 : Info(Info), NoteFailure(NoteFailure) {}
8010 ~DelayedNoteFailureRAII() {
8011 if (NoteFailure) {
8012 bool ContinueAfterFailure = Info.noteFailure();
8013 (void)ContinueAfterFailure;
8014 assert(ContinueAfterFailure &&
8015 "Shouldn't have kept evaluating on failure.");
8016 }
8017 }
8018};
8019}
8020
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008021bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008022 // We don't call noteFailure immediately because the assignment happens after
8023 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008024 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008025 return Error(E);
8026
George Burgess IV8c892b52016-05-25 22:31:54 +00008027 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008028 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8029 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008030
Anders Carlssonacc79812008-11-16 07:17:21 +00008031 QualType LHSTy = E->getLHS()->getType();
8032 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008033
Chandler Carruthb29a7432014-10-11 11:03:30 +00008034 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008035 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008036 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008037 if (E->isAssignmentOp()) {
8038 LValue LV;
8039 EvaluateLValue(E->getLHS(), LV, Info);
8040 LHSOK = false;
8041 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008042 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8043 if (LHSOK) {
8044 LHS.makeComplexFloat();
8045 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8046 }
8047 } else {
8048 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8049 }
George Burgess IVa145e252016-05-25 22:38:36 +00008050 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008051 return false;
8052
Chandler Carruthb29a7432014-10-11 11:03:30 +00008053 if (E->getRHS()->getType()->isRealFloatingType()) {
8054 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8055 return false;
8056 RHS.makeComplexFloat();
8057 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8058 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008059 return false;
8060
8061 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008062 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008063 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008064 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008065 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8066
John McCalle3027922010-08-25 11:45:40 +00008067 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008068 return Success((CR_r == APFloat::cmpEqual &&
8069 CR_i == APFloat::cmpEqual), E);
8070 else {
John McCalle3027922010-08-25 11:45:40 +00008071 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008072 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008073 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008074 CR_r == APFloat::cmpLessThan ||
8075 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008076 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008077 CR_i == APFloat::cmpLessThan ||
8078 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008079 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008080 } else {
John McCalle3027922010-08-25 11:45:40 +00008081 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008082 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8083 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8084 else {
John McCalle3027922010-08-25 11:45:40 +00008085 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008086 "Invalid compex comparison.");
8087 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8088 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8089 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008090 }
8091 }
Mike Stump11289f42009-09-09 15:08:12 +00008092
Anders Carlssonacc79812008-11-16 07:17:21 +00008093 if (LHSTy->isRealFloatingType() &&
8094 RHSTy->isRealFloatingType()) {
8095 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008096
Richard Smith253c2a32012-01-27 01:14:48 +00008097 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008098 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008099 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008100
Richard Smith253c2a32012-01-27 01:14:48 +00008101 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008102 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008103
Anders Carlssonacc79812008-11-16 07:17:21 +00008104 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008105
Anders Carlssonacc79812008-11-16 07:17:21 +00008106 switch (E->getOpcode()) {
8107 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008108 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008109 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008110 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008111 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008112 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008113 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008114 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008115 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008116 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008117 E);
John McCalle3027922010-08-25 11:45:40 +00008118 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008119 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008120 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008121 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008122 || CR == APFloat::cmpLessThan
8123 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008124 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008125 }
Mike Stump11289f42009-09-09 15:08:12 +00008126
Eli Friedmana38da572009-04-28 19:17:36 +00008127 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008128 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008129 LValue LHSValue, RHSValue;
8130
8131 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008132 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008133 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008134
Richard Smith253c2a32012-01-27 01:14:48 +00008135 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008136 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008137
Richard Smith8b3497e2011-10-31 01:37:14 +00008138 // Reject differing bases from the normal codepath; we special-case
8139 // comparisons to null.
8140 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008141 if (E->getOpcode() == BO_Sub) {
8142 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008143 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008144 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008145 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008146 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008147 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008148 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008149 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8150 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8151 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008152 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008153 // Make sure both labels come from the same function.
8154 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8155 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008156 return Error(E);
8157 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008158 }
Richard Smith83c68212011-10-31 05:11:32 +00008159 // Inequalities and subtractions between unrelated pointers have
8160 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008161 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008162 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008163 // A constant address may compare equal to the address of a symbol.
8164 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008165 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008166 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8167 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008168 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008169 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008170 // distinct addresses. In clang, the result of such a comparison is
8171 // unspecified, so it is not a constant expression. However, we do know
8172 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008173 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8174 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008175 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008176 // We can't tell whether weak symbols will end up pointing to the same
8177 // object.
8178 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008179 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008180 // We can't compare the address of the start of one object with the
8181 // past-the-end address of another object, per C++ DR1652.
8182 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8183 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8184 (RHSValue.Base && RHSValue.Offset.isZero() &&
8185 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8186 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008187 // We can't tell whether an object is at the same address as another
8188 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008189 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8190 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008191 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008192 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008193 // (Note that clang defaults to -fmerge-all-constants, which can
8194 // lead to inconsistent results for comparisons involving the address
8195 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008196 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008197 }
Eli Friedman64004332009-03-23 04:38:34 +00008198
Richard Smith1b470412012-02-01 08:10:20 +00008199 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8200 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8201
Richard Smith84f6dcf2012-02-02 01:16:57 +00008202 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8203 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8204
John McCalle3027922010-08-25 11:45:40 +00008205 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008206 // C++11 [expr.add]p6:
8207 // Unless both pointers point to elements of the same array object, or
8208 // one past the last element of the array object, the behavior is
8209 // undefined.
8210 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8211 !AreElementsOfSameArray(getType(LHSValue.Base),
8212 LHSDesignator, RHSDesignator))
8213 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8214
Chris Lattner882bdf22010-04-20 17:13:14 +00008215 QualType Type = E->getLHS()->getType();
8216 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008217
Richard Smithd62306a2011-11-10 06:34:14 +00008218 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008219 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008220 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008221
Richard Smith84c6b3d2013-09-10 21:34:14 +00008222 // As an extension, a type may have zero size (empty struct or union in
8223 // C, array of zero length). Pointer subtraction in such cases has
8224 // undefined behavior, so is not constant.
8225 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008226 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008227 << ElementType;
8228 return false;
8229 }
8230
Richard Smith1b470412012-02-01 08:10:20 +00008231 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8232 // and produce incorrect results when it overflows. Such behavior
8233 // appears to be non-conforming, but is common, so perhaps we should
8234 // assume the standard intended for such cases to be undefined behavior
8235 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008236
Richard Smith1b470412012-02-01 08:10:20 +00008237 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8238 // overflow in the final conversion to ptrdiff_t.
8239 APSInt LHS(
8240 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8241 APSInt RHS(
8242 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8243 APSInt ElemSize(
8244 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8245 APSInt TrueResult = (LHS - RHS) / ElemSize;
8246 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8247
Richard Smith0c6124b2015-12-03 01:36:22 +00008248 if (Result.extend(65) != TrueResult &&
8249 !HandleOverflow(Info, E, TrueResult, E->getType()))
8250 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008251 return Success(Result, E);
8252 }
Richard Smithde21b242012-01-31 06:41:30 +00008253
8254 // C++11 [expr.rel]p3:
8255 // Pointers to void (after pointer conversions) can be compared, with a
8256 // result defined as follows: If both pointers represent the same
8257 // address or are both the null pointer value, the result is true if the
8258 // operator is <= or >= and false otherwise; otherwise the result is
8259 // unspecified.
8260 // We interpret this as applying to pointers to *cv* void.
8261 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008262 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008263 CCEDiag(E, diag::note_constexpr_void_comparison);
8264
Richard Smith84f6dcf2012-02-02 01:16:57 +00008265 // C++11 [expr.rel]p2:
8266 // - If two pointers point to non-static data members of the same object,
8267 // or to subobjects or array elements fo such members, recursively, the
8268 // pointer to the later declared member compares greater provided the
8269 // two members have the same access control and provided their class is
8270 // not a union.
8271 // [...]
8272 // - Otherwise pointer comparisons are unspecified.
8273 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8274 E->isRelationalOp()) {
8275 bool WasArrayIndex;
8276 unsigned Mismatch =
8277 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8278 RHSDesignator, WasArrayIndex);
8279 // At the point where the designators diverge, the comparison has a
8280 // specified value if:
8281 // - we are comparing array indices
8282 // - we are comparing fields of a union, or fields with the same access
8283 // Otherwise, the result is unspecified and thus the comparison is not a
8284 // constant expression.
8285 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8286 Mismatch < RHSDesignator.Entries.size()) {
8287 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8288 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8289 if (!LF && !RF)
8290 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8291 else if (!LF)
8292 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8293 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8294 << RF->getParent() << RF;
8295 else if (!RF)
8296 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8297 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8298 << LF->getParent() << LF;
8299 else if (!LF->getParent()->isUnion() &&
8300 LF->getAccess() != RF->getAccess())
8301 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8302 << LF << LF->getAccess() << RF << RF->getAccess()
8303 << LF->getParent();
8304 }
8305 }
8306
Eli Friedman6c31cb42012-04-16 04:30:08 +00008307 // The comparison here must be unsigned, and performed with the same
8308 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008309 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8310 uint64_t CompareLHS = LHSOffset.getQuantity();
8311 uint64_t CompareRHS = RHSOffset.getQuantity();
8312 assert(PtrSize <= 64 && "Unexpected pointer width");
8313 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8314 CompareLHS &= Mask;
8315 CompareRHS &= Mask;
8316
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008317 // If there is a base and this is a relational operator, we can only
8318 // compare pointers within the object in question; otherwise, the result
8319 // depends on where the object is located in memory.
8320 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8321 QualType BaseTy = getType(LHSValue.Base);
8322 if (BaseTy->isIncompleteType())
8323 return Error(E);
8324 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8325 uint64_t OffsetLimit = Size.getQuantity();
8326 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8327 return Error(E);
8328 }
8329
Richard Smith8b3497e2011-10-31 01:37:14 +00008330 switch (E->getOpcode()) {
8331 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008332 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8333 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8334 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8335 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8336 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8337 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008338 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008339 }
8340 }
Richard Smith7bb00672012-02-01 01:42:44 +00008341
8342 if (LHSTy->isMemberPointerType()) {
8343 assert(E->isEqualityOp() && "unexpected member pointer operation");
8344 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8345
8346 MemberPtr LHSValue, RHSValue;
8347
8348 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008349 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008350 return false;
8351
8352 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8353 return false;
8354
8355 // C++11 [expr.eq]p2:
8356 // If both operands are null, they compare equal. Otherwise if only one is
8357 // null, they compare unequal.
8358 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8359 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8360 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8361 }
8362
8363 // Otherwise if either is a pointer to a virtual member function, the
8364 // result is unspecified.
8365 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8366 if (MD->isVirtual())
8367 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8368 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8369 if (MD->isVirtual())
8370 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8371
8372 // Otherwise they compare equal if and only if they would refer to the
8373 // same member of the same most derived object or the same subobject if
8374 // they were dereferenced with a hypothetical object of the associated
8375 // class type.
8376 bool Equal = LHSValue == RHSValue;
8377 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8378 }
8379
Richard Smithab44d9b2012-02-14 22:35:28 +00008380 if (LHSTy->isNullPtrType()) {
8381 assert(E->isComparisonOp() && "unexpected nullptr operation");
8382 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8383 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8384 // are compared, the result is true of the operator is <=, >= or ==, and
8385 // false otherwise.
8386 BinaryOperator::Opcode Opcode = E->getOpcode();
8387 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8388 }
8389
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008390 assert((!LHSTy->isIntegralOrEnumerationType() ||
8391 !RHSTy->isIntegralOrEnumerationType()) &&
8392 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8393 // We can't continue from here for non-integral types.
8394 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008395}
8396
Peter Collingbournee190dee2011-03-11 19:24:49 +00008397/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8398/// a result as the expression's type.
8399bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8400 const UnaryExprOrTypeTraitExpr *E) {
8401 switch(E->getKind()) {
8402 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008403 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008404 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008405 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008406 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008407 }
Eli Friedman64004332009-03-23 04:38:34 +00008408
Peter Collingbournee190dee2011-03-11 19:24:49 +00008409 case UETT_VecStep: {
8410 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008411
Peter Collingbournee190dee2011-03-11 19:24:49 +00008412 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008413 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008414
Peter Collingbournee190dee2011-03-11 19:24:49 +00008415 // The vec_step built-in functions that take a 3-component
8416 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8417 if (n == 3)
8418 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008419
Peter Collingbournee190dee2011-03-11 19:24:49 +00008420 return Success(n, E);
8421 } else
8422 return Success(1, E);
8423 }
8424
8425 case UETT_SizeOf: {
8426 QualType SrcTy = E->getTypeOfArgument();
8427 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8428 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008429 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8430 SrcTy = Ref->getPointeeType();
8431
Richard Smithd62306a2011-11-10 06:34:14 +00008432 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008433 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008434 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008435 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008436 }
Alexey Bataev00396512015-07-02 03:40:19 +00008437 case UETT_OpenMPRequiredSimdAlign:
8438 assert(E->isArgumentType());
8439 return Success(
8440 Info.Ctx.toCharUnitsFromBits(
8441 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8442 .getQuantity(),
8443 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008444 }
8445
8446 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008447}
8448
Peter Collingbournee9200682011-05-13 03:29:01 +00008449bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008450 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008451 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008452 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008453 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008454 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008455 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008456 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008457 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008458 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008459 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008460 APSInt IdxResult;
8461 if (!EvaluateInteger(Idx, IdxResult, Info))
8462 return false;
8463 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8464 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008465 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008466 CurrentType = AT->getElementType();
8467 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8468 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008469 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008470 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008471
James Y Knight7281c352015-12-29 22:31:18 +00008472 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008473 FieldDecl *MemberDecl = ON.getField();
8474 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008475 if (!RT)
8476 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008477 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008478 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008479 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008480 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008481 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008482 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008483 CurrentType = MemberDecl->getType().getNonReferenceType();
8484 break;
8485 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008486
James Y Knight7281c352015-12-29 22:31:18 +00008487 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008488 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008489
James Y Knight7281c352015-12-29 22:31:18 +00008490 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008491 CXXBaseSpecifier *BaseSpec = ON.getBase();
8492 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008493 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008494
8495 // Find the layout of the class whose base we are looking into.
8496 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008497 if (!RT)
8498 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008499 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008500 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008501 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8502
8503 // Find the base class itself.
8504 CurrentType = BaseSpec->getType();
8505 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8506 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008507 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008508
8509 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008510 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008511 break;
8512 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008513 }
8514 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008515 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008516}
8517
Chris Lattnere13042c2008-07-11 19:10:17 +00008518bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008519 switch (E->getOpcode()) {
8520 default:
8521 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8522 // See C99 6.6p3.
8523 return Error(E);
8524 case UO_Extension:
8525 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8526 // If so, we could clear the diagnostic ID.
8527 return Visit(E->getSubExpr());
8528 case UO_Plus:
8529 // The result is just the value.
8530 return Visit(E->getSubExpr());
8531 case UO_Minus: {
8532 if (!Visit(E->getSubExpr()))
8533 return false;
8534 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008535 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008536 if (Value.isSigned() && Value.isMinSignedValue() &&
8537 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8538 E->getType()))
8539 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008540 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008541 }
8542 case UO_Not: {
8543 if (!Visit(E->getSubExpr()))
8544 return false;
8545 if (!Result.isInt()) return Error(E);
8546 return Success(~Result.getInt(), E);
8547 }
8548 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008549 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008550 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008551 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008552 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008553 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008554 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008555}
Mike Stump11289f42009-09-09 15:08:12 +00008556
Chris Lattner477c4be2008-07-12 01:15:53 +00008557/// HandleCast - This is used to evaluate implicit or explicit casts where the
8558/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008559bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8560 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008561 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008562 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008563
Eli Friedmanc757de22011-03-25 00:43:55 +00008564 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008565 case CK_BaseToDerived:
8566 case CK_DerivedToBase:
8567 case CK_UncheckedDerivedToBase:
8568 case CK_Dynamic:
8569 case CK_ToUnion:
8570 case CK_ArrayToPointerDecay:
8571 case CK_FunctionToPointerDecay:
8572 case CK_NullToPointer:
8573 case CK_NullToMemberPointer:
8574 case CK_BaseToDerivedMemberPointer:
8575 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008576 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008577 case CK_ConstructorConversion:
8578 case CK_IntegralToPointer:
8579 case CK_ToVoid:
8580 case CK_VectorSplat:
8581 case CK_IntegralToFloating:
8582 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008583 case CK_CPointerToObjCPointerCast:
8584 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008585 case CK_AnyPointerToBlockPointerCast:
8586 case CK_ObjCObjectLValueCast:
8587 case CK_FloatingRealToComplex:
8588 case CK_FloatingComplexToReal:
8589 case CK_FloatingComplexCast:
8590 case CK_FloatingComplexToIntegralComplex:
8591 case CK_IntegralRealToComplex:
8592 case CK_IntegralComplexCast:
8593 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008594 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008595 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008596 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008597 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008598 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008599 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008600 llvm_unreachable("invalid cast kind for integral value");
8601
Eli Friedman9faf2f92011-03-25 19:07:11 +00008602 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008603 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008604 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008605 case CK_ARCProduceObject:
8606 case CK_ARCConsumeObject:
8607 case CK_ARCReclaimReturnedObject:
8608 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008609 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008610 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008611
Richard Smith4ef685b2012-01-17 21:17:26 +00008612 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008613 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008614 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008615 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008616 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008617
8618 case CK_MemberPointerToBoolean:
8619 case CK_PointerToBoolean:
8620 case CK_IntegralToBoolean:
8621 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008622 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008623 case CK_FloatingComplexToBoolean:
8624 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008625 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008626 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008627 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008628 uint64_t IntResult = BoolResult;
8629 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8630 IntResult = (uint64_t)-1;
8631 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008632 }
8633
Eli Friedmanc757de22011-03-25 00:43:55 +00008634 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008635 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008636 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008637
Eli Friedman742421e2009-02-20 01:15:07 +00008638 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008639 // Allow casts of address-of-label differences if they are no-ops
8640 // or narrowing. (The narrowing case isn't actually guaranteed to
8641 // be constant-evaluatable except in some narrow cases which are hard
8642 // to detect here. We let it through on the assumption the user knows
8643 // what they are doing.)
8644 if (Result.isAddrLabelDiff())
8645 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008646 // Only allow casts of lvalues if they are lossless.
8647 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8648 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008649
Richard Smith911e1422012-01-30 22:27:01 +00008650 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8651 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008652 }
Mike Stump11289f42009-09-09 15:08:12 +00008653
Eli Friedmanc757de22011-03-25 00:43:55 +00008654 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008655 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8656
John McCall45d55e42010-05-07 21:00:08 +00008657 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008658 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008659 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008660
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008661 if (LV.getLValueBase()) {
8662 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008663 // FIXME: Allow a larger integer size than the pointer size, and allow
8664 // narrowing back down to pointer width in subsequent integral casts.
8665 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008666 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008667 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008668
Richard Smithcf74da72011-11-16 07:18:12 +00008669 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008670 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008671 return true;
8672 }
8673
Yaxun Liu402804b2016-12-15 08:09:08 +00008674 uint64_t V;
8675 if (LV.isNullPointer())
8676 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8677 else
8678 V = LV.getLValueOffset().getQuantity();
8679
8680 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008681 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008682 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008683
Eli Friedmanc757de22011-03-25 00:43:55 +00008684 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008685 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008686 if (!EvaluateComplex(SubExpr, C, Info))
8687 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008688 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008689 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008690
Eli Friedmanc757de22011-03-25 00:43:55 +00008691 case CK_FloatingToIntegral: {
8692 APFloat F(0.0);
8693 if (!EvaluateFloat(SubExpr, F, Info))
8694 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008695
Richard Smith357362d2011-12-13 06:39:58 +00008696 APSInt Value;
8697 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8698 return false;
8699 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008700 }
8701 }
Mike Stump11289f42009-09-09 15:08:12 +00008702
Eli Friedmanc757de22011-03-25 00:43:55 +00008703 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008704}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008705
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008706bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8707 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008708 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008709 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8710 return false;
8711 if (!LV.isComplexInt())
8712 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008713 return Success(LV.getComplexIntReal(), E);
8714 }
8715
8716 return Visit(E->getSubExpr());
8717}
8718
Eli Friedman4e7a2412009-02-27 04:45:43 +00008719bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008720 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008721 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008722 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8723 return false;
8724 if (!LV.isComplexInt())
8725 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008726 return Success(LV.getComplexIntImag(), E);
8727 }
8728
Richard Smith4a678122011-10-24 18:44:57 +00008729 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008730 return Success(0, E);
8731}
8732
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008733bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8734 return Success(E->getPackLength(), E);
8735}
8736
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008737bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8738 return Success(E->getValue(), E);
8739}
8740
Chris Lattner05706e882008-07-11 18:11:29 +00008741//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008742// Float Evaluation
8743//===----------------------------------------------------------------------===//
8744
8745namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008746class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008747 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008748 APFloat &Result;
8749public:
8750 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008751 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008752
Richard Smith2e312c82012-03-03 22:46:17 +00008753 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008754 Result = V.getFloat();
8755 return true;
8756 }
Eli Friedman24c01542008-08-22 00:06:13 +00008757
Richard Smithfddd3842011-12-30 21:15:51 +00008758 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008759 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8760 return true;
8761 }
8762
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008763 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008764
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008765 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008766 bool VisitBinaryOperator(const BinaryOperator *E);
8767 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008768 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008769
John McCallb1fb0d32010-05-07 22:08:54 +00008770 bool VisitUnaryReal(const UnaryOperator *E);
8771 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008772
Richard Smithfddd3842011-12-30 21:15:51 +00008773 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008774};
8775} // end anonymous namespace
8776
8777static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008778 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008779 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008780}
8781
Jay Foad39c79802011-01-12 09:06:06 +00008782static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008783 QualType ResultTy,
8784 const Expr *Arg,
8785 bool SNaN,
8786 llvm::APFloat &Result) {
8787 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8788 if (!S) return false;
8789
8790 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8791
8792 llvm::APInt fill;
8793
8794 // Treat empty strings as if they were zero.
8795 if (S->getString().empty())
8796 fill = llvm::APInt(32, 0);
8797 else if (S->getString().getAsInteger(0, fill))
8798 return false;
8799
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008800 if (Context.getTargetInfo().isNan2008()) {
8801 if (SNaN)
8802 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8803 else
8804 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8805 } else {
8806 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8807 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8808 // a different encoding to what became a standard in 2008, and for pre-
8809 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8810 // sNaN. This is now known as "legacy NaN" encoding.
8811 if (SNaN)
8812 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8813 else
8814 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8815 }
8816
John McCall16291492010-02-28 13:00:19 +00008817 return true;
8818}
8819
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008820bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008821 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008822 default:
8823 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8824
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008825 case Builtin::BI__builtin_huge_val:
8826 case Builtin::BI__builtin_huge_valf:
8827 case Builtin::BI__builtin_huge_vall:
8828 case Builtin::BI__builtin_inf:
8829 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008830 case Builtin::BI__builtin_infl: {
8831 const llvm::fltSemantics &Sem =
8832 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008833 Result = llvm::APFloat::getInf(Sem);
8834 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008835 }
Mike Stump11289f42009-09-09 15:08:12 +00008836
John McCall16291492010-02-28 13:00:19 +00008837 case Builtin::BI__builtin_nans:
8838 case Builtin::BI__builtin_nansf:
8839 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008840 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8841 true, Result))
8842 return Error(E);
8843 return true;
John McCall16291492010-02-28 13:00:19 +00008844
Chris Lattner0b7282e2008-10-06 06:31:58 +00008845 case Builtin::BI__builtin_nan:
8846 case Builtin::BI__builtin_nanf:
8847 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008848 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008849 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008850 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8851 false, Result))
8852 return Error(E);
8853 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008854
8855 case Builtin::BI__builtin_fabs:
8856 case Builtin::BI__builtin_fabsf:
8857 case Builtin::BI__builtin_fabsl:
8858 if (!EvaluateFloat(E->getArg(0), Result, Info))
8859 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008860
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008861 if (Result.isNegative())
8862 Result.changeSign();
8863 return true;
8864
Richard Smith8889a3d2013-06-13 06:26:32 +00008865 // FIXME: Builtin::BI__builtin_powi
8866 // FIXME: Builtin::BI__builtin_powif
8867 // FIXME: Builtin::BI__builtin_powil
8868
Mike Stump11289f42009-09-09 15:08:12 +00008869 case Builtin::BI__builtin_copysign:
8870 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008871 case Builtin::BI__builtin_copysignl: {
8872 APFloat RHS(0.);
8873 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8874 !EvaluateFloat(E->getArg(1), RHS, Info))
8875 return false;
8876 Result.copySign(RHS);
8877 return true;
8878 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008879 }
8880}
8881
John McCallb1fb0d32010-05-07 22:08:54 +00008882bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008883 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8884 ComplexValue CV;
8885 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8886 return false;
8887 Result = CV.FloatReal;
8888 return true;
8889 }
8890
8891 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008892}
8893
8894bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008895 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8896 ComplexValue CV;
8897 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8898 return false;
8899 Result = CV.FloatImag;
8900 return true;
8901 }
8902
Richard Smith4a678122011-10-24 18:44:57 +00008903 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008904 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8905 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008906 return true;
8907}
8908
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008909bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008910 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008911 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008912 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008913 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008914 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008915 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8916 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008917 Result.changeSign();
8918 return true;
8919 }
8920}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008921
Eli Friedman24c01542008-08-22 00:06:13 +00008922bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008923 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8924 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008925
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008926 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008927 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008928 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008929 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008930 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8931 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008932}
8933
8934bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8935 Result = E->getValue();
8936 return true;
8937}
8938
Peter Collingbournee9200682011-05-13 03:29:01 +00008939bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8940 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008941
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008942 switch (E->getCastKind()) {
8943 default:
Richard Smith11562c52011-10-28 17:51:58 +00008944 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008945
8946 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008947 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008948 return EvaluateInteger(SubExpr, IntResult, Info) &&
8949 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8950 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008951 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008952
8953 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008954 if (!Visit(SubExpr))
8955 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008956 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8957 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008958 }
John McCalld7646252010-11-14 08:17:51 +00008959
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008960 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008961 ComplexValue V;
8962 if (!EvaluateComplex(SubExpr, V, Info))
8963 return false;
8964 Result = V.getComplexFloatReal();
8965 return true;
8966 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008967 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008968}
8969
Eli Friedman24c01542008-08-22 00:06:13 +00008970//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008971// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008972//===----------------------------------------------------------------------===//
8973
8974namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008975class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008976 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008977 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008978
Anders Carlsson537969c2008-11-16 20:27:53 +00008979public:
John McCall93d91dc2010-05-07 17:22:02 +00008980 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008981 : ExprEvaluatorBaseTy(info), Result(Result) {}
8982
Richard Smith2e312c82012-03-03 22:46:17 +00008983 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008984 Result.setFrom(V);
8985 return true;
8986 }
Mike Stump11289f42009-09-09 15:08:12 +00008987
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008988 bool ZeroInitialization(const Expr *E);
8989
Anders Carlsson537969c2008-11-16 20:27:53 +00008990 //===--------------------------------------------------------------------===//
8991 // Visitor Methods
8992 //===--------------------------------------------------------------------===//
8993
Peter Collingbournee9200682011-05-13 03:29:01 +00008994 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008995 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008996 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008997 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008998 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008999};
9000} // end anonymous namespace
9001
John McCall93d91dc2010-05-07 17:22:02 +00009002static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9003 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009004 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009005 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009006}
9007
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009008bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009009 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009010 if (ElemTy->isRealFloatingType()) {
9011 Result.makeComplexFloat();
9012 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9013 Result.FloatReal = Zero;
9014 Result.FloatImag = Zero;
9015 } else {
9016 Result.makeComplexInt();
9017 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9018 Result.IntReal = Zero;
9019 Result.IntImag = Zero;
9020 }
9021 return true;
9022}
9023
Peter Collingbournee9200682011-05-13 03:29:01 +00009024bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9025 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009026
9027 if (SubExpr->getType()->isRealFloatingType()) {
9028 Result.makeComplexFloat();
9029 APFloat &Imag = Result.FloatImag;
9030 if (!EvaluateFloat(SubExpr, Imag, Info))
9031 return false;
9032
9033 Result.FloatReal = APFloat(Imag.getSemantics());
9034 return true;
9035 } else {
9036 assert(SubExpr->getType()->isIntegerType() &&
9037 "Unexpected imaginary literal.");
9038
9039 Result.makeComplexInt();
9040 APSInt &Imag = Result.IntImag;
9041 if (!EvaluateInteger(SubExpr, Imag, Info))
9042 return false;
9043
9044 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9045 return true;
9046 }
9047}
9048
Peter Collingbournee9200682011-05-13 03:29:01 +00009049bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009050
John McCallfcef3cf2010-12-14 17:51:41 +00009051 switch (E->getCastKind()) {
9052 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009053 case CK_BaseToDerived:
9054 case CK_DerivedToBase:
9055 case CK_UncheckedDerivedToBase:
9056 case CK_Dynamic:
9057 case CK_ToUnion:
9058 case CK_ArrayToPointerDecay:
9059 case CK_FunctionToPointerDecay:
9060 case CK_NullToPointer:
9061 case CK_NullToMemberPointer:
9062 case CK_BaseToDerivedMemberPointer:
9063 case CK_DerivedToBaseMemberPointer:
9064 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009065 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009066 case CK_ConstructorConversion:
9067 case CK_IntegralToPointer:
9068 case CK_PointerToIntegral:
9069 case CK_PointerToBoolean:
9070 case CK_ToVoid:
9071 case CK_VectorSplat:
9072 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009073 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009074 case CK_IntegralToBoolean:
9075 case CK_IntegralToFloating:
9076 case CK_FloatingToIntegral:
9077 case CK_FloatingToBoolean:
9078 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009079 case CK_CPointerToObjCPointerCast:
9080 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009081 case CK_AnyPointerToBlockPointerCast:
9082 case CK_ObjCObjectLValueCast:
9083 case CK_FloatingComplexToReal:
9084 case CK_FloatingComplexToBoolean:
9085 case CK_IntegralComplexToReal:
9086 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009087 case CK_ARCProduceObject:
9088 case CK_ARCConsumeObject:
9089 case CK_ARCReclaimReturnedObject:
9090 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009091 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009092 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009093 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009094 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009095 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009096 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009097 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009098 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009099
John McCallfcef3cf2010-12-14 17:51:41 +00009100 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009101 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009102 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009103 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009104
9105 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009106 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009107 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009108 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009109
9110 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009111 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009112 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009113 return false;
9114
John McCallfcef3cf2010-12-14 17:51:41 +00009115 Result.makeComplexFloat();
9116 Result.FloatImag = APFloat(Real.getSemantics());
9117 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009118 }
9119
John McCallfcef3cf2010-12-14 17:51:41 +00009120 case CK_FloatingComplexCast: {
9121 if (!Visit(E->getSubExpr()))
9122 return false;
9123
9124 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9125 QualType From
9126 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9127
Richard Smith357362d2011-12-13 06:39:58 +00009128 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9129 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009130 }
9131
9132 case CK_FloatingComplexToIntegralComplex: {
9133 if (!Visit(E->getSubExpr()))
9134 return false;
9135
9136 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9137 QualType From
9138 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9139 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009140 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9141 To, Result.IntReal) &&
9142 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9143 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009144 }
9145
9146 case CK_IntegralRealToComplex: {
9147 APSInt &Real = Result.IntReal;
9148 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9149 return false;
9150
9151 Result.makeComplexInt();
9152 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9153 return true;
9154 }
9155
9156 case CK_IntegralComplexCast: {
9157 if (!Visit(E->getSubExpr()))
9158 return false;
9159
9160 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9161 QualType From
9162 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9163
Richard Smith911e1422012-01-30 22:27:01 +00009164 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9165 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009166 return true;
9167 }
9168
9169 case CK_IntegralComplexToFloatingComplex: {
9170 if (!Visit(E->getSubExpr()))
9171 return false;
9172
Ted Kremenek28831752012-08-23 20:46:57 +00009173 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009174 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009175 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009176 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009177 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9178 To, Result.FloatReal) &&
9179 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9180 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009181 }
9182 }
9183
9184 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009185}
9186
John McCall93d91dc2010-05-07 17:22:02 +00009187bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009188 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009189 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9190
Chandler Carrutha216cad2014-10-11 00:57:18 +00009191 // Track whether the LHS or RHS is real at the type system level. When this is
9192 // the case we can simplify our evaluation strategy.
9193 bool LHSReal = false, RHSReal = false;
9194
9195 bool LHSOK;
9196 if (E->getLHS()->getType()->isRealFloatingType()) {
9197 LHSReal = true;
9198 APFloat &Real = Result.FloatReal;
9199 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9200 if (LHSOK) {
9201 Result.makeComplexFloat();
9202 Result.FloatImag = APFloat(Real.getSemantics());
9203 }
9204 } else {
9205 LHSOK = Visit(E->getLHS());
9206 }
George Burgess IVa145e252016-05-25 22:38:36 +00009207 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009208 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009209
John McCall93d91dc2010-05-07 17:22:02 +00009210 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009211 if (E->getRHS()->getType()->isRealFloatingType()) {
9212 RHSReal = true;
9213 APFloat &Real = RHS.FloatReal;
9214 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9215 return false;
9216 RHS.makeComplexFloat();
9217 RHS.FloatImag = APFloat(Real.getSemantics());
9218 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009219 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009220
Chandler Carrutha216cad2014-10-11 00:57:18 +00009221 assert(!(LHSReal && RHSReal) &&
9222 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009223 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009224 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009225 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009226 if (Result.isComplexFloat()) {
9227 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9228 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009229 if (LHSReal)
9230 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9231 else if (!RHSReal)
9232 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9233 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009234 } else {
9235 Result.getComplexIntReal() += RHS.getComplexIntReal();
9236 Result.getComplexIntImag() += RHS.getComplexIntImag();
9237 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009238 break;
John McCalle3027922010-08-25 11:45:40 +00009239 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009240 if (Result.isComplexFloat()) {
9241 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9242 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009243 if (LHSReal) {
9244 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9245 Result.getComplexFloatImag().changeSign();
9246 } else if (!RHSReal) {
9247 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9248 APFloat::rmNearestTiesToEven);
9249 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009250 } else {
9251 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9252 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9253 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009254 break;
John McCalle3027922010-08-25 11:45:40 +00009255 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009256 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009257 // This is an implementation of complex multiplication according to the
9258 // constraints laid out in C11 Annex G. The implemantion uses the
9259 // following naming scheme:
9260 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009261 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009262 APFloat &A = LHS.getComplexFloatReal();
9263 APFloat &B = LHS.getComplexFloatImag();
9264 APFloat &C = RHS.getComplexFloatReal();
9265 APFloat &D = RHS.getComplexFloatImag();
9266 APFloat &ResR = Result.getComplexFloatReal();
9267 APFloat &ResI = Result.getComplexFloatImag();
9268 if (LHSReal) {
9269 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9270 ResR = A * C;
9271 ResI = A * D;
9272 } else if (RHSReal) {
9273 ResR = C * A;
9274 ResI = C * B;
9275 } else {
9276 // In the fully general case, we need to handle NaNs and infinities
9277 // robustly.
9278 APFloat AC = A * C;
9279 APFloat BD = B * D;
9280 APFloat AD = A * D;
9281 APFloat BC = B * C;
9282 ResR = AC - BD;
9283 ResI = AD + BC;
9284 if (ResR.isNaN() && ResI.isNaN()) {
9285 bool Recalc = false;
9286 if (A.isInfinity() || B.isInfinity()) {
9287 A = APFloat::copySign(
9288 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9289 B = APFloat::copySign(
9290 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9291 if (C.isNaN())
9292 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9293 if (D.isNaN())
9294 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9295 Recalc = true;
9296 }
9297 if (C.isInfinity() || D.isInfinity()) {
9298 C = APFloat::copySign(
9299 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9300 D = APFloat::copySign(
9301 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9302 if (A.isNaN())
9303 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9304 if (B.isNaN())
9305 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9306 Recalc = true;
9307 }
9308 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9309 AD.isInfinity() || BC.isInfinity())) {
9310 if (A.isNaN())
9311 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9312 if (B.isNaN())
9313 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9314 if (C.isNaN())
9315 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9316 if (D.isNaN())
9317 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9318 Recalc = true;
9319 }
9320 if (Recalc) {
9321 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9322 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9323 }
9324 }
9325 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009326 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009327 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009328 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009329 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9330 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009331 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009332 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9333 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9334 }
9335 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009336 case BO_Div:
9337 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009338 // This is an implementation of complex division according to the
9339 // constraints laid out in C11 Annex G. The implemantion uses the
9340 // following naming scheme:
9341 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009342 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009343 APFloat &A = LHS.getComplexFloatReal();
9344 APFloat &B = LHS.getComplexFloatImag();
9345 APFloat &C = RHS.getComplexFloatReal();
9346 APFloat &D = RHS.getComplexFloatImag();
9347 APFloat &ResR = Result.getComplexFloatReal();
9348 APFloat &ResI = Result.getComplexFloatImag();
9349 if (RHSReal) {
9350 ResR = A / C;
9351 ResI = B / C;
9352 } else {
9353 if (LHSReal) {
9354 // No real optimizations we can do here, stub out with zero.
9355 B = APFloat::getZero(A.getSemantics());
9356 }
9357 int DenomLogB = 0;
9358 APFloat MaxCD = maxnum(abs(C), abs(D));
9359 if (MaxCD.isFinite()) {
9360 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009361 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9362 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009363 }
9364 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009365 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9366 APFloat::rmNearestTiesToEven);
9367 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9368 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009369 if (ResR.isNaN() && ResI.isNaN()) {
9370 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9371 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9372 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9373 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9374 D.isFinite()) {
9375 A = APFloat::copySign(
9376 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9377 B = APFloat::copySign(
9378 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9379 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9380 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9381 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9382 C = APFloat::copySign(
9383 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9384 D = APFloat::copySign(
9385 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9386 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9387 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9388 }
9389 }
9390 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009391 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009392 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9393 return Error(E, diag::note_expr_divide_by_zero);
9394
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009395 ComplexValue LHS = Result;
9396 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9397 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9398 Result.getComplexIntReal() =
9399 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9400 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9401 Result.getComplexIntImag() =
9402 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9403 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9404 }
9405 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009406 }
9407
John McCall93d91dc2010-05-07 17:22:02 +00009408 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009409}
9410
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009411bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9412 // Get the operand value into 'Result'.
9413 if (!Visit(E->getSubExpr()))
9414 return false;
9415
9416 switch (E->getOpcode()) {
9417 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009418 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009419 case UO_Extension:
9420 return true;
9421 case UO_Plus:
9422 // The result is always just the subexpr.
9423 return true;
9424 case UO_Minus:
9425 if (Result.isComplexFloat()) {
9426 Result.getComplexFloatReal().changeSign();
9427 Result.getComplexFloatImag().changeSign();
9428 }
9429 else {
9430 Result.getComplexIntReal() = -Result.getComplexIntReal();
9431 Result.getComplexIntImag() = -Result.getComplexIntImag();
9432 }
9433 return true;
9434 case UO_Not:
9435 if (Result.isComplexFloat())
9436 Result.getComplexFloatImag().changeSign();
9437 else
9438 Result.getComplexIntImag() = -Result.getComplexIntImag();
9439 return true;
9440 }
9441}
9442
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009443bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9444 if (E->getNumInits() == 2) {
9445 if (E->getType()->isComplexType()) {
9446 Result.makeComplexFloat();
9447 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9448 return false;
9449 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9450 return false;
9451 } else {
9452 Result.makeComplexInt();
9453 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9454 return false;
9455 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9456 return false;
9457 }
9458 return true;
9459 }
9460 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9461}
9462
Anders Carlsson537969c2008-11-16 20:27:53 +00009463//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009464// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9465// implicit conversion.
9466//===----------------------------------------------------------------------===//
9467
9468namespace {
9469class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009470 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00009471 APValue &Result;
9472public:
9473 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9474 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9475
9476 bool Success(const APValue &V, const Expr *E) {
9477 Result = V;
9478 return true;
9479 }
9480
9481 bool ZeroInitialization(const Expr *E) {
9482 ImplicitValueInitExpr VIE(
9483 E->getType()->castAs<AtomicType>()->getValueType());
9484 return Evaluate(Result, Info, &VIE);
9485 }
9486
9487 bool VisitCastExpr(const CastExpr *E) {
9488 switch (E->getCastKind()) {
9489 default:
9490 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9491 case CK_NonAtomicToAtomic:
9492 return Evaluate(Result, Info, E->getSubExpr());
9493 }
9494 }
9495};
9496} // end anonymous namespace
9497
9498static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9499 assert(E->isRValue() && E->getType()->isAtomicType());
9500 return AtomicExprEvaluator(Info, Result).Visit(E);
9501}
9502
9503//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009504// Void expression evaluation, primarily for a cast to void on the LHS of a
9505// comma operator
9506//===----------------------------------------------------------------------===//
9507
9508namespace {
9509class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009510 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009511public:
9512 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9513
Richard Smith2e312c82012-03-03 22:46:17 +00009514 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009515
9516 bool VisitCastExpr(const CastExpr *E) {
9517 switch (E->getCastKind()) {
9518 default:
9519 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9520 case CK_ToVoid:
9521 VisitIgnoredValue(E->getSubExpr());
9522 return true;
9523 }
9524 }
Hal Finkela8443c32014-07-17 14:49:58 +00009525
9526 bool VisitCallExpr(const CallExpr *E) {
9527 switch (E->getBuiltinCallee()) {
9528 default:
9529 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9530 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009531 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009532 // The argument is not evaluated!
9533 return true;
9534 }
9535 }
Richard Smith42d3af92011-12-07 00:43:50 +00009536};
9537} // end anonymous namespace
9538
9539static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9540 assert(E->isRValue() && E->getType()->isVoidType());
9541 return VoidExprEvaluator(Info).Visit(E);
9542}
9543
9544//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009545// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009546//===----------------------------------------------------------------------===//
9547
Richard Smith2e312c82012-03-03 22:46:17 +00009548static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009549 // In C, function designators are not lvalues, but we evaluate them as if they
9550 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009551 QualType T = E->getType();
9552 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009553 LValue LV;
9554 if (!EvaluateLValue(E, LV, Info))
9555 return false;
9556 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009557 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009558 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009559 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009560 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009561 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009562 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009563 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009564 LValue LV;
9565 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009566 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009567 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009568 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009569 llvm::APFloat F(0.0);
9570 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009571 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009572 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009573 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009574 ComplexValue C;
9575 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009576 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009577 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009578 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009579 MemberPtr P;
9580 if (!EvaluateMemberPointer(E, P, Info))
9581 return false;
9582 P.moveInto(Result);
9583 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009584 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009585 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009586 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009587 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9588 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009589 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009590 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009591 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009592 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009593 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009594 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9595 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009596 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009597 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009598 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009599 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009600 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009601 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009602 if (!EvaluateVoid(E, Info))
9603 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009604 } else if (T->isAtomicType()) {
9605 if (!EvaluateAtomic(E, Result, Info))
9606 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009607 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009608 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009609 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009610 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009611 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009612 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009613 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009614
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009615 return true;
9616}
9617
Richard Smithb228a862012-02-15 02:18:13 +00009618/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9619/// cases, the in-place evaluation is essential, since later initializers for
9620/// an object can indirectly refer to subobjects which were initialized earlier.
9621static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009622 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009623 assert(!E->isValueDependent());
9624
Richard Smith7525ff62013-05-09 07:14:00 +00009625 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009626 return false;
9627
9628 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009629 // Evaluate arrays and record types in-place, so that later initializers can
9630 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009631 if (E->getType()->isArrayType())
9632 return EvaluateArray(E, This, Result, Info);
9633 else if (E->getType()->isRecordType())
9634 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009635 }
9636
9637 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009638 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009639}
9640
Richard Smithf57d8cb2011-12-09 22:58:01 +00009641/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9642/// lvalue-to-rvalue cast if it is an lvalue.
9643static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009644 if (E->getType().isNull())
9645 return false;
9646
Richard Smithfddd3842011-12-30 21:15:51 +00009647 if (!CheckLiteralType(Info, E))
9648 return false;
9649
Richard Smith2e312c82012-03-03 22:46:17 +00009650 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009651 return false;
9652
9653 if (E->isGLValue()) {
9654 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009655 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009656 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009657 return false;
9658 }
9659
Richard Smith2e312c82012-03-03 22:46:17 +00009660 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009661 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009662}
Richard Smith11562c52011-10-28 17:51:58 +00009663
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009664static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9665 const ASTContext &Ctx, bool &IsConst) {
9666 // Fast-path evaluations of integer literals, since we sometimes see files
9667 // containing vast quantities of these.
9668 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9669 Result.Val = APValue(APSInt(L->getValue(),
9670 L->getType()->isUnsignedIntegerType()));
9671 IsConst = true;
9672 return true;
9673 }
James Dennett0492ef02014-03-14 17:44:10 +00009674
9675 // This case should be rare, but we need to check it before we check on
9676 // the type below.
9677 if (Exp->getType().isNull()) {
9678 IsConst = false;
9679 return true;
9680 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009681
9682 // FIXME: Evaluating values of large array and record types can cause
9683 // performance problems. Only do so in C++11 for now.
9684 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9685 Exp->getType()->isRecordType()) &&
9686 !Ctx.getLangOpts().CPlusPlus11) {
9687 IsConst = false;
9688 return true;
9689 }
9690 return false;
9691}
9692
9693
Richard Smith7b553f12011-10-29 00:50:52 +00009694/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009695/// any crazy technique (that has nothing to do with language standards) that
9696/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009697/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9698/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009699bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009700 bool IsConst;
9701 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9702 return IsConst;
9703
Richard Smith6d4c6582013-11-05 22:18:15 +00009704 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009705 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009706}
9707
Jay Foad39c79802011-01-12 09:06:06 +00009708bool Expr::EvaluateAsBooleanCondition(bool &Result,
9709 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009710 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009711 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009712 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009713}
9714
Richard Smithce8eca52015-12-08 03:21:47 +00009715static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9716 Expr::SideEffectsKind SEK) {
9717 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9718 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9719}
9720
Richard Smith5fab0c92011-12-28 19:48:30 +00009721bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9722 SideEffectsKind AllowSideEffects) const {
9723 if (!getType()->isIntegralOrEnumerationType())
9724 return false;
9725
Richard Smith11562c52011-10-28 17:51:58 +00009726 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009727 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009728 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009729 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009730
Richard Smith11562c52011-10-28 17:51:58 +00009731 Result = ExprResult.Val.getInt();
9732 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009733}
9734
Richard Trieube234c32016-04-21 21:04:55 +00009735bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9736 SideEffectsKind AllowSideEffects) const {
9737 if (!getType()->isRealFloatingType())
9738 return false;
9739
9740 EvalResult ExprResult;
9741 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9742 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9743 return false;
9744
9745 Result = ExprResult.Val.getFloat();
9746 return true;
9747}
9748
Jay Foad39c79802011-01-12 09:06:06 +00009749bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009750 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009751
John McCall45d55e42010-05-07 21:00:08 +00009752 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009753 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9754 !CheckLValueConstantExpression(Info, getExprLoc(),
9755 Ctx.getLValueReferenceType(getType()), LV))
9756 return false;
9757
Richard Smith2e312c82012-03-03 22:46:17 +00009758 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009759 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009760}
9761
Richard Smithd0b4dd62011-12-19 06:19:21 +00009762bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9763 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009764 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009765 // FIXME: Evaluating initializers for large array and record types can cause
9766 // performance problems. Only do so in C++11 for now.
9767 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009768 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009769 return false;
9770
Richard Smithd0b4dd62011-12-19 06:19:21 +00009771 Expr::EvalStatus EStatus;
9772 EStatus.Diag = &Notes;
9773
Richard Smith0c6124b2015-12-03 01:36:22 +00009774 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9775 ? EvalInfo::EM_ConstantExpression
9776 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009777 InitInfo.setEvaluatingDecl(VD, Value);
9778
9779 LValue LVal;
9780 LVal.set(VD);
9781
Richard Smithfddd3842011-12-30 21:15:51 +00009782 // C++11 [basic.start.init]p2:
9783 // Variables with static storage duration or thread storage duration shall be
9784 // zero-initialized before any other initialization takes place.
9785 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009786 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009787 !VD->getType()->isReferenceType()) {
9788 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009789 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009790 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009791 return false;
9792 }
9793
Richard Smith7525ff62013-05-09 07:14:00 +00009794 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9795 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009796 EStatus.HasSideEffects)
9797 return false;
9798
9799 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9800 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009801}
9802
Richard Smith7b553f12011-10-29 00:50:52 +00009803/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9804/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009805bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009806 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009807 return EvaluateAsRValue(Result, Ctx) &&
9808 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009809}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009810
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009811APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009812 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009813 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009814 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009815 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009816 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009817 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009818 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009819
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009820 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009821}
John McCall864e3962010-05-07 05:32:02 +00009822
Richard Smithe9ff7702013-11-05 22:23:30 +00009823void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009824 bool IsConst;
9825 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009826 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009827 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009828 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9829 }
9830}
9831
Richard Smithe6c01442013-06-05 00:46:14 +00009832bool Expr::EvalResult::isGlobalLValue() const {
9833 assert(Val.isLValue());
9834 return IsGlobalLValue(Val.getLValueBase());
9835}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009836
9837
John McCall864e3962010-05-07 05:32:02 +00009838/// isIntegerConstantExpr - this recursive routine will test if an expression is
9839/// an integer constant expression.
9840
9841/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9842/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009843
9844// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009845// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9846// and a (possibly null) SourceLocation indicating the location of the problem.
9847//
John McCall864e3962010-05-07 05:32:02 +00009848// Note that to reduce code duplication, this helper does no evaluation
9849// itself; the caller checks whether the expression is evaluatable, and
9850// in the rare cases where CheckICE actually cares about the evaluated
9851// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009852
Dan Gohman28ade552010-07-26 21:25:24 +00009853namespace {
9854
Richard Smith9e575da2012-12-28 13:25:52 +00009855enum ICEKind {
9856 /// This expression is an ICE.
9857 IK_ICE,
9858 /// This expression is not an ICE, but if it isn't evaluated, it's
9859 /// a legal subexpression for an ICE. This return value is used to handle
9860 /// the comma operator in C99 mode, and non-constant subexpressions.
9861 IK_ICEIfUnevaluated,
9862 /// This expression is not an ICE, and is not a legal subexpression for one.
9863 IK_NotICE
9864};
9865
John McCall864e3962010-05-07 05:32:02 +00009866struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009867 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009868 SourceLocation Loc;
9869
Richard Smith9e575da2012-12-28 13:25:52 +00009870 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009871};
9872
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009873}
Dan Gohman28ade552010-07-26 21:25:24 +00009874
Richard Smith9e575da2012-12-28 13:25:52 +00009875static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9876
9877static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009878
Craig Toppera31a8822013-08-22 07:09:37 +00009879static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009880 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009881 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009882 !EVResult.Val.isInt())
9883 return ICEDiag(IK_NotICE, E->getLocStart());
9884
John McCall864e3962010-05-07 05:32:02 +00009885 return NoDiag();
9886}
9887
Craig Toppera31a8822013-08-22 07:09:37 +00009888static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009889 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009890 if (!E->getType()->isIntegralOrEnumerationType())
9891 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009892
9893 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009894#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009895#define STMT(Node, Base) case Expr::Node##Class:
9896#define EXPR(Node, Base)
9897#include "clang/AST/StmtNodes.inc"
9898 case Expr::PredefinedExprClass:
9899 case Expr::FloatingLiteralClass:
9900 case Expr::ImaginaryLiteralClass:
9901 case Expr::StringLiteralClass:
9902 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009903 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009904 case Expr::MemberExprClass:
9905 case Expr::CompoundAssignOperatorClass:
9906 case Expr::CompoundLiteralExprClass:
9907 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009908 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00009909 case Expr::ArrayInitLoopExprClass:
9910 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009911 case Expr::NoInitExprClass:
9912 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009913 case Expr::ImplicitValueInitExprClass:
9914 case Expr::ParenListExprClass:
9915 case Expr::VAArgExprClass:
9916 case Expr::AddrLabelExprClass:
9917 case Expr::StmtExprClass:
9918 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009919 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009920 case Expr::CXXDynamicCastExprClass:
9921 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009922 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009923 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009924 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009925 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009926 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009927 case Expr::CXXThisExprClass:
9928 case Expr::CXXThrowExprClass:
9929 case Expr::CXXNewExprClass:
9930 case Expr::CXXDeleteExprClass:
9931 case Expr::CXXPseudoDestructorExprClass:
9932 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009933 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009934 case Expr::DependentScopeDeclRefExprClass:
9935 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00009936 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009937 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009938 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009939 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009940 case Expr::CXXTemporaryObjectExprClass:
9941 case Expr::CXXUnresolvedConstructExprClass:
9942 case Expr::CXXDependentScopeMemberExprClass:
9943 case Expr::UnresolvedMemberExprClass:
9944 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009945 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009946 case Expr::ObjCArrayLiteralClass:
9947 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009948 case Expr::ObjCEncodeExprClass:
9949 case Expr::ObjCMessageExprClass:
9950 case Expr::ObjCSelectorExprClass:
9951 case Expr::ObjCProtocolExprClass:
9952 case Expr::ObjCIvarRefExprClass:
9953 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009954 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009955 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00009956 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +00009957 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009958 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009959 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009960 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009961 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009962 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009963 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009964 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009965 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009966 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009967 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009968 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009969 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009970 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009971 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009972 case Expr::CoawaitExprClass:
9973 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009974 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009975
Richard Smithf137f932014-01-25 20:50:08 +00009976 case Expr::InitListExprClass: {
9977 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9978 // form "T x = { a };" is equivalent to "T x = a;".
9979 // Unless we're initializing a reference, T is a scalar as it is known to be
9980 // of integral or enumeration type.
9981 if (E->isRValue())
9982 if (cast<InitListExpr>(E)->getNumInits() == 1)
9983 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9984 return ICEDiag(IK_NotICE, E->getLocStart());
9985 }
9986
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009987 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009988 case Expr::GNUNullExprClass:
9989 // GCC considers the GNU __null value to be an integral constant expression.
9990 return NoDiag();
9991
John McCall7c454bb2011-07-15 05:09:51 +00009992 case Expr::SubstNonTypeTemplateParmExprClass:
9993 return
9994 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9995
John McCall864e3962010-05-07 05:32:02 +00009996 case Expr::ParenExprClass:
9997 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009998 case Expr::GenericSelectionExprClass:
9999 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010000 case Expr::IntegerLiteralClass:
10001 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010002 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010003 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010004 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010005 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010006 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010007 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010008 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010009 return NoDiag();
10010 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010011 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010012 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10013 // constant expressions, but they can never be ICEs because an ICE cannot
10014 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010015 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010016 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010017 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010018 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010019 }
Richard Smith6365c912012-02-24 22:12:32 +000010020 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010021 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10022 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010023 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010024 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010025 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010026 // Parameter variables are never constants. Without this check,
10027 // getAnyInitializer() can find a default argument, which leads
10028 // to chaos.
10029 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010030 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010031
10032 // C++ 7.1.5.1p2
10033 // A variable of non-volatile const-qualified integral or enumeration
10034 // type initialized by an ICE can be used in ICEs.
10035 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010036 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010037 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010038
Richard Smithd0b4dd62011-12-19 06:19:21 +000010039 const VarDecl *VD;
10040 // Look for a declaration of this variable that has an initializer, and
10041 // check whether it is an ICE.
10042 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10043 return NoDiag();
10044 else
Richard Smith9e575da2012-12-28 13:25:52 +000010045 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010046 }
10047 }
Richard Smith9e575da2012-12-28 13:25:52 +000010048 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010049 }
John McCall864e3962010-05-07 05:32:02 +000010050 case Expr::UnaryOperatorClass: {
10051 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10052 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010053 case UO_PostInc:
10054 case UO_PostDec:
10055 case UO_PreInc:
10056 case UO_PreDec:
10057 case UO_AddrOf:
10058 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010059 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010060 // C99 6.6/3 allows increment and decrement within unevaluated
10061 // subexpressions of constant expressions, but they can never be ICEs
10062 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010063 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010064 case UO_Extension:
10065 case UO_LNot:
10066 case UO_Plus:
10067 case UO_Minus:
10068 case UO_Not:
10069 case UO_Real:
10070 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010071 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010072 }
Richard Smith9e575da2012-12-28 13:25:52 +000010073
John McCall864e3962010-05-07 05:32:02 +000010074 // OffsetOf falls through here.
10075 }
10076 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010077 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10078 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10079 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10080 // compliance: we should warn earlier for offsetof expressions with
10081 // array subscripts that aren't ICEs, and if the array subscripts
10082 // are ICEs, the value of the offsetof must be an integer constant.
10083 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010084 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010085 case Expr::UnaryExprOrTypeTraitExprClass: {
10086 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10087 if ((Exp->getKind() == UETT_SizeOf) &&
10088 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010089 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010090 return NoDiag();
10091 }
10092 case Expr::BinaryOperatorClass: {
10093 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10094 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010095 case BO_PtrMemD:
10096 case BO_PtrMemI:
10097 case BO_Assign:
10098 case BO_MulAssign:
10099 case BO_DivAssign:
10100 case BO_RemAssign:
10101 case BO_AddAssign:
10102 case BO_SubAssign:
10103 case BO_ShlAssign:
10104 case BO_ShrAssign:
10105 case BO_AndAssign:
10106 case BO_XorAssign:
10107 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010108 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10109 // constant expressions, but they can never be ICEs because an ICE cannot
10110 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010111 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010112
John McCalle3027922010-08-25 11:45:40 +000010113 case BO_Mul:
10114 case BO_Div:
10115 case BO_Rem:
10116 case BO_Add:
10117 case BO_Sub:
10118 case BO_Shl:
10119 case BO_Shr:
10120 case BO_LT:
10121 case BO_GT:
10122 case BO_LE:
10123 case BO_GE:
10124 case BO_EQ:
10125 case BO_NE:
10126 case BO_And:
10127 case BO_Xor:
10128 case BO_Or:
10129 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010130 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10131 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010132 if (Exp->getOpcode() == BO_Div ||
10133 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010134 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010135 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010136 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010137 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010138 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010139 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010140 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010141 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010142 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010143 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010144 }
10145 }
10146 }
John McCalle3027922010-08-25 11:45:40 +000010147 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010148 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010149 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10150 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010151 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10152 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010153 } else {
10154 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010155 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010156 }
10157 }
Richard Smith9e575da2012-12-28 13:25:52 +000010158 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010159 }
John McCalle3027922010-08-25 11:45:40 +000010160 case BO_LAnd:
10161 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010162 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10163 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010164 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010165 // Rare case where the RHS has a comma "side-effect"; we need
10166 // to actually check the condition to see whether the side
10167 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010168 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010169 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010170 return RHSResult;
10171 return NoDiag();
10172 }
10173
Richard Smith9e575da2012-12-28 13:25:52 +000010174 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010175 }
10176 }
10177 }
10178 case Expr::ImplicitCastExprClass:
10179 case Expr::CStyleCastExprClass:
10180 case Expr::CXXFunctionalCastExprClass:
10181 case Expr::CXXStaticCastExprClass:
10182 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010183 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010184 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010185 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010186 if (isa<ExplicitCastExpr>(E)) {
10187 if (const FloatingLiteral *FL
10188 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10189 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10190 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10191 APSInt IgnoredVal(DestWidth, !DestSigned);
10192 bool Ignored;
10193 // If the value does not fit in the destination type, the behavior is
10194 // undefined, so we are not required to treat it as a constant
10195 // expression.
10196 if (FL->getValue().convertToInteger(IgnoredVal,
10197 llvm::APFloat::rmTowardZero,
10198 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010199 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010200 return NoDiag();
10201 }
10202 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010203 switch (cast<CastExpr>(E)->getCastKind()) {
10204 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010205 case CK_AtomicToNonAtomic:
10206 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010207 case CK_NoOp:
10208 case CK_IntegralToBoolean:
10209 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010210 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010211 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010212 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010213 }
John McCall864e3962010-05-07 05:32:02 +000010214 }
John McCallc07a0c72011-02-17 10:25:35 +000010215 case Expr::BinaryConditionalOperatorClass: {
10216 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10217 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010218 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010219 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010220 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10221 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10222 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010223 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010224 return FalseResult;
10225 }
John McCall864e3962010-05-07 05:32:02 +000010226 case Expr::ConditionalOperatorClass: {
10227 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10228 // If the condition (ignoring parens) is a __builtin_constant_p call,
10229 // then only the true side is actually considered in an integer constant
10230 // expression, and it is fully evaluated. This is an important GNU
10231 // extension. See GCC PR38377 for discussion.
10232 if (const CallExpr *CallCE
10233 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010234 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010235 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010236 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010237 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010238 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010239
Richard Smithf57d8cb2011-12-09 22:58:01 +000010240 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10241 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010242
Richard Smith9e575da2012-12-28 13:25:52 +000010243 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010244 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010245 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010246 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010247 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010248 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010249 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010250 return NoDiag();
10251 // Rare case where the diagnostics depend on which side is evaluated
10252 // Note that if we get here, CondResult is 0, and at least one of
10253 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010254 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010255 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010256 return TrueResult;
10257 }
10258 case Expr::CXXDefaultArgExprClass:
10259 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010260 case Expr::CXXDefaultInitExprClass:
10261 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010262 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010263 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010264 }
10265 }
10266
David Blaikiee4d798f2012-01-20 21:50:17 +000010267 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010268}
10269
Richard Smithf57d8cb2011-12-09 22:58:01 +000010270/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010271static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010272 const Expr *E,
10273 llvm::APSInt *Value,
10274 SourceLocation *Loc) {
10275 if (!E->getType()->isIntegralOrEnumerationType()) {
10276 if (Loc) *Loc = E->getExprLoc();
10277 return false;
10278 }
10279
Richard Smith66e05fe2012-01-18 05:21:49 +000010280 APValue Result;
10281 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010282 return false;
10283
Richard Smith98710fc2014-11-13 23:03:19 +000010284 if (!Result.isInt()) {
10285 if (Loc) *Loc = E->getExprLoc();
10286 return false;
10287 }
10288
Richard Smith66e05fe2012-01-18 05:21:49 +000010289 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010290 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010291}
10292
Craig Toppera31a8822013-08-22 07:09:37 +000010293bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10294 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010295 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010296 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010297
Richard Smith9e575da2012-12-28 13:25:52 +000010298 ICEDiag D = CheckICE(this, Ctx);
10299 if (D.Kind != IK_ICE) {
10300 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010301 return false;
10302 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010303 return true;
10304}
10305
Craig Toppera31a8822013-08-22 07:09:37 +000010306bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010307 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010308 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010309 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10310
10311 if (!isIntegerConstantExpr(Ctx, Loc))
10312 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010313 // The only possible side-effects here are due to UB discovered in the
10314 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10315 // required to treat the expression as an ICE, so we produce the folded
10316 // value.
10317 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010318 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010319 return true;
10320}
Richard Smith66e05fe2012-01-18 05:21:49 +000010321
Craig Toppera31a8822013-08-22 07:09:37 +000010322bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010323 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010324}
10325
Craig Toppera31a8822013-08-22 07:09:37 +000010326bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010327 SourceLocation *Loc) const {
10328 // We support this checking in C++98 mode in order to diagnose compatibility
10329 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010330 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010331
Richard Smith98a0a492012-02-14 21:38:30 +000010332 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010333 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010334 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010335 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010336 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010337
10338 APValue Scratch;
10339 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10340
10341 if (!Diags.empty()) {
10342 IsConstExpr = false;
10343 if (Loc) *Loc = Diags[0].first;
10344 } else if (!IsConstExpr) {
10345 // FIXME: This shouldn't happen.
10346 if (Loc) *Loc = getExprLoc();
10347 }
10348
10349 return IsConstExpr;
10350}
Richard Smith253c2a32012-01-27 01:14:48 +000010351
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010352bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10353 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +000010354 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010355 Expr::EvalStatus Status;
10356 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10357
10358 ArgVector ArgValues(Args.size());
10359 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10360 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010361 if ((*I)->isValueDependent() ||
10362 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010363 // If evaluation fails, throw away the argument entirely.
10364 ArgValues[I - Args.begin()] = APValue();
10365 if (Info.EvalStatus.HasSideEffects)
10366 return false;
10367 }
10368
10369 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +000010370 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010371 ArgValues.data());
10372 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10373}
10374
Richard Smith253c2a32012-01-27 01:14:48 +000010375bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010376 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010377 PartialDiagnosticAt> &Diags) {
10378 // FIXME: It would be useful to check constexpr function templates, but at the
10379 // moment the constant expression evaluator cannot cope with the non-rigorous
10380 // ASTs which we build for dependent expressions.
10381 if (FD->isDependentContext())
10382 return true;
10383
10384 Expr::EvalStatus Status;
10385 Status.Diag = &Diags;
10386
Richard Smith6d4c6582013-11-05 22:18:15 +000010387 EvalInfo Info(FD->getASTContext(), Status,
10388 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010389
10390 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010391 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010392
Richard Smith7525ff62013-05-09 07:14:00 +000010393 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010394 // is a temporary being used as the 'this' pointer.
10395 LValue This;
10396 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010397 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010398
Richard Smith253c2a32012-01-27 01:14:48 +000010399 ArrayRef<const Expr*> Args;
10400
Richard Smith2e312c82012-03-03 22:46:17 +000010401 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010402 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10403 // Evaluate the call as a constant initializer, to allow the construction
10404 // of objects of non-literal types.
10405 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010406 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10407 } else {
10408 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010409 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010410 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010411 }
Richard Smith253c2a32012-01-27 01:14:48 +000010412
10413 return Diags.empty();
10414}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010415
10416bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10417 const FunctionDecl *FD,
10418 SmallVectorImpl<
10419 PartialDiagnosticAt> &Diags) {
10420 Expr::EvalStatus Status;
10421 Status.Diag = &Diags;
10422
10423 EvalInfo Info(FD->getASTContext(), Status,
10424 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10425
10426 // Fabricate a call stack frame to give the arguments a plausible cover story.
10427 ArrayRef<const Expr*> Args;
10428 ArgVector ArgValues(0);
10429 bool Success = EvaluateArgs(Args, ArgValues, Info);
10430 (void)Success;
10431 assert(Success &&
10432 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010433 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010434
10435 APValue ResultScratch;
10436 Evaluate(ResultScratch, Info, E);
10437 return Diags.empty();
10438}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010439
10440bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10441 unsigned Type) const {
10442 if (!getType()->isPointerType())
10443 return false;
10444
10445 Expr::EvalStatus Status;
10446 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010447 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010448}