blob: 5c5b3daf70cc712d536c7ce8692ac3462bdba910 [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 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000353 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
354 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000355 /// Add N to the address of this subobject.
Richard Smithd6cc1982017-01-31 02:23:02 +0000356 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
357 if (Invalid || !N) return;
358 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
George Burgess IVe3763372016-12-22 02:50:20 +0000359 if (isMostDerivedAnUnsizedArray()) {
360 // Can't verify -- trust that the user is doing the right thing (or if
361 // not, trust that the caller will catch the bad behavior).
Richard Smithd6cc1982017-01-31 02:23:02 +0000362 // FIXME: Should we reject if this overflows, at least?
363 Entries.back().ArrayIndex += TruncatedN;
George Burgess IVe3763372016-12-22 02:50:20 +0000364 return;
365 }
Richard Smithd6cc1982017-01-31 02:23:02 +0000366
Richard Smitha8105bc2012-01-06 16:39:00 +0000367 // [expr.add]p4: For the purposes of these operators, a pointer to a
368 // nonarray object behaves the same as a pointer to the first element of
369 // an array of length one with the type of the object as its element type.
Richard Smithd6cc1982017-01-31 02:23:02 +0000370 bool IsArray = MostDerivedPathLength == Entries.size() &&
371 MostDerivedIsArrayElement;
372 uint64_t ArrayIndex =
373 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
374 uint64_t ArraySize =
375 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
376
377 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
378 // Calculate the actual index in a wide enough type, so we can include
379 // it in the note.
380 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
381 (llvm::APInt&)N += ArrayIndex;
382 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
383 diagnosePointerArithmetic(Info, E, N);
Richard Smith96e0c102011-11-04 02:25:55 +0000384 setInvalid();
Richard Smithd6cc1982017-01-31 02:23:02 +0000385 return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000386 }
Richard Smithd6cc1982017-01-31 02:23:02 +0000387
388 ArrayIndex += TruncatedN;
389 assert(ArrayIndex <= ArraySize &&
390 "bounds check succeeded for out-of-bounds index");
391
392 if (IsArray)
393 Entries.back().ArrayIndex = ArrayIndex;
394 else
395 IsOnePastTheEnd = (ArrayIndex != 0);
Richard Smith96e0c102011-11-04 02:25:55 +0000396 }
397 };
398
Richard Smith254a73d2011-10-28 22:34:42 +0000399 /// A stack frame in the constexpr call stack.
400 struct CallStackFrame {
401 EvalInfo &Info;
402
403 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000404 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000405
Richard Smithf6f003a2011-12-16 19:06:07 +0000406 /// Callee - The function which was called.
407 const FunctionDecl *Callee;
408
Richard Smithd62306a2011-11-10 06:34:14 +0000409 /// This - The binding for the this pointer in this call, if any.
410 const LValue *This;
411
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000412 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000413 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000414 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000415
Eli Friedman4830ec82012-06-25 21:21:08 +0000416 // Note that we intentionally use std::map here so that references to
417 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000418 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000419 typedef MapTy::const_iterator temp_iterator;
420 /// Temporaries - Temporary lvalues materialized within this stack frame.
421 MapTy Temporaries;
422
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000423 /// CallLoc - The location of the call expression for this call.
424 SourceLocation CallLoc;
425
426 /// Index - The call index of this call.
427 unsigned Index;
428
Faisal Vali051e3a22017-02-16 04:12:21 +0000429 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
430 // on the overall stack usage of deeply-recursing constexpr evaluataions.
431 // (We should cache this map rather than recomputing it repeatedly.)
432 // But let's try this and see how it goes; we can look into caching the map
433 // as a later change.
434
435 /// LambdaCaptureFields - Mapping from captured variables/this to
436 /// corresponding data members in the closure class.
437 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
438 FieldDecl *LambdaThisCaptureField;
439
Richard Smithf6f003a2011-12-16 19:06:07 +0000440 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
441 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000442 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000443 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000444
445 APValue *getTemporary(const void *Key) {
446 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000447 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000448 }
449 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000450 };
451
Richard Smith852c9db2013-04-20 22:23:05 +0000452 /// Temporarily override 'this'.
453 class ThisOverrideRAII {
454 public:
455 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
456 : Frame(Frame), OldThis(Frame.This) {
457 if (Enable)
458 Frame.This = NewThis;
459 }
460 ~ThisOverrideRAII() {
461 Frame.This = OldThis;
462 }
463 private:
464 CallStackFrame &Frame;
465 const LValue *OldThis;
466 };
467
Richard Smith92b1ce02011-12-12 09:28:41 +0000468 /// A partial diagnostic which we might know in advance that we are not going
469 /// to emit.
470 class OptionalDiagnostic {
471 PartialDiagnostic *Diag;
472
473 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000474 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
475 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000476
477 template<typename T>
478 OptionalDiagnostic &operator<<(const T &v) {
479 if (Diag)
480 *Diag << v;
481 return *this;
482 }
Richard Smithfe800032012-01-31 04:08:20 +0000483
484 OptionalDiagnostic &operator<<(const APSInt &I) {
485 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000486 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000487 I.toString(Buffer);
488 *Diag << StringRef(Buffer.data(), Buffer.size());
489 }
490 return *this;
491 }
492
493 OptionalDiagnostic &operator<<(const APFloat &F) {
494 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000495 // FIXME: Force the precision of the source value down so we don't
496 // print digits which are usually useless (we don't really care here if
497 // we truncate a digit by accident in edge cases). Ideally,
498 // APFloat::toString would automatically print the shortest
499 // representation which rounds to the correct value, but it's a bit
500 // tricky to implement.
501 unsigned precision =
502 llvm::APFloat::semanticsPrecision(F.getSemantics());
503 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000504 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000505 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000506 *Diag << StringRef(Buffer.data(), Buffer.size());
507 }
508 return *this;
509 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000510 };
511
Richard Smith08d6a2c2013-07-24 07:11:57 +0000512 /// A cleanup, and a flag indicating whether it is lifetime-extended.
513 class Cleanup {
514 llvm::PointerIntPair<APValue*, 1, bool> Value;
515
516 public:
517 Cleanup(APValue *Val, bool IsLifetimeExtended)
518 : Value(Val, IsLifetimeExtended) {}
519
520 bool isLifetimeExtended() const { return Value.getInt(); }
521 void endLifetime() {
522 *Value.getPointer() = APValue();
523 }
524 };
525
Richard Smithb228a862012-02-15 02:18:13 +0000526 /// EvalInfo - This is a private struct used by the evaluator to capture
527 /// information about a subexpression as it is folded. It retains information
528 /// about the AST context, but also maintains information about the folded
529 /// expression.
530 ///
531 /// If an expression could be evaluated, it is still possible it is not a C
532 /// "integer constant expression" or constant expression. If not, this struct
533 /// captures information about how and why not.
534 ///
535 /// One bit of information passed *into* the request for constant folding
536 /// indicates whether the subexpression is "evaluated" or not according to C
537 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
538 /// evaluate the expression regardless of what the RHS is, but C only allows
539 /// certain things in certain situations.
Reid Kleckner06df4022016-12-13 19:48:32 +0000540 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000541 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000542
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000543 /// EvalStatus - Contains information about the evaluation.
544 Expr::EvalStatus &EvalStatus;
545
546 /// CurrentCall - The top of the constexpr call stack.
547 CallStackFrame *CurrentCall;
548
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000549 /// CallStackDepth - The number of calls in the call stack right now.
550 unsigned CallStackDepth;
551
Richard Smithb228a862012-02-15 02:18:13 +0000552 /// NextCallIndex - The next call index to assign.
553 unsigned NextCallIndex;
554
Richard Smitha3d3bd22013-05-08 02:12:03 +0000555 /// StepsLeft - The remaining number of evaluation steps we're permitted
556 /// to perform. This is essentially a limit for the number of statements
557 /// we will evaluate.
558 unsigned StepsLeft;
559
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000560 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000561 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000562 CallStackFrame BottomFrame;
563
Richard Smith08d6a2c2013-07-24 07:11:57 +0000564 /// A stack of values whose lifetimes end at the end of some surrounding
565 /// evaluation frame.
566 llvm::SmallVector<Cleanup, 16> CleanupStack;
567
Richard Smithd62306a2011-11-10 06:34:14 +0000568 /// EvaluatingDecl - This is the declaration whose initializer is being
569 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000570 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000571
572 /// EvaluatingDeclValue - This is the value being constructed for the
573 /// declaration whose initializer is being evaluated, if any.
574 APValue *EvaluatingDeclValue;
575
Richard Smith410306b2016-12-12 02:53:20 +0000576 /// The current array initialization index, if we're performing array
577 /// initialization.
578 uint64_t ArrayInitIndex = -1;
579
Richard Smith357362d2011-12-13 06:39:58 +0000580 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
581 /// notes attached to it will also be stored, otherwise they will not be.
582 bool HasActiveDiagnostic;
583
Richard Smith0c6124b2015-12-03 01:36:22 +0000584 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
585 /// fold (not just why it's not strictly a constant expression)?
586 bool HasFoldFailureDiagnostic;
587
George Burgess IV8c892b52016-05-25 22:31:54 +0000588 /// \brief Whether or not we're currently speculatively evaluating.
589 bool IsSpeculativelyEvaluating;
590
Richard Smith6d4c6582013-11-05 22:18:15 +0000591 enum EvaluationMode {
592 /// Evaluate as a constant expression. Stop if we find that the expression
593 /// is not a constant expression.
594 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000595
Richard Smith6d4c6582013-11-05 22:18:15 +0000596 /// Evaluate as a potential constant expression. Keep going if we hit a
597 /// construct that we can't evaluate yet (because we don't yet know the
598 /// value of something) but stop if we hit something that could never be
599 /// a constant expression.
600 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000601
Richard Smith6d4c6582013-11-05 22:18:15 +0000602 /// Fold the expression to a constant. Stop if we hit a side-effect that
603 /// we can't model.
604 EM_ConstantFold,
605
606 /// Evaluate the expression looking for integer overflow and similar
607 /// issues. Don't worry about side-effects, and try to visit all
608 /// subexpressions.
609 EM_EvaluateForOverflow,
610
611 /// Evaluate in any way we know how. Don't worry about side-effects that
612 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000613 EM_IgnoreSideEffects,
614
615 /// Evaluate as a constant expression. Stop if we find that the expression
616 /// is not a constant expression. Some expressions can be retried in the
617 /// optimizer if we don't constant fold them here, but in an unevaluated
618 /// context we try to fold them immediately since the optimizer never
619 /// gets a chance to look at it.
620 EM_ConstantExpressionUnevaluated,
621
622 /// Evaluate as a potential constant expression. Keep going if we hit a
623 /// construct that we can't evaluate yet (because we don't yet know the
624 /// value of something) but stop if we hit something that could never be
625 /// a constant expression. Some expressions can be retried in the
626 /// optimizer if we don't constant fold them here, but in an unevaluated
627 /// context we try to fold them immediately since the optimizer never
628 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000629 EM_PotentialConstantExpressionUnevaluated,
630
George Burgess IVf9013bf2017-02-10 22:52:29 +0000631 /// Evaluate as a constant expression. In certain scenarios, if:
632 /// - we find a MemberExpr with a base that can't be evaluated, or
633 /// - we find a variable initialized with a call to a function that has
634 /// the alloc_size attribute on it
635 /// then we may consider evaluation to have succeeded.
636 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000637 /// In either case, the LValue returned shall have an invalid base; in the
638 /// former, the base will be the invalid MemberExpr, in the latter, the
639 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
640 /// said CallExpr.
641 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000642 } EvalMode;
643
644 /// Are we checking whether the expression is a potential constant
645 /// expression?
646 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000647 return EvalMode == EM_PotentialConstantExpression ||
648 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000649 }
650
651 /// Are we checking an expression for overflow?
652 // FIXME: We should check for any kind of undefined or suspicious behavior
653 // in such constructs, not just overflow.
654 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
655
656 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000657 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000658 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000659 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000660 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
661 EvaluatingDecl((const ValueDecl *)nullptr),
662 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000663 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
664 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000665
Richard Smith7525ff62013-05-09 07:14:00 +0000666 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
667 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000668 EvaluatingDeclValue = &Value;
669 }
670
David Blaikiebbafb8a2012-03-11 07:00:24 +0000671 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000672
Richard Smith357362d2011-12-13 06:39:58 +0000673 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000674 // Don't perform any constexpr calls (other than the call we're checking)
675 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000676 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000677 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000678 if (NextCallIndex == 0) {
679 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000680 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000681 return false;
682 }
Richard Smith357362d2011-12-13 06:39:58 +0000683 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
684 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000685 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000686 << getLangOpts().ConstexprCallDepth;
687 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000688 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000689
Richard Smithb228a862012-02-15 02:18:13 +0000690 CallStackFrame *getCallFrame(unsigned CallIndex) {
691 assert(CallIndex && "no call index in getCallFrame");
692 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
693 // be null in this loop.
694 CallStackFrame *Frame = CurrentCall;
695 while (Frame->Index > CallIndex)
696 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000697 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000698 }
699
Richard Smitha3d3bd22013-05-08 02:12:03 +0000700 bool nextStep(const Stmt *S) {
701 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000702 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000703 return false;
704 }
705 --StepsLeft;
706 return true;
707 }
708
Richard Smith357362d2011-12-13 06:39:58 +0000709 private:
710 /// Add a diagnostic to the diagnostics list.
711 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
712 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
713 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
714 return EvalStatus.Diag->back().second;
715 }
716
Richard Smithf6f003a2011-12-16 19:06:07 +0000717 /// Add notes containing a call stack to the current point of evaluation.
718 void addCallStack(unsigned Limit);
719
Faisal Valie690b7a2016-07-02 22:34:24 +0000720 private:
721 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
722 unsigned ExtraNotes, bool IsCCEDiag) {
723
Richard Smith92b1ce02011-12-12 09:28:41 +0000724 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000725 // If we have a prior diagnostic, it will be noting that the expression
726 // isn't a constant expression. This diagnostic is more important,
727 // unless we require this evaluation to produce a constant expression.
728 //
729 // FIXME: We might want to show both diagnostics to the user in
730 // EM_ConstantFold mode.
731 if (!EvalStatus.Diag->empty()) {
732 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000733 case EM_ConstantFold:
734 case EM_IgnoreSideEffects:
735 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000736 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000737 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000738 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000739 case EM_ConstantExpression:
740 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000741 case EM_ConstantExpressionUnevaluated:
742 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000743 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000744 HasActiveDiagnostic = false;
745 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000746 }
747 }
748
Richard Smithf6f003a2011-12-16 19:06:07 +0000749 unsigned CallStackNotes = CallStackDepth - 1;
750 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
751 if (Limit)
752 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000753 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000754 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000755
Richard Smith357362d2011-12-13 06:39:58 +0000756 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000757 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000758 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000759 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
760 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000761 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000762 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000763 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000764 }
Richard Smith357362d2011-12-13 06:39:58 +0000765 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000766 return OptionalDiagnostic();
767 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000768 public:
769 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
770 OptionalDiagnostic
771 FFDiag(SourceLocation Loc,
772 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
773 unsigned ExtraNotes = 0) {
774 return Diag(Loc, DiagId, ExtraNotes, false);
775 }
776
777 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000778 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000779 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000780 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000781 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000782 HasActiveDiagnostic = false;
783 return OptionalDiagnostic();
784 }
785
Richard Smith92b1ce02011-12-12 09:28:41 +0000786 /// Diagnose that the evaluation does not produce a C++11 core constant
787 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000788 ///
789 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
790 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000791 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000792 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000793 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000794 // Don't override a previous diagnostic. Don't bother collecting
795 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000796 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000797 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000798 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000799 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000800 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000801 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000802 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
803 = diag::note_invalid_subexpr_in_const_expr,
804 unsigned ExtraNotes = 0) {
805 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
806 }
Richard Smith357362d2011-12-13 06:39:58 +0000807 /// Add a note to a prior diagnostic.
808 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
809 if (!HasActiveDiagnostic)
810 return OptionalDiagnostic();
811 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000812 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000813
814 /// Add a stack of notes to a prior diagnostic.
815 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
816 if (HasActiveDiagnostic) {
817 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
818 Diags.begin(), Diags.end());
819 }
820 }
Richard Smith253c2a32012-01-27 01:14:48 +0000821
Richard Smith6d4c6582013-11-05 22:18:15 +0000822 /// Should we continue evaluation after encountering a side-effect that we
823 /// couldn't model?
824 bool keepEvaluatingAfterSideEffect() {
825 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000826 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000827 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000828 case EM_EvaluateForOverflow:
829 case EM_IgnoreSideEffects:
830 return true;
831
Richard Smith6d4c6582013-11-05 22:18:15 +0000832 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000833 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000834 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000835 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000836 return false;
837 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000838 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000839 }
840
841 /// Note that we have had a side-effect, and determine whether we should
842 /// keep evaluating.
843 bool noteSideEffect() {
844 EvalStatus.HasSideEffects = true;
845 return keepEvaluatingAfterSideEffect();
846 }
847
Richard Smithce8eca52015-12-08 03:21:47 +0000848 /// Should we continue evaluation after encountering undefined behavior?
849 bool keepEvaluatingAfterUndefinedBehavior() {
850 switch (EvalMode) {
851 case EM_EvaluateForOverflow:
852 case EM_IgnoreSideEffects:
853 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000854 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000855 return true;
856
857 case EM_PotentialConstantExpression:
858 case EM_PotentialConstantExpressionUnevaluated:
859 case EM_ConstantExpression:
860 case EM_ConstantExpressionUnevaluated:
861 return false;
862 }
863 llvm_unreachable("Missed EvalMode case");
864 }
865
866 /// Note that we hit something that was technically undefined behavior, but
867 /// that we can evaluate past it (such as signed overflow or floating-point
868 /// division by zero.)
869 bool noteUndefinedBehavior() {
870 EvalStatus.HasUndefinedBehavior = true;
871 return keepEvaluatingAfterUndefinedBehavior();
872 }
873
Richard Smith253c2a32012-01-27 01:14:48 +0000874 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000875 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000876 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000877 if (!StepsLeft)
878 return false;
879
880 switch (EvalMode) {
881 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000882 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000883 case EM_EvaluateForOverflow:
884 return true;
885
886 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000887 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000888 case EM_ConstantFold:
889 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000890 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000891 return false;
892 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000893 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000894 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000895
George Burgess IV8c892b52016-05-25 22:31:54 +0000896 /// Notes that we failed to evaluate an expression that other expressions
897 /// directly depend on, and determine if we should keep evaluating. This
898 /// should only be called if we actually intend to keep evaluating.
899 ///
900 /// Call noteSideEffect() instead if we may be able to ignore the value that
901 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
902 ///
903 /// (Foo(), 1) // use noteSideEffect
904 /// (Foo() || true) // use noteSideEffect
905 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000906 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000907 // Failure when evaluating some expression often means there is some
908 // subexpression whose evaluation was skipped. Therefore, (because we
909 // don't track whether we skipped an expression when unwinding after an
910 // evaluation failure) every evaluation failure that bubbles up from a
911 // subexpression implies that a side-effect has potentially happened. We
912 // skip setting the HasSideEffects flag to true until we decide to
913 // continue evaluating after that point, which happens here.
914 bool KeepGoing = keepEvaluatingAfterFailure();
915 EvalStatus.HasSideEffects |= KeepGoing;
916 return KeepGoing;
917 }
918
Richard Smith410306b2016-12-12 02:53:20 +0000919 class ArrayInitLoopIndex {
920 EvalInfo &Info;
921 uint64_t OuterIndex;
922
923 public:
924 ArrayInitLoopIndex(EvalInfo &Info)
925 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
926 Info.ArrayInitIndex = 0;
927 }
928 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
929
930 operator uint64_t&() { return Info.ArrayInitIndex; }
931 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000932 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000933
934 /// Object used to treat all foldable expressions as constant expressions.
935 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000936 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000937 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000938 bool HadNoPriorDiags;
939 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000940
Richard Smith6d4c6582013-11-05 22:18:15 +0000941 explicit FoldConstant(EvalInfo &Info, bool Enabled)
942 : Info(Info),
943 Enabled(Enabled),
944 HadNoPriorDiags(Info.EvalStatus.Diag &&
945 Info.EvalStatus.Diag->empty() &&
946 !Info.EvalStatus.HasSideEffects),
947 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000948 if (Enabled &&
949 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
950 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000951 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000952 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000953 void keepDiagnostics() { Enabled = false; }
954 ~FoldConstant() {
955 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000956 !Info.EvalStatus.HasSideEffects)
957 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000958 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000959 }
960 };
Richard Smith17100ba2012-02-16 02:46:34 +0000961
George Burgess IV3a03fab2015-09-04 21:28:13 +0000962 /// RAII object used to treat the current evaluation as the correct pointer
963 /// offset fold for the current EvalMode
964 struct FoldOffsetRAII {
965 EvalInfo &Info;
966 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +0000967 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +0000968 : Info(Info), OldMode(Info.EvalMode) {
969 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +0000970 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000971 }
972
973 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
974 };
975
George Burgess IV8c892b52016-05-25 22:31:54 +0000976 /// RAII object used to optionally suppress diagnostics and side-effects from
977 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000978 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000979 /// Pair of EvalInfo, and a bit that stores whether or not we were
980 /// speculatively evaluating when we created this RAII.
981 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000982 Expr::EvalStatus Old;
983
George Burgess IV8c892b52016-05-25 22:31:54 +0000984 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
985 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
986 Old = Other.Old;
987 Other.InfoAndOldSpecEval.setPointer(nullptr);
988 }
989
990 void maybeRestoreState() {
991 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
992 if (!Info)
993 return;
994
995 Info->EvalStatus = Old;
996 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
997 }
998
Richard Smith17100ba2012-02-16 02:46:34 +0000999 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001000 SpeculativeEvaluationRAII() = default;
1001
1002 SpeculativeEvaluationRAII(
1003 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1004 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
1005 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +00001006 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001007 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001008 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001009
1010 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1011 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1012 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001013 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001014
1015 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1016 maybeRestoreState();
1017 moveFromAndCancel(std::move(Other));
1018 return *this;
1019 }
1020
1021 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001022 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001023
1024 /// RAII object wrapping a full-expression or block scope, and handling
1025 /// the ending of the lifetime of temporaries created within it.
1026 template<bool IsFullExpression>
1027 class ScopeRAII {
1028 EvalInfo &Info;
1029 unsigned OldStackSize;
1030 public:
1031 ScopeRAII(EvalInfo &Info)
1032 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1033 ~ScopeRAII() {
1034 // Body moved to a static method to encourage the compiler to inline away
1035 // instances of this class.
1036 cleanup(Info, OldStackSize);
1037 }
1038 private:
1039 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1040 unsigned NewEnd = OldStackSize;
1041 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1042 I != N; ++I) {
1043 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1044 // Full-expression cleanup of a lifetime-extended temporary: nothing
1045 // to do, just move this cleanup to the right place in the stack.
1046 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1047 ++NewEnd;
1048 } else {
1049 // End the lifetime of the object.
1050 Info.CleanupStack[I].endLifetime();
1051 }
1052 }
1053 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1054 Info.CleanupStack.end());
1055 }
1056 };
1057 typedef ScopeRAII<false> BlockScopeRAII;
1058 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001059}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001060
Richard Smitha8105bc2012-01-06 16:39:00 +00001061bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1062 CheckSubobjectKind CSK) {
1063 if (Invalid)
1064 return false;
1065 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001066 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001067 << CSK;
1068 setInvalid();
1069 return false;
1070 }
1071 return true;
1072}
1073
1074void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001075 const Expr *E,
1076 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001077 // If we're complaining, we must be able to statically determine the size of
1078 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001079 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001080 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001081 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001082 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001083 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001084 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001085 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001086 setInvalid();
1087}
1088
Richard Smithf6f003a2011-12-16 19:06:07 +00001089CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1090 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001091 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001092 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1093 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001094 Info.CurrentCall = this;
1095 ++Info.CallStackDepth;
1096}
1097
1098CallStackFrame::~CallStackFrame() {
1099 assert(Info.CurrentCall == this && "calls retired out of order");
1100 --Info.CallStackDepth;
1101 Info.CurrentCall = Caller;
1102}
1103
Richard Smith08d6a2c2013-07-24 07:11:57 +00001104APValue &CallStackFrame::createTemporary(const void *Key,
1105 bool IsLifetimeExtended) {
1106 APValue &Result = Temporaries[Key];
1107 assert(Result.isUninit() && "temporary created multiple times");
1108 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1109 return Result;
1110}
1111
Richard Smith84401042013-06-03 05:03:02 +00001112static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001113
1114void EvalInfo::addCallStack(unsigned Limit) {
1115 // Determine which calls to skip, if any.
1116 unsigned ActiveCalls = CallStackDepth - 1;
1117 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1118 if (Limit && Limit < ActiveCalls) {
1119 SkipStart = Limit / 2 + Limit % 2;
1120 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001121 }
1122
Richard Smithf6f003a2011-12-16 19:06:07 +00001123 // Walk the call stack and add the diagnostics.
1124 unsigned CallIdx = 0;
1125 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1126 Frame = Frame->Caller, ++CallIdx) {
1127 // Skip this call?
1128 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1129 if (CallIdx == SkipStart) {
1130 // Note that we're skipping calls.
1131 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1132 << unsigned(ActiveCalls - Limit);
1133 }
1134 continue;
1135 }
1136
Richard Smith5179eb72016-06-28 19:03:57 +00001137 // Use a different note for an inheriting constructor, because from the
1138 // user's perspective it's not really a function at all.
1139 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1140 if (CD->isInheritingConstructor()) {
1141 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1142 << CD->getParent();
1143 continue;
1144 }
1145 }
1146
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001147 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001148 llvm::raw_svector_ostream Out(Buffer);
1149 describeCall(Frame, Out);
1150 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1151 }
1152}
1153
1154namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001155 struct ComplexValue {
1156 private:
1157 bool IsInt;
1158
1159 public:
1160 APSInt IntReal, IntImag;
1161 APFloat FloatReal, FloatImag;
1162
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001163 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001164
1165 void makeComplexFloat() { IsInt = false; }
1166 bool isComplexFloat() const { return !IsInt; }
1167 APFloat &getComplexFloatReal() { return FloatReal; }
1168 APFloat &getComplexFloatImag() { return FloatImag; }
1169
1170 void makeComplexInt() { IsInt = true; }
1171 bool isComplexInt() const { return IsInt; }
1172 APSInt &getComplexIntReal() { return IntReal; }
1173 APSInt &getComplexIntImag() { return IntImag; }
1174
Richard Smith2e312c82012-03-03 22:46:17 +00001175 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001176 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001177 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001178 else
Richard Smith2e312c82012-03-03 22:46:17 +00001179 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001180 }
Richard Smith2e312c82012-03-03 22:46:17 +00001181 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001182 assert(v.isComplexFloat() || v.isComplexInt());
1183 if (v.isComplexFloat()) {
1184 makeComplexFloat();
1185 FloatReal = v.getComplexFloatReal();
1186 FloatImag = v.getComplexFloatImag();
1187 } else {
1188 makeComplexInt();
1189 IntReal = v.getComplexIntReal();
1190 IntImag = v.getComplexIntImag();
1191 }
1192 }
John McCall93d91dc2010-05-07 17:22:02 +00001193 };
John McCall45d55e42010-05-07 21:00:08 +00001194
1195 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001196 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001197 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001198 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001199 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001200 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001201 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001202
Richard Smithce40ad62011-11-12 22:28:03 +00001203 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001204 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001205 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001206 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001207 SubobjectDesignator &getLValueDesignator() { return Designator; }
1208 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001209 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001210
Richard Smith2e312c82012-03-03 22:46:17 +00001211 void moveInto(APValue &V) const {
1212 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001213 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1214 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001215 else {
1216 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1217 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1218 "Unsized array with a valid base?");
Richard Smith2e312c82012-03-03 22:46:17 +00001219 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001220 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001221 }
John McCall45d55e42010-05-07 21:00:08 +00001222 }
Richard Smith2e312c82012-03-03 22:46:17 +00001223 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001224 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001225 Base = V.getLValueBase();
1226 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001227 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001228 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001229 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001230 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001231 }
1232
Yaxun Liu402804b2016-12-15 08:09:08 +00001233 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1234 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
George Burgess IVe3763372016-12-22 02:50:20 +00001235#ifndef NDEBUG
1236 // We only allow a few types of invalid bases. Enforce that here.
1237 if (BInvalid) {
1238 const auto *E = B.get<const Expr *>();
1239 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1240 "Unexpected type of invalid base");
1241 }
1242#endif
1243
Richard Smithce40ad62011-11-12 22:28:03 +00001244 Base = B;
Yaxun Liu402804b2016-12-15 08:09:08 +00001245 Offset = CharUnits::fromQuantity(Offset_);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001246 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001247 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001248 Designator = SubobjectDesignator(getType(B));
Yaxun Liu402804b2016-12-15 08:09:08 +00001249 IsNullPtr = IsNullPtr_;
Richard Smitha8105bc2012-01-06 16:39:00 +00001250 }
1251
George Burgess IV3a03fab2015-09-04 21:28:13 +00001252 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1253 set(B, I, true);
1254 }
1255
Richard Smitha8105bc2012-01-06 16:39:00 +00001256 // Check that this LValue is not based on a null pointer. If it is, produce
1257 // a diagnostic and mark the designator as invalid.
1258 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1259 CheckSubobjectKind CSK) {
1260 if (Designator.Invalid)
1261 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001262 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001263 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001264 << CSK;
1265 Designator.setInvalid();
1266 return false;
1267 }
1268 return true;
1269 }
1270
1271 // Check this LValue refers to an object. If not, set the designator to be
1272 // invalid and emit a diagnostic.
1273 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001274 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001275 Designator.checkSubobject(Info, E, CSK);
1276 }
1277
1278 void addDecl(EvalInfo &Info, const Expr *E,
1279 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001280 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1281 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001282 }
George Burgess IVe3763372016-12-22 02:50:20 +00001283 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1284 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1285 assert(isBaseAnAllocSizeCall(Base) &&
1286 "Only alloc_size bases can have unsized arrays");
1287 Designator.FirstEntryIsAnUnsizedArray = true;
1288 Designator.addUnsizedArrayUnchecked(ElemTy);
1289 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001290 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001291 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1292 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001293 }
Richard Smith66c96992012-02-18 22:04:06 +00001294 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001295 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1296 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001297 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001298 void clearIsNullPointer() {
1299 IsNullPtr = false;
1300 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001301 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1302 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001303 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1304 // but we're not required to diagnose it and it's valid in C++.)
1305 if (!Index)
1306 return;
1307
1308 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1309 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1310 // offsets.
1311 uint64_t Offset64 = Offset.getQuantity();
1312 uint64_t ElemSize64 = ElementSize.getQuantity();
1313 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1314 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1315
1316 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001317 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001318 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001319 }
1320 void adjustOffset(CharUnits N) {
1321 Offset += N;
1322 if (N.getQuantity())
1323 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001324 }
John McCall45d55e42010-05-07 21:00:08 +00001325 };
Richard Smith027bf112011-11-17 22:56:20 +00001326
1327 struct MemberPtr {
1328 MemberPtr() {}
1329 explicit MemberPtr(const ValueDecl *Decl) :
1330 DeclAndIsDerivedMember(Decl, false), Path() {}
1331
1332 /// The member or (direct or indirect) field referred to by this member
1333 /// pointer, or 0 if this is a null member pointer.
1334 const ValueDecl *getDecl() const {
1335 return DeclAndIsDerivedMember.getPointer();
1336 }
1337 /// Is this actually a member of some type derived from the relevant class?
1338 bool isDerivedMember() const {
1339 return DeclAndIsDerivedMember.getInt();
1340 }
1341 /// Get the class which the declaration actually lives in.
1342 const CXXRecordDecl *getContainingRecord() const {
1343 return cast<CXXRecordDecl>(
1344 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1345 }
1346
Richard Smith2e312c82012-03-03 22:46:17 +00001347 void moveInto(APValue &V) const {
1348 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001349 }
Richard Smith2e312c82012-03-03 22:46:17 +00001350 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001351 assert(V.isMemberPointer());
1352 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1353 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1354 Path.clear();
1355 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1356 Path.insert(Path.end(), P.begin(), P.end());
1357 }
1358
1359 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1360 /// whether the member is a member of some class derived from the class type
1361 /// of the member pointer.
1362 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1363 /// Path - The path of base/derived classes from the member declaration's
1364 /// class (exclusive) to the class type of the member pointer (inclusive).
1365 SmallVector<const CXXRecordDecl*, 4> Path;
1366
1367 /// Perform a cast towards the class of the Decl (either up or down the
1368 /// hierarchy).
1369 bool castBack(const CXXRecordDecl *Class) {
1370 assert(!Path.empty());
1371 const CXXRecordDecl *Expected;
1372 if (Path.size() >= 2)
1373 Expected = Path[Path.size() - 2];
1374 else
1375 Expected = getContainingRecord();
1376 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1377 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1378 // if B does not contain the original member and is not a base or
1379 // derived class of the class containing the original member, the result
1380 // of the cast is undefined.
1381 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1382 // (D::*). We consider that to be a language defect.
1383 return false;
1384 }
1385 Path.pop_back();
1386 return true;
1387 }
1388 /// Perform a base-to-derived member pointer cast.
1389 bool castToDerived(const CXXRecordDecl *Derived) {
1390 if (!getDecl())
1391 return true;
1392 if (!isDerivedMember()) {
1393 Path.push_back(Derived);
1394 return true;
1395 }
1396 if (!castBack(Derived))
1397 return false;
1398 if (Path.empty())
1399 DeclAndIsDerivedMember.setInt(false);
1400 return true;
1401 }
1402 /// Perform a derived-to-base member pointer cast.
1403 bool castToBase(const CXXRecordDecl *Base) {
1404 if (!getDecl())
1405 return true;
1406 if (Path.empty())
1407 DeclAndIsDerivedMember.setInt(true);
1408 if (isDerivedMember()) {
1409 Path.push_back(Base);
1410 return true;
1411 }
1412 return castBack(Base);
1413 }
1414 };
Richard Smith357362d2011-12-13 06:39:58 +00001415
Richard Smith7bb00672012-02-01 01:42:44 +00001416 /// Compare two member pointers, which are assumed to be of the same type.
1417 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1418 if (!LHS.getDecl() || !RHS.getDecl())
1419 return !LHS.getDecl() && !RHS.getDecl();
1420 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1421 return false;
1422 return LHS.Path == RHS.Path;
1423 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001424}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001425
Richard Smith2e312c82012-03-03 22:46:17 +00001426static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001427static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1428 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001429 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001430static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1431 bool InvalidBaseOK = false);
1432static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1433 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001434static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1435 EvalInfo &Info);
1436static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001437static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001438static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001439 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001440static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001441static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001442static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1443 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001444static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001445
1446//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001447// Misc utilities
1448//===----------------------------------------------------------------------===//
1449
Richard Smithd6cc1982017-01-31 02:23:02 +00001450/// Negate an APSInt in place, converting it to a signed form if necessary, and
1451/// preserving its value (by extending by up to one bit as needed).
1452static void negateAsSigned(APSInt &Int) {
1453 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1454 Int = Int.extend(Int.getBitWidth() + 1);
1455 Int.setIsSigned(true);
1456 }
1457 Int = -Int;
1458}
1459
Richard Smith84401042013-06-03 05:03:02 +00001460/// Produce a string describing the given constexpr call.
1461static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1462 unsigned ArgIndex = 0;
1463 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1464 !isa<CXXConstructorDecl>(Frame->Callee) &&
1465 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1466
1467 if (!IsMemberCall)
1468 Out << *Frame->Callee << '(';
1469
1470 if (Frame->This && IsMemberCall) {
1471 APValue Val;
1472 Frame->This->moveInto(Val);
1473 Val.printPretty(Out, Frame->Info.Ctx,
1474 Frame->This->Designator.MostDerivedType);
1475 // FIXME: Add parens around Val if needed.
1476 Out << "->" << *Frame->Callee << '(';
1477 IsMemberCall = false;
1478 }
1479
1480 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1481 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1482 if (ArgIndex > (unsigned)IsMemberCall)
1483 Out << ", ";
1484
1485 const ParmVarDecl *Param = *I;
1486 const APValue &Arg = Frame->Arguments[ArgIndex];
1487 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1488
1489 if (ArgIndex == 0 && IsMemberCall)
1490 Out << "->" << *Frame->Callee << '(';
1491 }
1492
1493 Out << ')';
1494}
1495
Richard Smithd9f663b2013-04-22 15:31:51 +00001496/// Evaluate an expression to see if it had side-effects, and discard its
1497/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001498/// \return \c true if the caller should keep evaluating.
1499static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001500 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001501 if (!Evaluate(Scratch, Info, E))
1502 // We don't need the value, but we might have skipped a side effect here.
1503 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001504 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001505}
1506
Richard Smithd62306a2011-11-10 06:34:14 +00001507/// Should this call expression be treated as a string literal?
1508static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001509 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001510 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1511 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1512}
1513
Richard Smithce40ad62011-11-12 22:28:03 +00001514static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001515 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1516 // constant expression of pointer type that evaluates to...
1517
1518 // ... a null pointer value, or a prvalue core constant expression of type
1519 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001520 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001521
Richard Smithce40ad62011-11-12 22:28:03 +00001522 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1523 // ... the address of an object with static storage duration,
1524 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1525 return VD->hasGlobalStorage();
1526 // ... the address of a function,
1527 return isa<FunctionDecl>(D);
1528 }
1529
1530 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001531 switch (E->getStmtClass()) {
1532 default:
1533 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001534 case Expr::CompoundLiteralExprClass: {
1535 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1536 return CLE->isFileScope() && CLE->isLValue();
1537 }
Richard Smithe6c01442013-06-05 00:46:14 +00001538 case Expr::MaterializeTemporaryExprClass:
1539 // A materialized temporary might have been lifetime-extended to static
1540 // storage duration.
1541 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001542 // A string literal has static storage duration.
1543 case Expr::StringLiteralClass:
1544 case Expr::PredefinedExprClass:
1545 case Expr::ObjCStringLiteralClass:
1546 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001547 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001548 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001549 return true;
1550 case Expr::CallExprClass:
1551 return IsStringLiteralCall(cast<CallExpr>(E));
1552 // For GCC compatibility, &&label has static storage duration.
1553 case Expr::AddrLabelExprClass:
1554 return true;
1555 // A Block literal expression may be used as the initialization value for
1556 // Block variables at global or local static scope.
1557 case Expr::BlockExprClass:
1558 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001559 case Expr::ImplicitValueInitExprClass:
1560 // FIXME:
1561 // We can never form an lvalue with an implicit value initialization as its
1562 // base through expression evaluation, so these only appear in one case: the
1563 // implicit variable declaration we invent when checking whether a constexpr
1564 // constructor can produce a constant expression. We must assume that such
1565 // an expression might be a global lvalue.
1566 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001567 }
John McCall95007602010-05-10 23:27:23 +00001568}
1569
Richard Smithb228a862012-02-15 02:18:13 +00001570static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1571 assert(Base && "no location for a null lvalue");
1572 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1573 if (VD)
1574 Info.Note(VD->getLocation(), diag::note_declared_at);
1575 else
Ted Kremenek28831752012-08-23 20:46:57 +00001576 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001577 diag::note_constexpr_temporary_here);
1578}
1579
Richard Smith80815602011-11-07 05:07:52 +00001580/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001581/// value for an address or reference constant expression. Return true if we
1582/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001583static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1584 QualType Type, const LValue &LVal) {
1585 bool IsReferenceType = Type->isReferenceType();
1586
Richard Smith357362d2011-12-13 06:39:58 +00001587 APValue::LValueBase Base = LVal.getLValueBase();
1588 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1589
Richard Smith0dea49e2012-02-18 04:58:18 +00001590 // Check that the object is a global. Note that the fake 'this' object we
1591 // manufacture when checking potential constant expressions is conservatively
1592 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001593 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001594 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001595 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001596 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001597 << IsReferenceType << !Designator.Entries.empty()
1598 << !!VD << VD;
1599 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001600 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001601 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001602 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001603 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001604 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001605 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001606 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001607 LVal.getLValueCallIndex() == 0) &&
1608 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001609
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001610 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1611 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001612 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001613 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001614 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001615
Hans Wennborg82dd8772014-06-25 22:19:48 +00001616 // A dllimport variable never acts like a constant.
1617 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001618 return false;
1619 }
1620 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1621 // __declspec(dllimport) must be handled very carefully:
1622 // We must never initialize an expression with the thunk in C++.
1623 // Doing otherwise would allow the same id-expression to yield
1624 // different addresses for the same function in different translation
1625 // units. However, this means that we must dynamically initialize the
1626 // expression with the contents of the import address table at runtime.
1627 //
1628 // The C language has no notion of ODR; furthermore, it has no notion of
1629 // dynamic initialization. This means that we are permitted to
1630 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001631 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001632 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001633 }
1634 }
1635
Richard Smitha8105bc2012-01-06 16:39:00 +00001636 // Allow address constant expressions to be past-the-end pointers. This is
1637 // an extension: the standard requires them to point to an object.
1638 if (!IsReferenceType)
1639 return true;
1640
1641 // A reference constant expression must refer to an object.
1642 if (!Base) {
1643 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001644 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001645 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001646 }
1647
Richard Smith357362d2011-12-13 06:39:58 +00001648 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001649 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001650 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001651 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001652 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001653 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001654 }
1655
Richard Smith80815602011-11-07 05:07:52 +00001656 return true;
1657}
1658
Richard Smithfddd3842011-12-30 21:15:51 +00001659/// Check that this core constant expression is of literal type, and if not,
1660/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001661static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001662 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001663 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001664 return true;
1665
Richard Smith7525ff62013-05-09 07:14:00 +00001666 // C++1y: A constant initializer for an object o [...] may also invoke
1667 // constexpr constructors for o and its subobjects even if those objects
1668 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001669 //
1670 // C++11 missed this detail for aggregates, so classes like this:
1671 // struct foo_t { union { int i; volatile int j; } u; };
1672 // are not (obviously) initializable like so:
1673 // __attribute__((__require_constant_initialization__))
1674 // static const foo_t x = {{0}};
1675 // because "i" is a subobject with non-literal initialization (due to the
1676 // volatile member of the union). See:
1677 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1678 // Therefore, we use the C++1y behavior.
1679 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001680 return true;
1681
Richard Smithfddd3842011-12-30 21:15:51 +00001682 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001683 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001684 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001685 << E->getType();
1686 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001687 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001688 return false;
1689}
1690
Richard Smith0b0a0b62011-10-29 20:57:55 +00001691/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001692/// constant expression. If not, report an appropriate diagnostic. Does not
1693/// check that the expression is of literal type.
1694static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1695 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001696 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001697 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001698 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001699 return false;
1700 }
1701
Richard Smith77be48a2014-07-31 06:31:19 +00001702 // We allow _Atomic(T) to be initialized from anything that T can be
1703 // initialized from.
1704 if (const AtomicType *AT = Type->getAs<AtomicType>())
1705 Type = AT->getValueType();
1706
Richard Smithb228a862012-02-15 02:18:13 +00001707 // Core issue 1454: For a literal constant expression of array or class type,
1708 // each subobject of its value shall have been initialized by a constant
1709 // expression.
1710 if (Value.isArray()) {
1711 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1712 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1713 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1714 Value.getArrayInitializedElt(I)))
1715 return false;
1716 }
1717 if (!Value.hasArrayFiller())
1718 return true;
1719 return CheckConstantExpression(Info, DiagLoc, EltTy,
1720 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001721 }
Richard Smithb228a862012-02-15 02:18:13 +00001722 if (Value.isUnion() && Value.getUnionField()) {
1723 return CheckConstantExpression(Info, DiagLoc,
1724 Value.getUnionField()->getType(),
1725 Value.getUnionValue());
1726 }
1727 if (Value.isStruct()) {
1728 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1729 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1730 unsigned BaseIndex = 0;
1731 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1732 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1733 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1734 Value.getStructBase(BaseIndex)))
1735 return false;
1736 }
1737 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001738 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001739 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1740 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001741 return false;
1742 }
1743 }
1744
1745 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001746 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001747 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001748 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1749 }
1750
1751 // Everything else is fine.
1752 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001753}
1754
Benjamin Kramer8407df72015-03-09 16:47:52 +00001755static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001756 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001757}
1758
1759static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001760 if (Value.CallIndex)
1761 return false;
1762 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1763 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001764}
1765
Richard Smithcecf1842011-11-01 21:06:14 +00001766static bool IsWeakLValue(const LValue &Value) {
1767 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001768 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001769}
1770
David Majnemerb5116032014-12-09 23:32:34 +00001771static bool isZeroSized(const LValue &Value) {
1772 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001773 if (Decl && isa<VarDecl>(Decl)) {
1774 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001775 if (Ty->isArrayType())
1776 return Ty->isIncompleteType() ||
1777 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001778 }
1779 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001780}
1781
Richard Smith2e312c82012-03-03 22:46:17 +00001782static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001783 // A null base expression indicates a null pointer. These are always
1784 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001785 if (!Value.getLValueBase()) {
1786 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001787 return true;
1788 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001789
Richard Smith027bf112011-11-17 22:56:20 +00001790 // We have a non-null base. These are generally known to be true, but if it's
1791 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001792 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001793 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001794 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001795}
1796
Richard Smith2e312c82012-03-03 22:46:17 +00001797static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001798 switch (Val.getKind()) {
1799 case APValue::Uninitialized:
1800 return false;
1801 case APValue::Int:
1802 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001803 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001804 case APValue::Float:
1805 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001806 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001807 case APValue::ComplexInt:
1808 Result = Val.getComplexIntReal().getBoolValue() ||
1809 Val.getComplexIntImag().getBoolValue();
1810 return true;
1811 case APValue::ComplexFloat:
1812 Result = !Val.getComplexFloatReal().isZero() ||
1813 !Val.getComplexFloatImag().isZero();
1814 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001815 case APValue::LValue:
1816 return EvalPointerValueAsBool(Val, Result);
1817 case APValue::MemberPointer:
1818 Result = Val.getMemberPointerDecl();
1819 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001820 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001821 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001822 case APValue::Struct:
1823 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001824 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001825 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001826 }
1827
Richard Smith11562c52011-10-28 17:51:58 +00001828 llvm_unreachable("unknown APValue kind");
1829}
1830
1831static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1832 EvalInfo &Info) {
1833 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001834 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001835 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001836 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001837 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001838}
1839
Richard Smith357362d2011-12-13 06:39:58 +00001840template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001841static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001842 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001843 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001844 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001845 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001846}
1847
1848static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1849 QualType SrcType, const APFloat &Value,
1850 QualType DestType, APSInt &Result) {
1851 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001852 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001853 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001854
Richard Smith357362d2011-12-13 06:39:58 +00001855 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001856 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001857 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1858 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001859 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001860 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001861}
1862
Richard Smith357362d2011-12-13 06:39:58 +00001863static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1864 QualType SrcType, QualType DestType,
1865 APFloat &Result) {
1866 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001867 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001868 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1869 APFloat::rmNearestTiesToEven, &ignored)
1870 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001871 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001872 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001873}
1874
Richard Smith911e1422012-01-30 22:27:01 +00001875static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1876 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001877 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001878 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001879 APSInt Result = Value;
1880 // Figure out if this is a truncate, extend or noop cast.
1881 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001882 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001883 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001884 return Result;
1885}
1886
Richard Smith357362d2011-12-13 06:39:58 +00001887static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1888 QualType SrcType, const APSInt &Value,
1889 QualType DestType, APFloat &Result) {
1890 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1891 if (Result.convertFromAPInt(Value, Value.isSigned(),
1892 APFloat::rmNearestTiesToEven)
1893 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001894 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001895 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001896}
1897
Richard Smith49ca8aa2013-08-06 07:09:20 +00001898static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1899 APValue &Value, const FieldDecl *FD) {
1900 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1901
1902 if (!Value.isInt()) {
1903 // Trying to store a pointer-cast-to-integer into a bitfield.
1904 // FIXME: In this case, we should provide the diagnostic for casting
1905 // a pointer to an integer.
1906 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001907 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001908 return false;
1909 }
1910
1911 APSInt &Int = Value.getInt();
1912 unsigned OldBitWidth = Int.getBitWidth();
1913 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1914 if (NewBitWidth < OldBitWidth)
1915 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1916 return true;
1917}
1918
Eli Friedman803acb32011-12-22 03:51:45 +00001919static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1920 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001921 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001922 if (!Evaluate(SVal, Info, E))
1923 return false;
1924 if (SVal.isInt()) {
1925 Res = SVal.getInt();
1926 return true;
1927 }
1928 if (SVal.isFloat()) {
1929 Res = SVal.getFloat().bitcastToAPInt();
1930 return true;
1931 }
1932 if (SVal.isVector()) {
1933 QualType VecTy = E->getType();
1934 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1935 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1936 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1937 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1938 Res = llvm::APInt::getNullValue(VecSize);
1939 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1940 APValue &Elt = SVal.getVectorElt(i);
1941 llvm::APInt EltAsInt;
1942 if (Elt.isInt()) {
1943 EltAsInt = Elt.getInt();
1944 } else if (Elt.isFloat()) {
1945 EltAsInt = Elt.getFloat().bitcastToAPInt();
1946 } else {
1947 // Don't try to handle vectors of anything other than int or float
1948 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001949 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001950 return false;
1951 }
1952 unsigned BaseEltSize = EltAsInt.getBitWidth();
1953 if (BigEndian)
1954 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1955 else
1956 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1957 }
1958 return true;
1959 }
1960 // Give up if the input isn't an int, float, or vector. For example, we
1961 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001962 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001963 return false;
1964}
1965
Richard Smith43e77732013-05-07 04:50:00 +00001966/// Perform the given integer operation, which is known to need at most BitWidth
1967/// bits, and check for overflow in the original type (if that type was not an
1968/// unsigned type).
1969template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001970static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1971 const APSInt &LHS, const APSInt &RHS,
1972 unsigned BitWidth, Operation Op,
1973 APSInt &Result) {
1974 if (LHS.isUnsigned()) {
1975 Result = Op(LHS, RHS);
1976 return true;
1977 }
Richard Smith43e77732013-05-07 04:50:00 +00001978
1979 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001980 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001981 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001982 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001983 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001984 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001985 << Result.toString(10) << E->getType();
1986 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001987 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001988 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001989 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001990}
1991
1992/// Perform the given binary integer operation.
1993static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1994 BinaryOperatorKind Opcode, APSInt RHS,
1995 APSInt &Result) {
1996 switch (Opcode) {
1997 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001998 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001999 return false;
2000 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002001 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2002 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002003 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002004 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2005 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002006 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002007 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2008 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002009 case BO_And: Result = LHS & RHS; return true;
2010 case BO_Xor: Result = LHS ^ RHS; return true;
2011 case BO_Or: Result = LHS | RHS; return true;
2012 case BO_Div:
2013 case BO_Rem:
2014 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002015 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002016 return false;
2017 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002018 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2019 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2020 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002021 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2022 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002023 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2024 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002025 return true;
2026 case BO_Shl: {
2027 if (Info.getLangOpts().OpenCL)
2028 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2029 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2030 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2031 RHS.isUnsigned());
2032 else if (RHS.isSigned() && RHS.isNegative()) {
2033 // During constant-folding, a negative shift is an opposite shift. Such
2034 // a shift is not a constant expression.
2035 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2036 RHS = -RHS;
2037 goto shift_right;
2038 }
2039 shift_left:
2040 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2041 // the shifted type.
2042 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2043 if (SA != RHS) {
2044 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2045 << RHS << E->getType() << LHS.getBitWidth();
2046 } else if (LHS.isSigned()) {
2047 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2048 // operand, and must not overflow the corresponding unsigned type.
2049 if (LHS.isNegative())
2050 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2051 else if (LHS.countLeadingZeros() < SA)
2052 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2053 }
2054 Result = LHS << SA;
2055 return true;
2056 }
2057 case BO_Shr: {
2058 if (Info.getLangOpts().OpenCL)
2059 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2060 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2061 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2062 RHS.isUnsigned());
2063 else if (RHS.isSigned() && RHS.isNegative()) {
2064 // During constant-folding, a negative shift is an opposite shift. Such a
2065 // shift is not a constant expression.
2066 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2067 RHS = -RHS;
2068 goto shift_left;
2069 }
2070 shift_right:
2071 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2072 // shifted type.
2073 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2074 if (SA != RHS)
2075 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2076 << RHS << E->getType() << LHS.getBitWidth();
2077 Result = LHS >> SA;
2078 return true;
2079 }
2080
2081 case BO_LT: Result = LHS < RHS; return true;
2082 case BO_GT: Result = LHS > RHS; return true;
2083 case BO_LE: Result = LHS <= RHS; return true;
2084 case BO_GE: Result = LHS >= RHS; return true;
2085 case BO_EQ: Result = LHS == RHS; return true;
2086 case BO_NE: Result = LHS != RHS; return true;
2087 }
2088}
2089
Richard Smith861b5b52013-05-07 23:34:45 +00002090/// Perform the given binary floating-point operation, in-place, on LHS.
2091static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2092 APFloat &LHS, BinaryOperatorKind Opcode,
2093 const APFloat &RHS) {
2094 switch (Opcode) {
2095 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002096 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002097 return false;
2098 case BO_Mul:
2099 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2100 break;
2101 case BO_Add:
2102 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2103 break;
2104 case BO_Sub:
2105 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2106 break;
2107 case BO_Div:
2108 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2109 break;
2110 }
2111
Richard Smith0c6124b2015-12-03 01:36:22 +00002112 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002113 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002114 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002115 }
Richard Smith861b5b52013-05-07 23:34:45 +00002116 return true;
2117}
2118
Richard Smitha8105bc2012-01-06 16:39:00 +00002119/// Cast an lvalue referring to a base subobject to a derived class, by
2120/// truncating the lvalue's path to the given length.
2121static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2122 const RecordDecl *TruncatedType,
2123 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002124 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002125
2126 // Check we actually point to a derived class object.
2127 if (TruncatedElements == D.Entries.size())
2128 return true;
2129 assert(TruncatedElements >= D.MostDerivedPathLength &&
2130 "not casting to a derived class");
2131 if (!Result.checkSubobject(Info, E, CSK_Derived))
2132 return false;
2133
2134 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002135 const RecordDecl *RD = TruncatedType;
2136 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002137 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002138 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2139 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002140 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002141 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002142 else
Richard Smithd62306a2011-11-10 06:34:14 +00002143 Result.Offset -= Layout.getBaseClassOffset(Base);
2144 RD = Base;
2145 }
Richard Smith027bf112011-11-17 22:56:20 +00002146 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002147 return true;
2148}
2149
John McCalld7bca762012-05-01 00:38:49 +00002150static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002151 const CXXRecordDecl *Derived,
2152 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002153 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002154 if (!RL) {
2155 if (Derived->isInvalidDecl()) return false;
2156 RL = &Info.Ctx.getASTRecordLayout(Derived);
2157 }
2158
Richard Smithd62306a2011-11-10 06:34:14 +00002159 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002160 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002161 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002162}
2163
Richard Smitha8105bc2012-01-06 16:39:00 +00002164static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002165 const CXXRecordDecl *DerivedDecl,
2166 const CXXBaseSpecifier *Base) {
2167 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2168
John McCalld7bca762012-05-01 00:38:49 +00002169 if (!Base->isVirtual())
2170 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002171
Richard Smitha8105bc2012-01-06 16:39:00 +00002172 SubobjectDesignator &D = Obj.Designator;
2173 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002174 return false;
2175
Richard Smitha8105bc2012-01-06 16:39:00 +00002176 // Extract most-derived object and corresponding type.
2177 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2178 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2179 return false;
2180
2181 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002182 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002183 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2184 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002185 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002186 return true;
2187}
2188
Richard Smith84401042013-06-03 05:03:02 +00002189static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2190 QualType Type, LValue &Result) {
2191 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2192 PathE = E->path_end();
2193 PathI != PathE; ++PathI) {
2194 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2195 *PathI))
2196 return false;
2197 Type = (*PathI)->getType();
2198 }
2199 return true;
2200}
2201
Richard Smithd62306a2011-11-10 06:34:14 +00002202/// Update LVal to refer to the given field, which must be a member of the type
2203/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002204static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002205 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002206 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002207 if (!RL) {
2208 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002209 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002210 }
Richard Smithd62306a2011-11-10 06:34:14 +00002211
2212 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002213 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002214 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002215 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002216}
2217
Richard Smith1b78b3d2012-01-25 22:15:11 +00002218/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002219static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002220 LValue &LVal,
2221 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002222 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002223 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002224 return false;
2225 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002226}
2227
Richard Smithd62306a2011-11-10 06:34:14 +00002228/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002229static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2230 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002231 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2232 // extension.
2233 if (Type->isVoidType() || Type->isFunctionType()) {
2234 Size = CharUnits::One();
2235 return true;
2236 }
2237
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002238 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002239 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002240 return false;
2241 }
2242
Richard Smithd62306a2011-11-10 06:34:14 +00002243 if (!Type->isConstantSizeType()) {
2244 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002245 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002246 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002247 return false;
2248 }
2249
2250 Size = Info.Ctx.getTypeSizeInChars(Type);
2251 return true;
2252}
2253
2254/// Update a pointer value to model pointer arithmetic.
2255/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002256/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002257/// \param LVal - The pointer value to be updated.
2258/// \param EltTy - The pointee type represented by LVal.
2259/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002260static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2261 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002262 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002263 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002264 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002265 return false;
2266
Yaxun Liu402804b2016-12-15 08:09:08 +00002267 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002268 return true;
2269}
2270
Richard Smithd6cc1982017-01-31 02:23:02 +00002271static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2272 LValue &LVal, QualType EltTy,
2273 int64_t Adjustment) {
2274 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2275 APSInt::get(Adjustment));
2276}
2277
Richard Smith66c96992012-02-18 22:04:06 +00002278/// Update an lvalue to refer to a component of a complex number.
2279/// \param Info - Information about the ongoing evaluation.
2280/// \param LVal - The lvalue to be updated.
2281/// \param EltTy - The complex number's component type.
2282/// \param Imag - False for the real component, true for the imaginary.
2283static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2284 LValue &LVal, QualType EltTy,
2285 bool Imag) {
2286 if (Imag) {
2287 CharUnits SizeOfComponent;
2288 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2289 return false;
2290 LVal.Offset += SizeOfComponent;
2291 }
2292 LVal.addComplex(Info, E, EltTy, Imag);
2293 return true;
2294}
2295
Faisal Vali051e3a22017-02-16 04:12:21 +00002296static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2297 QualType Type, const LValue &LVal,
2298 APValue &RVal);
2299
Richard Smith27908702011-10-24 17:54:18 +00002300/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002301///
2302/// \param Info Information about the ongoing evaluation.
2303/// \param E An expression to be used when printing diagnostics.
2304/// \param VD The variable whose initializer should be obtained.
2305/// \param Frame The frame in which the variable was created. Must be null
2306/// if this variable is not local to the evaluation.
2307/// \param Result Filled in with a pointer to the value of the variable.
2308static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2309 const VarDecl *VD, CallStackFrame *Frame,
2310 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002311
Richard Smith254a73d2011-10-28 22:34:42 +00002312 // If this is a parameter to an active constexpr function call, perform
2313 // argument substitution.
2314 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002315 // Assume arguments of a potential constant expression are unknown
2316 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002317 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002318 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002319 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002320 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002321 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002322 }
Richard Smith3229b742013-05-05 21:17:10 +00002323 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002324 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002325 }
Richard Smith27908702011-10-24 17:54:18 +00002326
Richard Smithd9f663b2013-04-22 15:31:51 +00002327 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002328 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002329 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002330 if (!Result) {
2331 // Assume variables referenced within a lambda's call operator that were
2332 // not declared within the call operator are captures and during checking
2333 // of a potential constant expression, assume they are unknown constant
2334 // expressions.
2335 assert(isLambdaCallOperator(Frame->Callee) &&
2336 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2337 "missing value for local variable");
2338 if (Info.checkingPotentialConstantExpression())
2339 return false;
2340 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002341 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002342 diag::note_unimplemented_constexpr_lambda_feature_ast)
2343 << "captures not currently allowed";
2344 return false;
2345 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002346 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002347 }
2348
Richard Smithd0b4dd62011-12-19 06:19:21 +00002349 // Dig out the initializer, and use the declaration which it's attached to.
2350 const Expr *Init = VD->getAnyInitializer(VD);
2351 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002352 // If we're checking a potential constant expression, the variable could be
2353 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002354 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002355 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002356 return false;
2357 }
2358
Richard Smithd62306a2011-11-10 06:34:14 +00002359 // If we're currently evaluating the initializer of this declaration, use that
2360 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002361 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002362 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002363 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002364 }
2365
Richard Smithcecf1842011-11-01 21:06:14 +00002366 // Never evaluate the initializer of a weak variable. We can't be sure that
2367 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002368 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002369 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002370 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002371 }
Richard Smithcecf1842011-11-01 21:06:14 +00002372
Richard Smithd0b4dd62011-12-19 06:19:21 +00002373 // Check that we can fold the initializer. In C++, we will have already done
2374 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002375 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002376 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002377 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002378 Notes.size() + 1) << VD;
2379 Info.Note(VD->getLocation(), diag::note_declared_at);
2380 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002381 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002382 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002383 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002384 Notes.size() + 1) << VD;
2385 Info.Note(VD->getLocation(), diag::note_declared_at);
2386 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002387 }
Richard Smith27908702011-10-24 17:54:18 +00002388
Richard Smith3229b742013-05-05 21:17:10 +00002389 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002390 return true;
Richard Smith27908702011-10-24 17:54:18 +00002391}
2392
Richard Smith11562c52011-10-28 17:51:58 +00002393static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002394 Qualifiers Quals = T.getQualifiers();
2395 return Quals.hasConst() && !Quals.hasVolatile();
2396}
2397
Richard Smithe97cbd72011-11-11 04:05:33 +00002398/// Get the base index of the given base class within an APValue representing
2399/// the given derived class.
2400static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2401 const CXXRecordDecl *Base) {
2402 Base = Base->getCanonicalDecl();
2403 unsigned Index = 0;
2404 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2405 E = Derived->bases_end(); I != E; ++I, ++Index) {
2406 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2407 return Index;
2408 }
2409
2410 llvm_unreachable("base class missing from derived class's bases list");
2411}
2412
Richard Smith3da88fa2013-04-26 14:36:30 +00002413/// Extract the value of a character from a string literal.
2414static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2415 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002416 // FIXME: Support MakeStringConstant
2417 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2418 std::string Str;
2419 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2420 assert(Index <= Str.size() && "Index too large");
2421 return APSInt::getUnsigned(Str.c_str()[Index]);
2422 }
2423
Alexey Bataevec474782014-10-09 08:45:04 +00002424 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2425 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002426 const StringLiteral *S = cast<StringLiteral>(Lit);
2427 const ConstantArrayType *CAT =
2428 Info.Ctx.getAsConstantArrayType(S->getType());
2429 assert(CAT && "string literal isn't an array");
2430 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002431 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002432
2433 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002434 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002435 if (Index < S->getLength())
2436 Value = S->getCodeUnit(Index);
2437 return Value;
2438}
2439
Richard Smith3da88fa2013-04-26 14:36:30 +00002440// Expand a string literal into an array of characters.
2441static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2442 APValue &Result) {
2443 const StringLiteral *S = cast<StringLiteral>(Lit);
2444 const ConstantArrayType *CAT =
2445 Info.Ctx.getAsConstantArrayType(S->getType());
2446 assert(CAT && "string literal isn't an array");
2447 QualType CharType = CAT->getElementType();
2448 assert(CharType->isIntegerType() && "unexpected character type");
2449
2450 unsigned Elts = CAT->getSize().getZExtValue();
2451 Result = APValue(APValue::UninitArray(),
2452 std::min(S->getLength(), Elts), Elts);
2453 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2454 CharType->isUnsignedIntegerType());
2455 if (Result.hasArrayFiller())
2456 Result.getArrayFiller() = APValue(Value);
2457 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2458 Value = S->getCodeUnit(I);
2459 Result.getArrayInitializedElt(I) = APValue(Value);
2460 }
2461}
2462
2463// Expand an array so that it has more than Index filled elements.
2464static void expandArray(APValue &Array, unsigned Index) {
2465 unsigned Size = Array.getArraySize();
2466 assert(Index < Size);
2467
2468 // Always at least double the number of elements for which we store a value.
2469 unsigned OldElts = Array.getArrayInitializedElts();
2470 unsigned NewElts = std::max(Index+1, OldElts * 2);
2471 NewElts = std::min(Size, std::max(NewElts, 8u));
2472
2473 // Copy the data across.
2474 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2475 for (unsigned I = 0; I != OldElts; ++I)
2476 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2477 for (unsigned I = OldElts; I != NewElts; ++I)
2478 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2479 if (NewValue.hasArrayFiller())
2480 NewValue.getArrayFiller() = Array.getArrayFiller();
2481 Array.swap(NewValue);
2482}
2483
Richard Smithb01fe402014-09-16 01:24:02 +00002484/// Determine whether a type would actually be read by an lvalue-to-rvalue
2485/// conversion. If it's of class type, we may assume that the copy operation
2486/// is trivial. Note that this is never true for a union type with fields
2487/// (because the copy always "reads" the active member) and always true for
2488/// a non-class type.
2489static bool isReadByLvalueToRvalueConversion(QualType T) {
2490 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2491 if (!RD || (RD->isUnion() && !RD->field_empty()))
2492 return true;
2493 if (RD->isEmpty())
2494 return false;
2495
2496 for (auto *Field : RD->fields())
2497 if (isReadByLvalueToRvalueConversion(Field->getType()))
2498 return true;
2499
2500 for (auto &BaseSpec : RD->bases())
2501 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2502 return true;
2503
2504 return false;
2505}
2506
2507/// Diagnose an attempt to read from any unreadable field within the specified
2508/// type, which might be a class type.
2509static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2510 QualType T) {
2511 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2512 if (!RD)
2513 return false;
2514
2515 if (!RD->hasMutableFields())
2516 return false;
2517
2518 for (auto *Field : RD->fields()) {
2519 // If we're actually going to read this field in some way, then it can't
2520 // be mutable. If we're in a union, then assigning to a mutable field
2521 // (even an empty one) can change the active member, so that's not OK.
2522 // FIXME: Add core issue number for the union case.
2523 if (Field->isMutable() &&
2524 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002525 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002526 Info.Note(Field->getLocation(), diag::note_declared_at);
2527 return true;
2528 }
2529
2530 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2531 return true;
2532 }
2533
2534 for (auto &BaseSpec : RD->bases())
2535 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2536 return true;
2537
2538 // All mutable fields were empty, and thus not actually read.
2539 return false;
2540}
2541
Richard Smith861b5b52013-05-07 23:34:45 +00002542/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002543enum AccessKinds {
2544 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002545 AK_Assign,
2546 AK_Increment,
2547 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002548};
2549
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002550namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002551/// A handle to a complete object (an object that is not a subobject of
2552/// another object).
2553struct CompleteObject {
2554 /// The value of the complete object.
2555 APValue *Value;
2556 /// The type of the complete object.
2557 QualType Type;
2558
Craig Topper36250ad2014-05-12 05:36:57 +00002559 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002560 CompleteObject(APValue *Value, QualType Type)
2561 : Value(Value), Type(Type) {
2562 assert(Value && "missing value for complete object");
2563 }
2564
Aaron Ballman67347662015-02-15 22:00:28 +00002565 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002566};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002567} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002568
Richard Smith3da88fa2013-04-26 14:36:30 +00002569/// Find the designated sub-object of an rvalue.
2570template<typename SubobjectHandler>
2571typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002572findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002573 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002574 if (Sub.Invalid)
2575 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002576 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002577 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002578 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002579 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002580 << handler.AccessKind;
2581 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002582 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002583 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002584 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002585
Richard Smith3229b742013-05-05 21:17:10 +00002586 APValue *O = Obj.Value;
2587 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002588 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002589
Richard Smithd62306a2011-11-10 06:34:14 +00002590 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002591 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2592 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002593 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002594 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002595 return handler.failed();
2596 }
2597
Richard Smith49ca8aa2013-08-06 07:09:20 +00002598 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002599 // If we are reading an object of class type, there may still be more
2600 // things we need to check: if there are any mutable subobjects, we
2601 // cannot perform this read. (This only happens when performing a trivial
2602 // copy or assignment.)
2603 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2604 diagnoseUnreadableFields(Info, E, ObjType))
2605 return handler.failed();
2606
Richard Smith49ca8aa2013-08-06 07:09:20 +00002607 if (!handler.found(*O, ObjType))
2608 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002609
Richard Smith49ca8aa2013-08-06 07:09:20 +00002610 // If we modified a bit-field, truncate it to the right width.
2611 if (handler.AccessKind != AK_Read &&
2612 LastField && LastField->isBitField() &&
2613 !truncateBitfieldValue(Info, E, *O, LastField))
2614 return false;
2615
2616 return true;
2617 }
2618
Craig Topper36250ad2014-05-12 05:36:57 +00002619 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002620 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002621 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002622 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002623 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002624 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002625 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002626 // Note, it should not be possible to form a pointer with a valid
2627 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002628 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002629 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002630 << handler.AccessKind;
2631 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002632 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002633 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002634 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002635
2636 ObjType = CAT->getElementType();
2637
Richard Smith14a94132012-02-17 03:35:37 +00002638 // An array object is represented as either an Array APValue or as an
2639 // LValue which refers to a string literal.
2640 if (O->isLValue()) {
2641 assert(I == N - 1 && "extracting subobject of character?");
2642 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002643 if (handler.AccessKind != AK_Read)
2644 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2645 *O);
2646 else
2647 return handler.foundString(*O, ObjType, Index);
2648 }
2649
2650 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002651 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002652 else if (handler.AccessKind != AK_Read) {
2653 expandArray(*O, Index);
2654 O = &O->getArrayInitializedElt(Index);
2655 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002656 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002657 } else if (ObjType->isAnyComplexType()) {
2658 // Next subobject is a complex number.
2659 uint64_t Index = Sub.Entries[I].ArrayIndex;
2660 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002661 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002662 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002663 << handler.AccessKind;
2664 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002665 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002666 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002667 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002668
2669 bool WasConstQualified = ObjType.isConstQualified();
2670 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2671 if (WasConstQualified)
2672 ObjType.addConst();
2673
Richard Smith66c96992012-02-18 22:04:06 +00002674 assert(I == N - 1 && "extracting subobject of scalar?");
2675 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002676 return handler.found(Index ? O->getComplexIntImag()
2677 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002678 } else {
2679 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002680 return handler.found(Index ? O->getComplexFloatImag()
2681 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002682 }
Richard Smithd62306a2011-11-10 06:34:14 +00002683 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002684 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002685 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002686 << Field;
2687 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002688 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002689 }
2690
Richard Smithd62306a2011-11-10 06:34:14 +00002691 // Next subobject is a class, struct or union field.
2692 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2693 if (RD->isUnion()) {
2694 const FieldDecl *UnionField = O->getUnionField();
2695 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002696 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002697 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002698 << handler.AccessKind << Field << !UnionField << UnionField;
2699 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002700 }
Richard Smithd62306a2011-11-10 06:34:14 +00002701 O = &O->getUnionValue();
2702 } else
2703 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002704
2705 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002706 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002707 if (WasConstQualified && !Field->isMutable())
2708 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002709
2710 if (ObjType.isVolatileQualified()) {
2711 if (Info.getLangOpts().CPlusPlus) {
2712 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002713 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002714 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002715 Info.Note(Field->getLocation(), diag::note_declared_at);
2716 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002717 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002718 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002719 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002720 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002721
2722 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002723 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002724 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002725 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2726 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2727 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002728
2729 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002730 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002731 if (WasConstQualified)
2732 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002733 }
2734 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002735}
2736
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002737namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002738struct ExtractSubobjectHandler {
2739 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002740 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002741
2742 static const AccessKinds AccessKind = AK_Read;
2743
2744 typedef bool result_type;
2745 bool failed() { return false; }
2746 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002747 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002748 return true;
2749 }
2750 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002751 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002752 return true;
2753 }
2754 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002755 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002756 return true;
2757 }
2758 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002759 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002760 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2761 return true;
2762 }
2763};
Richard Smith3229b742013-05-05 21:17:10 +00002764} // end anonymous namespace
2765
Richard Smith3da88fa2013-04-26 14:36:30 +00002766const AccessKinds ExtractSubobjectHandler::AccessKind;
2767
2768/// Extract the designated sub-object of an rvalue.
2769static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002770 const CompleteObject &Obj,
2771 const SubobjectDesignator &Sub,
2772 APValue &Result) {
2773 ExtractSubobjectHandler Handler = { Info, Result };
2774 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002775}
2776
Richard Smith3229b742013-05-05 21:17:10 +00002777namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002778struct ModifySubobjectHandler {
2779 EvalInfo &Info;
2780 APValue &NewVal;
2781 const Expr *E;
2782
2783 typedef bool result_type;
2784 static const AccessKinds AccessKind = AK_Assign;
2785
2786 bool checkConst(QualType QT) {
2787 // Assigning to a const object has undefined behavior.
2788 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002789 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002790 return false;
2791 }
2792 return true;
2793 }
2794
2795 bool failed() { return false; }
2796 bool found(APValue &Subobj, QualType SubobjType) {
2797 if (!checkConst(SubobjType))
2798 return false;
2799 // We've been given ownership of NewVal, so just swap it in.
2800 Subobj.swap(NewVal);
2801 return true;
2802 }
2803 bool found(APSInt &Value, QualType SubobjType) {
2804 if (!checkConst(SubobjType))
2805 return false;
2806 if (!NewVal.isInt()) {
2807 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002808 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002809 return false;
2810 }
2811 Value = NewVal.getInt();
2812 return true;
2813 }
2814 bool found(APFloat &Value, QualType SubobjType) {
2815 if (!checkConst(SubobjType))
2816 return false;
2817 Value = NewVal.getFloat();
2818 return true;
2819 }
2820 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2821 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2822 }
2823};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002824} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002825
Richard Smith3229b742013-05-05 21:17:10 +00002826const AccessKinds ModifySubobjectHandler::AccessKind;
2827
Richard Smith3da88fa2013-04-26 14:36:30 +00002828/// Update the designated sub-object of an rvalue to the given value.
2829static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002830 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002831 const SubobjectDesignator &Sub,
2832 APValue &NewVal) {
2833 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002834 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002835}
2836
Richard Smith84f6dcf2012-02-02 01:16:57 +00002837/// Find the position where two subobject designators diverge, or equivalently
2838/// the length of the common initial subsequence.
2839static unsigned FindDesignatorMismatch(QualType ObjType,
2840 const SubobjectDesignator &A,
2841 const SubobjectDesignator &B,
2842 bool &WasArrayIndex) {
2843 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2844 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002845 if (!ObjType.isNull() &&
2846 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002847 // Next subobject is an array element.
2848 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2849 WasArrayIndex = true;
2850 return I;
2851 }
Richard Smith66c96992012-02-18 22:04:06 +00002852 if (ObjType->isAnyComplexType())
2853 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2854 else
2855 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002856 } else {
2857 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2858 WasArrayIndex = false;
2859 return I;
2860 }
2861 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2862 // Next subobject is a field.
2863 ObjType = FD->getType();
2864 else
2865 // Next subobject is a base class.
2866 ObjType = QualType();
2867 }
2868 }
2869 WasArrayIndex = false;
2870 return I;
2871}
2872
2873/// Determine whether the given subobject designators refer to elements of the
2874/// same array object.
2875static bool AreElementsOfSameArray(QualType ObjType,
2876 const SubobjectDesignator &A,
2877 const SubobjectDesignator &B) {
2878 if (A.Entries.size() != B.Entries.size())
2879 return false;
2880
George Burgess IVa51c4072015-10-16 01:49:01 +00002881 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002882 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2883 // A is a subobject of the array element.
2884 return false;
2885
2886 // If A (and B) designates an array element, the last entry will be the array
2887 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2888 // of length 1' case, and the entire path must match.
2889 bool WasArrayIndex;
2890 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2891 return CommonLength >= A.Entries.size() - IsArray;
2892}
2893
Richard Smith3229b742013-05-05 21:17:10 +00002894/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002895static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2896 AccessKinds AK, const LValue &LVal,
2897 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002898 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002899 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002900 return CompleteObject();
2901 }
2902
Craig Topper36250ad2014-05-12 05:36:57 +00002903 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002904 if (LVal.CallIndex) {
2905 Frame = Info.getCallFrame(LVal.CallIndex);
2906 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002907 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002908 << AK << LVal.Base.is<const ValueDecl*>();
2909 NoteLValueLocation(Info, LVal.Base);
2910 return CompleteObject();
2911 }
Richard Smith3229b742013-05-05 21:17:10 +00002912 }
2913
2914 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2915 // is not a constant expression (even if the object is non-volatile). We also
2916 // apply this rule to C++98, in order to conform to the expected 'volatile'
2917 // semantics.
2918 if (LValType.isVolatileQualified()) {
2919 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002920 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002921 << AK << LValType;
2922 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002923 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002924 return CompleteObject();
2925 }
2926
2927 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002928 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002929 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002930
2931 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2932 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2933 // In C++11, constexpr, non-volatile variables initialized with constant
2934 // expressions are constant expressions too. Inside constexpr functions,
2935 // parameters are constant expressions even if they're non-const.
2936 // In C++1y, objects local to a constant expression (those with a Frame) are
2937 // both readable and writable inside constant expressions.
2938 // In C, such things can also be folded, although they are not ICEs.
2939 const VarDecl *VD = dyn_cast<VarDecl>(D);
2940 if (VD) {
2941 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2942 VD = VDef;
2943 }
2944 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002945 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002946 return CompleteObject();
2947 }
2948
2949 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002950 if (BaseType.isVolatileQualified()) {
2951 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002952 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002953 << AK << 1 << VD;
2954 Info.Note(VD->getLocation(), diag::note_declared_at);
2955 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002956 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002957 }
2958 return CompleteObject();
2959 }
2960
2961 // Unless we're looking at a local variable or argument in a constexpr call,
2962 // the variable we're reading must be const.
2963 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002964 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002965 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2966 // OK, we can read and modify an object if we're in the process of
2967 // evaluating its initializer, because its lifetime began in this
2968 // evaluation.
2969 } else if (AK != AK_Read) {
2970 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002971 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002972 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00002973 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002974 // OK, we can read this variable.
2975 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002976 // In OpenCL if a variable is in constant address space it is a const value.
2977 if (!(BaseType.isConstQualified() ||
2978 (Info.getLangOpts().OpenCL &&
2979 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002980 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002981 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002982 Info.Note(VD->getLocation(), diag::note_declared_at);
2983 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002984 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002985 }
2986 return CompleteObject();
2987 }
2988 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2989 // We support folding of const floating-point types, in order to make
2990 // static const data members of such types (supported as an extension)
2991 // more useful.
2992 if (Info.getLangOpts().CPlusPlus11) {
2993 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2994 Info.Note(VD->getLocation(), diag::note_declared_at);
2995 } else {
2996 Info.CCEDiag(E);
2997 }
George Burgess IVb5316982016-12-27 05:33:20 +00002998 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
2999 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3000 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003001 } else {
3002 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003003 if (Info.checkingPotentialConstantExpression() &&
3004 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3005 // The definition of this variable could be constexpr. We can't
3006 // access it right now, but may be able to in future.
3007 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003008 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003009 Info.Note(VD->getLocation(), diag::note_declared_at);
3010 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003011 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003012 }
3013 return CompleteObject();
3014 }
3015 }
3016
3017 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3018 return CompleteObject();
3019 } else {
3020 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3021
3022 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003023 if (const MaterializeTemporaryExpr *MTE =
3024 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3025 assert(MTE->getStorageDuration() == SD_Static &&
3026 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003027
Richard Smithe6c01442013-06-05 00:46:14 +00003028 // Per C++1y [expr.const]p2:
3029 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3030 // - a [...] glvalue of integral or enumeration type that refers to
3031 // a non-volatile const object [...]
3032 // [...]
3033 // - a [...] glvalue of literal type that refers to a non-volatile
3034 // object whose lifetime began within the evaluation of e.
3035 //
3036 // C++11 misses the 'began within the evaluation of e' check and
3037 // instead allows all temporaries, including things like:
3038 // int &&r = 1;
3039 // int x = ++r;
3040 // constexpr int k = r;
3041 // Therefore we use the C++1y rules in C++11 too.
3042 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3043 const ValueDecl *ED = MTE->getExtendingDecl();
3044 if (!(BaseType.isConstQualified() &&
3045 BaseType->isIntegralOrEnumerationType()) &&
3046 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003047 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003048 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3049 return CompleteObject();
3050 }
3051
3052 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3053 assert(BaseVal && "got reference to unevaluated temporary");
3054 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003055 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003056 return CompleteObject();
3057 }
3058 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003059 BaseVal = Frame->getTemporary(Base);
3060 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003061 }
Richard Smith3229b742013-05-05 21:17:10 +00003062
3063 // Volatile temporary objects cannot be accessed in constant expressions.
3064 if (BaseType.isVolatileQualified()) {
3065 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003066 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003067 << AK << 0;
3068 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3069 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003070 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003071 }
3072 return CompleteObject();
3073 }
3074 }
3075
Richard Smith7525ff62013-05-09 07:14:00 +00003076 // During the construction of an object, it is not yet 'const'.
3077 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3078 // and this doesn't do quite the right thing for const subobjects of the
3079 // object under construction.
3080 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3081 BaseType = Info.Ctx.getCanonicalType(BaseType);
3082 BaseType.removeLocalConst();
3083 }
3084
Richard Smith6d4c6582013-11-05 22:18:15 +00003085 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003086 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003087 //
3088 // FIXME: Not all local state is mutable. Allow local constant subobjects
3089 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003090 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3091 Info.EvalStatus.HasSideEffects) ||
3092 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003093 return CompleteObject();
3094
3095 return CompleteObject(BaseVal, BaseType);
3096}
3097
Richard Smith243ef902013-05-05 23:31:59 +00003098/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3099/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3100/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003101///
3102/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003103/// \param Conv - The expression for which we are performing the conversion.
3104/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003105/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3106/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003107/// \param LVal - The glvalue on which we are attempting to perform this action.
3108/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003109static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003110 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003111 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003112 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003113 return false;
3114
Richard Smith3229b742013-05-05 21:17:10 +00003115 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003116 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003117 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003118 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3119 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3120 // initializer until now for such expressions. Such an expression can't be
3121 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003122 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003123 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003124 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003125 }
Richard Smith3229b742013-05-05 21:17:10 +00003126 APValue Lit;
3127 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3128 return false;
3129 CompleteObject LitObj(&Lit, Base->getType());
3130 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003131 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003132 // We represent a string literal array as an lvalue pointing at the
3133 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003134 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003135 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3136 CompleteObject StrObj(&Str, Base->getType());
3137 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003138 }
Richard Smith11562c52011-10-28 17:51:58 +00003139 }
3140
Richard Smith3229b742013-05-05 21:17:10 +00003141 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3142 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003143}
3144
3145/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003146static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003147 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003148 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003149 return false;
3150
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003151 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003152 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003153 return false;
3154 }
3155
Richard Smith3229b742013-05-05 21:17:10 +00003156 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3157 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003158}
3159
Richard Smith243ef902013-05-05 23:31:59 +00003160static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3161 return T->isSignedIntegerType() &&
3162 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3163}
3164
3165namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003166struct CompoundAssignSubobjectHandler {
3167 EvalInfo &Info;
3168 const Expr *E;
3169 QualType PromotedLHSType;
3170 BinaryOperatorKind Opcode;
3171 const APValue &RHS;
3172
3173 static const AccessKinds AccessKind = AK_Assign;
3174
3175 typedef bool result_type;
3176
3177 bool checkConst(QualType QT) {
3178 // Assigning to a const object has undefined behavior.
3179 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003180 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003181 return false;
3182 }
3183 return true;
3184 }
3185
3186 bool failed() { return false; }
3187 bool found(APValue &Subobj, QualType SubobjType) {
3188 switch (Subobj.getKind()) {
3189 case APValue::Int:
3190 return found(Subobj.getInt(), SubobjType);
3191 case APValue::Float:
3192 return found(Subobj.getFloat(), SubobjType);
3193 case APValue::ComplexInt:
3194 case APValue::ComplexFloat:
3195 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003196 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003197 return false;
3198 case APValue::LValue:
3199 return foundPointer(Subobj, SubobjType);
3200 default:
3201 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003202 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003203 return false;
3204 }
3205 }
3206 bool found(APSInt &Value, QualType SubobjType) {
3207 if (!checkConst(SubobjType))
3208 return false;
3209
3210 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3211 // We don't support compound assignment on integer-cast-to-pointer
3212 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003213 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003214 return false;
3215 }
3216
3217 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3218 SubobjType, Value);
3219 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3220 return false;
3221 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3222 return true;
3223 }
3224 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003225 return checkConst(SubobjType) &&
3226 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3227 Value) &&
3228 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3229 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003230 }
3231 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3232 if (!checkConst(SubobjType))
3233 return false;
3234
3235 QualType PointeeType;
3236 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3237 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003238
3239 if (PointeeType.isNull() || !RHS.isInt() ||
3240 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003241 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003242 return false;
3243 }
3244
Richard Smithd6cc1982017-01-31 02:23:02 +00003245 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003246 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003247 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003248
3249 LValue LVal;
3250 LVal.setFrom(Info.Ctx, Subobj);
3251 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3252 return false;
3253 LVal.moveInto(Subobj);
3254 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003255 }
3256 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3257 llvm_unreachable("shouldn't encounter string elements here");
3258 }
3259};
3260} // end anonymous namespace
3261
3262const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3263
3264/// Perform a compound assignment of LVal <op>= RVal.
3265static bool handleCompoundAssignment(
3266 EvalInfo &Info, const Expr *E,
3267 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3268 BinaryOperatorKind Opcode, const APValue &RVal) {
3269 if (LVal.Designator.Invalid)
3270 return false;
3271
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003272 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003273 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003274 return false;
3275 }
3276
3277 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3278 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3279 RVal };
3280 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3281}
3282
3283namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003284struct IncDecSubobjectHandler {
3285 EvalInfo &Info;
3286 const Expr *E;
3287 AccessKinds AccessKind;
3288 APValue *Old;
3289
3290 typedef bool result_type;
3291
3292 bool checkConst(QualType QT) {
3293 // Assigning to a const object has undefined behavior.
3294 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003295 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003296 return false;
3297 }
3298 return true;
3299 }
3300
3301 bool failed() { return false; }
3302 bool found(APValue &Subobj, QualType SubobjType) {
3303 // Stash the old value. Also clear Old, so we don't clobber it later
3304 // if we're post-incrementing a complex.
3305 if (Old) {
3306 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003307 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003308 }
3309
3310 switch (Subobj.getKind()) {
3311 case APValue::Int:
3312 return found(Subobj.getInt(), SubobjType);
3313 case APValue::Float:
3314 return found(Subobj.getFloat(), SubobjType);
3315 case APValue::ComplexInt:
3316 return found(Subobj.getComplexIntReal(),
3317 SubobjType->castAs<ComplexType>()->getElementType()
3318 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3319 case APValue::ComplexFloat:
3320 return found(Subobj.getComplexFloatReal(),
3321 SubobjType->castAs<ComplexType>()->getElementType()
3322 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3323 case APValue::LValue:
3324 return foundPointer(Subobj, SubobjType);
3325 default:
3326 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003327 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003328 return false;
3329 }
3330 }
3331 bool found(APSInt &Value, QualType SubobjType) {
3332 if (!checkConst(SubobjType))
3333 return false;
3334
3335 if (!SubobjType->isIntegerType()) {
3336 // We don't support increment / decrement on integer-cast-to-pointer
3337 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003338 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003339 return false;
3340 }
3341
3342 if (Old) *Old = APValue(Value);
3343
3344 // bool arithmetic promotes to int, and the conversion back to bool
3345 // doesn't reduce mod 2^n, so special-case it.
3346 if (SubobjType->isBooleanType()) {
3347 if (AccessKind == AK_Increment)
3348 Value = 1;
3349 else
3350 Value = !Value;
3351 return true;
3352 }
3353
3354 bool WasNegative = Value.isNegative();
3355 if (AccessKind == AK_Increment) {
3356 ++Value;
3357
3358 if (!WasNegative && Value.isNegative() &&
3359 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3360 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003361 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003362 }
3363 } else {
3364 --Value;
3365
3366 if (WasNegative && !Value.isNegative() &&
3367 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3368 unsigned BitWidth = Value.getBitWidth();
3369 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3370 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003371 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003372 }
3373 }
3374 return true;
3375 }
3376 bool found(APFloat &Value, QualType SubobjType) {
3377 if (!checkConst(SubobjType))
3378 return false;
3379
3380 if (Old) *Old = APValue(Value);
3381
3382 APFloat One(Value.getSemantics(), 1);
3383 if (AccessKind == AK_Increment)
3384 Value.add(One, APFloat::rmNearestTiesToEven);
3385 else
3386 Value.subtract(One, APFloat::rmNearestTiesToEven);
3387 return true;
3388 }
3389 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3390 if (!checkConst(SubobjType))
3391 return false;
3392
3393 QualType PointeeType;
3394 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3395 PointeeType = PT->getPointeeType();
3396 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003397 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003398 return false;
3399 }
3400
3401 LValue LVal;
3402 LVal.setFrom(Info.Ctx, Subobj);
3403 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3404 AccessKind == AK_Increment ? 1 : -1))
3405 return false;
3406 LVal.moveInto(Subobj);
3407 return true;
3408 }
3409 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3410 llvm_unreachable("shouldn't encounter string elements here");
3411 }
3412};
3413} // end anonymous namespace
3414
3415/// Perform an increment or decrement on LVal.
3416static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3417 QualType LValType, bool IsIncrement, APValue *Old) {
3418 if (LVal.Designator.Invalid)
3419 return false;
3420
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003421 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003422 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003423 return false;
3424 }
3425
3426 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3427 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3428 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3429 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3430}
3431
Richard Smithe97cbd72011-11-11 04:05:33 +00003432/// Build an lvalue for the object argument of a member function call.
3433static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3434 LValue &This) {
3435 if (Object->getType()->isPointerType())
3436 return EvaluatePointer(Object, This, Info);
3437
3438 if (Object->isGLValue())
3439 return EvaluateLValue(Object, This, Info);
3440
Richard Smithd9f663b2013-04-22 15:31:51 +00003441 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003442 return EvaluateTemporary(Object, This, Info);
3443
Faisal Valie690b7a2016-07-02 22:34:24 +00003444 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003445 return false;
3446}
3447
3448/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3449/// lvalue referring to the result.
3450///
3451/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003452/// \param LV - An lvalue referring to the base of the member pointer.
3453/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003454/// \param IncludeMember - Specifies whether the member itself is included in
3455/// the resulting LValue subobject designator. This is not possible when
3456/// creating a bound member function.
3457/// \return The field or method declaration to which the member pointer refers,
3458/// or 0 if evaluation fails.
3459static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003460 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003461 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003462 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003463 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003464 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003465 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003466 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003467
3468 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3469 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003470 if (!MemPtr.getDecl()) {
3471 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003472 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003473 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003474 }
Richard Smith253c2a32012-01-27 01:14:48 +00003475
Richard Smith027bf112011-11-17 22:56:20 +00003476 if (MemPtr.isDerivedMember()) {
3477 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003478 // The end of the derived-to-base path for the base object must match the
3479 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003480 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003481 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003482 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003483 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003484 }
Richard Smith027bf112011-11-17 22:56:20 +00003485 unsigned PathLengthToMember =
3486 LV.Designator.Entries.size() - MemPtr.Path.size();
3487 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3488 const CXXRecordDecl *LVDecl = getAsBaseClass(
3489 LV.Designator.Entries[PathLengthToMember + I]);
3490 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003491 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003492 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003493 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003494 }
Richard Smith027bf112011-11-17 22:56:20 +00003495 }
3496
3497 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003498 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003499 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003500 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003501 } else if (!MemPtr.Path.empty()) {
3502 // Extend the LValue path with the member pointer's path.
3503 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3504 MemPtr.Path.size() + IncludeMember);
3505
3506 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003507 if (const PointerType *PT = LVType->getAs<PointerType>())
3508 LVType = PT->getPointeeType();
3509 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3510 assert(RD && "member pointer access on non-class-type expression");
3511 // The first class in the path is that of the lvalue.
3512 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3513 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003514 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003515 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003516 RD = Base;
3517 }
3518 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003519 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3520 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003521 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003522 }
3523
3524 // Add the member. Note that we cannot build bound member functions here.
3525 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003526 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003527 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003528 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003529 } else if (const IndirectFieldDecl *IFD =
3530 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003531 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003532 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003533 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003534 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003535 }
Richard Smith027bf112011-11-17 22:56:20 +00003536 }
3537
3538 return MemPtr.getDecl();
3539}
3540
Richard Smith84401042013-06-03 05:03:02 +00003541static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3542 const BinaryOperator *BO,
3543 LValue &LV,
3544 bool IncludeMember = true) {
3545 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3546
3547 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003548 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003549 MemberPtr MemPtr;
3550 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3551 }
Craig Topper36250ad2014-05-12 05:36:57 +00003552 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003553 }
3554
3555 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3556 BO->getRHS(), IncludeMember);
3557}
3558
Richard Smith027bf112011-11-17 22:56:20 +00003559/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3560/// the provided lvalue, which currently refers to the base object.
3561static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3562 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003563 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003564 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003565 return false;
3566
Richard Smitha8105bc2012-01-06 16:39:00 +00003567 QualType TargetQT = E->getType();
3568 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3569 TargetQT = PT->getPointeeType();
3570
3571 // Check this cast lands within the final derived-to-base subobject path.
3572 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003573 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003574 << D.MostDerivedType << TargetQT;
3575 return false;
3576 }
3577
Richard Smith027bf112011-11-17 22:56:20 +00003578 // Check the type of the final cast. We don't need to check the path,
3579 // since a cast can only be formed if the path is unique.
3580 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003581 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3582 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003583 if (NewEntriesSize == D.MostDerivedPathLength)
3584 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3585 else
Richard Smith027bf112011-11-17 22:56:20 +00003586 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003587 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003588 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003589 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003590 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003591 }
Richard Smith027bf112011-11-17 22:56:20 +00003592
3593 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003594 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003595}
3596
Mike Stump876387b2009-10-27 22:09:17 +00003597namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003598enum EvalStmtResult {
3599 /// Evaluation failed.
3600 ESR_Failed,
3601 /// Hit a 'return' statement.
3602 ESR_Returned,
3603 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003604 ESR_Succeeded,
3605 /// Hit a 'continue' statement.
3606 ESR_Continue,
3607 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003608 ESR_Break,
3609 /// Still scanning for 'case' or 'default' statement.
3610 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003611};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003612}
Richard Smith254a73d2011-10-28 22:34:42 +00003613
Richard Smith97fcf4b2016-08-14 23:15:52 +00003614static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3615 // We don't need to evaluate the initializer for a static local.
3616 if (!VD->hasLocalStorage())
3617 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003618
Richard Smith97fcf4b2016-08-14 23:15:52 +00003619 LValue Result;
3620 Result.set(VD, Info.CurrentCall->Index);
3621 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003622
Richard Smith97fcf4b2016-08-14 23:15:52 +00003623 const Expr *InitE = VD->getInit();
3624 if (!InitE) {
3625 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3626 << false << VD->getType();
3627 Val = APValue();
3628 return false;
3629 }
Richard Smith51f03172013-06-20 03:00:05 +00003630
Richard Smith97fcf4b2016-08-14 23:15:52 +00003631 if (InitE->isValueDependent())
3632 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003633
Richard Smith97fcf4b2016-08-14 23:15:52 +00003634 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3635 // Wipe out any partially-computed value, to allow tracking that this
3636 // evaluation failed.
3637 Val = APValue();
3638 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003639 }
3640
3641 return true;
3642}
3643
Richard Smith97fcf4b2016-08-14 23:15:52 +00003644static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3645 bool OK = true;
3646
3647 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3648 OK &= EvaluateVarDecl(Info, VD);
3649
3650 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3651 for (auto *BD : DD->bindings())
3652 if (auto *VD = BD->getHoldingVar())
3653 OK &= EvaluateDecl(Info, VD);
3654
3655 return OK;
3656}
3657
3658
Richard Smith4e18ca52013-05-06 05:56:11 +00003659/// Evaluate a condition (either a variable declaration or an expression).
3660static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3661 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003662 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003663 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3664 return false;
3665 return EvaluateAsBooleanCondition(Cond, Result, Info);
3666}
3667
Richard Smith89210072016-04-04 23:29:43 +00003668namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003669/// \brief A location where the result (returned value) of evaluating a
3670/// statement should be stored.
3671struct StmtResult {
3672 /// The APValue that should be filled in with the returned value.
3673 APValue &Value;
3674 /// The location containing the result, if any (used to support RVO).
3675 const LValue *Slot;
3676};
Richard Smith89210072016-04-04 23:29:43 +00003677}
Richard Smith52a980a2015-08-28 02:43:42 +00003678
3679static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003680 const Stmt *S,
3681 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003682
3683/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003684static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003685 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003686 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003687 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003688 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003689 case ESR_Break:
3690 return ESR_Succeeded;
3691 case ESR_Succeeded:
3692 case ESR_Continue:
3693 return ESR_Continue;
3694 case ESR_Failed:
3695 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003696 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003697 return ESR;
3698 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003699 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003700}
3701
Richard Smith496ddcf2013-05-12 17:32:42 +00003702/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003703static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003704 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003705 BlockScopeRAII Scope(Info);
3706
Richard Smith496ddcf2013-05-12 17:32:42 +00003707 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003708 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003709 {
3710 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003711 if (const Stmt *Init = SS->getInit()) {
3712 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3713 if (ESR != ESR_Succeeded)
3714 return ESR;
3715 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003716 if (SS->getConditionVariable() &&
3717 !EvaluateDecl(Info, SS->getConditionVariable()))
3718 return ESR_Failed;
3719 if (!EvaluateInteger(SS->getCond(), Value, Info))
3720 return ESR_Failed;
3721 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003722
3723 // Find the switch case corresponding to the value of the condition.
3724 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003725 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003726 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3727 SC = SC->getNextSwitchCase()) {
3728 if (isa<DefaultStmt>(SC)) {
3729 Found = SC;
3730 continue;
3731 }
3732
3733 const CaseStmt *CS = cast<CaseStmt>(SC);
3734 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3735 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3736 : LHS;
3737 if (LHS <= Value && Value <= RHS) {
3738 Found = SC;
3739 break;
3740 }
3741 }
3742
3743 if (!Found)
3744 return ESR_Succeeded;
3745
3746 // Search the switch body for the switch case and evaluate it from there.
3747 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3748 case ESR_Break:
3749 return ESR_Succeeded;
3750 case ESR_Succeeded:
3751 case ESR_Continue:
3752 case ESR_Failed:
3753 case ESR_Returned:
3754 return ESR;
3755 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003756 // This can only happen if the switch case is nested within a statement
3757 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003758 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003759 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003760 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003761 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003762}
3763
Richard Smith254a73d2011-10-28 22:34:42 +00003764// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003765static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003766 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003767 if (!Info.nextStep(S))
3768 return ESR_Failed;
3769
Richard Smith496ddcf2013-05-12 17:32:42 +00003770 // If we're hunting down a 'case' or 'default' label, recurse through
3771 // substatements until we hit the label.
3772 if (Case) {
3773 // FIXME: We don't start the lifetime of objects whose initialization we
3774 // jump over. However, such objects must be of class type with a trivial
3775 // default constructor that initialize all subobjects, so must be empty,
3776 // so this almost never matters.
3777 switch (S->getStmtClass()) {
3778 case Stmt::CompoundStmtClass:
3779 // FIXME: Precompute which substatement of a compound statement we
3780 // would jump to, and go straight there rather than performing a
3781 // linear scan each time.
3782 case Stmt::LabelStmtClass:
3783 case Stmt::AttributedStmtClass:
3784 case Stmt::DoStmtClass:
3785 break;
3786
3787 case Stmt::CaseStmtClass:
3788 case Stmt::DefaultStmtClass:
3789 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003790 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003791 break;
3792
3793 case Stmt::IfStmtClass: {
3794 // FIXME: Precompute which side of an 'if' we would jump to, and go
3795 // straight there rather than scanning both sides.
3796 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003797
3798 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3799 // preceded by our switch label.
3800 BlockScopeRAII Scope(Info);
3801
Richard Smith496ddcf2013-05-12 17:32:42 +00003802 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3803 if (ESR != ESR_CaseNotFound || !IS->getElse())
3804 return ESR;
3805 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3806 }
3807
3808 case Stmt::WhileStmtClass: {
3809 EvalStmtResult ESR =
3810 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3811 if (ESR != ESR_Continue)
3812 return ESR;
3813 break;
3814 }
3815
3816 case Stmt::ForStmtClass: {
3817 const ForStmt *FS = cast<ForStmt>(S);
3818 EvalStmtResult ESR =
3819 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3820 if (ESR != ESR_Continue)
3821 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003822 if (FS->getInc()) {
3823 FullExpressionRAII IncScope(Info);
3824 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3825 return ESR_Failed;
3826 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003827 break;
3828 }
3829
3830 case Stmt::DeclStmtClass:
3831 // FIXME: If the variable has initialization that can't be jumped over,
3832 // bail out of any immediately-surrounding compound-statement too.
3833 default:
3834 return ESR_CaseNotFound;
3835 }
3836 }
3837
Richard Smith254a73d2011-10-28 22:34:42 +00003838 switch (S->getStmtClass()) {
3839 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003840 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003841 // Don't bother evaluating beyond an expression-statement which couldn't
3842 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003843 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003844 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003845 return ESR_Failed;
3846 return ESR_Succeeded;
3847 }
3848
Faisal Valie690b7a2016-07-02 22:34:24 +00003849 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003850 return ESR_Failed;
3851
3852 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003853 return ESR_Succeeded;
3854
Richard Smithd9f663b2013-04-22 15:31:51 +00003855 case Stmt::DeclStmtClass: {
3856 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003857 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003858 // Each declaration initialization is its own full-expression.
3859 // FIXME: This isn't quite right; if we're performing aggregate
3860 // initialization, each braced subexpression is its own full-expression.
3861 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003862 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003863 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003864 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003865 return ESR_Succeeded;
3866 }
3867
Richard Smith357362d2011-12-13 06:39:58 +00003868 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003869 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003870 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003871 if (RetExpr &&
3872 !(Result.Slot
3873 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3874 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003875 return ESR_Failed;
3876 return ESR_Returned;
3877 }
Richard Smith254a73d2011-10-28 22:34:42 +00003878
3879 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003880 BlockScopeRAII Scope(Info);
3881
Richard Smith254a73d2011-10-28 22:34:42 +00003882 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003883 for (const auto *BI : CS->body()) {
3884 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003885 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003886 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003887 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003888 return ESR;
3889 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003890 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003891 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003892
3893 case Stmt::IfStmtClass: {
3894 const IfStmt *IS = cast<IfStmt>(S);
3895
3896 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003897 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003898 if (const Stmt *Init = IS->getInit()) {
3899 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3900 if (ESR != ESR_Succeeded)
3901 return ESR;
3902 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003903 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003904 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003905 return ESR_Failed;
3906
3907 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3908 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3909 if (ESR != ESR_Succeeded)
3910 return ESR;
3911 }
3912 return ESR_Succeeded;
3913 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003914
3915 case Stmt::WhileStmtClass: {
3916 const WhileStmt *WS = cast<WhileStmt>(S);
3917 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003918 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003919 bool Continue;
3920 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3921 Continue))
3922 return ESR_Failed;
3923 if (!Continue)
3924 break;
3925
3926 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3927 if (ESR != ESR_Continue)
3928 return ESR;
3929 }
3930 return ESR_Succeeded;
3931 }
3932
3933 case Stmt::DoStmtClass: {
3934 const DoStmt *DS = cast<DoStmt>(S);
3935 bool Continue;
3936 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003937 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003938 if (ESR != ESR_Continue)
3939 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003940 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003941
Richard Smith08d6a2c2013-07-24 07:11:57 +00003942 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003943 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3944 return ESR_Failed;
3945 } while (Continue);
3946 return ESR_Succeeded;
3947 }
3948
3949 case Stmt::ForStmtClass: {
3950 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003951 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003952 if (FS->getInit()) {
3953 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3954 if (ESR != ESR_Succeeded)
3955 return ESR;
3956 }
3957 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003958 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003959 bool Continue = true;
3960 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3961 FS->getCond(), Continue))
3962 return ESR_Failed;
3963 if (!Continue)
3964 break;
3965
3966 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3967 if (ESR != ESR_Continue)
3968 return ESR;
3969
Richard Smith08d6a2c2013-07-24 07:11:57 +00003970 if (FS->getInc()) {
3971 FullExpressionRAII IncScope(Info);
3972 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3973 return ESR_Failed;
3974 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003975 }
3976 return ESR_Succeeded;
3977 }
3978
Richard Smith896e0d72013-05-06 06:51:17 +00003979 case Stmt::CXXForRangeStmtClass: {
3980 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003981 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003982
3983 // Initialize the __range variable.
3984 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3985 if (ESR != ESR_Succeeded)
3986 return ESR;
3987
3988 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003989 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3990 if (ESR != ESR_Succeeded)
3991 return ESR;
3992 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003993 if (ESR != ESR_Succeeded)
3994 return ESR;
3995
3996 while (true) {
3997 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003998 {
3999 bool Continue = true;
4000 FullExpressionRAII CondExpr(Info);
4001 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4002 return ESR_Failed;
4003 if (!Continue)
4004 break;
4005 }
Richard Smith896e0d72013-05-06 06:51:17 +00004006
4007 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004008 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004009 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4010 if (ESR != ESR_Succeeded)
4011 return ESR;
4012
4013 // Loop body.
4014 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4015 if (ESR != ESR_Continue)
4016 return ESR;
4017
4018 // Increment: ++__begin
4019 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4020 return ESR_Failed;
4021 }
4022
4023 return ESR_Succeeded;
4024 }
4025
Richard Smith496ddcf2013-05-12 17:32:42 +00004026 case Stmt::SwitchStmtClass:
4027 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4028
Richard Smith4e18ca52013-05-06 05:56:11 +00004029 case Stmt::ContinueStmtClass:
4030 return ESR_Continue;
4031
4032 case Stmt::BreakStmtClass:
4033 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004034
4035 case Stmt::LabelStmtClass:
4036 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4037
4038 case Stmt::AttributedStmtClass:
4039 // As a general principle, C++11 attributes can be ignored without
4040 // any semantic impact.
4041 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4042 Case);
4043
4044 case Stmt::CaseStmtClass:
4045 case Stmt::DefaultStmtClass:
4046 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004047 }
4048}
4049
Richard Smithcc36f692011-12-22 02:22:31 +00004050/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4051/// default constructor. If so, we'll fold it whether or not it's marked as
4052/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4053/// so we need special handling.
4054static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004055 const CXXConstructorDecl *CD,
4056 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004057 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4058 return false;
4059
Richard Smith66e05fe2012-01-18 05:21:49 +00004060 // Value-initialization does not call a trivial default constructor, so such a
4061 // call is a core constant expression whether or not the constructor is
4062 // constexpr.
4063 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004064 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004065 // FIXME: If DiagDecl is an implicitly-declared special member function,
4066 // we should be much more explicit about why it's not constexpr.
4067 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4068 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4069 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004070 } else {
4071 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4072 }
4073 }
4074 return true;
4075}
4076
Richard Smith357362d2011-12-13 06:39:58 +00004077/// CheckConstexprFunction - Check that a function can be called in a constant
4078/// expression.
4079static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4080 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004081 const FunctionDecl *Definition,
4082 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004083 // Potential constant expressions can contain calls to declared, but not yet
4084 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004085 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004086 Declaration->isConstexpr())
4087 return false;
4088
Richard Smith0838f3a2013-05-14 05:18:44 +00004089 // Bail out with no diagnostic if the function declaration itself is invalid.
4090 // We will have produced a relevant diagnostic while parsing it.
4091 if (Declaration->isInvalidDecl())
4092 return false;
4093
Richard Smith357362d2011-12-13 06:39:58 +00004094 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004095 if (Definition && Definition->isConstexpr() &&
4096 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004097 return true;
4098
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004099 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004100 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00004101
Richard Smith5179eb72016-06-28 19:03:57 +00004102 // If this function is not constexpr because it is an inherited
4103 // non-constexpr constructor, diagnose that directly.
4104 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4105 if (CD && CD->isInheritingConstructor()) {
4106 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4107 if (!Inherited->isConstexpr())
4108 DiagDecl = CD = Inherited;
4109 }
4110
4111 // FIXME: If DiagDecl is an implicitly-declared special member function
4112 // or an inheriting constructor, we should be much more explicit about why
4113 // it's not constexpr.
4114 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004115 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004116 << CD->getInheritedConstructor().getConstructor()->getParent();
4117 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004118 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004119 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004120 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4121 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004122 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004123 }
4124 return false;
4125}
4126
Richard Smithbe6dd812014-11-19 21:27:17 +00004127/// Determine if a class has any fields that might need to be copied by a
4128/// trivial copy or move operation.
4129static bool hasFields(const CXXRecordDecl *RD) {
4130 if (!RD || RD->isEmpty())
4131 return false;
4132 for (auto *FD : RD->fields()) {
4133 if (FD->isUnnamedBitfield())
4134 continue;
4135 return true;
4136 }
4137 for (auto &Base : RD->bases())
4138 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4139 return true;
4140 return false;
4141}
4142
Richard Smithd62306a2011-11-10 06:34:14 +00004143namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004144typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004145}
4146
4147/// EvaluateArgs - Evaluate the arguments to a function call.
4148static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4149 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004150 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004151 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004152 I != E; ++I) {
4153 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4154 // If we're checking for a potential constant expression, evaluate all
4155 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004156 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004157 return false;
4158 Success = false;
4159 }
4160 }
4161 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004162}
4163
Richard Smith254a73d2011-10-28 22:34:42 +00004164/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004165static bool HandleFunctionCall(SourceLocation CallLoc,
4166 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004167 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004168 EvalInfo &Info, APValue &Result,
4169 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004170 ArgVector ArgValues(Args.size());
4171 if (!EvaluateArgs(Args, ArgValues, Info))
4172 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004173
Richard Smith253c2a32012-01-27 01:14:48 +00004174 if (!Info.CheckCallLimit(CallLoc))
4175 return false;
4176
4177 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004178
4179 // For a trivial copy or move assignment, perform an APValue copy. This is
4180 // essential for unions, where the operations performed by the assignment
4181 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004182 //
4183 // Skip this for non-union classes with no fields; in that case, the defaulted
4184 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004185 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004186 if (MD && MD->isDefaulted() &&
4187 (MD->getParent()->isUnion() ||
4188 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004189 assert(This &&
4190 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4191 LValue RHS;
4192 RHS.setFrom(Info.Ctx, ArgValues[0]);
4193 APValue RHSValue;
4194 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4195 RHS, RHSValue))
4196 return false;
4197 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4198 RHSValue))
4199 return false;
4200 This->moveInto(Result);
4201 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004202 } else if (MD && isLambdaCallOperator(MD)) {
4203 // We're in a lambda; determine the lambda capture field maps.
4204 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4205 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004206 }
4207
Richard Smith52a980a2015-08-28 02:43:42 +00004208 StmtResult Ret = {Result, ResultSlot};
4209 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004210 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004211 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004212 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004213 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004214 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004215 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004216}
4217
Richard Smithd62306a2011-11-10 06:34:14 +00004218/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004219static bool HandleConstructorCall(const Expr *E, const LValue &This,
4220 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004221 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004222 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004223 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004224 if (!Info.CheckCallLimit(CallLoc))
4225 return false;
4226
Richard Smith3607ffe2012-02-13 03:54:03 +00004227 const CXXRecordDecl *RD = Definition->getParent();
4228 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004229 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004230 return false;
4231 }
4232
Richard Smith5179eb72016-06-28 19:03:57 +00004233 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004234
Richard Smith52a980a2015-08-28 02:43:42 +00004235 // FIXME: Creating an APValue just to hold a nonexistent return value is
4236 // wasteful.
4237 APValue RetVal;
4238 StmtResult Ret = {RetVal, nullptr};
4239
Richard Smith5179eb72016-06-28 19:03:57 +00004240 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004241 if (Definition->isDelegatingConstructor()) {
4242 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004243 {
4244 FullExpressionRAII InitScope(Info);
4245 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4246 return false;
4247 }
Richard Smith52a980a2015-08-28 02:43:42 +00004248 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004249 }
4250
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004251 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004252 // essential for unions (or classes with anonymous union members), where the
4253 // operations performed by the constructor cannot be represented by
4254 // ctor-initializers.
4255 //
4256 // Skip this for empty non-union classes; we should not perform an
4257 // lvalue-to-rvalue conversion on them because their copy constructor does not
4258 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004259 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004260 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004261 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004262 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004263 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004264 return handleLValueToRValueConversion(
4265 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4266 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004267 }
4268
4269 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004270 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004271 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004272 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004273
John McCalld7bca762012-05-01 00:38:49 +00004274 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004275 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4276
Richard Smith08d6a2c2013-07-24 07:11:57 +00004277 // A scope for temporaries lifetime-extended by reference members.
4278 BlockScopeRAII LifetimeExtendedScope(Info);
4279
Richard Smith253c2a32012-01-27 01:14:48 +00004280 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004281 unsigned BasesSeen = 0;
4282#ifndef NDEBUG
4283 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4284#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004285 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004286 LValue Subobject = This;
4287 APValue *Value = &Result;
4288
4289 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004290 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004291 if (I->isBaseInitializer()) {
4292 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004293#ifndef NDEBUG
4294 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004295 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004296 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4297 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4298 "base class initializers not in expected order");
4299 ++BaseIt;
4300#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004301 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004302 BaseType->getAsCXXRecordDecl(), &Layout))
4303 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004304 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004305 } else if ((FD = I->getMember())) {
4306 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004307 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004308 if (RD->isUnion()) {
4309 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004310 Value = &Result.getUnionValue();
4311 } else {
4312 Value = &Result.getStructField(FD->getFieldIndex());
4313 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004314 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004315 // Walk the indirect field decl's chain to find the object to initialize,
4316 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004317 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004318 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004319 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4320 // Switch the union field if it differs. This happens if we had
4321 // preceding zero-initialization, and we're now initializing a union
4322 // subobject other than the first.
4323 // FIXME: In this case, the values of the other subobjects are
4324 // specified, since zero-initialization sets all padding bits to zero.
4325 if (Value->isUninit() ||
4326 (Value->isUnion() && Value->getUnionField() != FD)) {
4327 if (CD->isUnion())
4328 *Value = APValue(FD);
4329 else
4330 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004331 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004332 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004333 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004334 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004335 if (CD->isUnion())
4336 Value = &Value->getUnionValue();
4337 else
4338 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004339 }
Richard Smithd62306a2011-11-10 06:34:14 +00004340 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004341 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004342 }
Richard Smith253c2a32012-01-27 01:14:48 +00004343
Richard Smith08d6a2c2013-07-24 07:11:57 +00004344 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004345 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4346 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004347 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004348 // If we're checking for a potential constant expression, evaluate all
4349 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004350 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004351 return false;
4352 Success = false;
4353 }
Richard Smithd62306a2011-11-10 06:34:14 +00004354 }
4355
Richard Smithd9f663b2013-04-22 15:31:51 +00004356 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004357 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004358}
4359
Richard Smith5179eb72016-06-28 19:03:57 +00004360static bool HandleConstructorCall(const Expr *E, const LValue &This,
4361 ArrayRef<const Expr*> Args,
4362 const CXXConstructorDecl *Definition,
4363 EvalInfo &Info, APValue &Result) {
4364 ArgVector ArgValues(Args.size());
4365 if (!EvaluateArgs(Args, ArgValues, Info))
4366 return false;
4367
4368 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4369 Info, Result);
4370}
4371
Eli Friedman9a156e52008-11-12 09:44:48 +00004372//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004373// Generic Evaluation
4374//===----------------------------------------------------------------------===//
4375namespace {
4376
Aaron Ballman68af21c2014-01-03 19:26:43 +00004377template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004378class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004379 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004380private:
Richard Smith52a980a2015-08-28 02:43:42 +00004381 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004382 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004383 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004384 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004385 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004386 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004387 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004388
Richard Smith17100ba2012-02-16 02:46:34 +00004389 // Check whether a conditional operator with a non-constant condition is a
4390 // potential constant expression. If neither arm is a potential constant
4391 // expression, then the conditional operator is not either.
4392 template<typename ConditionalOperator>
4393 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004394 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004395
4396 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004397 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004398 {
Richard Smith17100ba2012-02-16 02:46:34 +00004399 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004400 StmtVisitorTy::Visit(E->getFalseExpr());
4401 if (Diag.empty())
4402 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004403 }
Richard Smith17100ba2012-02-16 02:46:34 +00004404
George Burgess IV8c892b52016-05-25 22:31:54 +00004405 {
4406 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004407 Diag.clear();
4408 StmtVisitorTy::Visit(E->getTrueExpr());
4409 if (Diag.empty())
4410 return;
4411 }
4412
4413 Error(E, diag::note_constexpr_conditional_never_const);
4414 }
4415
4416
4417 template<typename ConditionalOperator>
4418 bool HandleConditionalOperator(const ConditionalOperator *E) {
4419 bool BoolResult;
4420 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004421 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004422 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004423 return false;
4424 }
4425 if (Info.noteFailure()) {
4426 StmtVisitorTy::Visit(E->getTrueExpr());
4427 StmtVisitorTy::Visit(E->getFalseExpr());
4428 }
Richard Smith17100ba2012-02-16 02:46:34 +00004429 return false;
4430 }
4431
4432 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4433 return StmtVisitorTy::Visit(EvalExpr);
4434 }
4435
Peter Collingbournee9200682011-05-13 03:29:01 +00004436protected:
4437 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004438 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004439 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4440
Richard Smith92b1ce02011-12-12 09:28:41 +00004441 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004442 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004443 }
4444
Aaron Ballman68af21c2014-01-03 19:26:43 +00004445 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004446
4447public:
4448 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4449
4450 EvalInfo &getEvalInfo() { return Info; }
4451
Richard Smithf57d8cb2011-12-09 22:58:01 +00004452 /// Report an evaluation error. This should only be called when an error is
4453 /// first discovered. When propagating an error, just return false.
4454 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004455 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004456 return false;
4457 }
4458 bool Error(const Expr *E) {
4459 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4460 }
4461
Aaron Ballman68af21c2014-01-03 19:26:43 +00004462 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004463 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004464 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004465 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004466 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004467 }
4468
Aaron Ballman68af21c2014-01-03 19:26:43 +00004469 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004470 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004471 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004472 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004473 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004474 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004475 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004476 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004477 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004478 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004479 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004480 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004481 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004482 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004483 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004484 // The initializer may not have been parsed yet, or might be erroneous.
4485 if (!E->getExpr())
4486 return Error(E);
4487 return StmtVisitorTy::Visit(E->getExpr());
4488 }
Richard Smith5894a912011-12-19 22:12:41 +00004489 // We cannot create any objects for which cleanups are required, so there is
4490 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004491 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004492 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004493
Aaron Ballman68af21c2014-01-03 19:26:43 +00004494 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004495 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4496 return static_cast<Derived*>(this)->VisitCastExpr(E);
4497 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004498 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004499 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4500 return static_cast<Derived*>(this)->VisitCastExpr(E);
4501 }
4502
Aaron Ballman68af21c2014-01-03 19:26:43 +00004503 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004504 switch (E->getOpcode()) {
4505 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004506 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004507
4508 case BO_Comma:
4509 VisitIgnoredValue(E->getLHS());
4510 return StmtVisitorTy::Visit(E->getRHS());
4511
4512 case BO_PtrMemD:
4513 case BO_PtrMemI: {
4514 LValue Obj;
4515 if (!HandleMemberPointerAccess(Info, E, Obj))
4516 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004517 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004518 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004519 return false;
4520 return DerivedSuccess(Result, E);
4521 }
4522 }
4523 }
4524
Aaron Ballman68af21c2014-01-03 19:26:43 +00004525 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004526 // Evaluate and cache the common expression. We treat it as a temporary,
4527 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004528 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004529 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004530 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004531
Richard Smith17100ba2012-02-16 02:46:34 +00004532 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004533 }
4534
Aaron Ballman68af21c2014-01-03 19:26:43 +00004535 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004536 bool IsBcpCall = false;
4537 // If the condition (ignoring parens) is a __builtin_constant_p call,
4538 // the result is a constant expression if it can be folded without
4539 // side-effects. This is an important GNU extension. See GCC PR38377
4540 // for discussion.
4541 if (const CallExpr *CallCE =
4542 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004543 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004544 IsBcpCall = true;
4545
4546 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4547 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004548 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004549 return false;
4550
Richard Smith6d4c6582013-11-05 22:18:15 +00004551 FoldConstant Fold(Info, IsBcpCall);
4552 if (!HandleConditionalOperator(E)) {
4553 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004554 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004555 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004556
4557 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004558 }
4559
Aaron Ballman68af21c2014-01-03 19:26:43 +00004560 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004561 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4562 return DerivedSuccess(*Value, E);
4563
4564 const Expr *Source = E->getSourceExpr();
4565 if (!Source)
4566 return Error(E);
4567 if (Source == E) { // sanity checking.
4568 assert(0 && "OpaqueValueExpr recursively refers to itself");
4569 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004570 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004571 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004572 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004573
Aaron Ballman68af21c2014-01-03 19:26:43 +00004574 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004575 APValue Result;
4576 if (!handleCallExpr(E, Result, nullptr))
4577 return false;
4578 return DerivedSuccess(Result, E);
4579 }
4580
4581 bool handleCallExpr(const CallExpr *E, APValue &Result,
4582 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004583 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004584 QualType CalleeType = Callee->getType();
4585
Craig Topper36250ad2014-05-12 05:36:57 +00004586 const FunctionDecl *FD = nullptr;
4587 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004588 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004589 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004590
Richard Smithe97cbd72011-11-11 04:05:33 +00004591 // Extract function decl and 'this' pointer from the callee.
4592 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004593 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004594 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4595 // Explicit bound member calls, such as x.f() or p->g();
4596 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004597 return false;
4598 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004599 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004600 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004601 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4602 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004603 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4604 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004605 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004606 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004607 return Error(Callee);
4608
4609 FD = dyn_cast<FunctionDecl>(Member);
4610 if (!FD)
4611 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004612 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004613 LValue Call;
4614 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004615 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004616
Richard Smitha8105bc2012-01-06 16:39:00 +00004617 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004618 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004619 FD = dyn_cast_or_null<FunctionDecl>(
4620 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004621 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004622 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004623 // Don't call function pointers which have been cast to some other type.
4624 // Per DR (no number yet), the caller and callee can differ in noexcept.
4625 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4626 CalleeType->getPointeeType(), FD->getType())) {
4627 return Error(E);
4628 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004629
4630 // Overloaded operator calls to member functions are represented as normal
4631 // calls with '*this' as the first argument.
4632 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4633 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004634 // FIXME: When selecting an implicit conversion for an overloaded
4635 // operator delete, we sometimes try to evaluate calls to conversion
4636 // operators without a 'this' parameter!
4637 if (Args.empty())
4638 return Error(E);
4639
Richard Smithe97cbd72011-11-11 04:05:33 +00004640 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4641 return false;
4642 This = &ThisVal;
4643 Args = Args.slice(1);
Faisal Valid92e7492017-01-08 18:56:11 +00004644 } else if (MD && MD->isLambdaStaticInvoker()) {
4645 // Map the static invoker for the lambda back to the call operator.
4646 // Conveniently, we don't have to slice out the 'this' argument (as is
4647 // being done for the non-static case), since a static member function
4648 // doesn't have an implicit argument passed in.
4649 const CXXRecordDecl *ClosureClass = MD->getParent();
4650 assert(
4651 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4652 "Number of captures must be zero for conversion to function-ptr");
4653
4654 const CXXMethodDecl *LambdaCallOp =
4655 ClosureClass->getLambdaCallOperator();
4656
4657 // Set 'FD', the function that will be called below, to the call
4658 // operator. If the closure object represents a generic lambda, find
4659 // the corresponding specialization of the call operator.
4660
4661 if (ClosureClass->isGenericLambda()) {
4662 assert(MD->isFunctionTemplateSpecialization() &&
4663 "A generic lambda's static-invoker function must be a "
4664 "template specialization");
4665 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4666 FunctionTemplateDecl *CallOpTemplate =
4667 LambdaCallOp->getDescribedFunctionTemplate();
4668 void *InsertPos = nullptr;
4669 FunctionDecl *CorrespondingCallOpSpecialization =
4670 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4671 assert(CorrespondingCallOpSpecialization &&
4672 "We must always have a function call operator specialization "
4673 "that corresponds to our static invoker specialization");
4674 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4675 } else
4676 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004677 }
4678
Faisal Valid92e7492017-01-08 18:56:11 +00004679
Richard Smithe97cbd72011-11-11 04:05:33 +00004680 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004681 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004682
Richard Smith47b34932012-02-01 02:39:43 +00004683 if (This && !This->checkSubobject(Info, E, CSK_This))
4684 return false;
4685
Richard Smith3607ffe2012-02-13 03:54:03 +00004686 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4687 // calls to such functions in constant expressions.
4688 if (This && !HasQualifier &&
4689 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4690 return Error(E, diag::note_constexpr_virtual_call);
4691
Craig Topper36250ad2014-05-12 05:36:57 +00004692 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004693 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004694
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004695 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004696 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4697 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004698 return false;
4699
Richard Smith52a980a2015-08-28 02:43:42 +00004700 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004701 }
4702
Aaron Ballman68af21c2014-01-03 19:26:43 +00004703 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004704 return StmtVisitorTy::Visit(E->getInitializer());
4705 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004706 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004707 if (E->getNumInits() == 0)
4708 return DerivedZeroInitialization(E);
4709 if (E->getNumInits() == 1)
4710 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004711 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004712 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004713 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004714 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004715 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004716 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004717 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004718 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004719 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004720 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004721 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004722
Richard Smithd62306a2011-11-10 06:34:14 +00004723 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004724 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004725 assert(!E->isArrow() && "missing call to bound member function?");
4726
Richard Smith2e312c82012-03-03 22:46:17 +00004727 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004728 if (!Evaluate(Val, Info, E->getBase()))
4729 return false;
4730
4731 QualType BaseTy = E->getBase()->getType();
4732
4733 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004734 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004735 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004736 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004737 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4738
Richard Smith3229b742013-05-05 21:17:10 +00004739 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004740 SubobjectDesignator Designator(BaseTy);
4741 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004742
Richard Smith3229b742013-05-05 21:17:10 +00004743 APValue Result;
4744 return extractSubobject(Info, E, Obj, Designator, Result) &&
4745 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004746 }
4747
Aaron Ballman68af21c2014-01-03 19:26:43 +00004748 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004749 switch (E->getCastKind()) {
4750 default:
4751 break;
4752
Richard Smitha23ab512013-05-23 00:30:41 +00004753 case CK_AtomicToNonAtomic: {
4754 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004755 // This does not need to be done in place even for class/array types:
4756 // atomic-to-non-atomic conversion implies copying the object
4757 // representation.
4758 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004759 return false;
4760 return DerivedSuccess(AtomicVal, E);
4761 }
4762
Richard Smith11562c52011-10-28 17:51:58 +00004763 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004764 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004765 return StmtVisitorTy::Visit(E->getSubExpr());
4766
4767 case CK_LValueToRValue: {
4768 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004769 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4770 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004771 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004772 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004773 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004774 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004775 return false;
4776 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004777 }
4778 }
4779
Richard Smithf57d8cb2011-12-09 22:58:01 +00004780 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004781 }
4782
Aaron Ballman68af21c2014-01-03 19:26:43 +00004783 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004784 return VisitUnaryPostIncDec(UO);
4785 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004786 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004787 return VisitUnaryPostIncDec(UO);
4788 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004789 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004790 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004791 return Error(UO);
4792
4793 LValue LVal;
4794 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4795 return false;
4796 APValue RVal;
4797 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4798 UO->isIncrementOp(), &RVal))
4799 return false;
4800 return DerivedSuccess(RVal, UO);
4801 }
4802
Aaron Ballman68af21c2014-01-03 19:26:43 +00004803 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004804 // We will have checked the full-expressions inside the statement expression
4805 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004806 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004807 return Error(E);
4808
Richard Smith08d6a2c2013-07-24 07:11:57 +00004809 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004810 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004811 if (CS->body_empty())
4812 return true;
4813
Richard Smith51f03172013-06-20 03:00:05 +00004814 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4815 BE = CS->body_end();
4816 /**/; ++BI) {
4817 if (BI + 1 == BE) {
4818 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4819 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004820 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004821 diag::note_constexpr_stmt_expr_unsupported);
4822 return false;
4823 }
4824 return this->Visit(FinalExpr);
4825 }
4826
4827 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004828 StmtResult Result = { ReturnValue, nullptr };
4829 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004830 if (ESR != ESR_Succeeded) {
4831 // FIXME: If the statement-expression terminated due to 'return',
4832 // 'break', or 'continue', it would be nice to propagate that to
4833 // the outer statement evaluation rather than bailing out.
4834 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004835 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004836 diag::note_constexpr_stmt_expr_unsupported);
4837 return false;
4838 }
4839 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004840
4841 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004842 }
4843
Richard Smith4a678122011-10-24 18:44:57 +00004844 /// Visit a value which is evaluated, but whose value is ignored.
4845 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004846 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004847 }
David Majnemere9807b22016-02-26 04:23:19 +00004848
4849 /// Potentially visit a MemberExpr's base expression.
4850 void VisitIgnoredBaseExpression(const Expr *E) {
4851 // While MSVC doesn't evaluate the base expression, it does diagnose the
4852 // presence of side-effecting behavior.
4853 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4854 return;
4855 VisitIgnoredValue(E);
4856 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004857};
4858
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004859}
Peter Collingbournee9200682011-05-13 03:29:01 +00004860
4861//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004862// Common base class for lvalue and temporary evaluation.
4863//===----------------------------------------------------------------------===//
4864namespace {
4865template<class Derived>
4866class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004867 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004868protected:
4869 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004870 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004871 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004872 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004873
4874 bool Success(APValue::LValueBase B) {
4875 Result.set(B);
4876 return true;
4877 }
4878
George Burgess IVf9013bf2017-02-10 22:52:29 +00004879 bool evaluatePointer(const Expr *E, LValue &Result) {
4880 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4881 }
4882
Richard Smith027bf112011-11-17 22:56:20 +00004883public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004884 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4885 : ExprEvaluatorBaseTy(Info), Result(Result),
4886 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00004887
Richard Smith2e312c82012-03-03 22:46:17 +00004888 bool Success(const APValue &V, const Expr *E) {
4889 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004890 return true;
4891 }
Richard Smith027bf112011-11-17 22:56:20 +00004892
Richard Smith027bf112011-11-17 22:56:20 +00004893 bool VisitMemberExpr(const MemberExpr *E) {
4894 // Handle non-static data members.
4895 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004896 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004897 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004898 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00004899 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004900 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004901 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004902 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004903 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004904 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004905 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004906 BaseTy = E->getBase()->getType();
4907 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004908 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004909 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004910 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004911 Result.setInvalid(E);
4912 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004913 }
Richard Smith027bf112011-11-17 22:56:20 +00004914
Richard Smith1b78b3d2012-01-25 22:15:11 +00004915 const ValueDecl *MD = E->getMemberDecl();
4916 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4917 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4918 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4919 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004920 if (!HandleLValueMember(this->Info, E, Result, FD))
4921 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004922 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004923 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4924 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004925 } else
4926 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004927
Richard Smith1b78b3d2012-01-25 22:15:11 +00004928 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004929 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004930 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004931 RefValue))
4932 return false;
4933 return Success(RefValue, E);
4934 }
4935 return true;
4936 }
4937
4938 bool VisitBinaryOperator(const BinaryOperator *E) {
4939 switch (E->getOpcode()) {
4940 default:
4941 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4942
4943 case BO_PtrMemD:
4944 case BO_PtrMemI:
4945 return HandleMemberPointerAccess(this->Info, E, Result);
4946 }
4947 }
4948
4949 bool VisitCastExpr(const CastExpr *E) {
4950 switch (E->getCastKind()) {
4951 default:
4952 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4953
4954 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004955 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004956 if (!this->Visit(E->getSubExpr()))
4957 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004958
4959 // Now figure out the necessary offset to add to the base LV to get from
4960 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004961 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4962 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004963 }
4964 }
4965};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004966}
Richard Smith027bf112011-11-17 22:56:20 +00004967
4968//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004969// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004970//
4971// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4972// function designators (in C), decl references to void objects (in C), and
4973// temporaries (if building with -Wno-address-of-temporary).
4974//
4975// LValue evaluation produces values comprising a base expression of one of the
4976// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004977// - Declarations
4978// * VarDecl
4979// * FunctionDecl
4980// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00004981// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00004982// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004983// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004984// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004985// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004986// * ObjCEncodeExpr
4987// * AddrLabelExpr
4988// * BlockExpr
4989// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004990// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004991// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004992// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004993// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4994// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004995// * A MaterializeTemporaryExpr that has static storage duration, with no
4996// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004997// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004998//===----------------------------------------------------------------------===//
4999namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005000class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005001 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005002public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005003 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5004 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005005
Richard Smith11562c52011-10-28 17:51:58 +00005006 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005007 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005008
Peter Collingbournee9200682011-05-13 03:29:01 +00005009 bool VisitDeclRefExpr(const DeclRefExpr *E);
5010 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005011 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005012 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5013 bool VisitMemberExpr(const MemberExpr *E);
5014 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5015 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005016 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005017 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005018 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5019 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005020 bool VisitUnaryReal(const UnaryOperator *E);
5021 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005022 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5023 return VisitUnaryPreIncDec(UO);
5024 }
5025 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5026 return VisitUnaryPreIncDec(UO);
5027 }
Richard Smith3229b742013-05-05 21:17:10 +00005028 bool VisitBinAssign(const BinaryOperator *BO);
5029 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005030
Peter Collingbournee9200682011-05-13 03:29:01 +00005031 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005032 switch (E->getCastKind()) {
5033 default:
Richard Smith027bf112011-11-17 22:56:20 +00005034 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005035
Eli Friedmance3e02a2011-10-11 00:13:24 +00005036 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005037 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005038 if (!Visit(E->getSubExpr()))
5039 return false;
5040 Result.Designator.setInvalid();
5041 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005042
Richard Smith027bf112011-11-17 22:56:20 +00005043 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005044 if (!Visit(E->getSubExpr()))
5045 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005046 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005047 }
5048 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005049};
5050} // end anonymous namespace
5051
Richard Smith11562c52011-10-28 17:51:58 +00005052/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005053/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005054/// * function designators in C, and
5055/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005056/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005057static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5058 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005059 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005060 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005061 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005062}
5063
Peter Collingbournee9200682011-05-13 03:29:01 +00005064bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005065 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005066 return Success(FD);
5067 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005068 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005069 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005070 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005071 return Error(E);
5072}
Richard Smith733237d2011-10-24 23:14:33 +00005073
Faisal Vali0528a312016-11-13 06:09:16 +00005074
Richard Smith11562c52011-10-28 17:51:58 +00005075bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005076
5077 // If we are within a lambda's call operator, check whether the 'VD' referred
5078 // to within 'E' actually represents a lambda-capture that maps to a
5079 // data-member/field within the closure object, and if so, evaluate to the
5080 // field or what the field refers to.
5081 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5082 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5083 if (Info.checkingPotentialConstantExpression())
5084 return false;
5085 // Start with 'Result' referring to the complete closure object...
5086 Result = *Info.CurrentCall->This;
5087 // ... then update it to refer to the field of the closure object
5088 // that represents the capture.
5089 if (!HandleLValueMember(Info, E, Result, FD))
5090 return false;
5091 // And if the field is of reference type, update 'Result' to refer to what
5092 // the field refers to.
5093 if (FD->getType()->isReferenceType()) {
5094 APValue RVal;
5095 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5096 RVal))
5097 return false;
5098 Result.setFrom(Info.Ctx, RVal);
5099 }
5100 return true;
5101 }
5102 }
Craig Topper36250ad2014-05-12 05:36:57 +00005103 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005104 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5105 // Only if a local variable was declared in the function currently being
5106 // evaluated, do we expect to be able to find its value in the current
5107 // frame. (Otherwise it was likely declared in an enclosing context and
5108 // could either have a valid evaluatable value (for e.g. a constexpr
5109 // variable) or be ill-formed (and trigger an appropriate evaluation
5110 // diagnostic)).
5111 if (Info.CurrentCall->Callee &&
5112 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5113 Frame = Info.CurrentCall;
5114 }
5115 }
Richard Smith3229b742013-05-05 21:17:10 +00005116
Richard Smithfec09922011-11-01 16:57:24 +00005117 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005118 if (Frame) {
5119 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005120 return true;
5121 }
Richard Smithce40ad62011-11-12 22:28:03 +00005122 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005123 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005124
Richard Smith3229b742013-05-05 21:17:10 +00005125 APValue *V;
5126 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005127 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005128 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005129 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005130 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005131 return false;
5132 }
Richard Smith3229b742013-05-05 21:17:10 +00005133 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005134}
5135
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005136bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5137 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005138 // Walk through the expression to find the materialized temporary itself.
5139 SmallVector<const Expr *, 2> CommaLHSs;
5140 SmallVector<SubobjectAdjustment, 2> Adjustments;
5141 const Expr *Inner = E->GetTemporaryExpr()->
5142 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005143
Richard Smith84401042013-06-03 05:03:02 +00005144 // If we passed any comma operators, evaluate their LHSs.
5145 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5146 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5147 return false;
5148
Richard Smithe6c01442013-06-05 00:46:14 +00005149 // A materialized temporary with static storage duration can appear within the
5150 // result of a constant expression evaluation, so we need to preserve its
5151 // value for use outside this evaluation.
5152 APValue *Value;
5153 if (E->getStorageDuration() == SD_Static) {
5154 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005155 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005156 Result.set(E);
5157 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005158 Value = &Info.CurrentCall->
5159 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005160 Result.set(E, Info.CurrentCall->Index);
5161 }
5162
Richard Smithea4ad5d2013-06-06 08:19:16 +00005163 QualType Type = Inner->getType();
5164
Richard Smith84401042013-06-03 05:03:02 +00005165 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005166 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5167 (E->getStorageDuration() == SD_Static &&
5168 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5169 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005170 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005171 }
Richard Smith84401042013-06-03 05:03:02 +00005172
5173 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005174 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5175 --I;
5176 switch (Adjustments[I].Kind) {
5177 case SubobjectAdjustment::DerivedToBaseAdjustment:
5178 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5179 Type, Result))
5180 return false;
5181 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5182 break;
5183
5184 case SubobjectAdjustment::FieldAdjustment:
5185 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5186 return false;
5187 Type = Adjustments[I].Field->getType();
5188 break;
5189
5190 case SubobjectAdjustment::MemberPointerAdjustment:
5191 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5192 Adjustments[I].Ptr.RHS))
5193 return false;
5194 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5195 break;
5196 }
5197 }
5198
5199 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005200}
5201
Peter Collingbournee9200682011-05-13 03:29:01 +00005202bool
5203LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005204 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5205 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005206 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5207 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005208 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005209}
5210
Richard Smith6e525142011-12-27 12:18:28 +00005211bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005212 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005213 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005214
Faisal Valie690b7a2016-07-02 22:34:24 +00005215 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005216 << E->getExprOperand()->getType()
5217 << E->getExprOperand()->getSourceRange();
5218 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005219}
5220
Francois Pichet0066db92012-04-16 04:08:35 +00005221bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5222 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005223}
Francois Pichet0066db92012-04-16 04:08:35 +00005224
Peter Collingbournee9200682011-05-13 03:29:01 +00005225bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005226 // Handle static data members.
5227 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005228 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005229 return VisitVarDecl(E, VD);
5230 }
5231
Richard Smith254a73d2011-10-28 22:34:42 +00005232 // Handle static member functions.
5233 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5234 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005235 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005236 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005237 }
5238 }
5239
Richard Smithd62306a2011-11-10 06:34:14 +00005240 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005241 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005242}
5243
Peter Collingbournee9200682011-05-13 03:29:01 +00005244bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005245 // FIXME: Deal with vectors as array subscript bases.
5246 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005247 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005248
George Burgess IVf9013bf2017-02-10 22:52:29 +00005249 if (!evaluatePointer(E->getBase(), Result))
John McCall45d55e42010-05-07 21:00:08 +00005250 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005251
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005252 APSInt Index;
5253 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005254 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005255
Richard Smithd6cc1982017-01-31 02:23:02 +00005256 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005257}
Eli Friedman9a156e52008-11-12 09:44:48 +00005258
Peter Collingbournee9200682011-05-13 03:29:01 +00005259bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005260 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005261}
5262
Richard Smith66c96992012-02-18 22:04:06 +00005263bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5264 if (!Visit(E->getSubExpr()))
5265 return false;
5266 // __real is a no-op on scalar lvalues.
5267 if (E->getSubExpr()->getType()->isAnyComplexType())
5268 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5269 return true;
5270}
5271
5272bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5273 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5274 "lvalue __imag__ on scalar?");
5275 if (!Visit(E->getSubExpr()))
5276 return false;
5277 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5278 return true;
5279}
5280
Richard Smith243ef902013-05-05 23:31:59 +00005281bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005282 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005283 return Error(UO);
5284
5285 if (!this->Visit(UO->getSubExpr()))
5286 return false;
5287
Richard Smith243ef902013-05-05 23:31:59 +00005288 return handleIncDec(
5289 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005290 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005291}
5292
5293bool LValueExprEvaluator::VisitCompoundAssignOperator(
5294 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005295 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005296 return Error(CAO);
5297
Richard Smith3229b742013-05-05 21:17:10 +00005298 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005299
5300 // The overall lvalue result is the result of evaluating the LHS.
5301 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005302 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005303 Evaluate(RHS, this->Info, CAO->getRHS());
5304 return false;
5305 }
5306
Richard Smith3229b742013-05-05 21:17:10 +00005307 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5308 return false;
5309
Richard Smith43e77732013-05-07 04:50:00 +00005310 return handleCompoundAssignment(
5311 this->Info, CAO,
5312 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5313 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005314}
5315
5316bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005317 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005318 return Error(E);
5319
Richard Smith3229b742013-05-05 21:17:10 +00005320 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005321
5322 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005323 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005324 Evaluate(NewVal, this->Info, E->getRHS());
5325 return false;
5326 }
5327
Richard Smith3229b742013-05-05 21:17:10 +00005328 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5329 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005330
5331 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005332 NewVal);
5333}
5334
Eli Friedman9a156e52008-11-12 09:44:48 +00005335//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005336// Pointer Evaluation
5337//===----------------------------------------------------------------------===//
5338
George Burgess IVe3763372016-12-22 02:50:20 +00005339/// \brief Attempts to compute the number of bytes available at the pointer
5340/// returned by a function with the alloc_size attribute. Returns true if we
5341/// were successful. Places an unsigned number into `Result`.
5342///
5343/// This expects the given CallExpr to be a call to a function with an
5344/// alloc_size attribute.
5345static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5346 const CallExpr *Call,
5347 llvm::APInt &Result) {
5348 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5349
5350 // alloc_size args are 1-indexed, 0 means not present.
5351 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5352 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5353 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5354 if (Call->getNumArgs() <= SizeArgNo)
5355 return false;
5356
5357 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5358 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5359 return false;
5360 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5361 return false;
5362 Into = Into.zextOrSelf(BitsInSizeT);
5363 return true;
5364 };
5365
5366 APSInt SizeOfElem;
5367 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5368 return false;
5369
5370 if (!AllocSize->getNumElemsParam()) {
5371 Result = std::move(SizeOfElem);
5372 return true;
5373 }
5374
5375 APSInt NumberOfElems;
5376 // Argument numbers start at 1
5377 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5378 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5379 return false;
5380
5381 bool Overflow;
5382 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5383 if (Overflow)
5384 return false;
5385
5386 Result = std::move(BytesAvailable);
5387 return true;
5388}
5389
5390/// \brief Convenience function. LVal's base must be a call to an alloc_size
5391/// function.
5392static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5393 const LValue &LVal,
5394 llvm::APInt &Result) {
5395 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5396 "Can't get the size of a non alloc_size function");
5397 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5398 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5399 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5400}
5401
5402/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5403/// a function with the alloc_size attribute. If it was possible to do so, this
5404/// function will return true, make Result's Base point to said function call,
5405/// and mark Result's Base as invalid.
5406static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5407 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005408 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005409 return false;
5410
5411 // Because we do no form of static analysis, we only support const variables.
5412 //
5413 // Additionally, we can't support parameters, nor can we support static
5414 // variables (in the latter case, use-before-assign isn't UB; in the former,
5415 // we have no clue what they'll be assigned to).
5416 const auto *VD =
5417 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5418 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5419 return false;
5420
5421 const Expr *Init = VD->getAnyInitializer();
5422 if (!Init)
5423 return false;
5424
5425 const Expr *E = Init->IgnoreParens();
5426 if (!tryUnwrapAllocSizeCall(E))
5427 return false;
5428
5429 // Store E instead of E unwrapped so that the type of the LValue's base is
5430 // what the user wanted.
5431 Result.setInvalid(E);
5432
5433 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5434 Result.addUnsizedArray(Info, Pointee);
5435 return true;
5436}
5437
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005438namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005439class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005440 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005441 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005442 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005443
Peter Collingbournee9200682011-05-13 03:29:01 +00005444 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005445 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005446 return true;
5447 }
George Burgess IVe3763372016-12-22 02:50:20 +00005448
George Burgess IVf9013bf2017-02-10 22:52:29 +00005449 bool evaluateLValue(const Expr *E, LValue &Result) {
5450 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5451 }
5452
5453 bool evaluatePointer(const Expr *E, LValue &Result) {
5454 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5455 }
5456
George Burgess IVe3763372016-12-22 02:50:20 +00005457 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005458public:
Mike Stump11289f42009-09-09 15:08:12 +00005459
George Burgess IVf9013bf2017-02-10 22:52:29 +00005460 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5461 : ExprEvaluatorBaseTy(info), Result(Result),
5462 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005463
Richard Smith2e312c82012-03-03 22:46:17 +00005464 bool Success(const APValue &V, const Expr *E) {
5465 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005466 return true;
5467 }
Richard Smithfddd3842011-12-30 21:15:51 +00005468 bool ZeroInitialization(const Expr *E) {
Yaxun Liu402804b2016-12-15 08:09:08 +00005469 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5470 Result.set((Expr*)nullptr, 0, false, true, Offset);
5471 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005472 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005473
John McCall45d55e42010-05-07 21:00:08 +00005474 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005475 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005476 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005477 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005478 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005479 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005480 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005481 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005482 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005483 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005484 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005485 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005486 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005487 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005488 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005489 }
Richard Smithd62306a2011-11-10 06:34:14 +00005490 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005491 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005492 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005493 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005494 if (!Info.CurrentCall->This) {
5495 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005496 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005497 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005498 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005499 return false;
5500 }
Richard Smithd62306a2011-11-10 06:34:14 +00005501 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005502 // If we are inside a lambda's call operator, the 'this' expression refers
5503 // to the enclosing '*this' object (either by value or reference) which is
5504 // either copied into the closure object's field that represents the '*this'
5505 // or refers to '*this'.
5506 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5507 // Update 'Result' to refer to the data member/field of the closure object
5508 // that represents the '*this' capture.
5509 if (!HandleLValueMember(Info, E, Result,
5510 Info.CurrentCall->LambdaThisCaptureField))
5511 return false;
5512 // If we captured '*this' by reference, replace the field with its referent.
5513 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5514 ->isPointerType()) {
5515 APValue RVal;
5516 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5517 RVal))
5518 return false;
5519
5520 Result.setFrom(Info.Ctx, RVal);
5521 }
5522 }
Richard Smithd62306a2011-11-10 06:34:14 +00005523 return true;
5524 }
John McCallc07a0c72011-02-17 10:25:35 +00005525
Eli Friedman449fe542009-03-23 04:56:01 +00005526 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005527};
Chris Lattner05706e882008-07-11 18:11:29 +00005528} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005529
George Burgess IVf9013bf2017-02-10 22:52:29 +00005530static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5531 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005532 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005533 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005534}
5535
John McCall45d55e42010-05-07 21:00:08 +00005536bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005537 if (E->getOpcode() != BO_Add &&
5538 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005539 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005540
Chris Lattner05706e882008-07-11 18:11:29 +00005541 const Expr *PExp = E->getLHS();
5542 const Expr *IExp = E->getRHS();
5543 if (IExp->getType()->isPointerType())
5544 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005545
George Burgess IVf9013bf2017-02-10 22:52:29 +00005546 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005547 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005548 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005549
John McCall45d55e42010-05-07 21:00:08 +00005550 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005551 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005552 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005553
Richard Smith96e0c102011-11-04 02:25:55 +00005554 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005555 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005556
Ted Kremenek28831752012-08-23 20:46:57 +00005557 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005558 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005559}
Eli Friedman9a156e52008-11-12 09:44:48 +00005560
John McCall45d55e42010-05-07 21:00:08 +00005561bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005562 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005563}
Mike Stump11289f42009-09-09 15:08:12 +00005564
Peter Collingbournee9200682011-05-13 03:29:01 +00005565bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5566 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005567
Eli Friedman847a2bc2009-12-27 05:43:15 +00005568 switch (E->getCastKind()) {
5569 default:
5570 break;
5571
John McCalle3027922010-08-25 11:45:40 +00005572 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005573 case CK_CPointerToObjCPointerCast:
5574 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005575 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005576 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005577 if (!Visit(SubExpr))
5578 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005579 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5580 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5581 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005582 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005583 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005584 if (SubExpr->getType()->isVoidPointerType())
5585 CCEDiag(E, diag::note_constexpr_invalid_cast)
5586 << 3 << SubExpr->getType();
5587 else
5588 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5589 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005590 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5591 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005592 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005593
Anders Carlsson18275092010-10-31 20:41:46 +00005594 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005595 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005596 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005597 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005598 if (!Result.Base && Result.Offset.isZero())
5599 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005600
Richard Smithd62306a2011-11-10 06:34:14 +00005601 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005602 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005603 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5604 castAs<PointerType>()->getPointeeType(),
5605 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005606
Richard Smith027bf112011-11-17 22:56:20 +00005607 case CK_BaseToDerived:
5608 if (!Visit(E->getSubExpr()))
5609 return false;
5610 if (!Result.Base && Result.Offset.isZero())
5611 return true;
5612 return HandleBaseToDerivedCast(Info, E, Result);
5613
Richard Smith0b0a0b62011-10-29 20:57:55 +00005614 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005615 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005616 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005617
John McCalle3027922010-08-25 11:45:40 +00005618 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005619 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5620
Richard Smith2e312c82012-03-03 22:46:17 +00005621 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005622 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005623 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005624
John McCall45d55e42010-05-07 21:00:08 +00005625 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005626 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5627 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005628 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005629 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005630 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005631 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005632 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005633 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005634 return true;
5635 } else {
5636 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005637 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005638 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005639 }
5640 }
John McCalle3027922010-08-25 11:45:40 +00005641 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005642 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005643 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005644 return false;
5645 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005646 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005647 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005648 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005649 return false;
5650 }
Richard Smith96e0c102011-11-04 02:25:55 +00005651 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005652 if (const ConstantArrayType *CAT
5653 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5654 Result.addArray(Info, E, CAT);
5655 else
5656 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005657 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005658
John McCalle3027922010-08-25 11:45:40 +00005659 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005660 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005661
5662 case CK_LValueToRValue: {
5663 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005664 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005665 return false;
5666
5667 APValue RVal;
5668 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5669 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5670 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005671 return InvalidBaseOK &&
5672 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005673 return Success(RVal, E);
5674 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005675 }
5676
Richard Smith11562c52011-10-28 17:51:58 +00005677 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005678}
Chris Lattner05706e882008-07-11 18:11:29 +00005679
Hal Finkel0dd05d42014-10-03 17:18:37 +00005680static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5681 // C++ [expr.alignof]p3:
5682 // When alignof is applied to a reference type, the result is the
5683 // alignment of the referenced type.
5684 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5685 T = Ref->getPointeeType();
5686
5687 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005688 if (T.getQualifiers().hasUnaligned())
5689 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005690 return Info.Ctx.toCharUnitsFromBits(
5691 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5692}
5693
5694static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5695 E = E->IgnoreParens();
5696
5697 // The kinds of expressions that we have special-case logic here for
5698 // should be kept up to date with the special checks for those
5699 // expressions in Sema.
5700
5701 // alignof decl is always accepted, even if it doesn't make sense: we default
5702 // to 1 in those cases.
5703 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5704 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5705 /*RefAsPointee*/true);
5706
5707 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5708 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5709 /*RefAsPointee*/true);
5710
5711 return GetAlignOfType(Info, E->getType());
5712}
5713
George Burgess IVe3763372016-12-22 02:50:20 +00005714// To be clear: this happily visits unsupported builtins. Better name welcomed.
5715bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5716 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5717 return true;
5718
George Burgess IVf9013bf2017-02-10 22:52:29 +00005719 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005720 return false;
5721
5722 Result.setInvalid(E);
5723 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5724 Result.addUnsizedArray(Info, PointeeTy);
5725 return true;
5726}
5727
Peter Collingbournee9200682011-05-13 03:29:01 +00005728bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005729 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005730 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005731
Richard Smith6328cbd2016-11-16 00:57:23 +00005732 if (unsigned BuiltinOp = E->getBuiltinCallee())
5733 return VisitBuiltinCallExpr(E, BuiltinOp);
5734
George Burgess IVe3763372016-12-22 02:50:20 +00005735 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005736}
5737
5738bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5739 unsigned BuiltinOp) {
5740 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005741 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005742 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005743 case Builtin::BI__builtin_assume_aligned: {
5744 // We need to be very careful here because: if the pointer does not have the
5745 // asserted alignment, then the behavior is undefined, and undefined
5746 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005747 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005748 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005749
Hal Finkel0dd05d42014-10-03 17:18:37 +00005750 LValue OffsetResult(Result);
5751 APSInt Alignment;
5752 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5753 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005754 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005755
5756 if (E->getNumArgs() > 2) {
5757 APSInt Offset;
5758 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5759 return false;
5760
Richard Smith642a2362017-01-30 23:30:26 +00005761 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005762 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5763 }
5764
5765 // If there is a base object, then it must have the correct alignment.
5766 if (OffsetResult.Base) {
5767 CharUnits BaseAlignment;
5768 if (const ValueDecl *VD =
5769 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5770 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5771 } else {
5772 BaseAlignment =
5773 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5774 }
5775
5776 if (BaseAlignment < Align) {
5777 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005778 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005779 CCEDiag(E->getArg(0),
5780 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005781 << (unsigned)BaseAlignment.getQuantity()
5782 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005783 return false;
5784 }
5785 }
5786
5787 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005788 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005789 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005790
Richard Smith642a2362017-01-30 23:30:26 +00005791 (OffsetResult.Base
5792 ? CCEDiag(E->getArg(0),
5793 diag::note_constexpr_baa_insufficient_alignment) << 1
5794 : CCEDiag(E->getArg(0),
5795 diag::note_constexpr_baa_value_insufficient_alignment))
5796 << (int)OffsetResult.Offset.getQuantity()
5797 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005798 return false;
5799 }
5800
5801 return true;
5802 }
Richard Smithe9507952016-11-12 01:39:56 +00005803
5804 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005805 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005806 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005807 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005808 if (Info.getLangOpts().CPlusPlus11)
5809 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5810 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005811 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005812 else
5813 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5814 // Fall through.
5815 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005816 case Builtin::BI__builtin_wcschr:
5817 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005818 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005819 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005820 if (!Visit(E->getArg(0)))
5821 return false;
5822 APSInt Desired;
5823 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5824 return false;
5825 uint64_t MaxLength = uint64_t(-1);
5826 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005827 BuiltinOp != Builtin::BIwcschr &&
5828 BuiltinOp != Builtin::BI__builtin_strchr &&
5829 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005830 APSInt N;
5831 if (!EvaluateInteger(E->getArg(2), N, Info))
5832 return false;
5833 MaxLength = N.getExtValue();
5834 }
5835
Richard Smith8110c9d2016-11-29 19:45:17 +00005836 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005837
Richard Smith8110c9d2016-11-29 19:45:17 +00005838 // Figure out what value we're actually looking for (after converting to
5839 // the corresponding unsigned type if necessary).
5840 uint64_t DesiredVal;
5841 bool StopAtNull = false;
5842 switch (BuiltinOp) {
5843 case Builtin::BIstrchr:
5844 case Builtin::BI__builtin_strchr:
5845 // strchr compares directly to the passed integer, and therefore
5846 // always fails if given an int that is not a char.
5847 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5848 E->getArg(1)->getType(),
5849 Desired),
5850 Desired))
5851 return ZeroInitialization(E);
5852 StopAtNull = true;
5853 // Fall through.
5854 case Builtin::BImemchr:
5855 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005856 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005857 // memchr compares by converting both sides to unsigned char. That's also
5858 // correct for strchr if we get this far (to cope with plain char being
5859 // unsigned in the strchr case).
5860 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5861 break;
Richard Smithe9507952016-11-12 01:39:56 +00005862
Richard Smith8110c9d2016-11-29 19:45:17 +00005863 case Builtin::BIwcschr:
5864 case Builtin::BI__builtin_wcschr:
5865 StopAtNull = true;
5866 // Fall through.
5867 case Builtin::BIwmemchr:
5868 case Builtin::BI__builtin_wmemchr:
5869 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5870 DesiredVal = Desired.getZExtValue();
5871 break;
5872 }
Richard Smithe9507952016-11-12 01:39:56 +00005873
5874 for (; MaxLength; --MaxLength) {
5875 APValue Char;
5876 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5877 !Char.isInt())
5878 return false;
5879 if (Char.getInt().getZExtValue() == DesiredVal)
5880 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005881 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005882 break;
5883 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5884 return false;
5885 }
5886 // Not found: return nullptr.
5887 return ZeroInitialization(E);
5888 }
5889
Richard Smith6cbd65d2013-07-11 02:27:57 +00005890 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005891 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005892 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005893}
Chris Lattner05706e882008-07-11 18:11:29 +00005894
5895//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005896// Member Pointer Evaluation
5897//===----------------------------------------------------------------------===//
5898
5899namespace {
5900class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005901 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005902 MemberPtr &Result;
5903
5904 bool Success(const ValueDecl *D) {
5905 Result = MemberPtr(D);
5906 return true;
5907 }
5908public:
5909
5910 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5911 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5912
Richard Smith2e312c82012-03-03 22:46:17 +00005913 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005914 Result.setFrom(V);
5915 return true;
5916 }
Richard Smithfddd3842011-12-30 21:15:51 +00005917 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005918 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005919 }
5920
5921 bool VisitCastExpr(const CastExpr *E);
5922 bool VisitUnaryAddrOf(const UnaryOperator *E);
5923};
5924} // end anonymous namespace
5925
5926static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5927 EvalInfo &Info) {
5928 assert(E->isRValue() && E->getType()->isMemberPointerType());
5929 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5930}
5931
5932bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5933 switch (E->getCastKind()) {
5934 default:
5935 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5936
5937 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005938 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005939 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005940
5941 case CK_BaseToDerivedMemberPointer: {
5942 if (!Visit(E->getSubExpr()))
5943 return false;
5944 if (E->path_empty())
5945 return true;
5946 // Base-to-derived member pointer casts store the path in derived-to-base
5947 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5948 // the wrong end of the derived->base arc, so stagger the path by one class.
5949 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5950 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5951 PathI != PathE; ++PathI) {
5952 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5953 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5954 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005955 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005956 }
5957 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5958 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005959 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005960 return true;
5961 }
5962
5963 case CK_DerivedToBaseMemberPointer:
5964 if (!Visit(E->getSubExpr()))
5965 return false;
5966 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5967 PathE = E->path_end(); PathI != PathE; ++PathI) {
5968 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5969 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5970 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005971 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005972 }
5973 return true;
5974 }
5975}
5976
5977bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5978 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5979 // member can be formed.
5980 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5981}
5982
5983//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005984// Record Evaluation
5985//===----------------------------------------------------------------------===//
5986
5987namespace {
5988 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005989 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005990 const LValue &This;
5991 APValue &Result;
5992 public:
5993
5994 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5995 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5996
Richard Smith2e312c82012-03-03 22:46:17 +00005997 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005998 Result = V;
5999 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006000 }
Richard Smithb8348f52016-05-12 22:16:28 +00006001 bool ZeroInitialization(const Expr *E) {
6002 return ZeroInitialization(E, E->getType());
6003 }
6004 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006005
Richard Smith52a980a2015-08-28 02:43:42 +00006006 bool VisitCallExpr(const CallExpr *E) {
6007 return handleCallExpr(E, Result, &This);
6008 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006009 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006010 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006011 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6012 return VisitCXXConstructExpr(E, E->getType());
6013 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006014 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006015 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006016 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006017 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006018 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006019}
Richard Smithd62306a2011-11-10 06:34:14 +00006020
Richard Smithfddd3842011-12-30 21:15:51 +00006021/// Perform zero-initialization on an object of non-union class type.
6022/// C++11 [dcl.init]p5:
6023/// To zero-initialize an object or reference of type T means:
6024/// [...]
6025/// -- if T is a (possibly cv-qualified) non-union class type,
6026/// each non-static data member and each base-class subobject is
6027/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006028static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6029 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006030 const LValue &This, APValue &Result) {
6031 assert(!RD->isUnion() && "Expected non-union class type");
6032 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6033 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006034 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006035
John McCalld7bca762012-05-01 00:38:49 +00006036 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006037 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6038
6039 if (CD) {
6040 unsigned Index = 0;
6041 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006042 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006043 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6044 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006045 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6046 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006047 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006048 Result.getStructBase(Index)))
6049 return false;
6050 }
6051 }
6052
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006053 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006054 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006055 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006056 continue;
6057
6058 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006059 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006060 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006061
David Blaikie2d7c57e2012-04-30 02:36:29 +00006062 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006063 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006064 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006065 return false;
6066 }
6067
6068 return true;
6069}
6070
Richard Smithb8348f52016-05-12 22:16:28 +00006071bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6072 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006073 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006074 if (RD->isUnion()) {
6075 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6076 // object's first non-static named data member is zero-initialized
6077 RecordDecl::field_iterator I = RD->field_begin();
6078 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006079 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006080 return true;
6081 }
6082
6083 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006084 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006085 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006086 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006087 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006088 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006089 }
6090
Richard Smith5d108602012-02-17 00:44:16 +00006091 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006092 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006093 return false;
6094 }
6095
Richard Smitha8105bc2012-01-06 16:39:00 +00006096 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006097}
6098
Richard Smithe97cbd72011-11-11 04:05:33 +00006099bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6100 switch (E->getCastKind()) {
6101 default:
6102 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6103
6104 case CK_ConstructorConversion:
6105 return Visit(E->getSubExpr());
6106
6107 case CK_DerivedToBase:
6108 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006109 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006110 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006111 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006112 if (!DerivedObject.isStruct())
6113 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006114
6115 // Derived-to-base rvalue conversion: just slice off the derived part.
6116 APValue *Value = &DerivedObject;
6117 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6118 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6119 PathE = E->path_end(); PathI != PathE; ++PathI) {
6120 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6121 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6122 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6123 RD = Base;
6124 }
6125 Result = *Value;
6126 return true;
6127 }
6128 }
6129}
6130
Richard Smithd62306a2011-11-10 06:34:14 +00006131bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006132 if (E->isTransparent())
6133 return Visit(E->getInit(0));
6134
Richard Smithd62306a2011-11-10 06:34:14 +00006135 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006136 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006137 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6138
6139 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006140 const FieldDecl *Field = E->getInitializedFieldInUnion();
6141 Result = APValue(Field);
6142 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006143 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006144
6145 // If the initializer list for a union does not contain any elements, the
6146 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006147 // FIXME: The element should be initialized from an initializer list.
6148 // Is this difference ever observable for initializer lists which
6149 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006150 ImplicitValueInitExpr VIE(Field->getType());
6151 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6152
Richard Smithd62306a2011-11-10 06:34:14 +00006153 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006154 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6155 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006156
6157 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6158 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6159 isa<CXXDefaultInitExpr>(InitExpr));
6160
Richard Smithb228a862012-02-15 02:18:13 +00006161 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006162 }
6163
Richard Smith872307e2016-03-08 22:17:41 +00006164 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006165 if (Result.isUninit())
6166 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6167 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006168 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006169 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006170
6171 // Initialize base classes.
6172 if (CXXRD) {
6173 for (const auto &Base : CXXRD->bases()) {
6174 assert(ElementNo < E->getNumInits() && "missing init for base class");
6175 const Expr *Init = E->getInit(ElementNo);
6176
6177 LValue Subobject = This;
6178 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6179 return false;
6180
6181 APValue &FieldVal = Result.getStructBase(ElementNo);
6182 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006183 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006184 return false;
6185 Success = false;
6186 }
6187 ++ElementNo;
6188 }
6189 }
6190
6191 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006192 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006193 // Anonymous bit-fields are not considered members of the class for
6194 // purposes of aggregate initialization.
6195 if (Field->isUnnamedBitfield())
6196 continue;
6197
6198 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006199
Richard Smith253c2a32012-01-27 01:14:48 +00006200 bool HaveInit = ElementNo < E->getNumInits();
6201
6202 // FIXME: Diagnostics here should point to the end of the initializer
6203 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006204 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006205 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006206 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006207
6208 // Perform an implicit value-initialization for members beyond the end of
6209 // the initializer list.
6210 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006211 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006212
Richard Smith852c9db2013-04-20 22:23:05 +00006213 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6214 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6215 isa<CXXDefaultInitExpr>(Init));
6216
Richard Smith49ca8aa2013-08-06 07:09:20 +00006217 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6218 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6219 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006220 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006221 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006222 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006223 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006224 }
6225 }
6226
Richard Smith253c2a32012-01-27 01:14:48 +00006227 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006228}
6229
Richard Smithb8348f52016-05-12 22:16:28 +00006230bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6231 QualType T) {
6232 // Note that E's type is not necessarily the type of our class here; we might
6233 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006234 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006235 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6236
Richard Smithfddd3842011-12-30 21:15:51 +00006237 bool ZeroInit = E->requiresZeroInitialization();
6238 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006239 // If we've already performed zero-initialization, we're already done.
6240 if (!Result.isUninit())
6241 return true;
6242
Richard Smithda3f4fd2014-03-05 23:32:50 +00006243 // We can get here in two different ways:
6244 // 1) We're performing value-initialization, and should zero-initialize
6245 // the object, or
6246 // 2) We're performing default-initialization of an object with a trivial
6247 // constexpr default constructor, in which case we should start the
6248 // lifetimes of all the base subobjects (there can be no data member
6249 // subobjects in this case) per [basic.life]p1.
6250 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006251 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006252 }
6253
Craig Topper36250ad2014-05-12 05:36:57 +00006254 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006255 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006256
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006257 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006258 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006259
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006260 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006261 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006262 if (const MaterializeTemporaryExpr *ME
6263 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6264 return Visit(ME->GetTemporaryExpr());
6265
Richard Smithb8348f52016-05-12 22:16:28 +00006266 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006267 return false;
6268
Craig Topper5fc8fc22014-08-27 06:28:36 +00006269 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006270 return HandleConstructorCall(E, This, Args,
6271 cast<CXXConstructorDecl>(Definition), Info,
6272 Result);
6273}
6274
6275bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6276 const CXXInheritedCtorInitExpr *E) {
6277 if (!Info.CurrentCall) {
6278 assert(Info.checkingPotentialConstantExpression());
6279 return false;
6280 }
6281
6282 const CXXConstructorDecl *FD = E->getConstructor();
6283 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6284 return false;
6285
6286 const FunctionDecl *Definition = nullptr;
6287 auto Body = FD->getBody(Definition);
6288
6289 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6290 return false;
6291
6292 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006293 cast<CXXConstructorDecl>(Definition), Info,
6294 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006295}
6296
Richard Smithcc1b96d2013-06-12 22:31:48 +00006297bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6298 const CXXStdInitializerListExpr *E) {
6299 const ConstantArrayType *ArrayType =
6300 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6301
6302 LValue Array;
6303 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6304 return false;
6305
6306 // Get a pointer to the first element of the array.
6307 Array.addArray(Info, E, ArrayType);
6308
6309 // FIXME: Perform the checks on the field types in SemaInit.
6310 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6311 RecordDecl::field_iterator Field = Record->field_begin();
6312 if (Field == Record->field_end())
6313 return Error(E);
6314
6315 // Start pointer.
6316 if (!Field->getType()->isPointerType() ||
6317 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6318 ArrayType->getElementType()))
6319 return Error(E);
6320
6321 // FIXME: What if the initializer_list type has base classes, etc?
6322 Result = APValue(APValue::UninitStruct(), 0, 2);
6323 Array.moveInto(Result.getStructField(0));
6324
6325 if (++Field == Record->field_end())
6326 return Error(E);
6327
6328 if (Field->getType()->isPointerType() &&
6329 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6330 ArrayType->getElementType())) {
6331 // End pointer.
6332 if (!HandleLValueArrayAdjustment(Info, E, Array,
6333 ArrayType->getElementType(),
6334 ArrayType->getSize().getZExtValue()))
6335 return false;
6336 Array.moveInto(Result.getStructField(1));
6337 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6338 // Length.
6339 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6340 else
6341 return Error(E);
6342
6343 if (++Field != Record->field_end())
6344 return Error(E);
6345
6346 return true;
6347}
6348
Faisal Valic72a08c2017-01-09 03:02:53 +00006349bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6350 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6351 if (ClosureClass->isInvalidDecl()) return false;
6352
6353 if (Info.checkingPotentialConstantExpression()) return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00006354
6355 const size_t NumFields =
6356 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006357
6358 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6359 E->capture_init_end()) &&
6360 "The number of lambda capture initializers should equal the number of "
6361 "fields within the closure type");
6362
Faisal Vali051e3a22017-02-16 04:12:21 +00006363 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6364 // Iterate through all the lambda's closure object's fields and initialize
6365 // them.
6366 auto *CaptureInitIt = E->capture_init_begin();
6367 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6368 bool Success = true;
6369 for (const auto *Field : ClosureClass->fields()) {
6370 assert(CaptureInitIt != E->capture_init_end());
6371 // Get the initializer for this field
6372 Expr *const CurFieldInit = *CaptureInitIt++;
6373
6374 // If there is no initializer, either this is a VLA or an error has
6375 // occurred.
6376 if (!CurFieldInit)
6377 return Error(E);
6378
6379 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6380 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6381 if (!Info.keepEvaluatingAfterFailure())
6382 return false;
6383 Success = false;
6384 }
6385 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006386 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006387 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006388}
6389
Richard Smithd62306a2011-11-10 06:34:14 +00006390static bool EvaluateRecord(const Expr *E, const LValue &This,
6391 APValue &Result, EvalInfo &Info) {
6392 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006393 "can't evaluate expression as a record rvalue");
6394 return RecordExprEvaluator(Info, This, Result).Visit(E);
6395}
6396
6397//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006398// Temporary Evaluation
6399//
6400// Temporaries are represented in the AST as rvalues, but generally behave like
6401// lvalues. The full-object of which the temporary is a subobject is implicitly
6402// materialized so that a reference can bind to it.
6403//===----------------------------------------------------------------------===//
6404namespace {
6405class TemporaryExprEvaluator
6406 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6407public:
6408 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006409 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006410
6411 /// Visit an expression which constructs the value of this temporary.
6412 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006413 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006414 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6415 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006416 }
6417
6418 bool VisitCastExpr(const CastExpr *E) {
6419 switch (E->getCastKind()) {
6420 default:
6421 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6422
6423 case CK_ConstructorConversion:
6424 return VisitConstructExpr(E->getSubExpr());
6425 }
6426 }
6427 bool VisitInitListExpr(const InitListExpr *E) {
6428 return VisitConstructExpr(E);
6429 }
6430 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6431 return VisitConstructExpr(E);
6432 }
6433 bool VisitCallExpr(const CallExpr *E) {
6434 return VisitConstructExpr(E);
6435 }
Richard Smith513955c2014-12-17 19:24:30 +00006436 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6437 return VisitConstructExpr(E);
6438 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006439 bool VisitLambdaExpr(const LambdaExpr *E) {
6440 return VisitConstructExpr(E);
6441 }
Richard Smith027bf112011-11-17 22:56:20 +00006442};
6443} // end anonymous namespace
6444
6445/// Evaluate an expression of record type as a temporary.
6446static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006447 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006448 return TemporaryExprEvaluator(Info, Result).Visit(E);
6449}
6450
6451//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006452// Vector Evaluation
6453//===----------------------------------------------------------------------===//
6454
6455namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006456 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006457 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006458 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006459 public:
Mike Stump11289f42009-09-09 15:08:12 +00006460
Richard Smith2d406342011-10-22 21:10:00 +00006461 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6462 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006463
Craig Topper9798b932015-09-29 04:30:05 +00006464 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006465 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6466 // FIXME: remove this APValue copy.
6467 Result = APValue(V.data(), V.size());
6468 return true;
6469 }
Richard Smith2e312c82012-03-03 22:46:17 +00006470 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006471 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006472 Result = V;
6473 return true;
6474 }
Richard Smithfddd3842011-12-30 21:15:51 +00006475 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006476
Richard Smith2d406342011-10-22 21:10:00 +00006477 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006478 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006479 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006480 bool VisitInitListExpr(const InitListExpr *E);
6481 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006482 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006483 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006484 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006485 };
6486} // end anonymous namespace
6487
6488static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006489 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006490 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006491}
6492
George Burgess IV533ff002015-12-11 00:23:35 +00006493bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006494 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006495 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006496
Richard Smith161f09a2011-12-06 22:44:34 +00006497 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006498 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006499
Eli Friedmanc757de22011-03-25 00:43:55 +00006500 switch (E->getCastKind()) {
6501 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006502 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006503 if (SETy->isIntegerType()) {
6504 APSInt IntResult;
6505 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006506 return false;
6507 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006508 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006509 APFloat FloatResult(0.0);
6510 if (!EvaluateFloat(SE, FloatResult, Info))
6511 return false;
6512 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006513 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006514 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006515 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006516
6517 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006518 SmallVector<APValue, 4> Elts(NElts, Val);
6519 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006520 }
Eli Friedman803acb32011-12-22 03:51:45 +00006521 case CK_BitCast: {
6522 // Evaluate the operand into an APInt we can extract from.
6523 llvm::APInt SValInt;
6524 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6525 return false;
6526 // Extract the elements
6527 QualType EltTy = VTy->getElementType();
6528 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6529 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6530 SmallVector<APValue, 4> Elts;
6531 if (EltTy->isRealFloatingType()) {
6532 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006533 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006534 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006535 FloatEltSize = 80;
6536 for (unsigned i = 0; i < NElts; i++) {
6537 llvm::APInt Elt;
6538 if (BigEndian)
6539 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6540 else
6541 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006542 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006543 }
6544 } else if (EltTy->isIntegerType()) {
6545 for (unsigned i = 0; i < NElts; i++) {
6546 llvm::APInt Elt;
6547 if (BigEndian)
6548 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6549 else
6550 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6551 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6552 }
6553 } else {
6554 return Error(E);
6555 }
6556 return Success(Elts, E);
6557 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006558 default:
Richard Smith11562c52011-10-28 17:51:58 +00006559 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006560 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006561}
6562
Richard Smith2d406342011-10-22 21:10:00 +00006563bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006564VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006565 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006566 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006567 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006568
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006569 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006570 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006571
Eli Friedmanb9c71292012-01-03 23:24:20 +00006572 // The number of initializers can be less than the number of
6573 // vector elements. For OpenCL, this can be due to nested vector
6574 // initialization. For GCC compatibility, missing trailing elements
6575 // should be initialized with zeroes.
6576 unsigned CountInits = 0, CountElts = 0;
6577 while (CountElts < NumElements) {
6578 // Handle nested vector initialization.
6579 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006580 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006581 APValue v;
6582 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6583 return Error(E);
6584 unsigned vlen = v.getVectorLength();
6585 for (unsigned j = 0; j < vlen; j++)
6586 Elements.push_back(v.getVectorElt(j));
6587 CountElts += vlen;
6588 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006589 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006590 if (CountInits < NumInits) {
6591 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006592 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006593 } else // trailing integer zero.
6594 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6595 Elements.push_back(APValue(sInt));
6596 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006597 } else {
6598 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006599 if (CountInits < NumInits) {
6600 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006601 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006602 } else // trailing float zero.
6603 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6604 Elements.push_back(APValue(f));
6605 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006606 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006607 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006608 }
Richard Smith2d406342011-10-22 21:10:00 +00006609 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006610}
6611
Richard Smith2d406342011-10-22 21:10:00 +00006612bool
Richard Smithfddd3842011-12-30 21:15:51 +00006613VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006614 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006615 QualType EltTy = VT->getElementType();
6616 APValue ZeroElement;
6617 if (EltTy->isIntegerType())
6618 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6619 else
6620 ZeroElement =
6621 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6622
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006623 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006624 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006625}
6626
Richard Smith2d406342011-10-22 21:10:00 +00006627bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006628 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006629 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006630}
6631
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006632//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006633// Array Evaluation
6634//===----------------------------------------------------------------------===//
6635
6636namespace {
6637 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006638 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006639 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006640 APValue &Result;
6641 public:
6642
Richard Smithd62306a2011-11-10 06:34:14 +00006643 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6644 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006645
6646 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006647 assert((V.isArray() || V.isLValue()) &&
6648 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006649 Result = V;
6650 return true;
6651 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006652
Richard Smithfddd3842011-12-30 21:15:51 +00006653 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006654 const ConstantArrayType *CAT =
6655 Info.Ctx.getAsConstantArrayType(E->getType());
6656 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006657 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006658
6659 Result = APValue(APValue::UninitArray(), 0,
6660 CAT->getSize().getZExtValue());
6661 if (!Result.hasArrayFiller()) return true;
6662
Richard Smithfddd3842011-12-30 21:15:51 +00006663 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006664 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006665 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006666 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006667 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006668 }
6669
Richard Smith52a980a2015-08-28 02:43:42 +00006670 bool VisitCallExpr(const CallExpr *E) {
6671 return handleCallExpr(E, Result, &This);
6672 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006673 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006674 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006675 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006676 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6677 const LValue &Subobject,
6678 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006679 };
6680} // end anonymous namespace
6681
Richard Smithd62306a2011-11-10 06:34:14 +00006682static bool EvaluateArray(const Expr *E, const LValue &This,
6683 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006684 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006685 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006686}
6687
6688bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6689 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6690 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006691 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006692
Richard Smithca2cfbf2011-12-22 01:07:19 +00006693 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6694 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006695 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006696 LValue LV;
6697 if (!EvaluateLValue(E->getInit(0), LV, Info))
6698 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006699 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006700 LV.moveInto(Val);
6701 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006702 }
6703
Richard Smith253c2a32012-01-27 01:14:48 +00006704 bool Success = true;
6705
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006706 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6707 "zero-initialized array shouldn't have any initialized elts");
6708 APValue Filler;
6709 if (Result.isArray() && Result.hasArrayFiller())
6710 Filler = Result.getArrayFiller();
6711
Richard Smith9543c5e2013-04-22 14:44:29 +00006712 unsigned NumEltsToInit = E->getNumInits();
6713 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006714 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006715
6716 // If the initializer might depend on the array index, run it for each
6717 // array element. For now, just whitelist non-class value-initialization.
6718 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6719 NumEltsToInit = NumElts;
6720
6721 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006722
6723 // If the array was previously zero-initialized, preserve the
6724 // zero-initialized values.
6725 if (!Filler.isUninit()) {
6726 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6727 Result.getArrayInitializedElt(I) = Filler;
6728 if (Result.hasArrayFiller())
6729 Result.getArrayFiller() = Filler;
6730 }
6731
Richard Smithd62306a2011-11-10 06:34:14 +00006732 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006733 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006734 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6735 const Expr *Init =
6736 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006737 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006738 Info, Subobject, Init) ||
6739 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006740 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006741 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006742 return false;
6743 Success = false;
6744 }
Richard Smithd62306a2011-11-10 06:34:14 +00006745 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006746
Richard Smith9543c5e2013-04-22 14:44:29 +00006747 if (!Result.hasArrayFiller())
6748 return Success;
6749
6750 // If we get here, we have a trivial filler, which we can just evaluate
6751 // once and splat over the rest of the array elements.
6752 assert(FillerExpr && "no array filler for incomplete init list");
6753 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6754 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006755}
6756
Richard Smith410306b2016-12-12 02:53:20 +00006757bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6758 if (E->getCommonExpr() &&
6759 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6760 Info, E->getCommonExpr()->getSourceExpr()))
6761 return false;
6762
6763 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6764
6765 uint64_t Elements = CAT->getSize().getZExtValue();
6766 Result = APValue(APValue::UninitArray(), Elements, Elements);
6767
6768 LValue Subobject = This;
6769 Subobject.addArray(Info, E, CAT);
6770
6771 bool Success = true;
6772 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6773 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6774 Info, Subobject, E->getSubExpr()) ||
6775 !HandleLValueArrayAdjustment(Info, E, Subobject,
6776 CAT->getElementType(), 1)) {
6777 if (!Info.noteFailure())
6778 return false;
6779 Success = false;
6780 }
6781 }
6782
6783 return Success;
6784}
6785
Richard Smith027bf112011-11-17 22:56:20 +00006786bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006787 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6788}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006789
Richard Smith9543c5e2013-04-22 14:44:29 +00006790bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6791 const LValue &Subobject,
6792 APValue *Value,
6793 QualType Type) {
6794 bool HadZeroInit = !Value->isUninit();
6795
6796 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6797 unsigned N = CAT->getSize().getZExtValue();
6798
6799 // Preserve the array filler if we had prior zero-initialization.
6800 APValue Filler =
6801 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6802 : APValue();
6803
6804 *Value = APValue(APValue::UninitArray(), N, N);
6805
6806 if (HadZeroInit)
6807 for (unsigned I = 0; I != N; ++I)
6808 Value->getArrayInitializedElt(I) = Filler;
6809
6810 // Initialize the elements.
6811 LValue ArrayElt = Subobject;
6812 ArrayElt.addArray(Info, E, CAT);
6813 for (unsigned I = 0; I != N; ++I)
6814 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6815 CAT->getElementType()) ||
6816 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6817 CAT->getElementType(), 1))
6818 return false;
6819
6820 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006821 }
Richard Smith027bf112011-11-17 22:56:20 +00006822
Richard Smith9543c5e2013-04-22 14:44:29 +00006823 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006824 return Error(E);
6825
Richard Smithb8348f52016-05-12 22:16:28 +00006826 return RecordExprEvaluator(Info, Subobject, *Value)
6827 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006828}
6829
Richard Smithf3e9e432011-11-07 09:22:26 +00006830//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006831// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006832//
6833// As a GNU extension, we support casting pointers to sufficiently-wide integer
6834// types and back in constant folding. Integer values are thus represented
6835// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006836//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006837
6838namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006839class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006840 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006841 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006842public:
Richard Smith2e312c82012-03-03 22:46:17 +00006843 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006844 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006845
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006846 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006847 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006848 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006849 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006850 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006851 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006852 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006853 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006854 return true;
6855 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006856 bool Success(const llvm::APSInt &SI, const Expr *E) {
6857 return Success(SI, E, Result);
6858 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006859
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006860 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006861 assert(E->getType()->isIntegralOrEnumerationType() &&
6862 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006863 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006864 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006865 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006866 Result.getInt().setIsUnsigned(
6867 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006868 return true;
6869 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006870 bool Success(const llvm::APInt &I, const Expr *E) {
6871 return Success(I, E, Result);
6872 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006873
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006874 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006875 assert(E->getType()->isIntegralOrEnumerationType() &&
6876 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006877 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006878 return true;
6879 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006880 bool Success(uint64_t Value, const Expr *E) {
6881 return Success(Value, E, Result);
6882 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006883
Ken Dyckdbc01912011-03-11 02:13:43 +00006884 bool Success(CharUnits Size, const Expr *E) {
6885 return Success(Size.getQuantity(), E);
6886 }
6887
Richard Smith2e312c82012-03-03 22:46:17 +00006888 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006889 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006890 Result = V;
6891 return true;
6892 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006893 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006894 }
Mike Stump11289f42009-09-09 15:08:12 +00006895
Richard Smithfddd3842011-12-30 21:15:51 +00006896 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006897
Peter Collingbournee9200682011-05-13 03:29:01 +00006898 //===--------------------------------------------------------------------===//
6899 // Visitor Methods
6900 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006901
Chris Lattner7174bf32008-07-12 00:38:25 +00006902 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006903 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006904 }
6905 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006906 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006907 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006908
6909 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6910 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006911 if (CheckReferencedDecl(E, E->getDecl()))
6912 return true;
6913
6914 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006915 }
6916 bool VisitMemberExpr(const MemberExpr *E) {
6917 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006918 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006919 return true;
6920 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006921
6922 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006923 }
6924
Peter Collingbournee9200682011-05-13 03:29:01 +00006925 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006926 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006927 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006928 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006929 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006930
Peter Collingbournee9200682011-05-13 03:29:01 +00006931 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006932 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006933
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006934 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006935 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006936 }
Mike Stump11289f42009-09-09 15:08:12 +00006937
Ted Kremeneke65b0862012-03-06 20:05:56 +00006938 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6939 return Success(E->getValue(), E);
6940 }
Richard Smith410306b2016-12-12 02:53:20 +00006941
6942 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6943 if (Info.ArrayInitIndex == uint64_t(-1)) {
6944 // We were asked to evaluate this subexpression independent of the
6945 // enclosing ArrayInitLoopExpr. We can't do that.
6946 Info.FFDiag(E);
6947 return false;
6948 }
6949 return Success(Info.ArrayInitIndex, E);
6950 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00006951
Richard Smith4ce706a2011-10-11 21:43:33 +00006952 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006953 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006954 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006955 }
6956
Douglas Gregor29c42f22012-02-24 07:38:34 +00006957 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6958 return Success(E->getValue(), E);
6959 }
6960
John Wiegley6242b6a2011-04-28 00:16:57 +00006961 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6962 return Success(E->getValue(), E);
6963 }
6964
John Wiegleyf9f65842011-04-25 06:54:41 +00006965 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6966 return Success(E->getValue(), E);
6967 }
6968
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006969 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006970 bool VisitUnaryImag(const UnaryOperator *E);
6971
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006972 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006973 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006974
Eli Friedman4e7a2412009-02-27 04:45:43 +00006975 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006976};
Chris Lattner05706e882008-07-11 18:11:29 +00006977} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006978
Richard Smith11562c52011-10-28 17:51:58 +00006979/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6980/// produce either the integer value or a pointer.
6981///
6982/// GCC has a heinous extension which folds casts between pointer types and
6983/// pointer-sized integral types. We support this by allowing the evaluation of
6984/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6985/// Some simple arithmetic on such values is supported (they are treated much
6986/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006987static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006988 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006989 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006990 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006991}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006992
Richard Smithf57d8cb2011-12-09 22:58:01 +00006993static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006994 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006995 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006996 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006997 if (!Val.isInt()) {
6998 // FIXME: It would be better to produce the diagnostic for casting
6999 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007000 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007001 return false;
7002 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007003 Result = Val.getInt();
7004 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007005}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007006
Richard Smithf57d8cb2011-12-09 22:58:01 +00007007/// Check whether the given declaration can be directly converted to an integral
7008/// rvalue. If not, no diagnostic is produced; there are other things we can
7009/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007010bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007011 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007012 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007013 // Check for signedness/width mismatches between E type and ECD value.
7014 bool SameSign = (ECD->getInitVal().isSigned()
7015 == E->getType()->isSignedIntegerOrEnumerationType());
7016 bool SameWidth = (ECD->getInitVal().getBitWidth()
7017 == Info.Ctx.getIntWidth(E->getType()));
7018 if (SameSign && SameWidth)
7019 return Success(ECD->getInitVal(), E);
7020 else {
7021 // Get rid of mismatch (otherwise Success assertions will fail)
7022 // by computing a new value matching the type of E.
7023 llvm::APSInt Val = ECD->getInitVal();
7024 if (!SameSign)
7025 Val.setIsSigned(!ECD->getInitVal().isSigned());
7026 if (!SameWidth)
7027 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7028 return Success(Val, E);
7029 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007030 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007031 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007032}
7033
Chris Lattner86ee2862008-10-06 06:40:35 +00007034/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7035/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007036static int EvaluateBuiltinClassifyType(const CallExpr *E,
7037 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007038 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007039 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007040 enum gcc_type_class {
7041 no_type_class = -1,
7042 void_type_class, integer_type_class, char_type_class,
7043 enumeral_type_class, boolean_type_class,
7044 pointer_type_class, reference_type_class, offset_type_class,
7045 real_type_class, complex_type_class,
7046 function_type_class, method_type_class,
7047 record_type_class, union_type_class,
7048 array_type_class, string_type_class,
7049 lang_type_class
7050 };
Mike Stump11289f42009-09-09 15:08:12 +00007051
7052 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007053 // ideal, however it is what gcc does.
7054 if (E->getNumArgs() == 0)
7055 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007056
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007057 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7058 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7059
7060 switch (CanTy->getTypeClass()) {
7061#define TYPE(ID, BASE)
7062#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7063#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7064#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7065#include "clang/AST/TypeNodes.def"
7066 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7067
7068 case Type::Builtin:
7069 switch (BT->getKind()) {
7070#define BUILTIN_TYPE(ID, SINGLETON_ID)
7071#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7072#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7073#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7074#include "clang/AST/BuiltinTypes.def"
7075 case BuiltinType::Void:
7076 return void_type_class;
7077
7078 case BuiltinType::Bool:
7079 return boolean_type_class;
7080
7081 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7082 case BuiltinType::UChar:
7083 case BuiltinType::UShort:
7084 case BuiltinType::UInt:
7085 case BuiltinType::ULong:
7086 case BuiltinType::ULongLong:
7087 case BuiltinType::UInt128:
7088 return integer_type_class;
7089
7090 case BuiltinType::NullPtr:
7091 return pointer_type_class;
7092
7093 case BuiltinType::WChar_U:
7094 case BuiltinType::Char16:
7095 case BuiltinType::Char32:
7096 case BuiltinType::ObjCId:
7097 case BuiltinType::ObjCClass:
7098 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007099#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7100 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007101#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007102 case BuiltinType::OCLSampler:
7103 case BuiltinType::OCLEvent:
7104 case BuiltinType::OCLClkEvent:
7105 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007106 case BuiltinType::OCLReserveID:
7107 case BuiltinType::Dependent:
7108 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7109 };
7110
7111 case Type::Enum:
7112 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7113 break;
7114
7115 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007116 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007117 break;
7118
7119 case Type::MemberPointer:
7120 if (CanTy->isMemberDataPointerType())
7121 return offset_type_class;
7122 else {
7123 // We expect member pointers to be either data or function pointers,
7124 // nothing else.
7125 assert(CanTy->isMemberFunctionPointerType());
7126 return method_type_class;
7127 }
7128
7129 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007130 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007131
7132 case Type::FunctionNoProto:
7133 case Type::FunctionProto:
7134 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7135
7136 case Type::Record:
7137 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7138 switch (RT->getDecl()->getTagKind()) {
7139 case TagTypeKind::TTK_Struct:
7140 case TagTypeKind::TTK_Class:
7141 case TagTypeKind::TTK_Interface:
7142 return record_type_class;
7143
7144 case TagTypeKind::TTK_Enum:
7145 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7146
7147 case TagTypeKind::TTK_Union:
7148 return union_type_class;
7149 }
7150 }
David Blaikie83d382b2011-09-23 05:06:16 +00007151 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007152
7153 case Type::ConstantArray:
7154 case Type::VariableArray:
7155 case Type::IncompleteArray:
7156 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7157
7158 case Type::BlockPointer:
7159 case Type::LValueReference:
7160 case Type::RValueReference:
7161 case Type::Vector:
7162 case Type::ExtVector:
7163 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007164 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007165 case Type::ObjCObject:
7166 case Type::ObjCInterface:
7167 case Type::ObjCObjectPointer:
7168 case Type::Pipe:
7169 case Type::Atomic:
7170 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7171 }
7172
7173 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007174}
7175
Richard Smith5fab0c92011-12-28 19:48:30 +00007176/// EvaluateBuiltinConstantPForLValue - Determine the result of
7177/// __builtin_constant_p when applied to the given lvalue.
7178///
7179/// An lvalue is only "constant" if it is a pointer or reference to the first
7180/// character of a string literal.
7181template<typename LValue>
7182static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007183 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007184 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7185}
7186
7187/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7188/// GCC as we can manage.
7189static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7190 QualType ArgType = Arg->getType();
7191
7192 // __builtin_constant_p always has one operand. The rules which gcc follows
7193 // are not precisely documented, but are as follows:
7194 //
7195 // - If the operand is of integral, floating, complex or enumeration type,
7196 // and can be folded to a known value of that type, it returns 1.
7197 // - If the operand and can be folded to a pointer to the first character
7198 // of a string literal (or such a pointer cast to an integral type), it
7199 // returns 1.
7200 //
7201 // Otherwise, it returns 0.
7202 //
7203 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7204 // its support for this does not currently work.
7205 if (ArgType->isIntegralOrEnumerationType()) {
7206 Expr::EvalResult Result;
7207 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7208 return false;
7209
7210 APValue &V = Result.Val;
7211 if (V.getKind() == APValue::Int)
7212 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007213 if (V.getKind() == APValue::LValue)
7214 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007215 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7216 return Arg->isEvaluatable(Ctx);
7217 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7218 LValue LV;
7219 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007220 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007221 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7222 : EvaluatePointer(Arg, LV, Info)) &&
7223 !Status.HasSideEffects)
7224 return EvaluateBuiltinConstantPForLValue(LV);
7225 }
7226
7227 // Anything else isn't considered to be sufficiently constant.
7228 return false;
7229}
7230
John McCall95007602010-05-10 23:27:23 +00007231/// Retrieves the "underlying object type" of the given expression,
7232/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007233static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007234 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7235 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007236 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007237 } else if (const Expr *E = B.get<const Expr*>()) {
7238 if (isa<CompoundLiteralExpr>(E))
7239 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007240 }
7241
7242 return QualType();
7243}
7244
George Burgess IV3a03fab2015-09-04 21:28:13 +00007245/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007246/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007247/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007248/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7249///
7250/// Always returns an RValue with a pointer representation.
7251static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7252 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7253
7254 auto *NoParens = E->IgnoreParens();
7255 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007256 if (Cast == nullptr)
7257 return NoParens;
7258
7259 // We only conservatively allow a few kinds of casts, because this code is
7260 // inherently a simple solution that seeks to support the common case.
7261 auto CastKind = Cast->getCastKind();
7262 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7263 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007264 return NoParens;
7265
7266 auto *SubExpr = Cast->getSubExpr();
7267 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7268 return NoParens;
7269 return ignorePointerCastsAndParens(SubExpr);
7270}
7271
George Burgess IVa51c4072015-10-16 01:49:01 +00007272/// Checks to see if the given LValue's Designator is at the end of the LValue's
7273/// record layout. e.g.
7274/// struct { struct { int a, b; } fst, snd; } obj;
7275/// obj.fst // no
7276/// obj.snd // yes
7277/// obj.fst.a // no
7278/// obj.fst.b // no
7279/// obj.snd.a // no
7280/// obj.snd.b // yes
7281///
7282/// Please note: this function is specialized for how __builtin_object_size
7283/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007284///
7285/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007286static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7287 assert(!LVal.Designator.Invalid);
7288
George Burgess IV4168d752016-06-27 19:40:41 +00007289 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7290 const RecordDecl *Parent = FD->getParent();
7291 Invalid = Parent->isInvalidDecl();
7292 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007293 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007294 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007295 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7296 };
7297
7298 auto &Base = LVal.getLValueBase();
7299 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7300 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007301 bool Invalid;
7302 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7303 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007304 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007305 for (auto *FD : IFD->chain()) {
7306 bool Invalid;
7307 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7308 return Invalid;
7309 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007310 }
7311 }
7312
George Burgess IVe3763372016-12-22 02:50:20 +00007313 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007314 QualType BaseType = getType(Base);
George Burgess IVe3763372016-12-22 02:50:20 +00007315 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7316 assert(isBaseAnAllocSizeCall(Base) &&
7317 "Unsized array in non-alloc_size call?");
7318 // If this is an alloc_size base, we should ignore the initial array index
7319 ++I;
7320 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7321 }
7322
7323 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7324 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007325 if (BaseType->isArrayType()) {
7326 // Because __builtin_object_size treats arrays as objects, we can ignore
7327 // the index iff this is the last array in the Designator.
7328 if (I + 1 == E)
7329 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007330 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7331 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007332 if (Index + 1 != CAT->getSize())
7333 return false;
7334 BaseType = CAT->getElementType();
7335 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007336 const auto *CT = BaseType->castAs<ComplexType>();
7337 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007338 if (Index != 1)
7339 return false;
7340 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007341 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007342 bool Invalid;
7343 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7344 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007345 BaseType = FD->getType();
7346 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007347 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007348 return false;
7349 }
7350 }
7351 return true;
7352}
7353
George Burgess IVe3763372016-12-22 02:50:20 +00007354/// Tests to see if the LValue has a user-specified designator (that isn't
7355/// necessarily valid). Note that this always returns 'true' if the LValue has
7356/// an unsized array as its first designator entry, because there's currently no
7357/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007358static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007359 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007360 return false;
7361
George Burgess IVe3763372016-12-22 02:50:20 +00007362 if (!LVal.Designator.Entries.empty())
7363 return LVal.Designator.isMostDerivedAnUnsizedArray();
7364
George Burgess IVa51c4072015-10-16 01:49:01 +00007365 if (!LVal.InvalidBase)
7366 return true;
7367
George Burgess IVe3763372016-12-22 02:50:20 +00007368 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7369 // the LValueBase.
7370 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7371 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007372}
7373
George Burgess IVe3763372016-12-22 02:50:20 +00007374/// Attempts to detect a user writing into a piece of memory that's impossible
7375/// to figure out the size of by just using types.
7376static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7377 const SubobjectDesignator &Designator = LVal.Designator;
7378 // Notes:
7379 // - Users can only write off of the end when we have an invalid base. Invalid
7380 // bases imply we don't know where the memory came from.
7381 // - We used to be a bit more aggressive here; we'd only be conservative if
7382 // the array at the end was flexible, or if it had 0 or 1 elements. This
7383 // broke some common standard library extensions (PR30346), but was
7384 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7385 // with some sort of whitelist. OTOH, it seems that GCC is always
7386 // conservative with the last element in structs (if it's an array), so our
7387 // current behavior is more compatible than a whitelisting approach would
7388 // be.
7389 return LVal.InvalidBase &&
7390 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7391 Designator.MostDerivedIsArrayElement &&
7392 isDesignatorAtObjectEnd(Ctx, LVal);
7393}
7394
7395/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7396/// Fails if the conversion would cause loss of precision.
7397static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7398 CharUnits &Result) {
7399 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7400 if (Int.ugt(CharUnitsMax))
7401 return false;
7402 Result = CharUnits::fromQuantity(Int.getZExtValue());
7403 return true;
7404}
7405
7406/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7407/// determine how many bytes exist from the beginning of the object to either
7408/// the end of the current subobject, or the end of the object itself, depending
7409/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007410///
George Burgess IVe3763372016-12-22 02:50:20 +00007411/// If this returns false, the value of Result is undefined.
7412static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7413 unsigned Type, const LValue &LVal,
7414 CharUnits &EndOffset) {
7415 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007416
George Burgess IV7fb7e362017-01-03 23:35:19 +00007417 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7418 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7419 return false;
7420 return HandleSizeof(Info, ExprLoc, Ty, Result);
7421 };
7422
George Burgess IVe3763372016-12-22 02:50:20 +00007423 // We want to evaluate the size of the entire object. This is a valid fallback
7424 // for when Type=1 and the designator is invalid, because we're asked for an
7425 // upper-bound.
7426 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7427 // Type=3 wants a lower bound, so we can't fall back to this.
7428 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007429 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007430
7431 llvm::APInt APEndOffset;
7432 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7433 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7434 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7435
7436 if (LVal.InvalidBase)
7437 return false;
7438
7439 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007440 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007441 }
7442
George Burgess IVe3763372016-12-22 02:50:20 +00007443 // We want to evaluate the size of a subobject.
7444 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007445
7446 // The following is a moderately common idiom in C:
7447 //
7448 // struct Foo { int a; char c[1]; };
7449 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7450 // strcpy(&F->c[0], Bar);
7451 //
George Burgess IVe3763372016-12-22 02:50:20 +00007452 // In order to not break too much legacy code, we need to support it.
7453 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7454 // If we can resolve this to an alloc_size call, we can hand that back,
7455 // because we know for certain how many bytes there are to write to.
7456 llvm::APInt APEndOffset;
7457 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7458 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7459 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7460
7461 // If we cannot determine the size of the initial allocation, then we can't
7462 // given an accurate upper-bound. However, we are still able to give
7463 // conservative lower-bounds for Type=3.
7464 if (Type == 1)
7465 return false;
7466 }
7467
7468 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007469 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007470 return false;
7471
George Burgess IVe3763372016-12-22 02:50:20 +00007472 // According to the GCC documentation, we want the size of the subobject
7473 // denoted by the pointer. But that's not quite right -- what we actually
7474 // want is the size of the immediately-enclosing array, if there is one.
7475 int64_t ElemsRemaining;
7476 if (Designator.MostDerivedIsArrayElement &&
7477 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7478 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7479 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7480 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7481 } else {
7482 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7483 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007484
George Burgess IVe3763372016-12-22 02:50:20 +00007485 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7486 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007487}
7488
George Burgess IVe3763372016-12-22 02:50:20 +00007489/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7490/// returns true and stores the result in @p Size.
7491///
7492/// If @p WasError is non-null, this will report whether the failure to evaluate
7493/// is to be treated as an Error in IntExprEvaluator.
7494static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7495 EvalInfo &Info, uint64_t &Size) {
7496 // Determine the denoted object.
7497 LValue LVal;
7498 {
7499 // The operand of __builtin_object_size is never evaluated for side-effects.
7500 // If there are any, but we can determine the pointed-to object anyway, then
7501 // ignore the side-effects.
7502 SpeculativeEvaluationRAII SpeculativeEval(Info);
7503 FoldOffsetRAII Fold(Info);
7504
7505 if (E->isGLValue()) {
7506 // It's possible for us to be given GLValues if we're called via
7507 // Expr::tryEvaluateObjectSize.
7508 APValue RVal;
7509 if (!EvaluateAsRValue(Info, E, RVal))
7510 return false;
7511 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007512 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7513 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007514 return false;
7515 }
7516
7517 // If we point to before the start of the object, there are no accessible
7518 // bytes.
7519 if (LVal.getLValueOffset().isNegative()) {
7520 Size = 0;
7521 return true;
7522 }
7523
7524 CharUnits EndOffset;
7525 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7526 return false;
7527
7528 // If we've fallen outside of the end offset, just pretend there's nothing to
7529 // write to/read from.
7530 if (EndOffset <= LVal.getLValueOffset())
7531 Size = 0;
7532 else
7533 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7534 return true;
John McCall95007602010-05-10 23:27:23 +00007535}
7536
Peter Collingbournee9200682011-05-13 03:29:01 +00007537bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007538 if (unsigned BuiltinOp = E->getBuiltinCallee())
7539 return VisitBuiltinCallExpr(E, BuiltinOp);
7540
7541 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7542}
7543
7544bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7545 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007546 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007547 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007548 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007549
7550 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007551 // The type was checked when we built the expression.
7552 unsigned Type =
7553 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7554 assert(Type <= 3 && "unexpected type");
7555
George Burgess IVe3763372016-12-22 02:50:20 +00007556 uint64_t Size;
7557 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7558 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007559
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007560 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007561 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007562
Richard Smith01ade172012-05-23 04:13:20 +00007563 // Expression had no side effects, but we couldn't statically determine the
7564 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007565 switch (Info.EvalMode) {
7566 case EvalInfo::EM_ConstantExpression:
7567 case EvalInfo::EM_PotentialConstantExpression:
7568 case EvalInfo::EM_ConstantFold:
7569 case EvalInfo::EM_EvaluateForOverflow:
7570 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007571 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007572 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007573 return Error(E);
7574 case EvalInfo::EM_ConstantExpressionUnevaluated:
7575 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007576 // Reduce it to a constant now.
7577 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007578 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007579
7580 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007581 }
7582
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007583 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007584 case Builtin::BI__builtin_bswap32:
7585 case Builtin::BI__builtin_bswap64: {
7586 APSInt Val;
7587 if (!EvaluateInteger(E->getArg(0), Val, Info))
7588 return false;
7589
7590 return Success(Val.byteSwap(), E);
7591 }
7592
Richard Smith8889a3d2013-06-13 06:26:32 +00007593 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007594 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007595
7596 // FIXME: BI__builtin_clrsb
7597 // FIXME: BI__builtin_clrsbl
7598 // FIXME: BI__builtin_clrsbll
7599
Richard Smith80b3c8e2013-06-13 05:04:16 +00007600 case Builtin::BI__builtin_clz:
7601 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007602 case Builtin::BI__builtin_clzll:
7603 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007604 APSInt Val;
7605 if (!EvaluateInteger(E->getArg(0), Val, Info))
7606 return false;
7607 if (!Val)
7608 return Error(E);
7609
7610 return Success(Val.countLeadingZeros(), E);
7611 }
7612
Richard Smith8889a3d2013-06-13 06:26:32 +00007613 case Builtin::BI__builtin_constant_p:
7614 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7615
Richard Smith80b3c8e2013-06-13 05:04:16 +00007616 case Builtin::BI__builtin_ctz:
7617 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007618 case Builtin::BI__builtin_ctzll:
7619 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007620 APSInt Val;
7621 if (!EvaluateInteger(E->getArg(0), Val, Info))
7622 return false;
7623 if (!Val)
7624 return Error(E);
7625
7626 return Success(Val.countTrailingZeros(), E);
7627 }
7628
Richard Smith8889a3d2013-06-13 06:26:32 +00007629 case Builtin::BI__builtin_eh_return_data_regno: {
7630 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7631 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7632 return Success(Operand, E);
7633 }
7634
7635 case Builtin::BI__builtin_expect:
7636 return Visit(E->getArg(0));
7637
7638 case Builtin::BI__builtin_ffs:
7639 case Builtin::BI__builtin_ffsl:
7640 case Builtin::BI__builtin_ffsll: {
7641 APSInt Val;
7642 if (!EvaluateInteger(E->getArg(0), Val, Info))
7643 return false;
7644
7645 unsigned N = Val.countTrailingZeros();
7646 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7647 }
7648
7649 case Builtin::BI__builtin_fpclassify: {
7650 APFloat Val(0.0);
7651 if (!EvaluateFloat(E->getArg(5), Val, Info))
7652 return false;
7653 unsigned Arg;
7654 switch (Val.getCategory()) {
7655 case APFloat::fcNaN: Arg = 0; break;
7656 case APFloat::fcInfinity: Arg = 1; break;
7657 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7658 case APFloat::fcZero: Arg = 4; break;
7659 }
7660 return Visit(E->getArg(Arg));
7661 }
7662
7663 case Builtin::BI__builtin_isinf_sign: {
7664 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007665 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007666 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7667 }
7668
Richard Smithea3019d2013-10-15 19:07:14 +00007669 case Builtin::BI__builtin_isinf: {
7670 APFloat Val(0.0);
7671 return EvaluateFloat(E->getArg(0), Val, Info) &&
7672 Success(Val.isInfinity() ? 1 : 0, E);
7673 }
7674
7675 case Builtin::BI__builtin_isfinite: {
7676 APFloat Val(0.0);
7677 return EvaluateFloat(E->getArg(0), Val, Info) &&
7678 Success(Val.isFinite() ? 1 : 0, E);
7679 }
7680
7681 case Builtin::BI__builtin_isnan: {
7682 APFloat Val(0.0);
7683 return EvaluateFloat(E->getArg(0), Val, Info) &&
7684 Success(Val.isNaN() ? 1 : 0, E);
7685 }
7686
7687 case Builtin::BI__builtin_isnormal: {
7688 APFloat Val(0.0);
7689 return EvaluateFloat(E->getArg(0), Val, Info) &&
7690 Success(Val.isNormal() ? 1 : 0, E);
7691 }
7692
Richard Smith8889a3d2013-06-13 06:26:32 +00007693 case Builtin::BI__builtin_parity:
7694 case Builtin::BI__builtin_parityl:
7695 case Builtin::BI__builtin_parityll: {
7696 APSInt Val;
7697 if (!EvaluateInteger(E->getArg(0), Val, Info))
7698 return false;
7699
7700 return Success(Val.countPopulation() % 2, E);
7701 }
7702
Richard Smith80b3c8e2013-06-13 05:04:16 +00007703 case Builtin::BI__builtin_popcount:
7704 case Builtin::BI__builtin_popcountl:
7705 case Builtin::BI__builtin_popcountll: {
7706 APSInt Val;
7707 if (!EvaluateInteger(E->getArg(0), Val, Info))
7708 return false;
7709
7710 return Success(Val.countPopulation(), E);
7711 }
7712
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007713 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007714 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007715 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007716 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007717 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007718 << /*isConstexpr*/0 << /*isConstructor*/0
7719 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007720 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007721 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007722 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007723 case Builtin::BI__builtin_strlen:
7724 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007725 // As an extension, we support __builtin_strlen() as a constant expression,
7726 // and support folding strlen() to a constant.
7727 LValue String;
7728 if (!EvaluatePointer(E->getArg(0), String, Info))
7729 return false;
7730
Richard Smith8110c9d2016-11-29 19:45:17 +00007731 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7732
Richard Smithe6c19f22013-11-15 02:10:04 +00007733 // Fast path: if it's a string literal, search the string value.
7734 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7735 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007736 // The string literal may have embedded null characters. Find the first
7737 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007738 StringRef Str = S->getBytes();
7739 int64_t Off = String.Offset.getQuantity();
7740 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007741 S->getCharByteWidth() == 1 &&
7742 // FIXME: Add fast-path for wchar_t too.
7743 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007744 Str = Str.substr(Off);
7745
7746 StringRef::size_type Pos = Str.find(0);
7747 if (Pos != StringRef::npos)
7748 Str = Str.substr(0, Pos);
7749
7750 return Success(Str.size(), E);
7751 }
7752
7753 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007754 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007755
7756 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007757 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7758 APValue Char;
7759 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7760 !Char.isInt())
7761 return false;
7762 if (!Char.getInt())
7763 return Success(Strlen, E);
7764 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7765 return false;
7766 }
7767 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007768
Richard Smithe151bab2016-11-11 23:43:35 +00007769 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007770 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007771 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007772 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007773 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007774 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007775 // A call to strlen is not a constant expression.
7776 if (Info.getLangOpts().CPlusPlus11)
7777 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7778 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007779 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007780 else
7781 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7782 // Fall through.
7783 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007784 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007785 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007786 case Builtin::BI__builtin_wcsncmp:
7787 case Builtin::BI__builtin_memcmp:
7788 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007789 LValue String1, String2;
7790 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7791 !EvaluatePointer(E->getArg(1), String2, Info))
7792 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007793
7794 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7795
Richard Smithe151bab2016-11-11 23:43:35 +00007796 uint64_t MaxLength = uint64_t(-1);
7797 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007798 BuiltinOp != Builtin::BIwcscmp &&
7799 BuiltinOp != Builtin::BI__builtin_strcmp &&
7800 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007801 APSInt N;
7802 if (!EvaluateInteger(E->getArg(2), N, Info))
7803 return false;
7804 MaxLength = N.getExtValue();
7805 }
7806 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007807 BuiltinOp != Builtin::BIwmemcmp &&
7808 BuiltinOp != Builtin::BI__builtin_memcmp &&
7809 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007810 for (; MaxLength; --MaxLength) {
7811 APValue Char1, Char2;
7812 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7813 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7814 !Char1.isInt() || !Char2.isInt())
7815 return false;
7816 if (Char1.getInt() != Char2.getInt())
7817 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7818 if (StopAtNull && !Char1.getInt())
7819 return Success(0, E);
7820 assert(!(StopAtNull && !Char2.getInt()));
7821 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7822 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7823 return false;
7824 }
7825 // We hit the strncmp / memcmp limit.
7826 return Success(0, E);
7827 }
7828
Richard Smith01ba47d2012-04-13 00:45:38 +00007829 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007830 case Builtin::BI__atomic_is_lock_free:
7831 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007832 APSInt SizeVal;
7833 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7834 return false;
7835
7836 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7837 // of two less than the maximum inline atomic width, we know it is
7838 // lock-free. If the size isn't a power of two, or greater than the
7839 // maximum alignment where we promote atomics, we know it is not lock-free
7840 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7841 // the answer can only be determined at runtime; for example, 16-byte
7842 // atomics have lock-free implementations on some, but not all,
7843 // x86-64 processors.
7844
7845 // Check power-of-two.
7846 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007847 if (Size.isPowerOfTwo()) {
7848 // Check against inlining width.
7849 unsigned InlineWidthBits =
7850 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7851 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7852 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7853 Size == CharUnits::One() ||
7854 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7855 Expr::NPC_NeverValueDependent))
7856 // OK, we will inline appropriately-aligned operations of this size,
7857 // and _Atomic(T) is appropriately-aligned.
7858 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007859
Richard Smith01ba47d2012-04-13 00:45:38 +00007860 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7861 castAs<PointerType>()->getPointeeType();
7862 if (!PointeeType->isIncompleteType() &&
7863 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7864 // OK, we will inline operations on this object.
7865 return Success(1, E);
7866 }
7867 }
7868 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007869
Richard Smith01ba47d2012-04-13 00:45:38 +00007870 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7871 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007872 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007873 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007874}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007875
Richard Smith8b3497e2011-10-31 01:37:14 +00007876static bool HasSameBase(const LValue &A, const LValue &B) {
7877 if (!A.getLValueBase())
7878 return !B.getLValueBase();
7879 if (!B.getLValueBase())
7880 return false;
7881
Richard Smithce40ad62011-11-12 22:28:03 +00007882 if (A.getLValueBase().getOpaqueValue() !=
7883 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007884 const Decl *ADecl = GetLValueBaseDecl(A);
7885 if (!ADecl)
7886 return false;
7887 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007888 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007889 return false;
7890 }
7891
7892 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007893 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007894}
7895
Richard Smithd20f1e62014-10-21 23:01:04 +00007896/// \brief Determine whether this is a pointer past the end of the complete
7897/// object referred to by the lvalue.
7898static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7899 const LValue &LV) {
7900 // A null pointer can be viewed as being "past the end" but we don't
7901 // choose to look at it that way here.
7902 if (!LV.getLValueBase())
7903 return false;
7904
7905 // If the designator is valid and refers to a subobject, we're not pointing
7906 // past the end.
7907 if (!LV.getLValueDesignator().Invalid &&
7908 !LV.getLValueDesignator().isOnePastTheEnd())
7909 return false;
7910
David Majnemerc378ca52015-08-29 08:32:55 +00007911 // A pointer to an incomplete type might be past-the-end if the type's size is
7912 // zero. We cannot tell because the type is incomplete.
7913 QualType Ty = getType(LV.getLValueBase());
7914 if (Ty->isIncompleteType())
7915 return true;
7916
Richard Smithd20f1e62014-10-21 23:01:04 +00007917 // We're a past-the-end pointer if we point to the byte after the object,
7918 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007919 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007920 return LV.getLValueOffset() == Size;
7921}
7922
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007923namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007924
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007925/// \brief Data recursive integer evaluator of certain binary operators.
7926///
7927/// We use a data recursive algorithm for binary operators so that we are able
7928/// to handle extreme cases of chained binary operators without causing stack
7929/// overflow.
7930class DataRecursiveIntBinOpEvaluator {
7931 struct EvalResult {
7932 APValue Val;
7933 bool Failed;
7934
7935 EvalResult() : Failed(false) { }
7936
7937 void swap(EvalResult &RHS) {
7938 Val.swap(RHS.Val);
7939 Failed = RHS.Failed;
7940 RHS.Failed = false;
7941 }
7942 };
7943
7944 struct Job {
7945 const Expr *E;
7946 EvalResult LHSResult; // meaningful only for binary operator expression.
7947 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007948
David Blaikie73726062015-08-12 23:09:24 +00007949 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007950 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007951
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007952 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007953 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007954 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007955
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007956 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007957 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007958 };
7959
7960 SmallVector<Job, 16> Queue;
7961
7962 IntExprEvaluator &IntEval;
7963 EvalInfo &Info;
7964 APValue &FinalResult;
7965
7966public:
7967 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7968 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7969
7970 /// \brief True if \param E is a binary operator that we are going to handle
7971 /// data recursively.
7972 /// We handle binary operators that are comma, logical, or that have operands
7973 /// with integral or enumeration type.
7974 static bool shouldEnqueue(const BinaryOperator *E) {
7975 return E->getOpcode() == BO_Comma ||
7976 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007977 (E->isRValue() &&
7978 E->getType()->isIntegralOrEnumerationType() &&
7979 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007980 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007981 }
7982
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007983 bool Traverse(const BinaryOperator *E) {
7984 enqueue(E);
7985 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007986 while (!Queue.empty())
7987 process(PrevResult);
7988
7989 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007990
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007991 FinalResult.swap(PrevResult.Val);
7992 return true;
7993 }
7994
7995private:
7996 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7997 return IntEval.Success(Value, E, Result);
7998 }
7999 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8000 return IntEval.Success(Value, E, Result);
8001 }
8002 bool Error(const Expr *E) {
8003 return IntEval.Error(E);
8004 }
8005 bool Error(const Expr *E, diag::kind D) {
8006 return IntEval.Error(E, D);
8007 }
8008
8009 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8010 return Info.CCEDiag(E, D);
8011 }
8012
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008013 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8014 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008015 bool &SuppressRHSDiags);
8016
8017 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8018 const BinaryOperator *E, APValue &Result);
8019
8020 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8021 Result.Failed = !Evaluate(Result.Val, Info, E);
8022 if (Result.Failed)
8023 Result.Val = APValue();
8024 }
8025
Richard Trieuba4d0872012-03-21 23:30:30 +00008026 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008027
8028 void enqueue(const Expr *E) {
8029 E = E->IgnoreParens();
8030 Queue.resize(Queue.size()+1);
8031 Queue.back().E = E;
8032 Queue.back().Kind = Job::AnyExprKind;
8033 }
8034};
8035
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008036}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008037
8038bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008039 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008040 bool &SuppressRHSDiags) {
8041 if (E->getOpcode() == BO_Comma) {
8042 // Ignore LHS but note if we could not evaluate it.
8043 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008044 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008045 return true;
8046 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008047
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008048 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008049 bool LHSAsBool;
8050 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008051 // We were able to evaluate the LHS, see if we can get away with not
8052 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008053 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8054 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008055 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008056 }
8057 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008058 LHSResult.Failed = true;
8059
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008060 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008061 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008062 if (!Info.noteSideEffect())
8063 return false;
8064
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008065 // We can't evaluate the LHS; however, sometimes the result
8066 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8067 // Don't ignore RHS and suppress diagnostics from this arm.
8068 SuppressRHSDiags = true;
8069 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008070
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008071 return true;
8072 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008073
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008074 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8075 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008076
George Burgess IVa145e252016-05-25 22:38:36 +00008077 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008078 return false; // Ignore RHS;
8079
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008080 return true;
8081}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008082
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008083static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8084 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008085 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8086 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8087 // offsets.
8088 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8089 CharUnits &Offset = LVal.getLValueOffset();
8090 uint64_t Offset64 = Offset.getQuantity();
8091 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8092 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8093 : Offset64 + Index64);
8094}
8095
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008096bool DataRecursiveIntBinOpEvaluator::
8097 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8098 const BinaryOperator *E, APValue &Result) {
8099 if (E->getOpcode() == BO_Comma) {
8100 if (RHSResult.Failed)
8101 return false;
8102 Result = RHSResult.Val;
8103 return true;
8104 }
8105
8106 if (E->isLogicalOp()) {
8107 bool lhsResult, rhsResult;
8108 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8109 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8110
8111 if (LHSIsOK) {
8112 if (RHSIsOK) {
8113 if (E->getOpcode() == BO_LOr)
8114 return Success(lhsResult || rhsResult, E, Result);
8115 else
8116 return Success(lhsResult && rhsResult, E, Result);
8117 }
8118 } else {
8119 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008120 // We can't evaluate the LHS; however, sometimes the result
8121 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8122 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008123 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008124 }
8125 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008126
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008127 return false;
8128 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008129
8130 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8131 E->getRHS()->getType()->isIntegralOrEnumerationType());
8132
8133 if (LHSResult.Failed || RHSResult.Failed)
8134 return false;
8135
8136 const APValue &LHSVal = LHSResult.Val;
8137 const APValue &RHSVal = RHSResult.Val;
8138
8139 // Handle cases like (unsigned long)&a + 4.
8140 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8141 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008142 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008143 return true;
8144 }
8145
8146 // Handle cases like 4 + (unsigned long)&a
8147 if (E->getOpcode() == BO_Add &&
8148 RHSVal.isLValue() && LHSVal.isInt()) {
8149 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008150 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008151 return true;
8152 }
8153
8154 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8155 // Handle (intptr_t)&&A - (intptr_t)&&B.
8156 if (!LHSVal.getLValueOffset().isZero() ||
8157 !RHSVal.getLValueOffset().isZero())
8158 return false;
8159 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8160 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8161 if (!LHSExpr || !RHSExpr)
8162 return false;
8163 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8164 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8165 if (!LHSAddrExpr || !RHSAddrExpr)
8166 return false;
8167 // Make sure both labels come from the same function.
8168 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8169 RHSAddrExpr->getLabel()->getDeclContext())
8170 return false;
8171 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8172 return true;
8173 }
Richard Smith43e77732013-05-07 04:50:00 +00008174
8175 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008176 if (!LHSVal.isInt() || !RHSVal.isInt())
8177 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008178
8179 // Set up the width and signedness manually, in case it can't be deduced
8180 // from the operation we're performing.
8181 // FIXME: Don't do this in the cases where we can deduce it.
8182 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8183 E->getType()->isUnsignedIntegerOrEnumerationType());
8184 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8185 RHSVal.getInt(), Value))
8186 return false;
8187 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008188}
8189
Richard Trieuba4d0872012-03-21 23:30:30 +00008190void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008191 Job &job = Queue.back();
8192
8193 switch (job.Kind) {
8194 case Job::AnyExprKind: {
8195 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8196 if (shouldEnqueue(Bop)) {
8197 job.Kind = Job::BinOpKind;
8198 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008199 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008200 }
8201 }
8202
8203 EvaluateExpr(job.E, Result);
8204 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008205 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008206 }
8207
8208 case Job::BinOpKind: {
8209 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008210 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008211 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008212 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008213 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008214 }
8215 if (SuppressRHSDiags)
8216 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008217 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008218 job.Kind = Job::BinOpVisitedLHSKind;
8219 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008220 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008221 }
8222
8223 case Job::BinOpVisitedLHSKind: {
8224 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8225 EvalResult RHS;
8226 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008227 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008228 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008229 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008230 }
8231 }
8232
8233 llvm_unreachable("Invalid Job::Kind!");
8234}
8235
George Burgess IV8c892b52016-05-25 22:31:54 +00008236namespace {
8237/// Used when we determine that we should fail, but can keep evaluating prior to
8238/// noting that we had a failure.
8239class DelayedNoteFailureRAII {
8240 EvalInfo &Info;
8241 bool NoteFailure;
8242
8243public:
8244 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8245 : Info(Info), NoteFailure(NoteFailure) {}
8246 ~DelayedNoteFailureRAII() {
8247 if (NoteFailure) {
8248 bool ContinueAfterFailure = Info.noteFailure();
8249 (void)ContinueAfterFailure;
8250 assert(ContinueAfterFailure &&
8251 "Shouldn't have kept evaluating on failure.");
8252 }
8253 }
8254};
8255}
8256
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008257bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008258 // We don't call noteFailure immediately because the assignment happens after
8259 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008260 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008261 return Error(E);
8262
George Burgess IV8c892b52016-05-25 22:31:54 +00008263 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008264 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8265 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008266
Anders Carlssonacc79812008-11-16 07:17:21 +00008267 QualType LHSTy = E->getLHS()->getType();
8268 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008269
Chandler Carruthb29a7432014-10-11 11:03:30 +00008270 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008271 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008272 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008273 if (E->isAssignmentOp()) {
8274 LValue LV;
8275 EvaluateLValue(E->getLHS(), LV, Info);
8276 LHSOK = false;
8277 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008278 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8279 if (LHSOK) {
8280 LHS.makeComplexFloat();
8281 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8282 }
8283 } else {
8284 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8285 }
George Burgess IVa145e252016-05-25 22:38:36 +00008286 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008287 return false;
8288
Chandler Carruthb29a7432014-10-11 11:03:30 +00008289 if (E->getRHS()->getType()->isRealFloatingType()) {
8290 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8291 return false;
8292 RHS.makeComplexFloat();
8293 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8294 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008295 return false;
8296
8297 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008298 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008299 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008300 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008301 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8302
John McCalle3027922010-08-25 11:45:40 +00008303 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008304 return Success((CR_r == APFloat::cmpEqual &&
8305 CR_i == APFloat::cmpEqual), E);
8306 else {
John McCalle3027922010-08-25 11:45:40 +00008307 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008308 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008309 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008310 CR_r == APFloat::cmpLessThan ||
8311 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008312 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008313 CR_i == APFloat::cmpLessThan ||
8314 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008315 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008316 } else {
John McCalle3027922010-08-25 11:45:40 +00008317 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008318 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8319 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8320 else {
John McCalle3027922010-08-25 11:45:40 +00008321 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008322 "Invalid compex comparison.");
8323 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8324 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8325 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008326 }
8327 }
Mike Stump11289f42009-09-09 15:08:12 +00008328
Anders Carlssonacc79812008-11-16 07:17:21 +00008329 if (LHSTy->isRealFloatingType() &&
8330 RHSTy->isRealFloatingType()) {
8331 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008332
Richard Smith253c2a32012-01-27 01:14:48 +00008333 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008334 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008335 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008336
Richard Smith253c2a32012-01-27 01:14:48 +00008337 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008338 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008339
Anders Carlssonacc79812008-11-16 07:17:21 +00008340 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008341
Anders Carlssonacc79812008-11-16 07:17:21 +00008342 switch (E->getOpcode()) {
8343 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008344 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008345 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008346 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008347 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008348 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008349 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008350 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008351 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008352 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008353 E);
John McCalle3027922010-08-25 11:45:40 +00008354 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008355 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008356 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008357 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008358 || CR == APFloat::cmpLessThan
8359 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008360 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008361 }
Mike Stump11289f42009-09-09 15:08:12 +00008362
Eli Friedmana38da572009-04-28 19:17:36 +00008363 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008364 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008365 LValue LHSValue, RHSValue;
8366
8367 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008368 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008369 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008370
Richard Smith253c2a32012-01-27 01:14:48 +00008371 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008372 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008373
Richard Smith8b3497e2011-10-31 01:37:14 +00008374 // Reject differing bases from the normal codepath; we special-case
8375 // comparisons to null.
8376 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008377 if (E->getOpcode() == BO_Sub) {
8378 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008379 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008380 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008381 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008382 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008383 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008384 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008385 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8386 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8387 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008388 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008389 // Make sure both labels come from the same function.
8390 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8391 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008392 return Error(E);
8393 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008394 }
Richard Smith83c68212011-10-31 05:11:32 +00008395 // Inequalities and subtractions between unrelated pointers have
8396 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008397 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008398 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008399 // A constant address may compare equal to the address of a symbol.
8400 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008401 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008402 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8403 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008404 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008405 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008406 // distinct addresses. In clang, the result of such a comparison is
8407 // unspecified, so it is not a constant expression. However, we do know
8408 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008409 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8410 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008411 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008412 // We can't tell whether weak symbols will end up pointing to the same
8413 // object.
8414 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008415 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008416 // We can't compare the address of the start of one object with the
8417 // past-the-end address of another object, per C++ DR1652.
8418 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8419 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8420 (RHSValue.Base && RHSValue.Offset.isZero() &&
8421 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8422 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008423 // We can't tell whether an object is at the same address as another
8424 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008425 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8426 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008427 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008428 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008429 // (Note that clang defaults to -fmerge-all-constants, which can
8430 // lead to inconsistent results for comparisons involving the address
8431 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008432 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008433 }
Eli Friedman64004332009-03-23 04:38:34 +00008434
Richard Smith1b470412012-02-01 08:10:20 +00008435 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8436 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8437
Richard Smith84f6dcf2012-02-02 01:16:57 +00008438 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8439 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8440
John McCalle3027922010-08-25 11:45:40 +00008441 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008442 // C++11 [expr.add]p6:
8443 // Unless both pointers point to elements of the same array object, or
8444 // one past the last element of the array object, the behavior is
8445 // undefined.
8446 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8447 !AreElementsOfSameArray(getType(LHSValue.Base),
8448 LHSDesignator, RHSDesignator))
8449 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8450
Chris Lattner882bdf22010-04-20 17:13:14 +00008451 QualType Type = E->getLHS()->getType();
8452 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008453
Richard Smithd62306a2011-11-10 06:34:14 +00008454 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008455 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008456 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008457
Richard Smith84c6b3d2013-09-10 21:34:14 +00008458 // As an extension, a type may have zero size (empty struct or union in
8459 // C, array of zero length). Pointer subtraction in such cases has
8460 // undefined behavior, so is not constant.
8461 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008462 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008463 << ElementType;
8464 return false;
8465 }
8466
Richard Smith1b470412012-02-01 08:10:20 +00008467 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8468 // and produce incorrect results when it overflows. Such behavior
8469 // appears to be non-conforming, but is common, so perhaps we should
8470 // assume the standard intended for such cases to be undefined behavior
8471 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008472
Richard Smith1b470412012-02-01 08:10:20 +00008473 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8474 // overflow in the final conversion to ptrdiff_t.
8475 APSInt LHS(
8476 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8477 APSInt RHS(
8478 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8479 APSInt ElemSize(
8480 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8481 APSInt TrueResult = (LHS - RHS) / ElemSize;
8482 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8483
Richard Smith0c6124b2015-12-03 01:36:22 +00008484 if (Result.extend(65) != TrueResult &&
8485 !HandleOverflow(Info, E, TrueResult, E->getType()))
8486 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008487 return Success(Result, E);
8488 }
Richard Smithde21b242012-01-31 06:41:30 +00008489
8490 // C++11 [expr.rel]p3:
8491 // Pointers to void (after pointer conversions) can be compared, with a
8492 // result defined as follows: If both pointers represent the same
8493 // address or are both the null pointer value, the result is true if the
8494 // operator is <= or >= and false otherwise; otherwise the result is
8495 // unspecified.
8496 // We interpret this as applying to pointers to *cv* void.
8497 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008498 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008499 CCEDiag(E, diag::note_constexpr_void_comparison);
8500
Richard Smith84f6dcf2012-02-02 01:16:57 +00008501 // C++11 [expr.rel]p2:
8502 // - If two pointers point to non-static data members of the same object,
8503 // or to subobjects or array elements fo such members, recursively, the
8504 // pointer to the later declared member compares greater provided the
8505 // two members have the same access control and provided their class is
8506 // not a union.
8507 // [...]
8508 // - Otherwise pointer comparisons are unspecified.
8509 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8510 E->isRelationalOp()) {
8511 bool WasArrayIndex;
8512 unsigned Mismatch =
8513 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8514 RHSDesignator, WasArrayIndex);
8515 // At the point where the designators diverge, the comparison has a
8516 // specified value if:
8517 // - we are comparing array indices
8518 // - we are comparing fields of a union, or fields with the same access
8519 // Otherwise, the result is unspecified and thus the comparison is not a
8520 // constant expression.
8521 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8522 Mismatch < RHSDesignator.Entries.size()) {
8523 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8524 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8525 if (!LF && !RF)
8526 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8527 else if (!LF)
8528 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8529 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8530 << RF->getParent() << RF;
8531 else if (!RF)
8532 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8533 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8534 << LF->getParent() << LF;
8535 else if (!LF->getParent()->isUnion() &&
8536 LF->getAccess() != RF->getAccess())
8537 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8538 << LF << LF->getAccess() << RF << RF->getAccess()
8539 << LF->getParent();
8540 }
8541 }
8542
Eli Friedman6c31cb42012-04-16 04:30:08 +00008543 // The comparison here must be unsigned, and performed with the same
8544 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008545 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8546 uint64_t CompareLHS = LHSOffset.getQuantity();
8547 uint64_t CompareRHS = RHSOffset.getQuantity();
8548 assert(PtrSize <= 64 && "Unexpected pointer width");
8549 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8550 CompareLHS &= Mask;
8551 CompareRHS &= Mask;
8552
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008553 // If there is a base and this is a relational operator, we can only
8554 // compare pointers within the object in question; otherwise, the result
8555 // depends on where the object is located in memory.
8556 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8557 QualType BaseTy = getType(LHSValue.Base);
8558 if (BaseTy->isIncompleteType())
8559 return Error(E);
8560 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8561 uint64_t OffsetLimit = Size.getQuantity();
8562 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8563 return Error(E);
8564 }
8565
Richard Smith8b3497e2011-10-31 01:37:14 +00008566 switch (E->getOpcode()) {
8567 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008568 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8569 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8570 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8571 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8572 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8573 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008574 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008575 }
8576 }
Richard Smith7bb00672012-02-01 01:42:44 +00008577
8578 if (LHSTy->isMemberPointerType()) {
8579 assert(E->isEqualityOp() && "unexpected member pointer operation");
8580 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8581
8582 MemberPtr LHSValue, RHSValue;
8583
8584 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008585 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008586 return false;
8587
8588 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8589 return false;
8590
8591 // C++11 [expr.eq]p2:
8592 // If both operands are null, they compare equal. Otherwise if only one is
8593 // null, they compare unequal.
8594 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8595 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8596 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8597 }
8598
8599 // Otherwise if either is a pointer to a virtual member function, the
8600 // result is unspecified.
8601 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8602 if (MD->isVirtual())
8603 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8604 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8605 if (MD->isVirtual())
8606 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8607
8608 // Otherwise they compare equal if and only if they would refer to the
8609 // same member of the same most derived object or the same subobject if
8610 // they were dereferenced with a hypothetical object of the associated
8611 // class type.
8612 bool Equal = LHSValue == RHSValue;
8613 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8614 }
8615
Richard Smithab44d9b2012-02-14 22:35:28 +00008616 if (LHSTy->isNullPtrType()) {
8617 assert(E->isComparisonOp() && "unexpected nullptr operation");
8618 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8619 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8620 // are compared, the result is true of the operator is <=, >= or ==, and
8621 // false otherwise.
8622 BinaryOperator::Opcode Opcode = E->getOpcode();
8623 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8624 }
8625
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008626 assert((!LHSTy->isIntegralOrEnumerationType() ||
8627 !RHSTy->isIntegralOrEnumerationType()) &&
8628 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8629 // We can't continue from here for non-integral types.
8630 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008631}
8632
Peter Collingbournee190dee2011-03-11 19:24:49 +00008633/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8634/// a result as the expression's type.
8635bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8636 const UnaryExprOrTypeTraitExpr *E) {
8637 switch(E->getKind()) {
8638 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008639 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008640 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008641 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008642 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008643 }
Eli Friedman64004332009-03-23 04:38:34 +00008644
Peter Collingbournee190dee2011-03-11 19:24:49 +00008645 case UETT_VecStep: {
8646 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008647
Peter Collingbournee190dee2011-03-11 19:24:49 +00008648 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008649 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008650
Peter Collingbournee190dee2011-03-11 19:24:49 +00008651 // The vec_step built-in functions that take a 3-component
8652 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8653 if (n == 3)
8654 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008655
Peter Collingbournee190dee2011-03-11 19:24:49 +00008656 return Success(n, E);
8657 } else
8658 return Success(1, E);
8659 }
8660
8661 case UETT_SizeOf: {
8662 QualType SrcTy = E->getTypeOfArgument();
8663 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8664 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008665 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8666 SrcTy = Ref->getPointeeType();
8667
Richard Smithd62306a2011-11-10 06:34:14 +00008668 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008669 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008670 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008671 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008672 }
Alexey Bataev00396512015-07-02 03:40:19 +00008673 case UETT_OpenMPRequiredSimdAlign:
8674 assert(E->isArgumentType());
8675 return Success(
8676 Info.Ctx.toCharUnitsFromBits(
8677 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8678 .getQuantity(),
8679 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008680 }
8681
8682 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008683}
8684
Peter Collingbournee9200682011-05-13 03:29:01 +00008685bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008686 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008687 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008688 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008689 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008690 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008691 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008692 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008693 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008694 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008695 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008696 APSInt IdxResult;
8697 if (!EvaluateInteger(Idx, IdxResult, Info))
8698 return false;
8699 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8700 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008701 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008702 CurrentType = AT->getElementType();
8703 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8704 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008705 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008706 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008707
James Y Knight7281c352015-12-29 22:31:18 +00008708 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008709 FieldDecl *MemberDecl = ON.getField();
8710 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008711 if (!RT)
8712 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008713 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008714 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008715 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008716 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008717 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008718 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008719 CurrentType = MemberDecl->getType().getNonReferenceType();
8720 break;
8721 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008722
James Y Knight7281c352015-12-29 22:31:18 +00008723 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008724 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008725
James Y Knight7281c352015-12-29 22:31:18 +00008726 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008727 CXXBaseSpecifier *BaseSpec = ON.getBase();
8728 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008729 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008730
8731 // Find the layout of the class whose base we are looking into.
8732 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008733 if (!RT)
8734 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008735 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008736 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008737 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8738
8739 // Find the base class itself.
8740 CurrentType = BaseSpec->getType();
8741 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8742 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008743 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008744
8745 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008746 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008747 break;
8748 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008749 }
8750 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008751 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008752}
8753
Chris Lattnere13042c2008-07-11 19:10:17 +00008754bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008755 switch (E->getOpcode()) {
8756 default:
8757 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8758 // See C99 6.6p3.
8759 return Error(E);
8760 case UO_Extension:
8761 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8762 // If so, we could clear the diagnostic ID.
8763 return Visit(E->getSubExpr());
8764 case UO_Plus:
8765 // The result is just the value.
8766 return Visit(E->getSubExpr());
8767 case UO_Minus: {
8768 if (!Visit(E->getSubExpr()))
8769 return false;
8770 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008771 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008772 if (Value.isSigned() && Value.isMinSignedValue() &&
8773 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8774 E->getType()))
8775 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008776 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008777 }
8778 case UO_Not: {
8779 if (!Visit(E->getSubExpr()))
8780 return false;
8781 if (!Result.isInt()) return Error(E);
8782 return Success(~Result.getInt(), E);
8783 }
8784 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008785 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008786 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008787 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008788 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008789 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008790 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008791}
Mike Stump11289f42009-09-09 15:08:12 +00008792
Chris Lattner477c4be2008-07-12 01:15:53 +00008793/// HandleCast - This is used to evaluate implicit or explicit casts where the
8794/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008795bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8796 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008797 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008798 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008799
Eli Friedmanc757de22011-03-25 00:43:55 +00008800 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008801 case CK_BaseToDerived:
8802 case CK_DerivedToBase:
8803 case CK_UncheckedDerivedToBase:
8804 case CK_Dynamic:
8805 case CK_ToUnion:
8806 case CK_ArrayToPointerDecay:
8807 case CK_FunctionToPointerDecay:
8808 case CK_NullToPointer:
8809 case CK_NullToMemberPointer:
8810 case CK_BaseToDerivedMemberPointer:
8811 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008812 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008813 case CK_ConstructorConversion:
8814 case CK_IntegralToPointer:
8815 case CK_ToVoid:
8816 case CK_VectorSplat:
8817 case CK_IntegralToFloating:
8818 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008819 case CK_CPointerToObjCPointerCast:
8820 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008821 case CK_AnyPointerToBlockPointerCast:
8822 case CK_ObjCObjectLValueCast:
8823 case CK_FloatingRealToComplex:
8824 case CK_FloatingComplexToReal:
8825 case CK_FloatingComplexCast:
8826 case CK_FloatingComplexToIntegralComplex:
8827 case CK_IntegralRealToComplex:
8828 case CK_IntegralComplexCast:
8829 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008830 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008831 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008832 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008833 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008834 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008835 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008836 llvm_unreachable("invalid cast kind for integral value");
8837
Eli Friedman9faf2f92011-03-25 19:07:11 +00008838 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008839 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008840 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008841 case CK_ARCProduceObject:
8842 case CK_ARCConsumeObject:
8843 case CK_ARCReclaimReturnedObject:
8844 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008845 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008846 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008847
Richard Smith4ef685b2012-01-17 21:17:26 +00008848 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008849 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008850 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008851 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008852 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008853
8854 case CK_MemberPointerToBoolean:
8855 case CK_PointerToBoolean:
8856 case CK_IntegralToBoolean:
8857 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008858 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008859 case CK_FloatingComplexToBoolean:
8860 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008861 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008862 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008863 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008864 uint64_t IntResult = BoolResult;
8865 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8866 IntResult = (uint64_t)-1;
8867 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008868 }
8869
Eli Friedmanc757de22011-03-25 00:43:55 +00008870 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008871 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008872 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008873
Eli Friedman742421e2009-02-20 01:15:07 +00008874 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008875 // Allow casts of address-of-label differences if they are no-ops
8876 // or narrowing. (The narrowing case isn't actually guaranteed to
8877 // be constant-evaluatable except in some narrow cases which are hard
8878 // to detect here. We let it through on the assumption the user knows
8879 // what they are doing.)
8880 if (Result.isAddrLabelDiff())
8881 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008882 // Only allow casts of lvalues if they are lossless.
8883 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8884 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008885
Richard Smith911e1422012-01-30 22:27:01 +00008886 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8887 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008888 }
Mike Stump11289f42009-09-09 15:08:12 +00008889
Eli Friedmanc757de22011-03-25 00:43:55 +00008890 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008891 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8892
John McCall45d55e42010-05-07 21:00:08 +00008893 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008894 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008895 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008896
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008897 if (LV.getLValueBase()) {
8898 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008899 // FIXME: Allow a larger integer size than the pointer size, and allow
8900 // narrowing back down to pointer width in subsequent integral casts.
8901 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008902 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008903 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008904
Richard Smithcf74da72011-11-16 07:18:12 +00008905 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008906 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008907 return true;
8908 }
8909
Yaxun Liu402804b2016-12-15 08:09:08 +00008910 uint64_t V;
8911 if (LV.isNullPointer())
8912 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8913 else
8914 V = LV.getLValueOffset().getQuantity();
8915
8916 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008917 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008918 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008919
Eli Friedmanc757de22011-03-25 00:43:55 +00008920 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008921 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008922 if (!EvaluateComplex(SubExpr, C, Info))
8923 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008924 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008925 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008926
Eli Friedmanc757de22011-03-25 00:43:55 +00008927 case CK_FloatingToIntegral: {
8928 APFloat F(0.0);
8929 if (!EvaluateFloat(SubExpr, F, Info))
8930 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008931
Richard Smith357362d2011-12-13 06:39:58 +00008932 APSInt Value;
8933 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8934 return false;
8935 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008936 }
8937 }
Mike Stump11289f42009-09-09 15:08:12 +00008938
Eli Friedmanc757de22011-03-25 00:43:55 +00008939 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008940}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008941
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008942bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8943 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008944 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008945 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8946 return false;
8947 if (!LV.isComplexInt())
8948 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008949 return Success(LV.getComplexIntReal(), E);
8950 }
8951
8952 return Visit(E->getSubExpr());
8953}
8954
Eli Friedman4e7a2412009-02-27 04:45:43 +00008955bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008956 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008957 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008958 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8959 return false;
8960 if (!LV.isComplexInt())
8961 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008962 return Success(LV.getComplexIntImag(), E);
8963 }
8964
Richard Smith4a678122011-10-24 18:44:57 +00008965 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008966 return Success(0, E);
8967}
8968
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008969bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8970 return Success(E->getPackLength(), E);
8971}
8972
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008973bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8974 return Success(E->getValue(), E);
8975}
8976
Chris Lattner05706e882008-07-11 18:11:29 +00008977//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008978// Float Evaluation
8979//===----------------------------------------------------------------------===//
8980
8981namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008982class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008983 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008984 APFloat &Result;
8985public:
8986 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008987 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008988
Richard Smith2e312c82012-03-03 22:46:17 +00008989 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008990 Result = V.getFloat();
8991 return true;
8992 }
Eli Friedman24c01542008-08-22 00:06:13 +00008993
Richard Smithfddd3842011-12-30 21:15:51 +00008994 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008995 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8996 return true;
8997 }
8998
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008999 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009000
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009001 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009002 bool VisitBinaryOperator(const BinaryOperator *E);
9003 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009004 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009005
John McCallb1fb0d32010-05-07 22:08:54 +00009006 bool VisitUnaryReal(const UnaryOperator *E);
9007 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009008
Richard Smithfddd3842011-12-30 21:15:51 +00009009 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009010};
9011} // end anonymous namespace
9012
9013static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009014 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009015 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009016}
9017
Jay Foad39c79802011-01-12 09:06:06 +00009018static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009019 QualType ResultTy,
9020 const Expr *Arg,
9021 bool SNaN,
9022 llvm::APFloat &Result) {
9023 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9024 if (!S) return false;
9025
9026 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9027
9028 llvm::APInt fill;
9029
9030 // Treat empty strings as if they were zero.
9031 if (S->getString().empty())
9032 fill = llvm::APInt(32, 0);
9033 else if (S->getString().getAsInteger(0, fill))
9034 return false;
9035
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009036 if (Context.getTargetInfo().isNan2008()) {
9037 if (SNaN)
9038 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9039 else
9040 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9041 } else {
9042 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9043 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9044 // a different encoding to what became a standard in 2008, and for pre-
9045 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9046 // sNaN. This is now known as "legacy NaN" encoding.
9047 if (SNaN)
9048 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9049 else
9050 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9051 }
9052
John McCall16291492010-02-28 13:00:19 +00009053 return true;
9054}
9055
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009056bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009057 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009058 default:
9059 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9060
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009061 case Builtin::BI__builtin_huge_val:
9062 case Builtin::BI__builtin_huge_valf:
9063 case Builtin::BI__builtin_huge_vall:
9064 case Builtin::BI__builtin_inf:
9065 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009066 case Builtin::BI__builtin_infl: {
9067 const llvm::fltSemantics &Sem =
9068 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009069 Result = llvm::APFloat::getInf(Sem);
9070 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009071 }
Mike Stump11289f42009-09-09 15:08:12 +00009072
John McCall16291492010-02-28 13:00:19 +00009073 case Builtin::BI__builtin_nans:
9074 case Builtin::BI__builtin_nansf:
9075 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009076 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9077 true, Result))
9078 return Error(E);
9079 return true;
John McCall16291492010-02-28 13:00:19 +00009080
Chris Lattner0b7282e2008-10-06 06:31:58 +00009081 case Builtin::BI__builtin_nan:
9082 case Builtin::BI__builtin_nanf:
9083 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00009084 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009085 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009086 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9087 false, Result))
9088 return Error(E);
9089 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009090
9091 case Builtin::BI__builtin_fabs:
9092 case Builtin::BI__builtin_fabsf:
9093 case Builtin::BI__builtin_fabsl:
9094 if (!EvaluateFloat(E->getArg(0), Result, Info))
9095 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009096
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009097 if (Result.isNegative())
9098 Result.changeSign();
9099 return true;
9100
Richard Smith8889a3d2013-06-13 06:26:32 +00009101 // FIXME: Builtin::BI__builtin_powi
9102 // FIXME: Builtin::BI__builtin_powif
9103 // FIXME: Builtin::BI__builtin_powil
9104
Mike Stump11289f42009-09-09 15:08:12 +00009105 case Builtin::BI__builtin_copysign:
9106 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009107 case Builtin::BI__builtin_copysignl: {
9108 APFloat RHS(0.);
9109 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9110 !EvaluateFloat(E->getArg(1), RHS, Info))
9111 return false;
9112 Result.copySign(RHS);
9113 return true;
9114 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009115 }
9116}
9117
John McCallb1fb0d32010-05-07 22:08:54 +00009118bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009119 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9120 ComplexValue CV;
9121 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9122 return false;
9123 Result = CV.FloatReal;
9124 return true;
9125 }
9126
9127 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009128}
9129
9130bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009131 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9132 ComplexValue CV;
9133 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9134 return false;
9135 Result = CV.FloatImag;
9136 return true;
9137 }
9138
Richard Smith4a678122011-10-24 18:44:57 +00009139 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009140 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9141 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009142 return true;
9143}
9144
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009145bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009146 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009147 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009148 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009149 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009150 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009151 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9152 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009153 Result.changeSign();
9154 return true;
9155 }
9156}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009157
Eli Friedman24c01542008-08-22 00:06:13 +00009158bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009159 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9160 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009161
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009162 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009163 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009164 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009165 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009166 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9167 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009168}
9169
9170bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9171 Result = E->getValue();
9172 return true;
9173}
9174
Peter Collingbournee9200682011-05-13 03:29:01 +00009175bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9176 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009177
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009178 switch (E->getCastKind()) {
9179 default:
Richard Smith11562c52011-10-28 17:51:58 +00009180 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009181
9182 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009183 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009184 return EvaluateInteger(SubExpr, IntResult, Info) &&
9185 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9186 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009187 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009188
9189 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009190 if (!Visit(SubExpr))
9191 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009192 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9193 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009194 }
John McCalld7646252010-11-14 08:17:51 +00009195
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009196 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009197 ComplexValue V;
9198 if (!EvaluateComplex(SubExpr, V, Info))
9199 return false;
9200 Result = V.getComplexFloatReal();
9201 return true;
9202 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009203 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009204}
9205
Eli Friedman24c01542008-08-22 00:06:13 +00009206//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009207// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009208//===----------------------------------------------------------------------===//
9209
9210namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009211class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009212 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009213 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009214
Anders Carlsson537969c2008-11-16 20:27:53 +00009215public:
John McCall93d91dc2010-05-07 17:22:02 +00009216 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009217 : ExprEvaluatorBaseTy(info), Result(Result) {}
9218
Richard Smith2e312c82012-03-03 22:46:17 +00009219 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009220 Result.setFrom(V);
9221 return true;
9222 }
Mike Stump11289f42009-09-09 15:08:12 +00009223
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009224 bool ZeroInitialization(const Expr *E);
9225
Anders Carlsson537969c2008-11-16 20:27:53 +00009226 //===--------------------------------------------------------------------===//
9227 // Visitor Methods
9228 //===--------------------------------------------------------------------===//
9229
Peter Collingbournee9200682011-05-13 03:29:01 +00009230 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009231 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009232 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009233 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009234 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009235};
9236} // end anonymous namespace
9237
John McCall93d91dc2010-05-07 17:22:02 +00009238static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9239 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009240 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009241 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009242}
9243
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009244bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009245 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009246 if (ElemTy->isRealFloatingType()) {
9247 Result.makeComplexFloat();
9248 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9249 Result.FloatReal = Zero;
9250 Result.FloatImag = Zero;
9251 } else {
9252 Result.makeComplexInt();
9253 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9254 Result.IntReal = Zero;
9255 Result.IntImag = Zero;
9256 }
9257 return true;
9258}
9259
Peter Collingbournee9200682011-05-13 03:29:01 +00009260bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9261 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009262
9263 if (SubExpr->getType()->isRealFloatingType()) {
9264 Result.makeComplexFloat();
9265 APFloat &Imag = Result.FloatImag;
9266 if (!EvaluateFloat(SubExpr, Imag, Info))
9267 return false;
9268
9269 Result.FloatReal = APFloat(Imag.getSemantics());
9270 return true;
9271 } else {
9272 assert(SubExpr->getType()->isIntegerType() &&
9273 "Unexpected imaginary literal.");
9274
9275 Result.makeComplexInt();
9276 APSInt &Imag = Result.IntImag;
9277 if (!EvaluateInteger(SubExpr, Imag, Info))
9278 return false;
9279
9280 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9281 return true;
9282 }
9283}
9284
Peter Collingbournee9200682011-05-13 03:29:01 +00009285bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009286
John McCallfcef3cf2010-12-14 17:51:41 +00009287 switch (E->getCastKind()) {
9288 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009289 case CK_BaseToDerived:
9290 case CK_DerivedToBase:
9291 case CK_UncheckedDerivedToBase:
9292 case CK_Dynamic:
9293 case CK_ToUnion:
9294 case CK_ArrayToPointerDecay:
9295 case CK_FunctionToPointerDecay:
9296 case CK_NullToPointer:
9297 case CK_NullToMemberPointer:
9298 case CK_BaseToDerivedMemberPointer:
9299 case CK_DerivedToBaseMemberPointer:
9300 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009301 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009302 case CK_ConstructorConversion:
9303 case CK_IntegralToPointer:
9304 case CK_PointerToIntegral:
9305 case CK_PointerToBoolean:
9306 case CK_ToVoid:
9307 case CK_VectorSplat:
9308 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009309 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009310 case CK_IntegralToBoolean:
9311 case CK_IntegralToFloating:
9312 case CK_FloatingToIntegral:
9313 case CK_FloatingToBoolean:
9314 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009315 case CK_CPointerToObjCPointerCast:
9316 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009317 case CK_AnyPointerToBlockPointerCast:
9318 case CK_ObjCObjectLValueCast:
9319 case CK_FloatingComplexToReal:
9320 case CK_FloatingComplexToBoolean:
9321 case CK_IntegralComplexToReal:
9322 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009323 case CK_ARCProduceObject:
9324 case CK_ARCConsumeObject:
9325 case CK_ARCReclaimReturnedObject:
9326 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009327 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009328 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009329 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009330 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009331 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009332 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009333 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009334 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009335
John McCallfcef3cf2010-12-14 17:51:41 +00009336 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009337 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009338 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009339 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009340
9341 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009342 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009343 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009344 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009345
9346 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009347 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009348 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009349 return false;
9350
John McCallfcef3cf2010-12-14 17:51:41 +00009351 Result.makeComplexFloat();
9352 Result.FloatImag = APFloat(Real.getSemantics());
9353 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009354 }
9355
John McCallfcef3cf2010-12-14 17:51:41 +00009356 case CK_FloatingComplexCast: {
9357 if (!Visit(E->getSubExpr()))
9358 return false;
9359
9360 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9361 QualType From
9362 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9363
Richard Smith357362d2011-12-13 06:39:58 +00009364 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9365 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009366 }
9367
9368 case CK_FloatingComplexToIntegralComplex: {
9369 if (!Visit(E->getSubExpr()))
9370 return false;
9371
9372 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9373 QualType From
9374 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9375 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009376 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9377 To, Result.IntReal) &&
9378 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9379 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009380 }
9381
9382 case CK_IntegralRealToComplex: {
9383 APSInt &Real = Result.IntReal;
9384 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9385 return false;
9386
9387 Result.makeComplexInt();
9388 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9389 return true;
9390 }
9391
9392 case CK_IntegralComplexCast: {
9393 if (!Visit(E->getSubExpr()))
9394 return false;
9395
9396 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9397 QualType From
9398 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9399
Richard Smith911e1422012-01-30 22:27:01 +00009400 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9401 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009402 return true;
9403 }
9404
9405 case CK_IntegralComplexToFloatingComplex: {
9406 if (!Visit(E->getSubExpr()))
9407 return false;
9408
Ted Kremenek28831752012-08-23 20:46:57 +00009409 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009410 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009411 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009412 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009413 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9414 To, Result.FloatReal) &&
9415 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9416 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009417 }
9418 }
9419
9420 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009421}
9422
John McCall93d91dc2010-05-07 17:22:02 +00009423bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009424 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009425 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9426
Chandler Carrutha216cad2014-10-11 00:57:18 +00009427 // Track whether the LHS or RHS is real at the type system level. When this is
9428 // the case we can simplify our evaluation strategy.
9429 bool LHSReal = false, RHSReal = false;
9430
9431 bool LHSOK;
9432 if (E->getLHS()->getType()->isRealFloatingType()) {
9433 LHSReal = true;
9434 APFloat &Real = Result.FloatReal;
9435 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9436 if (LHSOK) {
9437 Result.makeComplexFloat();
9438 Result.FloatImag = APFloat(Real.getSemantics());
9439 }
9440 } else {
9441 LHSOK = Visit(E->getLHS());
9442 }
George Burgess IVa145e252016-05-25 22:38:36 +00009443 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009444 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009445
John McCall93d91dc2010-05-07 17:22:02 +00009446 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009447 if (E->getRHS()->getType()->isRealFloatingType()) {
9448 RHSReal = true;
9449 APFloat &Real = RHS.FloatReal;
9450 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9451 return false;
9452 RHS.makeComplexFloat();
9453 RHS.FloatImag = APFloat(Real.getSemantics());
9454 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009455 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009456
Chandler Carrutha216cad2014-10-11 00:57:18 +00009457 assert(!(LHSReal && RHSReal) &&
9458 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009459 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009460 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009461 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009462 if (Result.isComplexFloat()) {
9463 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9464 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009465 if (LHSReal)
9466 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9467 else if (!RHSReal)
9468 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9469 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009470 } else {
9471 Result.getComplexIntReal() += RHS.getComplexIntReal();
9472 Result.getComplexIntImag() += RHS.getComplexIntImag();
9473 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009474 break;
John McCalle3027922010-08-25 11:45:40 +00009475 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009476 if (Result.isComplexFloat()) {
9477 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9478 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009479 if (LHSReal) {
9480 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9481 Result.getComplexFloatImag().changeSign();
9482 } else if (!RHSReal) {
9483 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9484 APFloat::rmNearestTiesToEven);
9485 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009486 } else {
9487 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9488 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9489 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009490 break;
John McCalle3027922010-08-25 11:45:40 +00009491 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009492 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009493 // This is an implementation of complex multiplication according to the
9494 // constraints laid out in C11 Annex G. The implemantion uses the
9495 // following naming scheme:
9496 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009497 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009498 APFloat &A = LHS.getComplexFloatReal();
9499 APFloat &B = LHS.getComplexFloatImag();
9500 APFloat &C = RHS.getComplexFloatReal();
9501 APFloat &D = RHS.getComplexFloatImag();
9502 APFloat &ResR = Result.getComplexFloatReal();
9503 APFloat &ResI = Result.getComplexFloatImag();
9504 if (LHSReal) {
9505 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9506 ResR = A * C;
9507 ResI = A * D;
9508 } else if (RHSReal) {
9509 ResR = C * A;
9510 ResI = C * B;
9511 } else {
9512 // In the fully general case, we need to handle NaNs and infinities
9513 // robustly.
9514 APFloat AC = A * C;
9515 APFloat BD = B * D;
9516 APFloat AD = A * D;
9517 APFloat BC = B * C;
9518 ResR = AC - BD;
9519 ResI = AD + BC;
9520 if (ResR.isNaN() && ResI.isNaN()) {
9521 bool Recalc = false;
9522 if (A.isInfinity() || B.isInfinity()) {
9523 A = APFloat::copySign(
9524 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9525 B = APFloat::copySign(
9526 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9527 if (C.isNaN())
9528 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9529 if (D.isNaN())
9530 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9531 Recalc = true;
9532 }
9533 if (C.isInfinity() || D.isInfinity()) {
9534 C = APFloat::copySign(
9535 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9536 D = APFloat::copySign(
9537 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9538 if (A.isNaN())
9539 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9540 if (B.isNaN())
9541 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9542 Recalc = true;
9543 }
9544 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9545 AD.isInfinity() || BC.isInfinity())) {
9546 if (A.isNaN())
9547 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9548 if (B.isNaN())
9549 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9550 if (C.isNaN())
9551 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9552 if (D.isNaN())
9553 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9554 Recalc = true;
9555 }
9556 if (Recalc) {
9557 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9558 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9559 }
9560 }
9561 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009562 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009563 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009564 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009565 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9566 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009567 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009568 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9569 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9570 }
9571 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009572 case BO_Div:
9573 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009574 // This is an implementation of complex division according to the
9575 // constraints laid out in C11 Annex G. The implemantion uses the
9576 // following naming scheme:
9577 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009578 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009579 APFloat &A = LHS.getComplexFloatReal();
9580 APFloat &B = LHS.getComplexFloatImag();
9581 APFloat &C = RHS.getComplexFloatReal();
9582 APFloat &D = RHS.getComplexFloatImag();
9583 APFloat &ResR = Result.getComplexFloatReal();
9584 APFloat &ResI = Result.getComplexFloatImag();
9585 if (RHSReal) {
9586 ResR = A / C;
9587 ResI = B / C;
9588 } else {
9589 if (LHSReal) {
9590 // No real optimizations we can do here, stub out with zero.
9591 B = APFloat::getZero(A.getSemantics());
9592 }
9593 int DenomLogB = 0;
9594 APFloat MaxCD = maxnum(abs(C), abs(D));
9595 if (MaxCD.isFinite()) {
9596 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009597 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9598 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009599 }
9600 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009601 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9602 APFloat::rmNearestTiesToEven);
9603 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9604 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009605 if (ResR.isNaN() && ResI.isNaN()) {
9606 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9607 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9608 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9609 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9610 D.isFinite()) {
9611 A = APFloat::copySign(
9612 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9613 B = APFloat::copySign(
9614 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9615 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9616 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9617 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9618 C = APFloat::copySign(
9619 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9620 D = APFloat::copySign(
9621 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9622 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9623 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9624 }
9625 }
9626 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009627 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009628 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9629 return Error(E, diag::note_expr_divide_by_zero);
9630
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009631 ComplexValue LHS = Result;
9632 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9633 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9634 Result.getComplexIntReal() =
9635 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9636 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9637 Result.getComplexIntImag() =
9638 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9639 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9640 }
9641 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009642 }
9643
John McCall93d91dc2010-05-07 17:22:02 +00009644 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009645}
9646
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009647bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9648 // Get the operand value into 'Result'.
9649 if (!Visit(E->getSubExpr()))
9650 return false;
9651
9652 switch (E->getOpcode()) {
9653 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009654 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009655 case UO_Extension:
9656 return true;
9657 case UO_Plus:
9658 // The result is always just the subexpr.
9659 return true;
9660 case UO_Minus:
9661 if (Result.isComplexFloat()) {
9662 Result.getComplexFloatReal().changeSign();
9663 Result.getComplexFloatImag().changeSign();
9664 }
9665 else {
9666 Result.getComplexIntReal() = -Result.getComplexIntReal();
9667 Result.getComplexIntImag() = -Result.getComplexIntImag();
9668 }
9669 return true;
9670 case UO_Not:
9671 if (Result.isComplexFloat())
9672 Result.getComplexFloatImag().changeSign();
9673 else
9674 Result.getComplexIntImag() = -Result.getComplexIntImag();
9675 return true;
9676 }
9677}
9678
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009679bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9680 if (E->getNumInits() == 2) {
9681 if (E->getType()->isComplexType()) {
9682 Result.makeComplexFloat();
9683 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9684 return false;
9685 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9686 return false;
9687 } else {
9688 Result.makeComplexInt();
9689 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9690 return false;
9691 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9692 return false;
9693 }
9694 return true;
9695 }
9696 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9697}
9698
Anders Carlsson537969c2008-11-16 20:27:53 +00009699//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009700// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9701// implicit conversion.
9702//===----------------------------------------------------------------------===//
9703
9704namespace {
9705class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009706 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009707 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009708 APValue &Result;
9709public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009710 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9711 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009712
9713 bool Success(const APValue &V, const Expr *E) {
9714 Result = V;
9715 return true;
9716 }
9717
9718 bool ZeroInitialization(const Expr *E) {
9719 ImplicitValueInitExpr VIE(
9720 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009721 // For atomic-qualified class (and array) types in C++, initialize the
9722 // _Atomic-wrapped subobject directly, in-place.
9723 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9724 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009725 }
9726
9727 bool VisitCastExpr(const CastExpr *E) {
9728 switch (E->getCastKind()) {
9729 default:
9730 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9731 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009732 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9733 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009734 }
9735 }
9736};
9737} // end anonymous namespace
9738
Richard Smith64cb9ca2017-02-22 22:09:50 +00009739static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9740 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009741 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009742 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009743}
9744
9745//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009746// Void expression evaluation, primarily for a cast to void on the LHS of a
9747// comma operator
9748//===----------------------------------------------------------------------===//
9749
9750namespace {
9751class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009752 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009753public:
9754 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9755
Richard Smith2e312c82012-03-03 22:46:17 +00009756 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009757
9758 bool VisitCastExpr(const CastExpr *E) {
9759 switch (E->getCastKind()) {
9760 default:
9761 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9762 case CK_ToVoid:
9763 VisitIgnoredValue(E->getSubExpr());
9764 return true;
9765 }
9766 }
Hal Finkela8443c32014-07-17 14:49:58 +00009767
9768 bool VisitCallExpr(const CallExpr *E) {
9769 switch (E->getBuiltinCallee()) {
9770 default:
9771 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9772 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009773 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009774 // The argument is not evaluated!
9775 return true;
9776 }
9777 }
Richard Smith42d3af92011-12-07 00:43:50 +00009778};
9779} // end anonymous namespace
9780
9781static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9782 assert(E->isRValue() && E->getType()->isVoidType());
9783 return VoidExprEvaluator(Info).Visit(E);
9784}
9785
9786//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009787// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009788//===----------------------------------------------------------------------===//
9789
Richard Smith2e312c82012-03-03 22:46:17 +00009790static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009791 // In C, function designators are not lvalues, but we evaluate them as if they
9792 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009793 QualType T = E->getType();
9794 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009795 LValue LV;
9796 if (!EvaluateLValue(E, LV, Info))
9797 return false;
9798 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009799 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009800 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009801 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009802 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009803 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009804 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009805 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009806 LValue LV;
9807 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009808 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009809 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009810 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009811 llvm::APFloat F(0.0);
9812 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009813 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009814 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009815 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009816 ComplexValue C;
9817 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009818 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009819 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009820 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009821 MemberPtr P;
9822 if (!EvaluateMemberPointer(E, P, Info))
9823 return false;
9824 P.moveInto(Result);
9825 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009826 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009827 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009828 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009829 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9830 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009831 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009832 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009833 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009834 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009835 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009836 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9837 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009838 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009839 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009840 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009841 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009842 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009843 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009844 if (!EvaluateVoid(E, Info))
9845 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009846 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009847 QualType Unqual = T.getAtomicUnqualifiedType();
9848 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9849 LValue LV;
9850 LV.set(E, Info.CurrentCall->Index);
9851 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9852 if (!EvaluateAtomic(E, &LV, Value, Info))
9853 return false;
9854 } else {
9855 if (!EvaluateAtomic(E, nullptr, Result, Info))
9856 return false;
9857 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009858 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009859 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009860 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009861 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009862 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009863 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009864 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009865
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009866 return true;
9867}
9868
Richard Smithb228a862012-02-15 02:18:13 +00009869/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9870/// cases, the in-place evaluation is essential, since later initializers for
9871/// an object can indirectly refer to subobjects which were initialized earlier.
9872static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009873 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009874 assert(!E->isValueDependent());
9875
Richard Smith7525ff62013-05-09 07:14:00 +00009876 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009877 return false;
9878
9879 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009880 // Evaluate arrays and record types in-place, so that later initializers can
9881 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +00009882 QualType T = E->getType();
9883 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +00009884 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009885 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +00009886 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009887 else if (T->isAtomicType()) {
9888 QualType Unqual = T.getAtomicUnqualifiedType();
9889 if (Unqual->isArrayType() || Unqual->isRecordType())
9890 return EvaluateAtomic(E, &This, Result, Info);
9891 }
Richard Smithed5165f2011-11-04 05:33:44 +00009892 }
9893
9894 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009895 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009896}
9897
Richard Smithf57d8cb2011-12-09 22:58:01 +00009898/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9899/// lvalue-to-rvalue cast if it is an lvalue.
9900static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009901 if (E->getType().isNull())
9902 return false;
9903
Richard Smithfddd3842011-12-30 21:15:51 +00009904 if (!CheckLiteralType(Info, E))
9905 return false;
9906
Richard Smith2e312c82012-03-03 22:46:17 +00009907 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009908 return false;
9909
9910 if (E->isGLValue()) {
9911 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009912 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009913 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009914 return false;
9915 }
9916
Richard Smith2e312c82012-03-03 22:46:17 +00009917 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009918 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009919}
Richard Smith11562c52011-10-28 17:51:58 +00009920
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009921static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9922 const ASTContext &Ctx, bool &IsConst) {
9923 // Fast-path evaluations of integer literals, since we sometimes see files
9924 // containing vast quantities of these.
9925 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9926 Result.Val = APValue(APSInt(L->getValue(),
9927 L->getType()->isUnsignedIntegerType()));
9928 IsConst = true;
9929 return true;
9930 }
James Dennett0492ef02014-03-14 17:44:10 +00009931
9932 // This case should be rare, but we need to check it before we check on
9933 // the type below.
9934 if (Exp->getType().isNull()) {
9935 IsConst = false;
9936 return true;
9937 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009938
9939 // FIXME: Evaluating values of large array and record types can cause
9940 // performance problems. Only do so in C++11 for now.
9941 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9942 Exp->getType()->isRecordType()) &&
9943 !Ctx.getLangOpts().CPlusPlus11) {
9944 IsConst = false;
9945 return true;
9946 }
9947 return false;
9948}
9949
9950
Richard Smith7b553f12011-10-29 00:50:52 +00009951/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009952/// any crazy technique (that has nothing to do with language standards) that
9953/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009954/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9955/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009956bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009957 bool IsConst;
9958 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9959 return IsConst;
9960
Richard Smith6d4c6582013-11-05 22:18:15 +00009961 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009962 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009963}
9964
Jay Foad39c79802011-01-12 09:06:06 +00009965bool Expr::EvaluateAsBooleanCondition(bool &Result,
9966 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009967 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009968 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009969 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009970}
9971
Richard Smithce8eca52015-12-08 03:21:47 +00009972static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9973 Expr::SideEffectsKind SEK) {
9974 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9975 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9976}
9977
Richard Smith5fab0c92011-12-28 19:48:30 +00009978bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9979 SideEffectsKind AllowSideEffects) const {
9980 if (!getType()->isIntegralOrEnumerationType())
9981 return false;
9982
Richard Smith11562c52011-10-28 17:51:58 +00009983 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009984 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009985 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009986 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009987
Richard Smith11562c52011-10-28 17:51:58 +00009988 Result = ExprResult.Val.getInt();
9989 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009990}
9991
Richard Trieube234c32016-04-21 21:04:55 +00009992bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9993 SideEffectsKind AllowSideEffects) const {
9994 if (!getType()->isRealFloatingType())
9995 return false;
9996
9997 EvalResult ExprResult;
9998 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9999 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10000 return false;
10001
10002 Result = ExprResult.Val.getFloat();
10003 return true;
10004}
10005
Jay Foad39c79802011-01-12 09:06:06 +000010006bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010007 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010008
John McCall45d55e42010-05-07 21:00:08 +000010009 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010010 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10011 !CheckLValueConstantExpression(Info, getExprLoc(),
10012 Ctx.getLValueReferenceType(getType()), LV))
10013 return false;
10014
Richard Smith2e312c82012-03-03 22:46:17 +000010015 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010016 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010017}
10018
Richard Smithd0b4dd62011-12-19 06:19:21 +000010019bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10020 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010021 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010022 // FIXME: Evaluating initializers for large array and record types can cause
10023 // performance problems. Only do so in C++11 for now.
10024 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010025 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010026 return false;
10027
Richard Smithd0b4dd62011-12-19 06:19:21 +000010028 Expr::EvalStatus EStatus;
10029 EStatus.Diag = &Notes;
10030
Richard Smith0c6124b2015-12-03 01:36:22 +000010031 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10032 ? EvalInfo::EM_ConstantExpression
10033 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010034 InitInfo.setEvaluatingDecl(VD, Value);
10035
10036 LValue LVal;
10037 LVal.set(VD);
10038
Richard Smithfddd3842011-12-30 21:15:51 +000010039 // C++11 [basic.start.init]p2:
10040 // Variables with static storage duration or thread storage duration shall be
10041 // zero-initialized before any other initialization takes place.
10042 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010043 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010044 !VD->getType()->isReferenceType()) {
10045 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010046 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010047 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010048 return false;
10049 }
10050
Richard Smith7525ff62013-05-09 07:14:00 +000010051 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10052 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010053 EStatus.HasSideEffects)
10054 return false;
10055
10056 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10057 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010058}
10059
Richard Smith7b553f12011-10-29 00:50:52 +000010060/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10061/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010062bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010063 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010064 return EvaluateAsRValue(Result, Ctx) &&
10065 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010066}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010067
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010068APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010069 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010070 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010071 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010072 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010073 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010074 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010075 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010076
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010077 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010078}
John McCall864e3962010-05-07 05:32:02 +000010079
Richard Smithe9ff7702013-11-05 22:23:30 +000010080void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010081 bool IsConst;
10082 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010083 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010084 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010085 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10086 }
10087}
10088
Richard Smithe6c01442013-06-05 00:46:14 +000010089bool Expr::EvalResult::isGlobalLValue() const {
10090 assert(Val.isLValue());
10091 return IsGlobalLValue(Val.getLValueBase());
10092}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010093
10094
John McCall864e3962010-05-07 05:32:02 +000010095/// isIntegerConstantExpr - this recursive routine will test if an expression is
10096/// an integer constant expression.
10097
10098/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10099/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010100
10101// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010102// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10103// and a (possibly null) SourceLocation indicating the location of the problem.
10104//
John McCall864e3962010-05-07 05:32:02 +000010105// Note that to reduce code duplication, this helper does no evaluation
10106// itself; the caller checks whether the expression is evaluatable, and
10107// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010108// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010109
Dan Gohman28ade552010-07-26 21:25:24 +000010110namespace {
10111
Richard Smith9e575da2012-12-28 13:25:52 +000010112enum ICEKind {
10113 /// This expression is an ICE.
10114 IK_ICE,
10115 /// This expression is not an ICE, but if it isn't evaluated, it's
10116 /// a legal subexpression for an ICE. This return value is used to handle
10117 /// the comma operator in C99 mode, and non-constant subexpressions.
10118 IK_ICEIfUnevaluated,
10119 /// This expression is not an ICE, and is not a legal subexpression for one.
10120 IK_NotICE
10121};
10122
John McCall864e3962010-05-07 05:32:02 +000010123struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010124 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010125 SourceLocation Loc;
10126
Richard Smith9e575da2012-12-28 13:25:52 +000010127 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010128};
10129
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010130}
Dan Gohman28ade552010-07-26 21:25:24 +000010131
Richard Smith9e575da2012-12-28 13:25:52 +000010132static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10133
10134static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010135
Craig Toppera31a8822013-08-22 07:09:37 +000010136static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010137 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010138 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010139 !EVResult.Val.isInt())
10140 return ICEDiag(IK_NotICE, E->getLocStart());
10141
John McCall864e3962010-05-07 05:32:02 +000010142 return NoDiag();
10143}
10144
Craig Toppera31a8822013-08-22 07:09:37 +000010145static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010146 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010147 if (!E->getType()->isIntegralOrEnumerationType())
10148 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010149
10150 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010151#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010152#define STMT(Node, Base) case Expr::Node##Class:
10153#define EXPR(Node, Base)
10154#include "clang/AST/StmtNodes.inc"
10155 case Expr::PredefinedExprClass:
10156 case Expr::FloatingLiteralClass:
10157 case Expr::ImaginaryLiteralClass:
10158 case Expr::StringLiteralClass:
10159 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010160 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010161 case Expr::MemberExprClass:
10162 case Expr::CompoundAssignOperatorClass:
10163 case Expr::CompoundLiteralExprClass:
10164 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010165 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010166 case Expr::ArrayInitLoopExprClass:
10167 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010168 case Expr::NoInitExprClass:
10169 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010170 case Expr::ImplicitValueInitExprClass:
10171 case Expr::ParenListExprClass:
10172 case Expr::VAArgExprClass:
10173 case Expr::AddrLabelExprClass:
10174 case Expr::StmtExprClass:
10175 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010176 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010177 case Expr::CXXDynamicCastExprClass:
10178 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010179 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010180 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010181 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010182 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010183 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010184 case Expr::CXXThisExprClass:
10185 case Expr::CXXThrowExprClass:
10186 case Expr::CXXNewExprClass:
10187 case Expr::CXXDeleteExprClass:
10188 case Expr::CXXPseudoDestructorExprClass:
10189 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010190 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010191 case Expr::DependentScopeDeclRefExprClass:
10192 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010193 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010194 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010195 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010196 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010197 case Expr::CXXTemporaryObjectExprClass:
10198 case Expr::CXXUnresolvedConstructExprClass:
10199 case Expr::CXXDependentScopeMemberExprClass:
10200 case Expr::UnresolvedMemberExprClass:
10201 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010202 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010203 case Expr::ObjCArrayLiteralClass:
10204 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010205 case Expr::ObjCEncodeExprClass:
10206 case Expr::ObjCMessageExprClass:
10207 case Expr::ObjCSelectorExprClass:
10208 case Expr::ObjCProtocolExprClass:
10209 case Expr::ObjCIvarRefExprClass:
10210 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010211 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010212 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010213 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010214 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010215 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010216 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010217 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010218 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010219 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010220 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010221 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010222 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010223 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010224 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010225 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010226 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010227 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010228 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010229 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010230 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010231 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010232 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010233
Richard Smithf137f932014-01-25 20:50:08 +000010234 case Expr::InitListExprClass: {
10235 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10236 // form "T x = { a };" is equivalent to "T x = a;".
10237 // Unless we're initializing a reference, T is a scalar as it is known to be
10238 // of integral or enumeration type.
10239 if (E->isRValue())
10240 if (cast<InitListExpr>(E)->getNumInits() == 1)
10241 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10242 return ICEDiag(IK_NotICE, E->getLocStart());
10243 }
10244
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010245 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010246 case Expr::GNUNullExprClass:
10247 // GCC considers the GNU __null value to be an integral constant expression.
10248 return NoDiag();
10249
John McCall7c454bb2011-07-15 05:09:51 +000010250 case Expr::SubstNonTypeTemplateParmExprClass:
10251 return
10252 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10253
John McCall864e3962010-05-07 05:32:02 +000010254 case Expr::ParenExprClass:
10255 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010256 case Expr::GenericSelectionExprClass:
10257 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010258 case Expr::IntegerLiteralClass:
10259 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010260 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010261 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010262 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010263 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010264 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010265 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010266 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010267 return NoDiag();
10268 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010269 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010270 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10271 // constant expressions, but they can never be ICEs because an ICE cannot
10272 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010273 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010274 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010275 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010276 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010277 }
Richard Smith6365c912012-02-24 22:12:32 +000010278 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010279 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10280 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010281 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010282 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010283 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010284 // Parameter variables are never constants. Without this check,
10285 // getAnyInitializer() can find a default argument, which leads
10286 // to chaos.
10287 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010288 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010289
10290 // C++ 7.1.5.1p2
10291 // A variable of non-volatile const-qualified integral or enumeration
10292 // type initialized by an ICE can be used in ICEs.
10293 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010294 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010295 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010296
Richard Smithd0b4dd62011-12-19 06:19:21 +000010297 const VarDecl *VD;
10298 // Look for a declaration of this variable that has an initializer, and
10299 // check whether it is an ICE.
10300 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10301 return NoDiag();
10302 else
Richard Smith9e575da2012-12-28 13:25:52 +000010303 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010304 }
10305 }
Richard Smith9e575da2012-12-28 13:25:52 +000010306 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010307 }
John McCall864e3962010-05-07 05:32:02 +000010308 case Expr::UnaryOperatorClass: {
10309 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10310 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010311 case UO_PostInc:
10312 case UO_PostDec:
10313 case UO_PreInc:
10314 case UO_PreDec:
10315 case UO_AddrOf:
10316 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010317 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010318 // C99 6.6/3 allows increment and decrement within unevaluated
10319 // subexpressions of constant expressions, but they can never be ICEs
10320 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010321 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010322 case UO_Extension:
10323 case UO_LNot:
10324 case UO_Plus:
10325 case UO_Minus:
10326 case UO_Not:
10327 case UO_Real:
10328 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010329 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010330 }
Richard Smith9e575da2012-12-28 13:25:52 +000010331
John McCall864e3962010-05-07 05:32:02 +000010332 // OffsetOf falls through here.
10333 }
10334 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010335 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10336 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10337 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10338 // compliance: we should warn earlier for offsetof expressions with
10339 // array subscripts that aren't ICEs, and if the array subscripts
10340 // are ICEs, the value of the offsetof must be an integer constant.
10341 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010342 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010343 case Expr::UnaryExprOrTypeTraitExprClass: {
10344 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10345 if ((Exp->getKind() == UETT_SizeOf) &&
10346 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010347 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010348 return NoDiag();
10349 }
10350 case Expr::BinaryOperatorClass: {
10351 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10352 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010353 case BO_PtrMemD:
10354 case BO_PtrMemI:
10355 case BO_Assign:
10356 case BO_MulAssign:
10357 case BO_DivAssign:
10358 case BO_RemAssign:
10359 case BO_AddAssign:
10360 case BO_SubAssign:
10361 case BO_ShlAssign:
10362 case BO_ShrAssign:
10363 case BO_AndAssign:
10364 case BO_XorAssign:
10365 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010366 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10367 // constant expressions, but they can never be ICEs because an ICE cannot
10368 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010369 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010370
John McCalle3027922010-08-25 11:45:40 +000010371 case BO_Mul:
10372 case BO_Div:
10373 case BO_Rem:
10374 case BO_Add:
10375 case BO_Sub:
10376 case BO_Shl:
10377 case BO_Shr:
10378 case BO_LT:
10379 case BO_GT:
10380 case BO_LE:
10381 case BO_GE:
10382 case BO_EQ:
10383 case BO_NE:
10384 case BO_And:
10385 case BO_Xor:
10386 case BO_Or:
10387 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010388 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10389 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010390 if (Exp->getOpcode() == BO_Div ||
10391 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010392 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010393 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010394 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010395 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010396 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010397 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010398 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010399 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010400 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010401 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010402 }
10403 }
10404 }
John McCalle3027922010-08-25 11:45:40 +000010405 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010406 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010407 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10408 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010409 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10410 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010411 } else {
10412 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010413 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010414 }
10415 }
Richard Smith9e575da2012-12-28 13:25:52 +000010416 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010417 }
John McCalle3027922010-08-25 11:45:40 +000010418 case BO_LAnd:
10419 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010420 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10421 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010422 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010423 // Rare case where the RHS has a comma "side-effect"; we need
10424 // to actually check the condition to see whether the side
10425 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010426 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010427 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010428 return RHSResult;
10429 return NoDiag();
10430 }
10431
Richard Smith9e575da2012-12-28 13:25:52 +000010432 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010433 }
10434 }
10435 }
10436 case Expr::ImplicitCastExprClass:
10437 case Expr::CStyleCastExprClass:
10438 case Expr::CXXFunctionalCastExprClass:
10439 case Expr::CXXStaticCastExprClass:
10440 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010441 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010442 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010443 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010444 if (isa<ExplicitCastExpr>(E)) {
10445 if (const FloatingLiteral *FL
10446 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10447 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10448 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10449 APSInt IgnoredVal(DestWidth, !DestSigned);
10450 bool Ignored;
10451 // If the value does not fit in the destination type, the behavior is
10452 // undefined, so we are not required to treat it as a constant
10453 // expression.
10454 if (FL->getValue().convertToInteger(IgnoredVal,
10455 llvm::APFloat::rmTowardZero,
10456 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010457 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010458 return NoDiag();
10459 }
10460 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010461 switch (cast<CastExpr>(E)->getCastKind()) {
10462 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010463 case CK_AtomicToNonAtomic:
10464 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010465 case CK_NoOp:
10466 case CK_IntegralToBoolean:
10467 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010468 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010469 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010470 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010471 }
John McCall864e3962010-05-07 05:32:02 +000010472 }
John McCallc07a0c72011-02-17 10:25:35 +000010473 case Expr::BinaryConditionalOperatorClass: {
10474 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10475 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010476 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010477 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010478 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10479 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10480 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010481 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010482 return FalseResult;
10483 }
John McCall864e3962010-05-07 05:32:02 +000010484 case Expr::ConditionalOperatorClass: {
10485 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10486 // If the condition (ignoring parens) is a __builtin_constant_p call,
10487 // then only the true side is actually considered in an integer constant
10488 // expression, and it is fully evaluated. This is an important GNU
10489 // extension. See GCC PR38377 for discussion.
10490 if (const CallExpr *CallCE
10491 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010492 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010493 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010494 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010495 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010496 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010497
Richard Smithf57d8cb2011-12-09 22:58:01 +000010498 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10499 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010500
Richard Smith9e575da2012-12-28 13:25:52 +000010501 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010502 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010503 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010504 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010505 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010506 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010507 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010508 return NoDiag();
10509 // Rare case where the diagnostics depend on which side is evaluated
10510 // Note that if we get here, CondResult is 0, and at least one of
10511 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010512 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010513 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010514 return TrueResult;
10515 }
10516 case Expr::CXXDefaultArgExprClass:
10517 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010518 case Expr::CXXDefaultInitExprClass:
10519 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010520 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010521 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010522 }
10523 }
10524
David Blaikiee4d798f2012-01-20 21:50:17 +000010525 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010526}
10527
Richard Smithf57d8cb2011-12-09 22:58:01 +000010528/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010529static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010530 const Expr *E,
10531 llvm::APSInt *Value,
10532 SourceLocation *Loc) {
10533 if (!E->getType()->isIntegralOrEnumerationType()) {
10534 if (Loc) *Loc = E->getExprLoc();
10535 return false;
10536 }
10537
Richard Smith66e05fe2012-01-18 05:21:49 +000010538 APValue Result;
10539 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010540 return false;
10541
Richard Smith98710fc2014-11-13 23:03:19 +000010542 if (!Result.isInt()) {
10543 if (Loc) *Loc = E->getExprLoc();
10544 return false;
10545 }
10546
Richard Smith66e05fe2012-01-18 05:21:49 +000010547 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010548 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010549}
10550
Craig Toppera31a8822013-08-22 07:09:37 +000010551bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10552 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010553 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010554 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010555
Richard Smith9e575da2012-12-28 13:25:52 +000010556 ICEDiag D = CheckICE(this, Ctx);
10557 if (D.Kind != IK_ICE) {
10558 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010559 return false;
10560 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010561 return true;
10562}
10563
Craig Toppera31a8822013-08-22 07:09:37 +000010564bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010565 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010566 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010567 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10568
10569 if (!isIntegerConstantExpr(Ctx, Loc))
10570 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010571 // The only possible side-effects here are due to UB discovered in the
10572 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10573 // required to treat the expression as an ICE, so we produce the folded
10574 // value.
10575 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010576 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010577 return true;
10578}
Richard Smith66e05fe2012-01-18 05:21:49 +000010579
Craig Toppera31a8822013-08-22 07:09:37 +000010580bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010581 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010582}
10583
Craig Toppera31a8822013-08-22 07:09:37 +000010584bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010585 SourceLocation *Loc) const {
10586 // We support this checking in C++98 mode in order to diagnose compatibility
10587 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010588 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010589
Richard Smith98a0a492012-02-14 21:38:30 +000010590 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010591 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010592 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010593 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010594 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010595
10596 APValue Scratch;
10597 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10598
10599 if (!Diags.empty()) {
10600 IsConstExpr = false;
10601 if (Loc) *Loc = Diags[0].first;
10602 } else if (!IsConstExpr) {
10603 // FIXME: This shouldn't happen.
10604 if (Loc) *Loc = getExprLoc();
10605 }
10606
10607 return IsConstExpr;
10608}
Richard Smith253c2a32012-01-27 01:14:48 +000010609
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010610bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10611 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010612 ArrayRef<const Expr*> Args,
10613 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010614 Expr::EvalStatus Status;
10615 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10616
George Burgess IV177399e2017-01-09 04:12:14 +000010617 LValue ThisVal;
10618 const LValue *ThisPtr = nullptr;
10619 if (This) {
10620#ifndef NDEBUG
10621 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10622 assert(MD && "Don't provide `this` for non-methods.");
10623 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10624#endif
10625 if (EvaluateObjectArgument(Info, This, ThisVal))
10626 ThisPtr = &ThisVal;
10627 if (Info.EvalStatus.HasSideEffects)
10628 return false;
10629 }
10630
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010631 ArgVector ArgValues(Args.size());
10632 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10633 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010634 if ((*I)->isValueDependent() ||
10635 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010636 // If evaluation fails, throw away the argument entirely.
10637 ArgValues[I - Args.begin()] = APValue();
10638 if (Info.EvalStatus.HasSideEffects)
10639 return false;
10640 }
10641
10642 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010643 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010644 ArgValues.data());
10645 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10646}
10647
Richard Smith253c2a32012-01-27 01:14:48 +000010648bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010649 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010650 PartialDiagnosticAt> &Diags) {
10651 // FIXME: It would be useful to check constexpr function templates, but at the
10652 // moment the constant expression evaluator cannot cope with the non-rigorous
10653 // ASTs which we build for dependent expressions.
10654 if (FD->isDependentContext())
10655 return true;
10656
10657 Expr::EvalStatus Status;
10658 Status.Diag = &Diags;
10659
Richard Smith6d4c6582013-11-05 22:18:15 +000010660 EvalInfo Info(FD->getASTContext(), Status,
10661 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010662
10663 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010664 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010665
Richard Smith7525ff62013-05-09 07:14:00 +000010666 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010667 // is a temporary being used as the 'this' pointer.
10668 LValue This;
10669 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010670 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010671
Richard Smith253c2a32012-01-27 01:14:48 +000010672 ArrayRef<const Expr*> Args;
10673
Richard Smith2e312c82012-03-03 22:46:17 +000010674 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010675 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10676 // Evaluate the call as a constant initializer, to allow the construction
10677 // of objects of non-literal types.
10678 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010679 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10680 } else {
10681 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010682 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010683 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010684 }
Richard Smith253c2a32012-01-27 01:14:48 +000010685
10686 return Diags.empty();
10687}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010688
10689bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10690 const FunctionDecl *FD,
10691 SmallVectorImpl<
10692 PartialDiagnosticAt> &Diags) {
10693 Expr::EvalStatus Status;
10694 Status.Diag = &Diags;
10695
10696 EvalInfo Info(FD->getASTContext(), Status,
10697 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10698
10699 // Fabricate a call stack frame to give the arguments a plausible cover story.
10700 ArrayRef<const Expr*> Args;
10701 ArgVector ArgValues(0);
10702 bool Success = EvaluateArgs(Args, ArgValues, Info);
10703 (void)Success;
10704 assert(Success &&
10705 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010706 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010707
10708 APValue ResultScratch;
10709 Evaluate(ResultScratch, Info, E);
10710 return Diags.empty();
10711}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010712
10713bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10714 unsigned Type) const {
10715 if (!getType()->isPointerType())
10716 return false;
10717
10718 Expr::EvalStatus Status;
10719 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010720 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010721}