blob: 0c0c861e5d567795cb07ce8db8fc6fd2e518ec17 [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,
Daniel Jasperffdee092017-05-02 19:21:42 +0000151 uint64_t &ArraySize, QualType &Type, bool &IsArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000152 // 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) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000160 if (Type->isArrayType()) {
161 const ConstantArrayType *CAT =
162 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
163 Type = CAT->getElementType();
164 ArraySize = CAT->getSize().getZExtValue();
Richard Smitha8105bc2012-01-06 16:39:00 +0000165 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
Daniel Jasperffdee092017-05-02 19:21:42 +0000203 /// Indicator of whether the first entry is an unsized array.
204 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000205
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),
Daniel Jasperffdee092017-05-02 19:21:42 +0000234 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000235 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),
Daniel Jasperffdee092017-05-02 19:21:42 +0000240 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000241 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());
Daniel Jasperffdee092017-05-02 19:21:42 +0000247 if (V.getLValueBase()) {
248 bool IsArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000249 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000250 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
251 MostDerivedType, IsArray);
252 MostDerivedIsArrayElement = IsArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000253 }
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");
Daniel Jasperffdee092017-05-02 19:21:42 +0000266 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000267 }
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.
Daniel Jasperffdee092017-05-02 19:21:42 +0000356 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
357 if (Invalid || !N) return;
358 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
359 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).
362 // FIXME: Should we reject if this overflows, at least?
363 Entries.back().ArrayIndex += TruncatedN;
364 return;
365 }
366
367 // [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.
370 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);
384 setInvalid();
385 return;
386 }
387
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);
396 }
Richard Smith96e0c102011-11-04 02:25:55 +0000397 };
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,
Daniel Jasperffdee092017-05-02 19:21:42 +0000498 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000499 // 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) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000723
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.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000739 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000740 case EM_ConstantExpression:
741 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000742 case EM_ConstantExpressionUnevaluated:
743 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000744 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000745 HasActiveDiagnostic = false;
746 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000747 }
748 }
749
Richard Smithf6f003a2011-12-16 19:06:07 +0000750 unsigned CallStackNotes = CallStackDepth - 1;
751 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
752 if (Limit)
753 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000754 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000755 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000756
Richard Smith357362d2011-12-13 06:39:58 +0000757 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000758 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000759 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000760 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
761 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000762 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000763 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000764 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000765 }
Richard Smith357362d2011-12-13 06:39:58 +0000766 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000767 return OptionalDiagnostic();
768 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000769 public:
770 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
771 OptionalDiagnostic
772 FFDiag(SourceLocation Loc,
773 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
774 unsigned ExtraNotes = 0) {
775 return Diag(Loc, DiagId, ExtraNotes, false);
776 }
Daniel Jasperffdee092017-05-02 19:21:42 +0000777
Faisal Valie690b7a2016-07-02 22:34:24 +0000778 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000779 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000780 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000781 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000782 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000783 HasActiveDiagnostic = false;
784 return OptionalDiagnostic();
785 }
786
Richard Smith92b1ce02011-12-12 09:28:41 +0000787 /// Diagnose that the evaluation does not produce a C++11 core constant
788 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000789 ///
790 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
791 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000792 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000793 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000794 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000795 // Don't override a previous diagnostic. Don't bother collecting
796 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000797 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000798 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000799 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000800 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000801 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000802 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000803 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
804 = diag::note_invalid_subexpr_in_const_expr,
805 unsigned ExtraNotes = 0) {
806 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
807 }
Richard Smith357362d2011-12-13 06:39:58 +0000808 /// Add a note to a prior diagnostic.
809 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
810 if (!HasActiveDiagnostic)
811 return OptionalDiagnostic();
812 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000813 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000814
815 /// Add a stack of notes to a prior diagnostic.
816 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
817 if (HasActiveDiagnostic) {
818 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
819 Diags.begin(), Diags.end());
820 }
821 }
Richard Smith253c2a32012-01-27 01:14:48 +0000822
Richard Smith6d4c6582013-11-05 22:18:15 +0000823 /// Should we continue evaluation after encountering a side-effect that we
824 /// couldn't model?
825 bool keepEvaluatingAfterSideEffect() {
826 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000827 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000828 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000829 case EM_EvaluateForOverflow:
830 case EM_IgnoreSideEffects:
831 return true;
832
Richard Smith6d4c6582013-11-05 22:18:15 +0000833 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000834 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000835 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000836 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000837 return false;
838 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000839 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000840 }
841
842 /// Note that we have had a side-effect, and determine whether we should
843 /// keep evaluating.
844 bool noteSideEffect() {
845 EvalStatus.HasSideEffects = true;
846 return keepEvaluatingAfterSideEffect();
847 }
848
Richard Smithce8eca52015-12-08 03:21:47 +0000849 /// Should we continue evaluation after encountering undefined behavior?
850 bool keepEvaluatingAfterUndefinedBehavior() {
851 switch (EvalMode) {
852 case EM_EvaluateForOverflow:
853 case EM_IgnoreSideEffects:
854 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000855 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000856 return true;
857
858 case EM_PotentialConstantExpression:
859 case EM_PotentialConstantExpressionUnevaluated:
860 case EM_ConstantExpression:
861 case EM_ConstantExpressionUnevaluated:
862 return false;
863 }
864 llvm_unreachable("Missed EvalMode case");
865 }
866
867 /// Note that we hit something that was technically undefined behavior, but
868 /// that we can evaluate past it (such as signed overflow or floating-point
869 /// division by zero.)
870 bool noteUndefinedBehavior() {
871 EvalStatus.HasUndefinedBehavior = true;
872 return keepEvaluatingAfterUndefinedBehavior();
873 }
874
Richard Smith253c2a32012-01-27 01:14:48 +0000875 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000876 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000877 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000878 if (!StepsLeft)
879 return false;
880
881 switch (EvalMode) {
882 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000883 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000884 case EM_EvaluateForOverflow:
885 return true;
886
887 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000888 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000889 case EM_ConstantFold:
890 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000891 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000892 return false;
893 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000894 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000895 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000896
George Burgess IV8c892b52016-05-25 22:31:54 +0000897 /// Notes that we failed to evaluate an expression that other expressions
898 /// directly depend on, and determine if we should keep evaluating. This
899 /// should only be called if we actually intend to keep evaluating.
900 ///
901 /// Call noteSideEffect() instead if we may be able to ignore the value that
902 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
903 ///
904 /// (Foo(), 1) // use noteSideEffect
905 /// (Foo() || true) // use noteSideEffect
906 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000907 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000908 // Failure when evaluating some expression often means there is some
909 // subexpression whose evaluation was skipped. Therefore, (because we
910 // don't track whether we skipped an expression when unwinding after an
911 // evaluation failure) every evaluation failure that bubbles up from a
912 // subexpression implies that a side-effect has potentially happened. We
913 // skip setting the HasSideEffects flag to true until we decide to
914 // continue evaluating after that point, which happens here.
915 bool KeepGoing = keepEvaluatingAfterFailure();
916 EvalStatus.HasSideEffects |= KeepGoing;
917 return KeepGoing;
918 }
919
Richard Smith410306b2016-12-12 02:53:20 +0000920 class ArrayInitLoopIndex {
921 EvalInfo &Info;
922 uint64_t OuterIndex;
923
924 public:
925 ArrayInitLoopIndex(EvalInfo &Info)
926 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
927 Info.ArrayInitIndex = 0;
928 }
929 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
930
931 operator uint64_t&() { return Info.ArrayInitIndex; }
932 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000933 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000934
935 /// Object used to treat all foldable expressions as constant expressions.
936 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000937 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000938 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000939 bool HadNoPriorDiags;
940 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000941
Richard Smith6d4c6582013-11-05 22:18:15 +0000942 explicit FoldConstant(EvalInfo &Info, bool Enabled)
943 : Info(Info),
944 Enabled(Enabled),
945 HadNoPriorDiags(Info.EvalStatus.Diag &&
946 Info.EvalStatus.Diag->empty() &&
947 !Info.EvalStatus.HasSideEffects),
948 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000949 if (Enabled &&
950 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
951 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000952 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000953 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000954 void keepDiagnostics() { Enabled = false; }
955 ~FoldConstant() {
956 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000957 !Info.EvalStatus.HasSideEffects)
958 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000959 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000960 }
961 };
Richard Smith17100ba2012-02-16 02:46:34 +0000962
George Burgess IV3a03fab2015-09-04 21:28:13 +0000963 /// RAII object used to treat the current evaluation as the correct pointer
964 /// offset fold for the current EvalMode
965 struct FoldOffsetRAII {
966 EvalInfo &Info;
967 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +0000968 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +0000969 : Info(Info), OldMode(Info.EvalMode) {
970 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +0000971 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000972 }
973
974 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
975 };
976
George Burgess IV8c892b52016-05-25 22:31:54 +0000977 /// RAII object used to optionally suppress diagnostics and side-effects from
978 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000979 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000980 /// Pair of EvalInfo, and a bit that stores whether or not we were
981 /// speculatively evaluating when we created this RAII.
982 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000983 Expr::EvalStatus Old;
984
George Burgess IV8c892b52016-05-25 22:31:54 +0000985 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
986 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
987 Old = Other.Old;
988 Other.InfoAndOldSpecEval.setPointer(nullptr);
989 }
990
991 void maybeRestoreState() {
992 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
993 if (!Info)
994 return;
995
996 Info->EvalStatus = Old;
997 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
998 }
999
Richard Smith17100ba2012-02-16 02:46:34 +00001000 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001001 SpeculativeEvaluationRAII() = default;
1002
1003 SpeculativeEvaluationRAII(
1004 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1005 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
1006 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +00001007 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001008 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001009 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001010
1011 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1012 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1013 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001014 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001015
1016 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1017 maybeRestoreState();
1018 moveFromAndCancel(std::move(Other));
1019 return *this;
1020 }
1021
1022 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001023 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001024
1025 /// RAII object wrapping a full-expression or block scope, and handling
1026 /// the ending of the lifetime of temporaries created within it.
1027 template<bool IsFullExpression>
1028 class ScopeRAII {
1029 EvalInfo &Info;
1030 unsigned OldStackSize;
1031 public:
1032 ScopeRAII(EvalInfo &Info)
1033 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1034 ~ScopeRAII() {
1035 // Body moved to a static method to encourage the compiler to inline away
1036 // instances of this class.
1037 cleanup(Info, OldStackSize);
1038 }
1039 private:
1040 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1041 unsigned NewEnd = OldStackSize;
1042 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1043 I != N; ++I) {
1044 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1045 // Full-expression cleanup of a lifetime-extended temporary: nothing
1046 // to do, just move this cleanup to the right place in the stack.
1047 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1048 ++NewEnd;
1049 } else {
1050 // End the lifetime of the object.
1051 Info.CleanupStack[I].endLifetime();
1052 }
1053 }
1054 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1055 Info.CleanupStack.end());
1056 }
1057 };
1058 typedef ScopeRAII<false> BlockScopeRAII;
1059 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001060}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001061
Richard Smitha8105bc2012-01-06 16:39:00 +00001062bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1063 CheckSubobjectKind CSK) {
1064 if (Invalid)
1065 return false;
1066 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001067 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001068 << CSK;
1069 setInvalid();
1070 return false;
1071 }
1072 return true;
1073}
1074
1075void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001076 const Expr *E,
1077 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001078 // If we're complaining, we must be able to statically determine the size of
1079 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001080 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001081 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001082 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001083 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001084 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001085 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001086 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001087 setInvalid();
1088}
1089
Richard Smithf6f003a2011-12-16 19:06:07 +00001090CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1091 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001092 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001093 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1094 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001095 Info.CurrentCall = this;
1096 ++Info.CallStackDepth;
1097}
1098
1099CallStackFrame::~CallStackFrame() {
1100 assert(Info.CurrentCall == this && "calls retired out of order");
1101 --Info.CallStackDepth;
1102 Info.CurrentCall = Caller;
1103}
1104
Richard Smith08d6a2c2013-07-24 07:11:57 +00001105APValue &CallStackFrame::createTemporary(const void *Key,
1106 bool IsLifetimeExtended) {
1107 APValue &Result = Temporaries[Key];
1108 assert(Result.isUninit() && "temporary created multiple times");
1109 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1110 return Result;
1111}
1112
Richard Smith84401042013-06-03 05:03:02 +00001113static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001114
1115void EvalInfo::addCallStack(unsigned Limit) {
1116 // Determine which calls to skip, if any.
1117 unsigned ActiveCalls = CallStackDepth - 1;
1118 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1119 if (Limit && Limit < ActiveCalls) {
1120 SkipStart = Limit / 2 + Limit % 2;
1121 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001122 }
1123
Richard Smithf6f003a2011-12-16 19:06:07 +00001124 // Walk the call stack and add the diagnostics.
1125 unsigned CallIdx = 0;
1126 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1127 Frame = Frame->Caller, ++CallIdx) {
1128 // Skip this call?
1129 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1130 if (CallIdx == SkipStart) {
1131 // Note that we're skipping calls.
1132 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1133 << unsigned(ActiveCalls - Limit);
1134 }
1135 continue;
1136 }
1137
Richard Smith5179eb72016-06-28 19:03:57 +00001138 // Use a different note for an inheriting constructor, because from the
1139 // user's perspective it's not really a function at all.
1140 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1141 if (CD->isInheritingConstructor()) {
1142 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1143 << CD->getParent();
1144 continue;
1145 }
1146 }
1147
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001148 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001149 llvm::raw_svector_ostream Out(Buffer);
1150 describeCall(Frame, Out);
1151 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1152 }
1153}
1154
1155namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001156 struct ComplexValue {
1157 private:
1158 bool IsInt;
1159
1160 public:
1161 APSInt IntReal, IntImag;
1162 APFloat FloatReal, FloatImag;
1163
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001164 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001165
1166 void makeComplexFloat() { IsInt = false; }
1167 bool isComplexFloat() const { return !IsInt; }
1168 APFloat &getComplexFloatReal() { return FloatReal; }
1169 APFloat &getComplexFloatImag() { return FloatImag; }
1170
1171 void makeComplexInt() { IsInt = true; }
1172 bool isComplexInt() const { return IsInt; }
1173 APSInt &getComplexIntReal() { return IntReal; }
1174 APSInt &getComplexIntImag() { return IntImag; }
1175
Richard Smith2e312c82012-03-03 22:46:17 +00001176 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001177 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001178 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001179 else
Richard Smith2e312c82012-03-03 22:46:17 +00001180 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001181 }
Richard Smith2e312c82012-03-03 22:46:17 +00001182 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001183 assert(v.isComplexFloat() || v.isComplexInt());
1184 if (v.isComplexFloat()) {
1185 makeComplexFloat();
1186 FloatReal = v.getComplexFloatReal();
1187 FloatImag = v.getComplexFloatImag();
1188 } else {
1189 makeComplexInt();
1190 IntReal = v.getComplexIntReal();
1191 IntImag = v.getComplexIntImag();
1192 }
1193 }
John McCall93d91dc2010-05-07 17:22:02 +00001194 };
John McCall45d55e42010-05-07 21:00:08 +00001195
1196 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001197 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001198 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001199 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001200 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001201 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001202 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001203
Richard Smithce40ad62011-11-12 22:28:03 +00001204 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001205 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001206 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001207 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001208 SubobjectDesignator &getLValueDesignator() { return Designator; }
1209 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001210 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001211
Richard Smith2e312c82012-03-03 22:46:17 +00001212 void moveInto(APValue &V) const {
1213 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001214 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1215 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001216 else {
1217 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Daniel Jasperffdee092017-05-02 19:21:42 +00001218 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1219 "Unsized array with a valid base?");
Richard Smith2e312c82012-03-03 22:46:17 +00001220 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001221 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001222 }
John McCall45d55e42010-05-07 21:00:08 +00001223 }
Richard Smith2e312c82012-03-03 22:46:17 +00001224 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001225 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001226 Base = V.getLValueBase();
1227 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001228 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001229 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001230 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001231 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001232 }
1233
Tim Northover01503332017-05-26 02:16:00 +00001234 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
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;
Tim Northover01503332017-05-26 02:16:00 +00001245 Offset = CharUnits::fromQuantity(0);
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));
Tim Northover01503332017-05-26 02:16:00 +00001249 IsNullPtr = false;
1250 }
1251
1252 void setNull(QualType PointerTy, uint64_t TargetVal) {
1253 Base = (Expr *)nullptr;
1254 Offset = CharUnits::fromQuantity(TargetVal);
1255 InvalidBase = false;
1256 CallIndex = 0;
1257 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1258 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001259 }
1260
George Burgess IV3a03fab2015-09-04 21:28:13 +00001261 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1262 set(B, I, true);
1263 }
1264
Richard Smitha8105bc2012-01-06 16:39:00 +00001265 // Check that this LValue is not based on a null pointer. If it is, produce
1266 // a diagnostic and mark the designator as invalid.
1267 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1268 CheckSubobjectKind CSK) {
1269 if (Designator.Invalid)
1270 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001271 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001272 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001273 << CSK;
1274 Designator.setInvalid();
1275 return false;
1276 }
1277 return true;
1278 }
1279
1280 // Check this LValue refers to an object. If not, set the designator to be
1281 // invalid and emit a diagnostic.
1282 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001283 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001284 Designator.checkSubobject(Info, E, CSK);
1285 }
1286
1287 void addDecl(EvalInfo &Info, const Expr *E,
1288 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001289 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1290 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001291 }
Daniel Jasperffdee092017-05-02 19:21:42 +00001292 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1293 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1294 assert(isBaseAnAllocSizeCall(Base) &&
1295 "Only alloc_size bases can have unsized arrays");
1296 Designator.FirstEntryIsAnUnsizedArray = true;
1297 Designator.addUnsizedArrayUnchecked(ElemTy);
George Burgess IVe3763372016-12-22 02:50:20 +00001298 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001299 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001300 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1301 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001302 }
Richard Smith66c96992012-02-18 22:04:06 +00001303 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001304 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1305 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001306 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001307 void clearIsNullPointer() {
1308 IsNullPtr = false;
1309 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001310 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1311 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001312 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1313 // but we're not required to diagnose it and it's valid in C++.)
1314 if (!Index)
1315 return;
1316
1317 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1318 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1319 // offsets.
1320 uint64_t Offset64 = Offset.getQuantity();
1321 uint64_t ElemSize64 = ElementSize.getQuantity();
1322 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1323 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1324
1325 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001326 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001327 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001328 }
1329 void adjustOffset(CharUnits N) {
1330 Offset += N;
1331 if (N.getQuantity())
1332 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001333 }
John McCall45d55e42010-05-07 21:00:08 +00001334 };
Richard Smith027bf112011-11-17 22:56:20 +00001335
1336 struct MemberPtr {
1337 MemberPtr() {}
1338 explicit MemberPtr(const ValueDecl *Decl) :
1339 DeclAndIsDerivedMember(Decl, false), Path() {}
1340
1341 /// The member or (direct or indirect) field referred to by this member
1342 /// pointer, or 0 if this is a null member pointer.
1343 const ValueDecl *getDecl() const {
1344 return DeclAndIsDerivedMember.getPointer();
1345 }
1346 /// Is this actually a member of some type derived from the relevant class?
1347 bool isDerivedMember() const {
1348 return DeclAndIsDerivedMember.getInt();
1349 }
1350 /// Get the class which the declaration actually lives in.
1351 const CXXRecordDecl *getContainingRecord() const {
1352 return cast<CXXRecordDecl>(
1353 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1354 }
1355
Richard Smith2e312c82012-03-03 22:46:17 +00001356 void moveInto(APValue &V) const {
1357 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001358 }
Richard Smith2e312c82012-03-03 22:46:17 +00001359 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001360 assert(V.isMemberPointer());
1361 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1362 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1363 Path.clear();
1364 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1365 Path.insert(Path.end(), P.begin(), P.end());
1366 }
1367
1368 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1369 /// whether the member is a member of some class derived from the class type
1370 /// of the member pointer.
1371 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1372 /// Path - The path of base/derived classes from the member declaration's
1373 /// class (exclusive) to the class type of the member pointer (inclusive).
1374 SmallVector<const CXXRecordDecl*, 4> Path;
1375
1376 /// Perform a cast towards the class of the Decl (either up or down the
1377 /// hierarchy).
1378 bool castBack(const CXXRecordDecl *Class) {
1379 assert(!Path.empty());
1380 const CXXRecordDecl *Expected;
1381 if (Path.size() >= 2)
1382 Expected = Path[Path.size() - 2];
1383 else
1384 Expected = getContainingRecord();
1385 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1386 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1387 // if B does not contain the original member and is not a base or
1388 // derived class of the class containing the original member, the result
1389 // of the cast is undefined.
1390 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1391 // (D::*). We consider that to be a language defect.
1392 return false;
1393 }
1394 Path.pop_back();
1395 return true;
1396 }
1397 /// Perform a base-to-derived member pointer cast.
1398 bool castToDerived(const CXXRecordDecl *Derived) {
1399 if (!getDecl())
1400 return true;
1401 if (!isDerivedMember()) {
1402 Path.push_back(Derived);
1403 return true;
1404 }
1405 if (!castBack(Derived))
1406 return false;
1407 if (Path.empty())
1408 DeclAndIsDerivedMember.setInt(false);
1409 return true;
1410 }
1411 /// Perform a derived-to-base member pointer cast.
1412 bool castToBase(const CXXRecordDecl *Base) {
1413 if (!getDecl())
1414 return true;
1415 if (Path.empty())
1416 DeclAndIsDerivedMember.setInt(true);
1417 if (isDerivedMember()) {
1418 Path.push_back(Base);
1419 return true;
1420 }
1421 return castBack(Base);
1422 }
1423 };
Richard Smith357362d2011-12-13 06:39:58 +00001424
Richard Smith7bb00672012-02-01 01:42:44 +00001425 /// Compare two member pointers, which are assumed to be of the same type.
1426 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1427 if (!LHS.getDecl() || !RHS.getDecl())
1428 return !LHS.getDecl() && !RHS.getDecl();
1429 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1430 return false;
1431 return LHS.Path == RHS.Path;
1432 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001433}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001434
Richard Smith2e312c82012-03-03 22:46:17 +00001435static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001436static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1437 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001438 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001439static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1440 bool InvalidBaseOK = false);
1441static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1442 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001443static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1444 EvalInfo &Info);
1445static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001446static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001447static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001448 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001449static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001450static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001451static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1452 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001453static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001454
1455//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001456// Misc utilities
1457//===----------------------------------------------------------------------===//
1458
Richard Smithd6cc1982017-01-31 02:23:02 +00001459/// Negate an APSInt in place, converting it to a signed form if necessary, and
1460/// preserving its value (by extending by up to one bit as needed).
1461static void negateAsSigned(APSInt &Int) {
1462 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1463 Int = Int.extend(Int.getBitWidth() + 1);
1464 Int.setIsSigned(true);
1465 }
1466 Int = -Int;
1467}
1468
Richard Smith84401042013-06-03 05:03:02 +00001469/// Produce a string describing the given constexpr call.
1470static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1471 unsigned ArgIndex = 0;
1472 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1473 !isa<CXXConstructorDecl>(Frame->Callee) &&
1474 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1475
1476 if (!IsMemberCall)
1477 Out << *Frame->Callee << '(';
1478
1479 if (Frame->This && IsMemberCall) {
1480 APValue Val;
1481 Frame->This->moveInto(Val);
1482 Val.printPretty(Out, Frame->Info.Ctx,
1483 Frame->This->Designator.MostDerivedType);
1484 // FIXME: Add parens around Val if needed.
1485 Out << "->" << *Frame->Callee << '(';
1486 IsMemberCall = false;
1487 }
1488
1489 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1490 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1491 if (ArgIndex > (unsigned)IsMemberCall)
1492 Out << ", ";
1493
1494 const ParmVarDecl *Param = *I;
1495 const APValue &Arg = Frame->Arguments[ArgIndex];
1496 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1497
1498 if (ArgIndex == 0 && IsMemberCall)
1499 Out << "->" << *Frame->Callee << '(';
1500 }
1501
1502 Out << ')';
1503}
1504
Richard Smithd9f663b2013-04-22 15:31:51 +00001505/// Evaluate an expression to see if it had side-effects, and discard its
1506/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001507/// \return \c true if the caller should keep evaluating.
1508static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001509 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001510 if (!Evaluate(Scratch, Info, E))
1511 // We don't need the value, but we might have skipped a side effect here.
1512 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001513 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001514}
1515
Richard Smithd62306a2011-11-10 06:34:14 +00001516/// Should this call expression be treated as a string literal?
1517static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001518 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001519 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1520 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1521}
1522
Richard Smithce40ad62011-11-12 22:28:03 +00001523static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001524 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1525 // constant expression of pointer type that evaluates to...
1526
1527 // ... a null pointer value, or a prvalue core constant expression of type
1528 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001529 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001530
Richard Smithce40ad62011-11-12 22:28:03 +00001531 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1532 // ... the address of an object with static storage duration,
1533 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1534 return VD->hasGlobalStorage();
1535 // ... the address of a function,
1536 return isa<FunctionDecl>(D);
1537 }
1538
1539 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001540 switch (E->getStmtClass()) {
1541 default:
1542 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001543 case Expr::CompoundLiteralExprClass: {
1544 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1545 return CLE->isFileScope() && CLE->isLValue();
1546 }
Richard Smithe6c01442013-06-05 00:46:14 +00001547 case Expr::MaterializeTemporaryExprClass:
1548 // A materialized temporary might have been lifetime-extended to static
1549 // storage duration.
1550 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001551 // A string literal has static storage duration.
1552 case Expr::StringLiteralClass:
1553 case Expr::PredefinedExprClass:
1554 case Expr::ObjCStringLiteralClass:
1555 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001556 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001557 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001558 return true;
1559 case Expr::CallExprClass:
1560 return IsStringLiteralCall(cast<CallExpr>(E));
1561 // For GCC compatibility, &&label has static storage duration.
1562 case Expr::AddrLabelExprClass:
1563 return true;
1564 // A Block literal expression may be used as the initialization value for
1565 // Block variables at global or local static scope.
1566 case Expr::BlockExprClass:
1567 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001568 case Expr::ImplicitValueInitExprClass:
1569 // FIXME:
1570 // We can never form an lvalue with an implicit value initialization as its
1571 // base through expression evaluation, so these only appear in one case: the
1572 // implicit variable declaration we invent when checking whether a constexpr
1573 // constructor can produce a constant expression. We must assume that such
1574 // an expression might be a global lvalue.
1575 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001576 }
John McCall95007602010-05-10 23:27:23 +00001577}
1578
Richard Smithb228a862012-02-15 02:18:13 +00001579static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1580 assert(Base && "no location for a null lvalue");
1581 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1582 if (VD)
1583 Info.Note(VD->getLocation(), diag::note_declared_at);
1584 else
Ted Kremenek28831752012-08-23 20:46:57 +00001585 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001586 diag::note_constexpr_temporary_here);
1587}
1588
Richard Smith80815602011-11-07 05:07:52 +00001589/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001590/// value for an address or reference constant expression. Return true if we
1591/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001592static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1593 QualType Type, const LValue &LVal) {
1594 bool IsReferenceType = Type->isReferenceType();
1595
Richard Smith357362d2011-12-13 06:39:58 +00001596 APValue::LValueBase Base = LVal.getLValueBase();
1597 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1598
Richard Smith0dea49e2012-02-18 04:58:18 +00001599 // Check that the object is a global. Note that the fake 'this' object we
1600 // manufacture when checking potential constant expressions is conservatively
1601 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001602 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001603 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001604 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001605 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001606 << IsReferenceType << !Designator.Entries.empty()
1607 << !!VD << VD;
1608 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001609 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001610 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001611 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001612 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001613 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001614 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001615 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001616 LVal.getLValueCallIndex() == 0) &&
1617 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001618
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001619 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1620 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001621 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001622 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001623 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001624
Hans Wennborg82dd8772014-06-25 22:19:48 +00001625 // A dllimport variable never acts like a constant.
1626 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001627 return false;
1628 }
1629 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1630 // __declspec(dllimport) must be handled very carefully:
1631 // We must never initialize an expression with the thunk in C++.
1632 // Doing otherwise would allow the same id-expression to yield
1633 // different addresses for the same function in different translation
1634 // units. However, this means that we must dynamically initialize the
1635 // expression with the contents of the import address table at runtime.
1636 //
1637 // The C language has no notion of ODR; furthermore, it has no notion of
1638 // dynamic initialization. This means that we are permitted to
1639 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001640 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001641 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001642 }
1643 }
1644
Richard Smitha8105bc2012-01-06 16:39:00 +00001645 // Allow address constant expressions to be past-the-end pointers. This is
1646 // an extension: the standard requires them to point to an object.
1647 if (!IsReferenceType)
1648 return true;
1649
1650 // A reference constant expression must refer to an object.
1651 if (!Base) {
1652 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001653 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001654 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001655 }
1656
Richard Smith357362d2011-12-13 06:39:58 +00001657 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001658 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001659 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001660 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001661 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001662 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001663 }
1664
Richard Smith80815602011-11-07 05:07:52 +00001665 return true;
1666}
1667
Reid Klecknercd016d82017-07-07 22:04:29 +00001668/// Member pointers are constant expressions unless they point to a
1669/// non-virtual dllimport member function.
1670static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1671 SourceLocation Loc,
1672 QualType Type,
1673 const APValue &Value) {
1674 const ValueDecl *Member = Value.getMemberPointerDecl();
1675 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1676 if (!FD)
1677 return true;
1678 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1679}
1680
Richard Smithfddd3842011-12-30 21:15:51 +00001681/// Check that this core constant expression is of literal type, and if not,
1682/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001683static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001684 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001685 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001686 return true;
1687
Richard Smith7525ff62013-05-09 07:14:00 +00001688 // C++1y: A constant initializer for an object o [...] may also invoke
1689 // constexpr constructors for o and its subobjects even if those objects
1690 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001691 //
1692 // C++11 missed this detail for aggregates, so classes like this:
1693 // struct foo_t { union { int i; volatile int j; } u; };
1694 // are not (obviously) initializable like so:
1695 // __attribute__((__require_constant_initialization__))
1696 // static const foo_t x = {{0}};
1697 // because "i" is a subobject with non-literal initialization (due to the
1698 // volatile member of the union). See:
1699 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1700 // Therefore, we use the C++1y behavior.
1701 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001702 return true;
1703
Richard Smithfddd3842011-12-30 21:15:51 +00001704 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001705 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001706 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001707 << E->getType();
1708 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001709 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001710 return false;
1711}
1712
Richard Smith0b0a0b62011-10-29 20:57:55 +00001713/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001714/// constant expression. If not, report an appropriate diagnostic. Does not
1715/// check that the expression is of literal type.
1716static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1717 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001718 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001719 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001720 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001721 return false;
1722 }
1723
Richard Smith77be48a2014-07-31 06:31:19 +00001724 // We allow _Atomic(T) to be initialized from anything that T can be
1725 // initialized from.
1726 if (const AtomicType *AT = Type->getAs<AtomicType>())
1727 Type = AT->getValueType();
1728
Richard Smithb228a862012-02-15 02:18:13 +00001729 // Core issue 1454: For a literal constant expression of array or class type,
1730 // each subobject of its value shall have been initialized by a constant
1731 // expression.
1732 if (Value.isArray()) {
1733 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1734 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1735 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1736 Value.getArrayInitializedElt(I)))
1737 return false;
1738 }
1739 if (!Value.hasArrayFiller())
1740 return true;
1741 return CheckConstantExpression(Info, DiagLoc, EltTy,
1742 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001743 }
Richard Smithb228a862012-02-15 02:18:13 +00001744 if (Value.isUnion() && Value.getUnionField()) {
1745 return CheckConstantExpression(Info, DiagLoc,
1746 Value.getUnionField()->getType(),
1747 Value.getUnionValue());
1748 }
1749 if (Value.isStruct()) {
1750 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1751 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1752 unsigned BaseIndex = 0;
1753 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1754 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1755 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1756 Value.getStructBase(BaseIndex)))
1757 return false;
1758 }
1759 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001760 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001761 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1762 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001763 return false;
1764 }
1765 }
1766
1767 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001768 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001769 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001770 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1771 }
1772
Reid Klecknercd016d82017-07-07 22:04:29 +00001773 if (Value.isMemberPointer())
1774 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1775
Richard Smithb228a862012-02-15 02:18:13 +00001776 // Everything else is fine.
1777 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001778}
1779
Benjamin Kramer8407df72015-03-09 16:47:52 +00001780static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001781 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001782}
1783
1784static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001785 if (Value.CallIndex)
1786 return false;
1787 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1788 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001789}
1790
Richard Smithcecf1842011-11-01 21:06:14 +00001791static bool IsWeakLValue(const LValue &Value) {
1792 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001793 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001794}
1795
David Majnemerb5116032014-12-09 23:32:34 +00001796static bool isZeroSized(const LValue &Value) {
1797 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001798 if (Decl && isa<VarDecl>(Decl)) {
1799 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001800 if (Ty->isArrayType())
1801 return Ty->isIncompleteType() ||
1802 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001803 }
1804 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001805}
1806
Richard Smith2e312c82012-03-03 22:46:17 +00001807static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001808 // A null base expression indicates a null pointer. These are always
1809 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001810 if (!Value.getLValueBase()) {
1811 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001812 return true;
1813 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001814
Richard Smith027bf112011-11-17 22:56:20 +00001815 // We have a non-null base. These are generally known to be true, but if it's
1816 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001817 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001818 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001819 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001820}
1821
Richard Smith2e312c82012-03-03 22:46:17 +00001822static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001823 switch (Val.getKind()) {
1824 case APValue::Uninitialized:
1825 return false;
1826 case APValue::Int:
1827 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001828 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001829 case APValue::Float:
1830 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001831 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001832 case APValue::ComplexInt:
1833 Result = Val.getComplexIntReal().getBoolValue() ||
1834 Val.getComplexIntImag().getBoolValue();
1835 return true;
1836 case APValue::ComplexFloat:
1837 Result = !Val.getComplexFloatReal().isZero() ||
1838 !Val.getComplexFloatImag().isZero();
1839 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001840 case APValue::LValue:
1841 return EvalPointerValueAsBool(Val, Result);
1842 case APValue::MemberPointer:
1843 Result = Val.getMemberPointerDecl();
1844 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001845 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001846 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001847 case APValue::Struct:
1848 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001849 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001850 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001851 }
1852
Richard Smith11562c52011-10-28 17:51:58 +00001853 llvm_unreachable("unknown APValue kind");
1854}
1855
1856static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1857 EvalInfo &Info) {
1858 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001859 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001860 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001861 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001862 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001863}
1864
Richard Smith357362d2011-12-13 06:39:58 +00001865template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001866static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001867 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001868 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001869 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001870 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001871}
1872
1873static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1874 QualType SrcType, const APFloat &Value,
1875 QualType DestType, APSInt &Result) {
1876 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001877 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001878 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001879
Richard Smith357362d2011-12-13 06:39:58 +00001880 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001881 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001882 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1883 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001884 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001885 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001886}
1887
Richard Smith357362d2011-12-13 06:39:58 +00001888static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1889 QualType SrcType, QualType DestType,
1890 APFloat &Result) {
1891 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001892 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001893 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1894 APFloat::rmNearestTiesToEven, &ignored)
1895 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001896 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001897 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001898}
1899
Richard Smith911e1422012-01-30 22:27:01 +00001900static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1901 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001902 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001903 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001904 APSInt Result = Value;
1905 // Figure out if this is a truncate, extend or noop cast.
1906 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001907 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001908 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001909 return Result;
1910}
1911
Richard Smith357362d2011-12-13 06:39:58 +00001912static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1913 QualType SrcType, const APSInt &Value,
1914 QualType DestType, APFloat &Result) {
1915 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1916 if (Result.convertFromAPInt(Value, Value.isSigned(),
1917 APFloat::rmNearestTiesToEven)
1918 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001919 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001920 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001921}
1922
Richard Smith49ca8aa2013-08-06 07:09:20 +00001923static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1924 APValue &Value, const FieldDecl *FD) {
1925 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1926
1927 if (!Value.isInt()) {
1928 // Trying to store a pointer-cast-to-integer into a bitfield.
1929 // FIXME: In this case, we should provide the diagnostic for casting
1930 // a pointer to an integer.
1931 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001932 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001933 return false;
1934 }
1935
1936 APSInt &Int = Value.getInt();
1937 unsigned OldBitWidth = Int.getBitWidth();
1938 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1939 if (NewBitWidth < OldBitWidth)
1940 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1941 return true;
1942}
1943
Eli Friedman803acb32011-12-22 03:51:45 +00001944static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1945 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001946 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001947 if (!Evaluate(SVal, Info, E))
1948 return false;
1949 if (SVal.isInt()) {
1950 Res = SVal.getInt();
1951 return true;
1952 }
1953 if (SVal.isFloat()) {
1954 Res = SVal.getFloat().bitcastToAPInt();
1955 return true;
1956 }
1957 if (SVal.isVector()) {
1958 QualType VecTy = E->getType();
1959 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1960 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1961 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1962 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1963 Res = llvm::APInt::getNullValue(VecSize);
1964 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1965 APValue &Elt = SVal.getVectorElt(i);
1966 llvm::APInt EltAsInt;
1967 if (Elt.isInt()) {
1968 EltAsInt = Elt.getInt();
1969 } else if (Elt.isFloat()) {
1970 EltAsInt = Elt.getFloat().bitcastToAPInt();
1971 } else {
1972 // Don't try to handle vectors of anything other than int or float
1973 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001974 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001975 return false;
1976 }
1977 unsigned BaseEltSize = EltAsInt.getBitWidth();
1978 if (BigEndian)
1979 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1980 else
1981 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1982 }
1983 return true;
1984 }
1985 // Give up if the input isn't an int, float, or vector. For example, we
1986 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001987 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001988 return false;
1989}
1990
Richard Smith43e77732013-05-07 04:50:00 +00001991/// Perform the given integer operation, which is known to need at most BitWidth
1992/// bits, and check for overflow in the original type (if that type was not an
1993/// unsigned type).
1994template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001995static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1996 const APSInt &LHS, const APSInt &RHS,
1997 unsigned BitWidth, Operation Op,
1998 APSInt &Result) {
1999 if (LHS.isUnsigned()) {
2000 Result = Op(LHS, RHS);
2001 return true;
2002 }
Richard Smith43e77732013-05-07 04:50:00 +00002003
2004 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002005 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002006 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002007 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002008 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002009 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002010 << Result.toString(10) << E->getType();
2011 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002012 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002013 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002014 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002015}
2016
2017/// Perform the given binary integer operation.
2018static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2019 BinaryOperatorKind Opcode, APSInt RHS,
2020 APSInt &Result) {
2021 switch (Opcode) {
2022 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002023 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002024 return false;
2025 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002026 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2027 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002028 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002029 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2030 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002031 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002032 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2033 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002034 case BO_And: Result = LHS & RHS; return true;
2035 case BO_Xor: Result = LHS ^ RHS; return true;
2036 case BO_Or: Result = LHS | RHS; return true;
2037 case BO_Div:
2038 case BO_Rem:
2039 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002040 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002041 return false;
2042 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002043 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2044 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2045 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002046 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2047 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002048 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2049 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002050 return true;
2051 case BO_Shl: {
2052 if (Info.getLangOpts().OpenCL)
2053 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2054 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2055 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2056 RHS.isUnsigned());
2057 else if (RHS.isSigned() && RHS.isNegative()) {
2058 // During constant-folding, a negative shift is an opposite shift. Such
2059 // a shift is not a constant expression.
2060 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2061 RHS = -RHS;
2062 goto shift_right;
2063 }
2064 shift_left:
2065 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2066 // the shifted type.
2067 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2068 if (SA != RHS) {
2069 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2070 << RHS << E->getType() << LHS.getBitWidth();
2071 } else if (LHS.isSigned()) {
2072 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2073 // operand, and must not overflow the corresponding unsigned type.
2074 if (LHS.isNegative())
2075 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2076 else if (LHS.countLeadingZeros() < SA)
2077 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2078 }
2079 Result = LHS << SA;
2080 return true;
2081 }
2082 case BO_Shr: {
2083 if (Info.getLangOpts().OpenCL)
2084 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2085 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2086 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2087 RHS.isUnsigned());
2088 else if (RHS.isSigned() && RHS.isNegative()) {
2089 // During constant-folding, a negative shift is an opposite shift. Such a
2090 // shift is not a constant expression.
2091 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2092 RHS = -RHS;
2093 goto shift_left;
2094 }
2095 shift_right:
2096 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2097 // shifted type.
2098 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2099 if (SA != RHS)
2100 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2101 << RHS << E->getType() << LHS.getBitWidth();
2102 Result = LHS >> SA;
2103 return true;
2104 }
2105
2106 case BO_LT: Result = LHS < RHS; return true;
2107 case BO_GT: Result = LHS > RHS; return true;
2108 case BO_LE: Result = LHS <= RHS; return true;
2109 case BO_GE: Result = LHS >= RHS; return true;
2110 case BO_EQ: Result = LHS == RHS; return true;
2111 case BO_NE: Result = LHS != RHS; return true;
2112 }
2113}
2114
Richard Smith861b5b52013-05-07 23:34:45 +00002115/// Perform the given binary floating-point operation, in-place, on LHS.
2116static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2117 APFloat &LHS, BinaryOperatorKind Opcode,
2118 const APFloat &RHS) {
2119 switch (Opcode) {
2120 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002121 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002122 return false;
2123 case BO_Mul:
2124 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2125 break;
2126 case BO_Add:
2127 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2128 break;
2129 case BO_Sub:
2130 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2131 break;
2132 case BO_Div:
2133 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2134 break;
2135 }
2136
Richard Smith0c6124b2015-12-03 01:36:22 +00002137 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002138 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002139 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002140 }
Richard Smith861b5b52013-05-07 23:34:45 +00002141 return true;
2142}
2143
Richard Smitha8105bc2012-01-06 16:39:00 +00002144/// Cast an lvalue referring to a base subobject to a derived class, by
2145/// truncating the lvalue's path to the given length.
2146static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2147 const RecordDecl *TruncatedType,
2148 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002149 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002150
2151 // Check we actually point to a derived class object.
2152 if (TruncatedElements == D.Entries.size())
2153 return true;
2154 assert(TruncatedElements >= D.MostDerivedPathLength &&
2155 "not casting to a derived class");
2156 if (!Result.checkSubobject(Info, E, CSK_Derived))
2157 return false;
2158
2159 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002160 const RecordDecl *RD = TruncatedType;
2161 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002162 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002163 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2164 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002165 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002166 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002167 else
Richard Smithd62306a2011-11-10 06:34:14 +00002168 Result.Offset -= Layout.getBaseClassOffset(Base);
2169 RD = Base;
2170 }
Richard Smith027bf112011-11-17 22:56:20 +00002171 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002172 return true;
2173}
2174
John McCalld7bca762012-05-01 00:38:49 +00002175static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002176 const CXXRecordDecl *Derived,
2177 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002178 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002179 if (!RL) {
2180 if (Derived->isInvalidDecl()) return false;
2181 RL = &Info.Ctx.getASTRecordLayout(Derived);
2182 }
2183
Richard Smithd62306a2011-11-10 06:34:14 +00002184 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002185 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002186 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002187}
2188
Richard Smitha8105bc2012-01-06 16:39:00 +00002189static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002190 const CXXRecordDecl *DerivedDecl,
2191 const CXXBaseSpecifier *Base) {
2192 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2193
John McCalld7bca762012-05-01 00:38:49 +00002194 if (!Base->isVirtual())
2195 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002196
Richard Smitha8105bc2012-01-06 16:39:00 +00002197 SubobjectDesignator &D = Obj.Designator;
2198 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002199 return false;
2200
Richard Smitha8105bc2012-01-06 16:39:00 +00002201 // Extract most-derived object and corresponding type.
2202 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2203 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2204 return false;
2205
2206 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002207 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002208 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2209 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002210 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002211 return true;
2212}
2213
Richard Smith84401042013-06-03 05:03:02 +00002214static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2215 QualType Type, LValue &Result) {
2216 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2217 PathE = E->path_end();
2218 PathI != PathE; ++PathI) {
2219 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2220 *PathI))
2221 return false;
2222 Type = (*PathI)->getType();
2223 }
2224 return true;
2225}
2226
Richard Smithd62306a2011-11-10 06:34:14 +00002227/// Update LVal to refer to the given field, which must be a member of the type
2228/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002229static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002230 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002231 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002232 if (!RL) {
2233 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002234 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002235 }
Richard Smithd62306a2011-11-10 06:34:14 +00002236
2237 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002238 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002239 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002240 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002241}
2242
Richard Smith1b78b3d2012-01-25 22:15:11 +00002243/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002244static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002245 LValue &LVal,
2246 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002247 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002248 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002249 return false;
2250 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002251}
2252
Richard Smithd62306a2011-11-10 06:34:14 +00002253/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002254static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2255 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002256 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2257 // extension.
2258 if (Type->isVoidType() || Type->isFunctionType()) {
2259 Size = CharUnits::One();
2260 return true;
2261 }
2262
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002263 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002264 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002265 return false;
2266 }
2267
Richard Smithd62306a2011-11-10 06:34:14 +00002268 if (!Type->isConstantSizeType()) {
2269 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002270 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002271 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002272 return false;
2273 }
2274
2275 Size = Info.Ctx.getTypeSizeInChars(Type);
2276 return true;
2277}
2278
2279/// Update a pointer value to model pointer arithmetic.
2280/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002281/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002282/// \param LVal - The pointer value to be updated.
2283/// \param EltTy - The pointee type represented by LVal.
2284/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002285static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2286 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002287 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002288 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002289 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002290 return false;
2291
Yaxun Liu402804b2016-12-15 08:09:08 +00002292 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002293 return true;
2294}
2295
Richard Smithd6cc1982017-01-31 02:23:02 +00002296static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2297 LValue &LVal, QualType EltTy,
2298 int64_t Adjustment) {
2299 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2300 APSInt::get(Adjustment));
2301}
2302
Richard Smith66c96992012-02-18 22:04:06 +00002303/// Update an lvalue to refer to a component of a complex number.
2304/// \param Info - Information about the ongoing evaluation.
2305/// \param LVal - The lvalue to be updated.
2306/// \param EltTy - The complex number's component type.
2307/// \param Imag - False for the real component, true for the imaginary.
2308static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2309 LValue &LVal, QualType EltTy,
2310 bool Imag) {
2311 if (Imag) {
2312 CharUnits SizeOfComponent;
2313 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2314 return false;
2315 LVal.Offset += SizeOfComponent;
2316 }
2317 LVal.addComplex(Info, E, EltTy, Imag);
2318 return true;
2319}
2320
Faisal Vali051e3a22017-02-16 04:12:21 +00002321static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2322 QualType Type, const LValue &LVal,
2323 APValue &RVal);
2324
Richard Smith27908702011-10-24 17:54:18 +00002325/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002326///
2327/// \param Info Information about the ongoing evaluation.
2328/// \param E An expression to be used when printing diagnostics.
2329/// \param VD The variable whose initializer should be obtained.
2330/// \param Frame The frame in which the variable was created. Must be null
2331/// if this variable is not local to the evaluation.
2332/// \param Result Filled in with a pointer to the value of the variable.
2333static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2334 const VarDecl *VD, CallStackFrame *Frame,
2335 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002336
Richard Smith254a73d2011-10-28 22:34:42 +00002337 // If this is a parameter to an active constexpr function call, perform
2338 // argument substitution.
2339 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002340 // Assume arguments of a potential constant expression are unknown
2341 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002342 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002343 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002344 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002345 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002346 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002347 }
Richard Smith3229b742013-05-05 21:17:10 +00002348 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002349 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002350 }
Richard Smith27908702011-10-24 17:54:18 +00002351
Richard Smithd9f663b2013-04-22 15:31:51 +00002352 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002353 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002354 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002355 if (!Result) {
2356 // Assume variables referenced within a lambda's call operator that were
2357 // not declared within the call operator are captures and during checking
2358 // of a potential constant expression, assume they are unknown constant
2359 // expressions.
2360 assert(isLambdaCallOperator(Frame->Callee) &&
2361 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2362 "missing value for local variable");
2363 if (Info.checkingPotentialConstantExpression())
2364 return false;
2365 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002366 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002367 diag::note_unimplemented_constexpr_lambda_feature_ast)
2368 << "captures not currently allowed";
2369 return false;
2370 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002371 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002372 }
2373
Richard Smithd0b4dd62011-12-19 06:19:21 +00002374 // Dig out the initializer, and use the declaration which it's attached to.
2375 const Expr *Init = VD->getAnyInitializer(VD);
2376 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002377 // If we're checking a potential constant expression, the variable could be
2378 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002379 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002380 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002381 return false;
2382 }
2383
Richard Smithd62306a2011-11-10 06:34:14 +00002384 // If we're currently evaluating the initializer of this declaration, use that
2385 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002386 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002387 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002388 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002389 }
2390
Richard Smithcecf1842011-11-01 21:06:14 +00002391 // Never evaluate the initializer of a weak variable. We can't be sure that
2392 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002393 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002394 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002395 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002396 }
Richard Smithcecf1842011-11-01 21:06:14 +00002397
Richard Smithd0b4dd62011-12-19 06:19:21 +00002398 // Check that we can fold the initializer. In C++, we will have already done
2399 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002400 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002401 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002402 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002403 Notes.size() + 1) << VD;
2404 Info.Note(VD->getLocation(), diag::note_declared_at);
2405 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002406 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002407 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002408 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002409 Notes.size() + 1) << VD;
2410 Info.Note(VD->getLocation(), diag::note_declared_at);
2411 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002412 }
Richard Smith27908702011-10-24 17:54:18 +00002413
Richard Smith3229b742013-05-05 21:17:10 +00002414 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002415 return true;
Richard Smith27908702011-10-24 17:54:18 +00002416}
2417
Richard Smith11562c52011-10-28 17:51:58 +00002418static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002419 Qualifiers Quals = T.getQualifiers();
2420 return Quals.hasConst() && !Quals.hasVolatile();
2421}
2422
Richard Smithe97cbd72011-11-11 04:05:33 +00002423/// Get the base index of the given base class within an APValue representing
2424/// the given derived class.
2425static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2426 const CXXRecordDecl *Base) {
2427 Base = Base->getCanonicalDecl();
2428 unsigned Index = 0;
2429 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2430 E = Derived->bases_end(); I != E; ++I, ++Index) {
2431 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2432 return Index;
2433 }
2434
2435 llvm_unreachable("base class missing from derived class's bases list");
2436}
2437
Richard Smith3da88fa2013-04-26 14:36:30 +00002438/// Extract the value of a character from a string literal.
2439static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2440 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002441 // FIXME: Support MakeStringConstant
2442 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2443 std::string Str;
2444 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2445 assert(Index <= Str.size() && "Index too large");
2446 return APSInt::getUnsigned(Str.c_str()[Index]);
2447 }
2448
Alexey Bataevec474782014-10-09 08:45:04 +00002449 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2450 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002451 const StringLiteral *S = cast<StringLiteral>(Lit);
2452 const ConstantArrayType *CAT =
2453 Info.Ctx.getAsConstantArrayType(S->getType());
2454 assert(CAT && "string literal isn't an array");
2455 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002456 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002457
2458 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002459 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002460 if (Index < S->getLength())
2461 Value = S->getCodeUnit(Index);
2462 return Value;
2463}
2464
Richard Smith3da88fa2013-04-26 14:36:30 +00002465// Expand a string literal into an array of characters.
2466static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2467 APValue &Result) {
2468 const StringLiteral *S = cast<StringLiteral>(Lit);
2469 const ConstantArrayType *CAT =
2470 Info.Ctx.getAsConstantArrayType(S->getType());
2471 assert(CAT && "string literal isn't an array");
2472 QualType CharType = CAT->getElementType();
2473 assert(CharType->isIntegerType() && "unexpected character type");
2474
2475 unsigned Elts = CAT->getSize().getZExtValue();
2476 Result = APValue(APValue::UninitArray(),
2477 std::min(S->getLength(), Elts), Elts);
2478 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2479 CharType->isUnsignedIntegerType());
2480 if (Result.hasArrayFiller())
2481 Result.getArrayFiller() = APValue(Value);
2482 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2483 Value = S->getCodeUnit(I);
2484 Result.getArrayInitializedElt(I) = APValue(Value);
2485 }
2486}
2487
2488// Expand an array so that it has more than Index filled elements.
2489static void expandArray(APValue &Array, unsigned Index) {
2490 unsigned Size = Array.getArraySize();
2491 assert(Index < Size);
2492
2493 // Always at least double the number of elements for which we store a value.
2494 unsigned OldElts = Array.getArrayInitializedElts();
2495 unsigned NewElts = std::max(Index+1, OldElts * 2);
2496 NewElts = std::min(Size, std::max(NewElts, 8u));
2497
2498 // Copy the data across.
2499 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2500 for (unsigned I = 0; I != OldElts; ++I)
2501 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2502 for (unsigned I = OldElts; I != NewElts; ++I)
2503 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2504 if (NewValue.hasArrayFiller())
2505 NewValue.getArrayFiller() = Array.getArrayFiller();
2506 Array.swap(NewValue);
2507}
2508
Richard Smithb01fe402014-09-16 01:24:02 +00002509/// Determine whether a type would actually be read by an lvalue-to-rvalue
2510/// conversion. If it's of class type, we may assume that the copy operation
2511/// is trivial. Note that this is never true for a union type with fields
2512/// (because the copy always "reads" the active member) and always true for
2513/// a non-class type.
2514static bool isReadByLvalueToRvalueConversion(QualType T) {
2515 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2516 if (!RD || (RD->isUnion() && !RD->field_empty()))
2517 return true;
2518 if (RD->isEmpty())
2519 return false;
2520
2521 for (auto *Field : RD->fields())
2522 if (isReadByLvalueToRvalueConversion(Field->getType()))
2523 return true;
2524
2525 for (auto &BaseSpec : RD->bases())
2526 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2527 return true;
2528
2529 return false;
2530}
2531
2532/// Diagnose an attempt to read from any unreadable field within the specified
2533/// type, which might be a class type.
2534static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2535 QualType T) {
2536 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2537 if (!RD)
2538 return false;
2539
2540 if (!RD->hasMutableFields())
2541 return false;
2542
2543 for (auto *Field : RD->fields()) {
2544 // If we're actually going to read this field in some way, then it can't
2545 // be mutable. If we're in a union, then assigning to a mutable field
2546 // (even an empty one) can change the active member, so that's not OK.
2547 // FIXME: Add core issue number for the union case.
2548 if (Field->isMutable() &&
2549 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002550 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002551 Info.Note(Field->getLocation(), diag::note_declared_at);
2552 return true;
2553 }
2554
2555 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2556 return true;
2557 }
2558
2559 for (auto &BaseSpec : RD->bases())
2560 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2561 return true;
2562
2563 // All mutable fields were empty, and thus not actually read.
2564 return false;
2565}
2566
Richard Smith861b5b52013-05-07 23:34:45 +00002567/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002568enum AccessKinds {
2569 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002570 AK_Assign,
2571 AK_Increment,
2572 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002573};
2574
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002575namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002576/// A handle to a complete object (an object that is not a subobject of
2577/// another object).
2578struct CompleteObject {
2579 /// The value of the complete object.
2580 APValue *Value;
2581 /// The type of the complete object.
2582 QualType Type;
2583
Craig Topper36250ad2014-05-12 05:36:57 +00002584 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002585 CompleteObject(APValue *Value, QualType Type)
2586 : Value(Value), Type(Type) {
2587 assert(Value && "missing value for complete object");
2588 }
2589
Aaron Ballman67347662015-02-15 22:00:28 +00002590 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002591};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002592} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002593
Richard Smith3da88fa2013-04-26 14:36:30 +00002594/// Find the designated sub-object of an rvalue.
2595template<typename SubobjectHandler>
2596typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002597findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002598 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002599 if (Sub.Invalid)
2600 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002601 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002602 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002603 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002604 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002605 << handler.AccessKind;
2606 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002607 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002608 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002609 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002610
Richard Smith3229b742013-05-05 21:17:10 +00002611 APValue *O = Obj.Value;
2612 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002613 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002614
Richard Smithd62306a2011-11-10 06:34:14 +00002615 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002616 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2617 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002618 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002619 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002620 return handler.failed();
2621 }
2622
Richard Smith49ca8aa2013-08-06 07:09:20 +00002623 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002624 // If we are reading an object of class type, there may still be more
2625 // things we need to check: if there are any mutable subobjects, we
2626 // cannot perform this read. (This only happens when performing a trivial
2627 // copy or assignment.)
2628 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2629 diagnoseUnreadableFields(Info, E, ObjType))
2630 return handler.failed();
2631
Richard Smith49ca8aa2013-08-06 07:09:20 +00002632 if (!handler.found(*O, ObjType))
2633 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002634
Richard Smith49ca8aa2013-08-06 07:09:20 +00002635 // If we modified a bit-field, truncate it to the right width.
2636 if (handler.AccessKind != AK_Read &&
2637 LastField && LastField->isBitField() &&
2638 !truncateBitfieldValue(Info, E, *O, LastField))
2639 return false;
2640
2641 return true;
2642 }
2643
Craig Topper36250ad2014-05-12 05:36:57 +00002644 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002645 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002646 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002647 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002648 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002649 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002650 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002651 // Note, it should not be possible to form a pointer with a valid
2652 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002653 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002654 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002655 << handler.AccessKind;
2656 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002657 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002658 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002659 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002660
2661 ObjType = CAT->getElementType();
2662
Richard Smith14a94132012-02-17 03:35:37 +00002663 // An array object is represented as either an Array APValue or as an
2664 // LValue which refers to a string literal.
2665 if (O->isLValue()) {
2666 assert(I == N - 1 && "extracting subobject of character?");
2667 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002668 if (handler.AccessKind != AK_Read)
2669 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2670 *O);
2671 else
2672 return handler.foundString(*O, ObjType, Index);
2673 }
2674
2675 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002676 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002677 else if (handler.AccessKind != AK_Read) {
2678 expandArray(*O, Index);
2679 O = &O->getArrayInitializedElt(Index);
2680 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002681 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002682 } else if (ObjType->isAnyComplexType()) {
2683 // Next subobject is a complex number.
2684 uint64_t Index = Sub.Entries[I].ArrayIndex;
2685 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002686 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002687 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002688 << handler.AccessKind;
2689 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002690 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002691 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002692 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002693
2694 bool WasConstQualified = ObjType.isConstQualified();
2695 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2696 if (WasConstQualified)
2697 ObjType.addConst();
2698
Richard Smith66c96992012-02-18 22:04:06 +00002699 assert(I == N - 1 && "extracting subobject of scalar?");
2700 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002701 return handler.found(Index ? O->getComplexIntImag()
2702 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002703 } else {
2704 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002705 return handler.found(Index ? O->getComplexFloatImag()
2706 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002707 }
Richard Smithd62306a2011-11-10 06:34:14 +00002708 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002709 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002710 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002711 << Field;
2712 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002713 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002714 }
2715
Richard Smithd62306a2011-11-10 06:34:14 +00002716 // Next subobject is a class, struct or union field.
2717 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2718 if (RD->isUnion()) {
2719 const FieldDecl *UnionField = O->getUnionField();
2720 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002721 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002722 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002723 << handler.AccessKind << Field << !UnionField << UnionField;
2724 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002725 }
Richard Smithd62306a2011-11-10 06:34:14 +00002726 O = &O->getUnionValue();
2727 } else
2728 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002729
2730 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002731 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002732 if (WasConstQualified && !Field->isMutable())
2733 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002734
2735 if (ObjType.isVolatileQualified()) {
2736 if (Info.getLangOpts().CPlusPlus) {
2737 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002738 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002739 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002740 Info.Note(Field->getLocation(), diag::note_declared_at);
2741 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002742 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002743 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002744 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002745 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002746
2747 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002748 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002749 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002750 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2751 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2752 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002753
2754 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002755 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002756 if (WasConstQualified)
2757 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002758 }
2759 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002760}
2761
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002762namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002763struct ExtractSubobjectHandler {
2764 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002765 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002766
2767 static const AccessKinds AccessKind = AK_Read;
2768
2769 typedef bool result_type;
2770 bool failed() { return false; }
2771 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002772 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002773 return true;
2774 }
2775 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002776 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002777 return true;
2778 }
2779 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002780 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002781 return true;
2782 }
2783 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002784 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002785 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2786 return true;
2787 }
2788};
Richard Smith3229b742013-05-05 21:17:10 +00002789} // end anonymous namespace
2790
Richard Smith3da88fa2013-04-26 14:36:30 +00002791const AccessKinds ExtractSubobjectHandler::AccessKind;
2792
2793/// Extract the designated sub-object of an rvalue.
2794static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002795 const CompleteObject &Obj,
2796 const SubobjectDesignator &Sub,
2797 APValue &Result) {
2798 ExtractSubobjectHandler Handler = { Info, Result };
2799 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002800}
2801
Richard Smith3229b742013-05-05 21:17:10 +00002802namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002803struct ModifySubobjectHandler {
2804 EvalInfo &Info;
2805 APValue &NewVal;
2806 const Expr *E;
2807
2808 typedef bool result_type;
2809 static const AccessKinds AccessKind = AK_Assign;
2810
2811 bool checkConst(QualType QT) {
2812 // Assigning to a const object has undefined behavior.
2813 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002814 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002815 return false;
2816 }
2817 return true;
2818 }
2819
2820 bool failed() { return false; }
2821 bool found(APValue &Subobj, QualType SubobjType) {
2822 if (!checkConst(SubobjType))
2823 return false;
2824 // We've been given ownership of NewVal, so just swap it in.
2825 Subobj.swap(NewVal);
2826 return true;
2827 }
2828 bool found(APSInt &Value, QualType SubobjType) {
2829 if (!checkConst(SubobjType))
2830 return false;
2831 if (!NewVal.isInt()) {
2832 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002833 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002834 return false;
2835 }
2836 Value = NewVal.getInt();
2837 return true;
2838 }
2839 bool found(APFloat &Value, QualType SubobjType) {
2840 if (!checkConst(SubobjType))
2841 return false;
2842 Value = NewVal.getFloat();
2843 return true;
2844 }
2845 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2846 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2847 }
2848};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002849} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002850
Richard Smith3229b742013-05-05 21:17:10 +00002851const AccessKinds ModifySubobjectHandler::AccessKind;
2852
Richard Smith3da88fa2013-04-26 14:36:30 +00002853/// Update the designated sub-object of an rvalue to the given value.
2854static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002855 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002856 const SubobjectDesignator &Sub,
2857 APValue &NewVal) {
2858 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002859 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002860}
2861
Richard Smith84f6dcf2012-02-02 01:16:57 +00002862/// Find the position where two subobject designators diverge, or equivalently
2863/// the length of the common initial subsequence.
2864static unsigned FindDesignatorMismatch(QualType ObjType,
2865 const SubobjectDesignator &A,
2866 const SubobjectDesignator &B,
2867 bool &WasArrayIndex) {
2868 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2869 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002870 if (!ObjType.isNull() &&
2871 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002872 // Next subobject is an array element.
2873 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2874 WasArrayIndex = true;
2875 return I;
2876 }
Richard Smith66c96992012-02-18 22:04:06 +00002877 if (ObjType->isAnyComplexType())
2878 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2879 else
2880 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002881 } else {
2882 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2883 WasArrayIndex = false;
2884 return I;
2885 }
2886 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2887 // Next subobject is a field.
2888 ObjType = FD->getType();
2889 else
2890 // Next subobject is a base class.
2891 ObjType = QualType();
2892 }
2893 }
2894 WasArrayIndex = false;
2895 return I;
2896}
2897
2898/// Determine whether the given subobject designators refer to elements of the
2899/// same array object.
2900static bool AreElementsOfSameArray(QualType ObjType,
2901 const SubobjectDesignator &A,
2902 const SubobjectDesignator &B) {
2903 if (A.Entries.size() != B.Entries.size())
2904 return false;
2905
George Burgess IVa51c4072015-10-16 01:49:01 +00002906 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002907 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2908 // A is a subobject of the array element.
2909 return false;
2910
2911 // If A (and B) designates an array element, the last entry will be the array
2912 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2913 // of length 1' case, and the entire path must match.
2914 bool WasArrayIndex;
2915 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2916 return CommonLength >= A.Entries.size() - IsArray;
2917}
2918
Richard Smith3229b742013-05-05 21:17:10 +00002919/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002920static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2921 AccessKinds AK, const LValue &LVal,
2922 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002923 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002924 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002925 return CompleteObject();
2926 }
2927
Craig Topper36250ad2014-05-12 05:36:57 +00002928 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002929 if (LVal.CallIndex) {
2930 Frame = Info.getCallFrame(LVal.CallIndex);
2931 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002932 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002933 << AK << LVal.Base.is<const ValueDecl*>();
2934 NoteLValueLocation(Info, LVal.Base);
2935 return CompleteObject();
2936 }
Richard Smith3229b742013-05-05 21:17:10 +00002937 }
2938
2939 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2940 // is not a constant expression (even if the object is non-volatile). We also
2941 // apply this rule to C++98, in order to conform to the expected 'volatile'
2942 // semantics.
2943 if (LValType.isVolatileQualified()) {
2944 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002945 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002946 << AK << LValType;
2947 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002948 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002949 return CompleteObject();
2950 }
2951
2952 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002953 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002954 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002955
2956 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2957 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2958 // In C++11, constexpr, non-volatile variables initialized with constant
2959 // expressions are constant expressions too. Inside constexpr functions,
2960 // parameters are constant expressions even if they're non-const.
2961 // In C++1y, objects local to a constant expression (those with a Frame) are
2962 // both readable and writable inside constant expressions.
2963 // In C, such things can also be folded, although they are not ICEs.
2964 const VarDecl *VD = dyn_cast<VarDecl>(D);
2965 if (VD) {
2966 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2967 VD = VDef;
2968 }
2969 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002970 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002971 return CompleteObject();
2972 }
2973
2974 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002975 if (BaseType.isVolatileQualified()) {
2976 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002977 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002978 << AK << 1 << VD;
2979 Info.Note(VD->getLocation(), diag::note_declared_at);
2980 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002981 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002982 }
2983 return CompleteObject();
2984 }
2985
2986 // Unless we're looking at a local variable or argument in a constexpr call,
2987 // the variable we're reading must be const.
2988 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002989 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002990 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2991 // OK, we can read and modify an object if we're in the process of
2992 // evaluating its initializer, because its lifetime began in this
2993 // evaluation.
2994 } else if (AK != AK_Read) {
2995 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002996 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002997 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00002998 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002999 // OK, we can read this variable.
3000 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003001 // In OpenCL if a variable is in constant address space it is a const value.
3002 if (!(BaseType.isConstQualified() ||
3003 (Info.getLangOpts().OpenCL &&
3004 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003005 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003006 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003007 Info.Note(VD->getLocation(), diag::note_declared_at);
3008 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003009 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003010 }
3011 return CompleteObject();
3012 }
3013 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3014 // We support folding of const floating-point types, in order to make
3015 // static const data members of such types (supported as an extension)
3016 // more useful.
3017 if (Info.getLangOpts().CPlusPlus11) {
3018 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3019 Info.Note(VD->getLocation(), diag::note_declared_at);
3020 } else {
3021 Info.CCEDiag(E);
3022 }
George Burgess IVb5316982016-12-27 05:33:20 +00003023 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3024 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3025 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003026 } else {
3027 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003028 if (Info.checkingPotentialConstantExpression() &&
3029 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3030 // The definition of this variable could be constexpr. We can't
3031 // access it right now, but may be able to in future.
3032 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003033 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003034 Info.Note(VD->getLocation(), diag::note_declared_at);
3035 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003036 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003037 }
3038 return CompleteObject();
3039 }
3040 }
3041
3042 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3043 return CompleteObject();
3044 } else {
3045 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3046
3047 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003048 if (const MaterializeTemporaryExpr *MTE =
3049 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3050 assert(MTE->getStorageDuration() == SD_Static &&
3051 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003052
Richard Smithe6c01442013-06-05 00:46:14 +00003053 // Per C++1y [expr.const]p2:
3054 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3055 // - a [...] glvalue of integral or enumeration type that refers to
3056 // a non-volatile const object [...]
3057 // [...]
3058 // - a [...] glvalue of literal type that refers to a non-volatile
3059 // object whose lifetime began within the evaluation of e.
3060 //
3061 // C++11 misses the 'began within the evaluation of e' check and
3062 // instead allows all temporaries, including things like:
3063 // int &&r = 1;
3064 // int x = ++r;
3065 // constexpr int k = r;
3066 // Therefore we use the C++1y rules in C++11 too.
3067 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3068 const ValueDecl *ED = MTE->getExtendingDecl();
3069 if (!(BaseType.isConstQualified() &&
3070 BaseType->isIntegralOrEnumerationType()) &&
3071 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003072 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003073 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3074 return CompleteObject();
3075 }
3076
3077 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3078 assert(BaseVal && "got reference to unevaluated temporary");
3079 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003080 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003081 return CompleteObject();
3082 }
3083 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003084 BaseVal = Frame->getTemporary(Base);
3085 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003086 }
Richard Smith3229b742013-05-05 21:17:10 +00003087
3088 // Volatile temporary objects cannot be accessed in constant expressions.
3089 if (BaseType.isVolatileQualified()) {
3090 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003091 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003092 << AK << 0;
3093 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3094 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003095 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003096 }
3097 return CompleteObject();
3098 }
3099 }
3100
Richard Smith7525ff62013-05-09 07:14:00 +00003101 // During the construction of an object, it is not yet 'const'.
3102 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3103 // and this doesn't do quite the right thing for const subobjects of the
3104 // object under construction.
3105 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3106 BaseType = Info.Ctx.getCanonicalType(BaseType);
3107 BaseType.removeLocalConst();
3108 }
3109
Richard Smith6d4c6582013-11-05 22:18:15 +00003110 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003111 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003112 //
3113 // FIXME: Not all local state is mutable. Allow local constant subobjects
3114 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003115 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3116 Info.EvalStatus.HasSideEffects) ||
3117 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003118 return CompleteObject();
3119
3120 return CompleteObject(BaseVal, BaseType);
3121}
3122
Richard Smith243ef902013-05-05 23:31:59 +00003123/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3124/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3125/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003126///
3127/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003128/// \param Conv - The expression for which we are performing the conversion.
3129/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003130/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3131/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003132/// \param LVal - The glvalue on which we are attempting to perform this action.
3133/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003134static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003135 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003136 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003137 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003138 return false;
3139
Richard Smith3229b742013-05-05 21:17:10 +00003140 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003141 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003142 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003143 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3144 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3145 // initializer until now for such expressions. Such an expression can't be
3146 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003147 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003148 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003149 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003150 }
Richard Smith3229b742013-05-05 21:17:10 +00003151 APValue Lit;
3152 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3153 return false;
3154 CompleteObject LitObj(&Lit, Base->getType());
3155 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003156 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003157 // We represent a string literal array as an lvalue pointing at the
3158 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003159 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003160 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3161 CompleteObject StrObj(&Str, Base->getType());
3162 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003163 }
Richard Smith11562c52011-10-28 17:51:58 +00003164 }
3165
Richard Smith3229b742013-05-05 21:17:10 +00003166 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3167 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003168}
3169
3170/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003171static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003172 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003173 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003174 return false;
3175
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003176 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003177 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003178 return false;
3179 }
3180
Richard Smith3229b742013-05-05 21:17:10 +00003181 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3182 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003183}
3184
Richard Smith243ef902013-05-05 23:31:59 +00003185static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3186 return T->isSignedIntegerType() &&
3187 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3188}
3189
3190namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003191struct CompoundAssignSubobjectHandler {
3192 EvalInfo &Info;
3193 const Expr *E;
3194 QualType PromotedLHSType;
3195 BinaryOperatorKind Opcode;
3196 const APValue &RHS;
3197
3198 static const AccessKinds AccessKind = AK_Assign;
3199
3200 typedef bool result_type;
3201
3202 bool checkConst(QualType QT) {
3203 // Assigning to a const object has undefined behavior.
3204 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003205 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003206 return false;
3207 }
3208 return true;
3209 }
3210
3211 bool failed() { return false; }
3212 bool found(APValue &Subobj, QualType SubobjType) {
3213 switch (Subobj.getKind()) {
3214 case APValue::Int:
3215 return found(Subobj.getInt(), SubobjType);
3216 case APValue::Float:
3217 return found(Subobj.getFloat(), SubobjType);
3218 case APValue::ComplexInt:
3219 case APValue::ComplexFloat:
3220 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003221 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003222 return false;
3223 case APValue::LValue:
3224 return foundPointer(Subobj, SubobjType);
3225 default:
3226 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003227 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003228 return false;
3229 }
3230 }
3231 bool found(APSInt &Value, QualType SubobjType) {
3232 if (!checkConst(SubobjType))
3233 return false;
3234
3235 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3236 // We don't support compound assignment on integer-cast-to-pointer
3237 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003238 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003239 return false;
3240 }
3241
3242 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3243 SubobjType, Value);
3244 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3245 return false;
3246 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3247 return true;
3248 }
3249 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003250 return checkConst(SubobjType) &&
3251 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3252 Value) &&
3253 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3254 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003255 }
3256 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3257 if (!checkConst(SubobjType))
3258 return false;
3259
3260 QualType PointeeType;
3261 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3262 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003263
3264 if (PointeeType.isNull() || !RHS.isInt() ||
3265 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003266 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003267 return false;
3268 }
3269
Richard Smithd6cc1982017-01-31 02:23:02 +00003270 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003271 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003272 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003273
3274 LValue LVal;
3275 LVal.setFrom(Info.Ctx, Subobj);
3276 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3277 return false;
3278 LVal.moveInto(Subobj);
3279 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003280 }
3281 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3282 llvm_unreachable("shouldn't encounter string elements here");
3283 }
3284};
3285} // end anonymous namespace
3286
3287const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3288
3289/// Perform a compound assignment of LVal <op>= RVal.
3290static bool handleCompoundAssignment(
3291 EvalInfo &Info, const Expr *E,
3292 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3293 BinaryOperatorKind Opcode, const APValue &RVal) {
3294 if (LVal.Designator.Invalid)
3295 return false;
3296
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003297 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003298 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003299 return false;
3300 }
3301
3302 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3303 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3304 RVal };
3305 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3306}
3307
3308namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003309struct IncDecSubobjectHandler {
3310 EvalInfo &Info;
3311 const Expr *E;
3312 AccessKinds AccessKind;
3313 APValue *Old;
3314
3315 typedef bool result_type;
3316
3317 bool checkConst(QualType QT) {
3318 // Assigning to a const object has undefined behavior.
3319 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003320 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003321 return false;
3322 }
3323 return true;
3324 }
3325
3326 bool failed() { return false; }
3327 bool found(APValue &Subobj, QualType SubobjType) {
3328 // Stash the old value. Also clear Old, so we don't clobber it later
3329 // if we're post-incrementing a complex.
3330 if (Old) {
3331 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003332 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003333 }
3334
3335 switch (Subobj.getKind()) {
3336 case APValue::Int:
3337 return found(Subobj.getInt(), SubobjType);
3338 case APValue::Float:
3339 return found(Subobj.getFloat(), SubobjType);
3340 case APValue::ComplexInt:
3341 return found(Subobj.getComplexIntReal(),
3342 SubobjType->castAs<ComplexType>()->getElementType()
3343 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3344 case APValue::ComplexFloat:
3345 return found(Subobj.getComplexFloatReal(),
3346 SubobjType->castAs<ComplexType>()->getElementType()
3347 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3348 case APValue::LValue:
3349 return foundPointer(Subobj, SubobjType);
3350 default:
3351 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003352 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003353 return false;
3354 }
3355 }
3356 bool found(APSInt &Value, QualType SubobjType) {
3357 if (!checkConst(SubobjType))
3358 return false;
3359
3360 if (!SubobjType->isIntegerType()) {
3361 // We don't support increment / decrement on integer-cast-to-pointer
3362 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003363 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003364 return false;
3365 }
3366
3367 if (Old) *Old = APValue(Value);
3368
3369 // bool arithmetic promotes to int, and the conversion back to bool
3370 // doesn't reduce mod 2^n, so special-case it.
3371 if (SubobjType->isBooleanType()) {
3372 if (AccessKind == AK_Increment)
3373 Value = 1;
3374 else
3375 Value = !Value;
3376 return true;
3377 }
3378
3379 bool WasNegative = Value.isNegative();
3380 if (AccessKind == AK_Increment) {
3381 ++Value;
3382
3383 if (!WasNegative && Value.isNegative() &&
3384 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3385 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003386 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003387 }
3388 } else {
3389 --Value;
3390
3391 if (WasNegative && !Value.isNegative() &&
3392 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3393 unsigned BitWidth = Value.getBitWidth();
3394 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3395 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003396 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003397 }
3398 }
3399 return true;
3400 }
3401 bool found(APFloat &Value, QualType SubobjType) {
3402 if (!checkConst(SubobjType))
3403 return false;
3404
3405 if (Old) *Old = APValue(Value);
3406
3407 APFloat One(Value.getSemantics(), 1);
3408 if (AccessKind == AK_Increment)
3409 Value.add(One, APFloat::rmNearestTiesToEven);
3410 else
3411 Value.subtract(One, APFloat::rmNearestTiesToEven);
3412 return true;
3413 }
3414 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3415 if (!checkConst(SubobjType))
3416 return false;
3417
3418 QualType PointeeType;
3419 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3420 PointeeType = PT->getPointeeType();
3421 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003422 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003423 return false;
3424 }
3425
3426 LValue LVal;
3427 LVal.setFrom(Info.Ctx, Subobj);
3428 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3429 AccessKind == AK_Increment ? 1 : -1))
3430 return false;
3431 LVal.moveInto(Subobj);
3432 return true;
3433 }
3434 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3435 llvm_unreachable("shouldn't encounter string elements here");
3436 }
3437};
3438} // end anonymous namespace
3439
3440/// Perform an increment or decrement on LVal.
3441static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3442 QualType LValType, bool IsIncrement, APValue *Old) {
3443 if (LVal.Designator.Invalid)
3444 return false;
3445
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003446 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003447 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003448 return false;
3449 }
3450
3451 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3452 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3453 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3454 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3455}
3456
Richard Smithe97cbd72011-11-11 04:05:33 +00003457/// Build an lvalue for the object argument of a member function call.
3458static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3459 LValue &This) {
3460 if (Object->getType()->isPointerType())
3461 return EvaluatePointer(Object, This, Info);
3462
3463 if (Object->isGLValue())
3464 return EvaluateLValue(Object, This, Info);
3465
Richard Smithd9f663b2013-04-22 15:31:51 +00003466 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003467 return EvaluateTemporary(Object, This, Info);
3468
Faisal Valie690b7a2016-07-02 22:34:24 +00003469 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003470 return false;
3471}
3472
3473/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3474/// lvalue referring to the result.
3475///
3476/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003477/// \param LV - An lvalue referring to the base of the member pointer.
3478/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003479/// \param IncludeMember - Specifies whether the member itself is included in
3480/// the resulting LValue subobject designator. This is not possible when
3481/// creating a bound member function.
3482/// \return The field or method declaration to which the member pointer refers,
3483/// or 0 if evaluation fails.
3484static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003485 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003486 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003487 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003488 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003489 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003490 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003491 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003492
3493 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3494 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003495 if (!MemPtr.getDecl()) {
3496 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003497 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003498 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003499 }
Richard Smith253c2a32012-01-27 01:14:48 +00003500
Richard Smith027bf112011-11-17 22:56:20 +00003501 if (MemPtr.isDerivedMember()) {
3502 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003503 // The end of the derived-to-base path for the base object must match the
3504 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003505 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003506 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003507 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003508 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003509 }
Richard Smith027bf112011-11-17 22:56:20 +00003510 unsigned PathLengthToMember =
3511 LV.Designator.Entries.size() - MemPtr.Path.size();
3512 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3513 const CXXRecordDecl *LVDecl = getAsBaseClass(
3514 LV.Designator.Entries[PathLengthToMember + I]);
3515 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003516 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003517 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003518 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003519 }
Richard Smith027bf112011-11-17 22:56:20 +00003520 }
3521
3522 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003523 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003524 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003525 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003526 } else if (!MemPtr.Path.empty()) {
3527 // Extend the LValue path with the member pointer's path.
3528 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3529 MemPtr.Path.size() + IncludeMember);
3530
3531 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003532 if (const PointerType *PT = LVType->getAs<PointerType>())
3533 LVType = PT->getPointeeType();
3534 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3535 assert(RD && "member pointer access on non-class-type expression");
3536 // The first class in the path is that of the lvalue.
3537 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3538 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003539 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003540 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003541 RD = Base;
3542 }
3543 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003544 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3545 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003546 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003547 }
3548
3549 // Add the member. Note that we cannot build bound member functions here.
3550 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003551 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003552 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003553 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003554 } else if (const IndirectFieldDecl *IFD =
3555 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003556 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003557 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003558 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003559 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003560 }
Richard Smith027bf112011-11-17 22:56:20 +00003561 }
3562
3563 return MemPtr.getDecl();
3564}
3565
Richard Smith84401042013-06-03 05:03:02 +00003566static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3567 const BinaryOperator *BO,
3568 LValue &LV,
3569 bool IncludeMember = true) {
3570 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3571
3572 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003573 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003574 MemberPtr MemPtr;
3575 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3576 }
Craig Topper36250ad2014-05-12 05:36:57 +00003577 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003578 }
3579
3580 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3581 BO->getRHS(), IncludeMember);
3582}
3583
Richard Smith027bf112011-11-17 22:56:20 +00003584/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3585/// the provided lvalue, which currently refers to the base object.
3586static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3587 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003588 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003589 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003590 return false;
3591
Richard Smitha8105bc2012-01-06 16:39:00 +00003592 QualType TargetQT = E->getType();
3593 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3594 TargetQT = PT->getPointeeType();
3595
3596 // Check this cast lands within the final derived-to-base subobject path.
3597 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003598 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003599 << D.MostDerivedType << TargetQT;
3600 return false;
3601 }
3602
Richard Smith027bf112011-11-17 22:56:20 +00003603 // Check the type of the final cast. We don't need to check the path,
3604 // since a cast can only be formed if the path is unique.
3605 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003606 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3607 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003608 if (NewEntriesSize == D.MostDerivedPathLength)
3609 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3610 else
Richard Smith027bf112011-11-17 22:56:20 +00003611 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003612 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003613 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003614 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003615 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003616 }
Richard Smith027bf112011-11-17 22:56:20 +00003617
3618 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003619 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003620}
3621
Mike Stump876387b2009-10-27 22:09:17 +00003622namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003623enum EvalStmtResult {
3624 /// Evaluation failed.
3625 ESR_Failed,
3626 /// Hit a 'return' statement.
3627 ESR_Returned,
3628 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003629 ESR_Succeeded,
3630 /// Hit a 'continue' statement.
3631 ESR_Continue,
3632 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003633 ESR_Break,
3634 /// Still scanning for 'case' or 'default' statement.
3635 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003636};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003637}
Richard Smith254a73d2011-10-28 22:34:42 +00003638
Richard Smith97fcf4b2016-08-14 23:15:52 +00003639static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3640 // We don't need to evaluate the initializer for a static local.
3641 if (!VD->hasLocalStorage())
3642 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003643
Richard Smith97fcf4b2016-08-14 23:15:52 +00003644 LValue Result;
3645 Result.set(VD, Info.CurrentCall->Index);
3646 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003647
Richard Smith97fcf4b2016-08-14 23:15:52 +00003648 const Expr *InitE = VD->getInit();
3649 if (!InitE) {
3650 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3651 << false << VD->getType();
3652 Val = APValue();
3653 return false;
3654 }
Richard Smith51f03172013-06-20 03:00:05 +00003655
Richard Smith97fcf4b2016-08-14 23:15:52 +00003656 if (InitE->isValueDependent())
3657 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003658
Richard Smith97fcf4b2016-08-14 23:15:52 +00003659 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3660 // Wipe out any partially-computed value, to allow tracking that this
3661 // evaluation failed.
3662 Val = APValue();
3663 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003664 }
3665
3666 return true;
3667}
3668
Richard Smith97fcf4b2016-08-14 23:15:52 +00003669static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3670 bool OK = true;
3671
3672 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3673 OK &= EvaluateVarDecl(Info, VD);
3674
3675 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3676 for (auto *BD : DD->bindings())
3677 if (auto *VD = BD->getHoldingVar())
3678 OK &= EvaluateDecl(Info, VD);
3679
3680 return OK;
3681}
3682
3683
Richard Smith4e18ca52013-05-06 05:56:11 +00003684/// Evaluate a condition (either a variable declaration or an expression).
3685static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3686 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003687 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003688 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3689 return false;
3690 return EvaluateAsBooleanCondition(Cond, Result, Info);
3691}
3692
Richard Smith89210072016-04-04 23:29:43 +00003693namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003694/// \brief A location where the result (returned value) of evaluating a
3695/// statement should be stored.
3696struct StmtResult {
3697 /// The APValue that should be filled in with the returned value.
3698 APValue &Value;
3699 /// The location containing the result, if any (used to support RVO).
3700 const LValue *Slot;
3701};
Richard Smith89210072016-04-04 23:29:43 +00003702}
Richard Smith52a980a2015-08-28 02:43:42 +00003703
3704static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003705 const Stmt *S,
3706 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003707
3708/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003709static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003710 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003711 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003712 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003713 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003714 case ESR_Break:
3715 return ESR_Succeeded;
3716 case ESR_Succeeded:
3717 case ESR_Continue:
3718 return ESR_Continue;
3719 case ESR_Failed:
3720 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003721 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003722 return ESR;
3723 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003724 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003725}
3726
Richard Smith496ddcf2013-05-12 17:32:42 +00003727/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003728static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003729 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003730 BlockScopeRAII Scope(Info);
3731
Richard Smith496ddcf2013-05-12 17:32:42 +00003732 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003733 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003734 {
3735 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003736 if (const Stmt *Init = SS->getInit()) {
3737 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3738 if (ESR != ESR_Succeeded)
3739 return ESR;
3740 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003741 if (SS->getConditionVariable() &&
3742 !EvaluateDecl(Info, SS->getConditionVariable()))
3743 return ESR_Failed;
3744 if (!EvaluateInteger(SS->getCond(), Value, Info))
3745 return ESR_Failed;
3746 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003747
3748 // Find the switch case corresponding to the value of the condition.
3749 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003750 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003751 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3752 SC = SC->getNextSwitchCase()) {
3753 if (isa<DefaultStmt>(SC)) {
3754 Found = SC;
3755 continue;
3756 }
3757
3758 const CaseStmt *CS = cast<CaseStmt>(SC);
3759 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3760 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3761 : LHS;
3762 if (LHS <= Value && Value <= RHS) {
3763 Found = SC;
3764 break;
3765 }
3766 }
3767
3768 if (!Found)
3769 return ESR_Succeeded;
3770
3771 // Search the switch body for the switch case and evaluate it from there.
3772 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3773 case ESR_Break:
3774 return ESR_Succeeded;
3775 case ESR_Succeeded:
3776 case ESR_Continue:
3777 case ESR_Failed:
3778 case ESR_Returned:
3779 return ESR;
3780 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003781 // This can only happen if the switch case is nested within a statement
3782 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003783 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003784 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003785 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003786 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003787}
3788
Richard Smith254a73d2011-10-28 22:34:42 +00003789// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003790static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003791 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003792 if (!Info.nextStep(S))
3793 return ESR_Failed;
3794
Richard Smith496ddcf2013-05-12 17:32:42 +00003795 // If we're hunting down a 'case' or 'default' label, recurse through
3796 // substatements until we hit the label.
3797 if (Case) {
3798 // FIXME: We don't start the lifetime of objects whose initialization we
3799 // jump over. However, such objects must be of class type with a trivial
3800 // default constructor that initialize all subobjects, so must be empty,
3801 // so this almost never matters.
3802 switch (S->getStmtClass()) {
3803 case Stmt::CompoundStmtClass:
3804 // FIXME: Precompute which substatement of a compound statement we
3805 // would jump to, and go straight there rather than performing a
3806 // linear scan each time.
3807 case Stmt::LabelStmtClass:
3808 case Stmt::AttributedStmtClass:
3809 case Stmt::DoStmtClass:
3810 break;
3811
3812 case Stmt::CaseStmtClass:
3813 case Stmt::DefaultStmtClass:
3814 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003815 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003816 break;
3817
3818 case Stmt::IfStmtClass: {
3819 // FIXME: Precompute which side of an 'if' we would jump to, and go
3820 // straight there rather than scanning both sides.
3821 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003822
3823 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3824 // preceded by our switch label.
3825 BlockScopeRAII Scope(Info);
3826
Richard Smith496ddcf2013-05-12 17:32:42 +00003827 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3828 if (ESR != ESR_CaseNotFound || !IS->getElse())
3829 return ESR;
3830 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3831 }
3832
3833 case Stmt::WhileStmtClass: {
3834 EvalStmtResult ESR =
3835 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3836 if (ESR != ESR_Continue)
3837 return ESR;
3838 break;
3839 }
3840
3841 case Stmt::ForStmtClass: {
3842 const ForStmt *FS = cast<ForStmt>(S);
3843 EvalStmtResult ESR =
3844 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3845 if (ESR != ESR_Continue)
3846 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003847 if (FS->getInc()) {
3848 FullExpressionRAII IncScope(Info);
3849 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3850 return ESR_Failed;
3851 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003852 break;
3853 }
3854
3855 case Stmt::DeclStmtClass:
3856 // FIXME: If the variable has initialization that can't be jumped over,
3857 // bail out of any immediately-surrounding compound-statement too.
3858 default:
3859 return ESR_CaseNotFound;
3860 }
3861 }
3862
Richard Smith254a73d2011-10-28 22:34:42 +00003863 switch (S->getStmtClass()) {
3864 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003865 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003866 // Don't bother evaluating beyond an expression-statement which couldn't
3867 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003868 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003869 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003870 return ESR_Failed;
3871 return ESR_Succeeded;
3872 }
3873
Faisal Valie690b7a2016-07-02 22:34:24 +00003874 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003875 return ESR_Failed;
3876
3877 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003878 return ESR_Succeeded;
3879
Richard Smithd9f663b2013-04-22 15:31:51 +00003880 case Stmt::DeclStmtClass: {
3881 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003882 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003883 // Each declaration initialization is its own full-expression.
3884 // FIXME: This isn't quite right; if we're performing aggregate
3885 // initialization, each braced subexpression is its own full-expression.
3886 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003887 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003888 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003889 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003890 return ESR_Succeeded;
3891 }
3892
Richard Smith357362d2011-12-13 06:39:58 +00003893 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003894 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003895 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003896 if (RetExpr &&
3897 !(Result.Slot
3898 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3899 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003900 return ESR_Failed;
3901 return ESR_Returned;
3902 }
Richard Smith254a73d2011-10-28 22:34:42 +00003903
3904 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003905 BlockScopeRAII Scope(Info);
3906
Richard Smith254a73d2011-10-28 22:34:42 +00003907 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003908 for (const auto *BI : CS->body()) {
3909 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003910 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003911 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003912 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003913 return ESR;
3914 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003915 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003916 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003917
3918 case Stmt::IfStmtClass: {
3919 const IfStmt *IS = cast<IfStmt>(S);
3920
3921 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003922 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003923 if (const Stmt *Init = IS->getInit()) {
3924 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3925 if (ESR != ESR_Succeeded)
3926 return ESR;
3927 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003928 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003929 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003930 return ESR_Failed;
3931
3932 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3933 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3934 if (ESR != ESR_Succeeded)
3935 return ESR;
3936 }
3937 return ESR_Succeeded;
3938 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003939
3940 case Stmt::WhileStmtClass: {
3941 const WhileStmt *WS = cast<WhileStmt>(S);
3942 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003943 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003944 bool Continue;
3945 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3946 Continue))
3947 return ESR_Failed;
3948 if (!Continue)
3949 break;
3950
3951 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3952 if (ESR != ESR_Continue)
3953 return ESR;
3954 }
3955 return ESR_Succeeded;
3956 }
3957
3958 case Stmt::DoStmtClass: {
3959 const DoStmt *DS = cast<DoStmt>(S);
3960 bool Continue;
3961 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003962 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003963 if (ESR != ESR_Continue)
3964 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003965 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003966
Richard Smith08d6a2c2013-07-24 07:11:57 +00003967 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003968 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3969 return ESR_Failed;
3970 } while (Continue);
3971 return ESR_Succeeded;
3972 }
3973
3974 case Stmt::ForStmtClass: {
3975 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003976 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003977 if (FS->getInit()) {
3978 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3979 if (ESR != ESR_Succeeded)
3980 return ESR;
3981 }
3982 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003983 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003984 bool Continue = true;
3985 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3986 FS->getCond(), Continue))
3987 return ESR_Failed;
3988 if (!Continue)
3989 break;
3990
3991 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3992 if (ESR != ESR_Continue)
3993 return ESR;
3994
Richard Smith08d6a2c2013-07-24 07:11:57 +00003995 if (FS->getInc()) {
3996 FullExpressionRAII IncScope(Info);
3997 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3998 return ESR_Failed;
3999 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004000 }
4001 return ESR_Succeeded;
4002 }
4003
Richard Smith896e0d72013-05-06 06:51:17 +00004004 case Stmt::CXXForRangeStmtClass: {
4005 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004006 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004007
4008 // Initialize the __range variable.
4009 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4010 if (ESR != ESR_Succeeded)
4011 return ESR;
4012
4013 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004014 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4015 if (ESR != ESR_Succeeded)
4016 return ESR;
4017 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004018 if (ESR != ESR_Succeeded)
4019 return ESR;
4020
4021 while (true) {
4022 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004023 {
4024 bool Continue = true;
4025 FullExpressionRAII CondExpr(Info);
4026 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4027 return ESR_Failed;
4028 if (!Continue)
4029 break;
4030 }
Richard Smith896e0d72013-05-06 06:51:17 +00004031
4032 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004033 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004034 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4035 if (ESR != ESR_Succeeded)
4036 return ESR;
4037
4038 // Loop body.
4039 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4040 if (ESR != ESR_Continue)
4041 return ESR;
4042
4043 // Increment: ++__begin
4044 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4045 return ESR_Failed;
4046 }
4047
4048 return ESR_Succeeded;
4049 }
4050
Richard Smith496ddcf2013-05-12 17:32:42 +00004051 case Stmt::SwitchStmtClass:
4052 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4053
Richard Smith4e18ca52013-05-06 05:56:11 +00004054 case Stmt::ContinueStmtClass:
4055 return ESR_Continue;
4056
4057 case Stmt::BreakStmtClass:
4058 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004059
4060 case Stmt::LabelStmtClass:
4061 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4062
4063 case Stmt::AttributedStmtClass:
4064 // As a general principle, C++11 attributes can be ignored without
4065 // any semantic impact.
4066 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4067 Case);
4068
4069 case Stmt::CaseStmtClass:
4070 case Stmt::DefaultStmtClass:
4071 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004072 }
4073}
4074
Richard Smithcc36f692011-12-22 02:22:31 +00004075/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4076/// default constructor. If so, we'll fold it whether or not it's marked as
4077/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4078/// so we need special handling.
4079static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004080 const CXXConstructorDecl *CD,
4081 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004082 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4083 return false;
4084
Richard Smith66e05fe2012-01-18 05:21:49 +00004085 // Value-initialization does not call a trivial default constructor, so such a
4086 // call is a core constant expression whether or not the constructor is
4087 // constexpr.
4088 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004089 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004090 // FIXME: If DiagDecl is an implicitly-declared special member function,
4091 // we should be much more explicit about why it's not constexpr.
4092 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4093 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4094 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004095 } else {
4096 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4097 }
4098 }
4099 return true;
4100}
4101
Richard Smith357362d2011-12-13 06:39:58 +00004102/// CheckConstexprFunction - Check that a function can be called in a constant
4103/// expression.
4104static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4105 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004106 const FunctionDecl *Definition,
4107 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004108 // Potential constant expressions can contain calls to declared, but not yet
4109 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004110 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004111 Declaration->isConstexpr())
4112 return false;
4113
Richard Smith0838f3a2013-05-14 05:18:44 +00004114 // Bail out with no diagnostic if the function declaration itself is invalid.
4115 // We will have produced a relevant diagnostic while parsing it.
4116 if (Declaration->isInvalidDecl())
4117 return false;
4118
Richard Smith357362d2011-12-13 06:39:58 +00004119 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004120 if (Definition && Definition->isConstexpr() &&
4121 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004122 return true;
4123
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004124 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004125 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004126
Richard Smith5179eb72016-06-28 19:03:57 +00004127 // If this function is not constexpr because it is an inherited
4128 // non-constexpr constructor, diagnose that directly.
4129 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4130 if (CD && CD->isInheritingConstructor()) {
4131 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004132 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004133 DiagDecl = CD = Inherited;
4134 }
4135
4136 // FIXME: If DiagDecl is an implicitly-declared special member function
4137 // or an inheriting constructor, we should be much more explicit about why
4138 // it's not constexpr.
4139 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004140 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004141 << CD->getInheritedConstructor().getConstructor()->getParent();
4142 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004143 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004144 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004145 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4146 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004147 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004148 }
4149 return false;
4150}
4151
Richard Smithbe6dd812014-11-19 21:27:17 +00004152/// Determine if a class has any fields that might need to be copied by a
4153/// trivial copy or move operation.
4154static bool hasFields(const CXXRecordDecl *RD) {
4155 if (!RD || RD->isEmpty())
4156 return false;
4157 for (auto *FD : RD->fields()) {
4158 if (FD->isUnnamedBitfield())
4159 continue;
4160 return true;
4161 }
4162 for (auto &Base : RD->bases())
4163 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4164 return true;
4165 return false;
4166}
4167
Richard Smithd62306a2011-11-10 06:34:14 +00004168namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004169typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004170}
4171
4172/// EvaluateArgs - Evaluate the arguments to a function call.
4173static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4174 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004175 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004176 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004177 I != E; ++I) {
4178 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4179 // If we're checking for a potential constant expression, evaluate all
4180 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004181 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004182 return false;
4183 Success = false;
4184 }
4185 }
4186 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004187}
4188
Richard Smith254a73d2011-10-28 22:34:42 +00004189/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004190static bool HandleFunctionCall(SourceLocation CallLoc,
4191 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004192 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004193 EvalInfo &Info, APValue &Result,
4194 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004195 ArgVector ArgValues(Args.size());
4196 if (!EvaluateArgs(Args, ArgValues, Info))
4197 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004198
Richard Smith253c2a32012-01-27 01:14:48 +00004199 if (!Info.CheckCallLimit(CallLoc))
4200 return false;
4201
4202 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004203
4204 // For a trivial copy or move assignment, perform an APValue copy. This is
4205 // essential for unions, where the operations performed by the assignment
4206 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004207 //
4208 // Skip this for non-union classes with no fields; in that case, the defaulted
4209 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004210 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004211 if (MD && MD->isDefaulted() &&
4212 (MD->getParent()->isUnion() ||
4213 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004214 assert(This &&
4215 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4216 LValue RHS;
4217 RHS.setFrom(Info.Ctx, ArgValues[0]);
4218 APValue RHSValue;
4219 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4220 RHS, RHSValue))
4221 return false;
4222 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4223 RHSValue))
4224 return false;
4225 This->moveInto(Result);
4226 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004227 } else if (MD && isLambdaCallOperator(MD)) {
4228 // We're in a lambda; determine the lambda capture field maps.
4229 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4230 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004231 }
4232
Richard Smith52a980a2015-08-28 02:43:42 +00004233 StmtResult Ret = {Result, ResultSlot};
4234 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004235 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004236 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004237 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004238 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004239 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004240 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004241}
4242
Richard Smithd62306a2011-11-10 06:34:14 +00004243/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004244static bool HandleConstructorCall(const Expr *E, const LValue &This,
4245 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004246 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004247 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004248 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004249 if (!Info.CheckCallLimit(CallLoc))
4250 return false;
4251
Richard Smith3607ffe2012-02-13 03:54:03 +00004252 const CXXRecordDecl *RD = Definition->getParent();
4253 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004254 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004255 return false;
4256 }
4257
Richard Smith5179eb72016-06-28 19:03:57 +00004258 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004259
Richard Smith52a980a2015-08-28 02:43:42 +00004260 // FIXME: Creating an APValue just to hold a nonexistent return value is
4261 // wasteful.
4262 APValue RetVal;
4263 StmtResult Ret = {RetVal, nullptr};
4264
Richard Smith5179eb72016-06-28 19:03:57 +00004265 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004266 if (Definition->isDelegatingConstructor()) {
4267 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004268 {
4269 FullExpressionRAII InitScope(Info);
4270 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4271 return false;
4272 }
Richard Smith52a980a2015-08-28 02:43:42 +00004273 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004274 }
4275
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004276 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004277 // essential for unions (or classes with anonymous union members), where the
4278 // operations performed by the constructor cannot be represented by
4279 // ctor-initializers.
4280 //
4281 // Skip this for empty non-union classes; we should not perform an
4282 // lvalue-to-rvalue conversion on them because their copy constructor does not
4283 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004284 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004285 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004286 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004287 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004288 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004289 return handleLValueToRValueConversion(
4290 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4291 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004292 }
4293
4294 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004295 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004296 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004297 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004298
John McCalld7bca762012-05-01 00:38:49 +00004299 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004300 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4301
Richard Smith08d6a2c2013-07-24 07:11:57 +00004302 // A scope for temporaries lifetime-extended by reference members.
4303 BlockScopeRAII LifetimeExtendedScope(Info);
4304
Richard Smith253c2a32012-01-27 01:14:48 +00004305 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004306 unsigned BasesSeen = 0;
4307#ifndef NDEBUG
4308 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4309#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004310 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004311 LValue Subobject = This;
4312 APValue *Value = &Result;
4313
4314 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004315 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004316 if (I->isBaseInitializer()) {
4317 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004318#ifndef NDEBUG
4319 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004320 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004321 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4322 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4323 "base class initializers not in expected order");
4324 ++BaseIt;
4325#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004326 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004327 BaseType->getAsCXXRecordDecl(), &Layout))
4328 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004329 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004330 } else if ((FD = I->getMember())) {
4331 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004332 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004333 if (RD->isUnion()) {
4334 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004335 Value = &Result.getUnionValue();
4336 } else {
4337 Value = &Result.getStructField(FD->getFieldIndex());
4338 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004339 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004340 // Walk the indirect field decl's chain to find the object to initialize,
4341 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004342 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004343 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004344 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4345 // Switch the union field if it differs. This happens if we had
4346 // preceding zero-initialization, and we're now initializing a union
4347 // subobject other than the first.
4348 // FIXME: In this case, the values of the other subobjects are
4349 // specified, since zero-initialization sets all padding bits to zero.
4350 if (Value->isUninit() ||
4351 (Value->isUnion() && Value->getUnionField() != FD)) {
4352 if (CD->isUnion())
4353 *Value = APValue(FD);
4354 else
4355 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004356 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004357 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004358 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004359 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004360 if (CD->isUnion())
4361 Value = &Value->getUnionValue();
4362 else
4363 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004364 }
Richard Smithd62306a2011-11-10 06:34:14 +00004365 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004366 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004367 }
Richard Smith253c2a32012-01-27 01:14:48 +00004368
Richard Smith08d6a2c2013-07-24 07:11:57 +00004369 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004370 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4371 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004372 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004373 // If we're checking for a potential constant expression, evaluate all
4374 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004375 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004376 return false;
4377 Success = false;
4378 }
Richard Smithd62306a2011-11-10 06:34:14 +00004379 }
4380
Richard Smithd9f663b2013-04-22 15:31:51 +00004381 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004382 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004383}
4384
Richard Smith5179eb72016-06-28 19:03:57 +00004385static bool HandleConstructorCall(const Expr *E, const LValue &This,
4386 ArrayRef<const Expr*> Args,
4387 const CXXConstructorDecl *Definition,
4388 EvalInfo &Info, APValue &Result) {
4389 ArgVector ArgValues(Args.size());
4390 if (!EvaluateArgs(Args, ArgValues, Info))
4391 return false;
4392
4393 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4394 Info, Result);
4395}
4396
Eli Friedman9a156e52008-11-12 09:44:48 +00004397//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004398// Generic Evaluation
4399//===----------------------------------------------------------------------===//
4400namespace {
4401
Aaron Ballman68af21c2014-01-03 19:26:43 +00004402template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004403class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004404 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004405private:
Richard Smith52a980a2015-08-28 02:43:42 +00004406 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004407 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004408 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004409 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004410 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004411 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004412 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004413
Richard Smith17100ba2012-02-16 02:46:34 +00004414 // Check whether a conditional operator with a non-constant condition is a
4415 // potential constant expression. If neither arm is a potential constant
4416 // expression, then the conditional operator is not either.
4417 template<typename ConditionalOperator>
4418 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004419 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004420
4421 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004422 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004423 {
Richard Smith17100ba2012-02-16 02:46:34 +00004424 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004425 StmtVisitorTy::Visit(E->getFalseExpr());
4426 if (Diag.empty())
4427 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004428 }
Richard Smith17100ba2012-02-16 02:46:34 +00004429
George Burgess IV8c892b52016-05-25 22:31:54 +00004430 {
4431 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004432 Diag.clear();
4433 StmtVisitorTy::Visit(E->getTrueExpr());
4434 if (Diag.empty())
4435 return;
4436 }
4437
4438 Error(E, diag::note_constexpr_conditional_never_const);
4439 }
4440
4441
4442 template<typename ConditionalOperator>
4443 bool HandleConditionalOperator(const ConditionalOperator *E) {
4444 bool BoolResult;
4445 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004446 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004447 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004448 return false;
4449 }
4450 if (Info.noteFailure()) {
4451 StmtVisitorTy::Visit(E->getTrueExpr());
4452 StmtVisitorTy::Visit(E->getFalseExpr());
4453 }
Richard Smith17100ba2012-02-16 02:46:34 +00004454 return false;
4455 }
4456
4457 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4458 return StmtVisitorTy::Visit(EvalExpr);
4459 }
4460
Peter Collingbournee9200682011-05-13 03:29:01 +00004461protected:
4462 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004463 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004464 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4465
Richard Smith92b1ce02011-12-12 09:28:41 +00004466 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004467 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004468 }
4469
Aaron Ballman68af21c2014-01-03 19:26:43 +00004470 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004471
4472public:
4473 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4474
4475 EvalInfo &getEvalInfo() { return Info; }
4476
Richard Smithf57d8cb2011-12-09 22:58:01 +00004477 /// Report an evaluation error. This should only be called when an error is
4478 /// first discovered. When propagating an error, just return false.
4479 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004480 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004481 return false;
4482 }
4483 bool Error(const Expr *E) {
4484 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4485 }
4486
Aaron Ballman68af21c2014-01-03 19:26:43 +00004487 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004488 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004489 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004490 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004491 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004492 }
4493
Aaron Ballman68af21c2014-01-03 19:26:43 +00004494 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004495 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004496 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004497 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004498 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004499 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004500 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004501 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004502 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004503 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004504 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004505 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004506 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004507 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004508 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004509 // The initializer may not have been parsed yet, or might be erroneous.
4510 if (!E->getExpr())
4511 return Error(E);
4512 return StmtVisitorTy::Visit(E->getExpr());
4513 }
Richard Smith5894a912011-12-19 22:12:41 +00004514 // We cannot create any objects for which cleanups are required, so there is
4515 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004516 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004517 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004518
Aaron Ballman68af21c2014-01-03 19:26:43 +00004519 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004520 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4521 return static_cast<Derived*>(this)->VisitCastExpr(E);
4522 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004523 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004524 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4525 return static_cast<Derived*>(this)->VisitCastExpr(E);
4526 }
4527
Aaron Ballman68af21c2014-01-03 19:26:43 +00004528 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004529 switch (E->getOpcode()) {
4530 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004531 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004532
4533 case BO_Comma:
4534 VisitIgnoredValue(E->getLHS());
4535 return StmtVisitorTy::Visit(E->getRHS());
4536
4537 case BO_PtrMemD:
4538 case BO_PtrMemI: {
4539 LValue Obj;
4540 if (!HandleMemberPointerAccess(Info, E, Obj))
4541 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004542 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004543 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004544 return false;
4545 return DerivedSuccess(Result, E);
4546 }
4547 }
4548 }
4549
Aaron Ballman68af21c2014-01-03 19:26:43 +00004550 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004551 // Evaluate and cache the common expression. We treat it as a temporary,
4552 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004553 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004554 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004555 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004556
Richard Smith17100ba2012-02-16 02:46:34 +00004557 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004558 }
4559
Aaron Ballman68af21c2014-01-03 19:26:43 +00004560 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004561 bool IsBcpCall = false;
4562 // If the condition (ignoring parens) is a __builtin_constant_p call,
4563 // the result is a constant expression if it can be folded without
4564 // side-effects. This is an important GNU extension. See GCC PR38377
4565 // for discussion.
4566 if (const CallExpr *CallCE =
4567 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004568 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004569 IsBcpCall = true;
4570
4571 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4572 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004573 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004574 return false;
4575
Richard Smith6d4c6582013-11-05 22:18:15 +00004576 FoldConstant Fold(Info, IsBcpCall);
4577 if (!HandleConditionalOperator(E)) {
4578 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004579 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004580 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004581
4582 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004583 }
4584
Aaron Ballman68af21c2014-01-03 19:26:43 +00004585 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004586 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4587 return DerivedSuccess(*Value, E);
4588
4589 const Expr *Source = E->getSourceExpr();
4590 if (!Source)
4591 return Error(E);
4592 if (Source == E) { // sanity checking.
4593 assert(0 && "OpaqueValueExpr recursively refers to itself");
4594 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004595 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004596 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004597 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004598
Aaron Ballman68af21c2014-01-03 19:26:43 +00004599 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004600 APValue Result;
4601 if (!handleCallExpr(E, Result, nullptr))
4602 return false;
4603 return DerivedSuccess(Result, E);
4604 }
4605
4606 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004607 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004608 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004609 QualType CalleeType = Callee->getType();
4610
Craig Topper36250ad2014-05-12 05:36:57 +00004611 const FunctionDecl *FD = nullptr;
4612 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004613 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004614 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004615
Richard Smithe97cbd72011-11-11 04:05:33 +00004616 // Extract function decl and 'this' pointer from the callee.
4617 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004618 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004619 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4620 // Explicit bound member calls, such as x.f() or p->g();
4621 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004622 return false;
4623 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004624 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004625 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004626 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4627 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004628 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4629 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004630 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004631 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004632 return Error(Callee);
4633
4634 FD = dyn_cast<FunctionDecl>(Member);
4635 if (!FD)
4636 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004637 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004638 LValue Call;
4639 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004640 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004641
Richard Smitha8105bc2012-01-06 16:39:00 +00004642 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004643 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004644 FD = dyn_cast_or_null<FunctionDecl>(
4645 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004646 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004647 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004648 // Don't call function pointers which have been cast to some other type.
4649 // Per DR (no number yet), the caller and callee can differ in noexcept.
4650 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4651 CalleeType->getPointeeType(), FD->getType())) {
4652 return Error(E);
4653 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004654
4655 // Overloaded operator calls to member functions are represented as normal
4656 // calls with '*this' as the first argument.
4657 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4658 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004659 // FIXME: When selecting an implicit conversion for an overloaded
4660 // operator delete, we sometimes try to evaluate calls to conversion
4661 // operators without a 'this' parameter!
4662 if (Args.empty())
4663 return Error(E);
4664
Nick Lewycky13073a62017-06-12 21:15:44 +00004665 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004666 return false;
4667 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004668 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004669 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004670 // Map the static invoker for the lambda back to the call operator.
4671 // Conveniently, we don't have to slice out the 'this' argument (as is
4672 // being done for the non-static case), since a static member function
4673 // doesn't have an implicit argument passed in.
4674 const CXXRecordDecl *ClosureClass = MD->getParent();
4675 assert(
4676 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4677 "Number of captures must be zero for conversion to function-ptr");
4678
4679 const CXXMethodDecl *LambdaCallOp =
4680 ClosureClass->getLambdaCallOperator();
4681
4682 // Set 'FD', the function that will be called below, to the call
4683 // operator. If the closure object represents a generic lambda, find
4684 // the corresponding specialization of the call operator.
4685
4686 if (ClosureClass->isGenericLambda()) {
4687 assert(MD->isFunctionTemplateSpecialization() &&
4688 "A generic lambda's static-invoker function must be a "
4689 "template specialization");
4690 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4691 FunctionTemplateDecl *CallOpTemplate =
4692 LambdaCallOp->getDescribedFunctionTemplate();
4693 void *InsertPos = nullptr;
4694 FunctionDecl *CorrespondingCallOpSpecialization =
4695 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4696 assert(CorrespondingCallOpSpecialization &&
4697 "We must always have a function call operator specialization "
4698 "that corresponds to our static invoker specialization");
4699 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4700 } else
4701 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004702 }
4703
Daniel Jasperffdee092017-05-02 19:21:42 +00004704
Richard Smithe97cbd72011-11-11 04:05:33 +00004705 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004706 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004707
Richard Smith47b34932012-02-01 02:39:43 +00004708 if (This && !This->checkSubobject(Info, E, CSK_This))
4709 return false;
4710
Richard Smith3607ffe2012-02-13 03:54:03 +00004711 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4712 // calls to such functions in constant expressions.
4713 if (This && !HasQualifier &&
4714 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4715 return Error(E, diag::note_constexpr_virtual_call);
4716
Craig Topper36250ad2014-05-12 05:36:57 +00004717 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004718 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004719
Nick Lewycky13073a62017-06-12 21:15:44 +00004720 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4721 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004722 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004723 return false;
4724
Richard Smith52a980a2015-08-28 02:43:42 +00004725 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004726 }
4727
Aaron Ballman68af21c2014-01-03 19:26:43 +00004728 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004729 return StmtVisitorTy::Visit(E->getInitializer());
4730 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004731 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004732 if (E->getNumInits() == 0)
4733 return DerivedZeroInitialization(E);
4734 if (E->getNumInits() == 1)
4735 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004736 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004737 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004738 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004739 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004740 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004741 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004742 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004743 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004744 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004745 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004746 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004747
Richard Smithd62306a2011-11-10 06:34:14 +00004748 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004749 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004750 assert(!E->isArrow() && "missing call to bound member function?");
4751
Richard Smith2e312c82012-03-03 22:46:17 +00004752 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004753 if (!Evaluate(Val, Info, E->getBase()))
4754 return false;
4755
4756 QualType BaseTy = E->getBase()->getType();
4757
4758 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004759 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004760 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004761 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004762 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4763
Richard Smith3229b742013-05-05 21:17:10 +00004764 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004765 SubobjectDesignator Designator(BaseTy);
4766 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004767
Richard Smith3229b742013-05-05 21:17:10 +00004768 APValue Result;
4769 return extractSubobject(Info, E, Obj, Designator, Result) &&
4770 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004771 }
4772
Aaron Ballman68af21c2014-01-03 19:26:43 +00004773 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004774 switch (E->getCastKind()) {
4775 default:
4776 break;
4777
Richard Smitha23ab512013-05-23 00:30:41 +00004778 case CK_AtomicToNonAtomic: {
4779 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004780 // This does not need to be done in place even for class/array types:
4781 // atomic-to-non-atomic conversion implies copying the object
4782 // representation.
4783 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004784 return false;
4785 return DerivedSuccess(AtomicVal, E);
4786 }
4787
Richard Smith11562c52011-10-28 17:51:58 +00004788 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004789 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004790 return StmtVisitorTy::Visit(E->getSubExpr());
4791
4792 case CK_LValueToRValue: {
4793 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004794 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4795 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004796 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004797 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004798 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004799 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004800 return false;
4801 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004802 }
4803 }
4804
Richard Smithf57d8cb2011-12-09 22:58:01 +00004805 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004806 }
4807
Aaron Ballman68af21c2014-01-03 19:26:43 +00004808 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004809 return VisitUnaryPostIncDec(UO);
4810 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004811 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004812 return VisitUnaryPostIncDec(UO);
4813 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004814 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004815 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004816 return Error(UO);
4817
4818 LValue LVal;
4819 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4820 return false;
4821 APValue RVal;
4822 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4823 UO->isIncrementOp(), &RVal))
4824 return false;
4825 return DerivedSuccess(RVal, UO);
4826 }
4827
Aaron Ballman68af21c2014-01-03 19:26:43 +00004828 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004829 // We will have checked the full-expressions inside the statement expression
4830 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004831 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004832 return Error(E);
4833
Richard Smith08d6a2c2013-07-24 07:11:57 +00004834 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004835 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004836 if (CS->body_empty())
4837 return true;
4838
Richard Smith51f03172013-06-20 03:00:05 +00004839 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4840 BE = CS->body_end();
4841 /**/; ++BI) {
4842 if (BI + 1 == BE) {
4843 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4844 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004845 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004846 diag::note_constexpr_stmt_expr_unsupported);
4847 return false;
4848 }
4849 return this->Visit(FinalExpr);
4850 }
4851
4852 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004853 StmtResult Result = { ReturnValue, nullptr };
4854 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004855 if (ESR != ESR_Succeeded) {
4856 // FIXME: If the statement-expression terminated due to 'return',
4857 // 'break', or 'continue', it would be nice to propagate that to
4858 // the outer statement evaluation rather than bailing out.
4859 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004860 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004861 diag::note_constexpr_stmt_expr_unsupported);
4862 return false;
4863 }
4864 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004865
4866 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004867 }
4868
Richard Smith4a678122011-10-24 18:44:57 +00004869 /// Visit a value which is evaluated, but whose value is ignored.
4870 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004871 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004872 }
David Majnemere9807b22016-02-26 04:23:19 +00004873
4874 /// Potentially visit a MemberExpr's base expression.
4875 void VisitIgnoredBaseExpression(const Expr *E) {
4876 // While MSVC doesn't evaluate the base expression, it does diagnose the
4877 // presence of side-effecting behavior.
4878 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4879 return;
4880 VisitIgnoredValue(E);
4881 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004882};
4883
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004884}
Peter Collingbournee9200682011-05-13 03:29:01 +00004885
4886//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004887// Common base class for lvalue and temporary evaluation.
4888//===----------------------------------------------------------------------===//
4889namespace {
4890template<class Derived>
4891class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004892 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004893protected:
4894 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004895 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004896 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004897 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004898
4899 bool Success(APValue::LValueBase B) {
4900 Result.set(B);
4901 return true;
4902 }
4903
George Burgess IVf9013bf2017-02-10 22:52:29 +00004904 bool evaluatePointer(const Expr *E, LValue &Result) {
4905 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4906 }
4907
Richard Smith027bf112011-11-17 22:56:20 +00004908public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004909 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4910 : ExprEvaluatorBaseTy(Info), Result(Result),
4911 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00004912
Richard Smith2e312c82012-03-03 22:46:17 +00004913 bool Success(const APValue &V, const Expr *E) {
4914 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004915 return true;
4916 }
Richard Smith027bf112011-11-17 22:56:20 +00004917
Richard Smith027bf112011-11-17 22:56:20 +00004918 bool VisitMemberExpr(const MemberExpr *E) {
4919 // Handle non-static data members.
4920 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004921 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004922 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004923 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00004924 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004925 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004926 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004927 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004928 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004929 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004930 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004931 BaseTy = E->getBase()->getType();
4932 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004933 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004934 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004935 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004936 Result.setInvalid(E);
4937 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004938 }
Richard Smith027bf112011-11-17 22:56:20 +00004939
Richard Smith1b78b3d2012-01-25 22:15:11 +00004940 const ValueDecl *MD = E->getMemberDecl();
4941 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4942 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4943 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4944 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004945 if (!HandleLValueMember(this->Info, E, Result, FD))
4946 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004947 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004948 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4949 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004950 } else
4951 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004952
Richard Smith1b78b3d2012-01-25 22:15:11 +00004953 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004954 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004955 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004956 RefValue))
4957 return false;
4958 return Success(RefValue, E);
4959 }
4960 return true;
4961 }
4962
4963 bool VisitBinaryOperator(const BinaryOperator *E) {
4964 switch (E->getOpcode()) {
4965 default:
4966 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4967
4968 case BO_PtrMemD:
4969 case BO_PtrMemI:
4970 return HandleMemberPointerAccess(this->Info, E, Result);
4971 }
4972 }
4973
4974 bool VisitCastExpr(const CastExpr *E) {
4975 switch (E->getCastKind()) {
4976 default:
4977 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4978
4979 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004980 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004981 if (!this->Visit(E->getSubExpr()))
4982 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004983
4984 // Now figure out the necessary offset to add to the base LV to get from
4985 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004986 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4987 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004988 }
4989 }
4990};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004991}
Richard Smith027bf112011-11-17 22:56:20 +00004992
4993//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004994// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004995//
4996// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4997// function designators (in C), decl references to void objects (in C), and
4998// temporaries (if building with -Wno-address-of-temporary).
4999//
5000// LValue evaluation produces values comprising a base expression of one of the
5001// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005002// - Declarations
5003// * VarDecl
5004// * FunctionDecl
5005// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005006// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005007// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005008// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005009// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005010// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005011// * ObjCEncodeExpr
5012// * AddrLabelExpr
5013// * BlockExpr
5014// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005015// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005016// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005017// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005018// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5019// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005020// * A MaterializeTemporaryExpr that has static storage duration, with no
5021// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005022// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005023//===----------------------------------------------------------------------===//
5024namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005025class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005026 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005027public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005028 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5029 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005030
Richard Smith11562c52011-10-28 17:51:58 +00005031 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005032 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005033
Peter Collingbournee9200682011-05-13 03:29:01 +00005034 bool VisitDeclRefExpr(const DeclRefExpr *E);
5035 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005036 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005037 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5038 bool VisitMemberExpr(const MemberExpr *E);
5039 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5040 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005041 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005042 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005043 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5044 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005045 bool VisitUnaryReal(const UnaryOperator *E);
5046 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005047 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5048 return VisitUnaryPreIncDec(UO);
5049 }
5050 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5051 return VisitUnaryPreIncDec(UO);
5052 }
Richard Smith3229b742013-05-05 21:17:10 +00005053 bool VisitBinAssign(const BinaryOperator *BO);
5054 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005055
Peter Collingbournee9200682011-05-13 03:29:01 +00005056 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005057 switch (E->getCastKind()) {
5058 default:
Richard Smith027bf112011-11-17 22:56:20 +00005059 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005060
Eli Friedmance3e02a2011-10-11 00:13:24 +00005061 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005062 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005063 if (!Visit(E->getSubExpr()))
5064 return false;
5065 Result.Designator.setInvalid();
5066 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005067
Richard Smith027bf112011-11-17 22:56:20 +00005068 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005069 if (!Visit(E->getSubExpr()))
5070 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005071 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005072 }
5073 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005074};
5075} // end anonymous namespace
5076
Richard Smith11562c52011-10-28 17:51:58 +00005077/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005078/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005079/// * function designators in C, and
5080/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005081/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005082static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5083 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005084 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005085 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005086 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005087}
5088
Peter Collingbournee9200682011-05-13 03:29:01 +00005089bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005090 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005091 return Success(FD);
5092 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005093 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005094 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005095 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005096 return Error(E);
5097}
Richard Smith733237d2011-10-24 23:14:33 +00005098
Faisal Vali0528a312016-11-13 06:09:16 +00005099
Richard Smith11562c52011-10-28 17:51:58 +00005100bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005101
5102 // If we are within a lambda's call operator, check whether the 'VD' referred
5103 // to within 'E' actually represents a lambda-capture that maps to a
5104 // data-member/field within the closure object, and if so, evaluate to the
5105 // field or what the field refers to.
5106 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5107 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5108 if (Info.checkingPotentialConstantExpression())
5109 return false;
5110 // Start with 'Result' referring to the complete closure object...
5111 Result = *Info.CurrentCall->This;
5112 // ... then update it to refer to the field of the closure object
5113 // that represents the capture.
5114 if (!HandleLValueMember(Info, E, Result, FD))
5115 return false;
5116 // And if the field is of reference type, update 'Result' to refer to what
5117 // the field refers to.
5118 if (FD->getType()->isReferenceType()) {
5119 APValue RVal;
5120 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5121 RVal))
5122 return false;
5123 Result.setFrom(Info.Ctx, RVal);
5124 }
5125 return true;
5126 }
5127 }
Craig Topper36250ad2014-05-12 05:36:57 +00005128 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005129 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5130 // Only if a local variable was declared in the function currently being
5131 // evaluated, do we expect to be able to find its value in the current
5132 // frame. (Otherwise it was likely declared in an enclosing context and
5133 // could either have a valid evaluatable value (for e.g. a constexpr
5134 // variable) or be ill-formed (and trigger an appropriate evaluation
5135 // diagnostic)).
5136 if (Info.CurrentCall->Callee &&
5137 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5138 Frame = Info.CurrentCall;
5139 }
5140 }
Richard Smith3229b742013-05-05 21:17:10 +00005141
Richard Smithfec09922011-11-01 16:57:24 +00005142 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005143 if (Frame) {
5144 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005145 return true;
5146 }
Richard Smithce40ad62011-11-12 22:28:03 +00005147 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005148 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005149
Richard Smith3229b742013-05-05 21:17:10 +00005150 APValue *V;
5151 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005152 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005153 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005154 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005155 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005156 return false;
5157 }
Richard Smith3229b742013-05-05 21:17:10 +00005158 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005159}
5160
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005161bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5162 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005163 // Walk through the expression to find the materialized temporary itself.
5164 SmallVector<const Expr *, 2> CommaLHSs;
5165 SmallVector<SubobjectAdjustment, 2> Adjustments;
5166 const Expr *Inner = E->GetTemporaryExpr()->
5167 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005168
Richard Smith84401042013-06-03 05:03:02 +00005169 // If we passed any comma operators, evaluate their LHSs.
5170 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5171 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5172 return false;
5173
Richard Smithe6c01442013-06-05 00:46:14 +00005174 // A materialized temporary with static storage duration can appear within the
5175 // result of a constant expression evaluation, so we need to preserve its
5176 // value for use outside this evaluation.
5177 APValue *Value;
5178 if (E->getStorageDuration() == SD_Static) {
5179 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005180 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005181 Result.set(E);
5182 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005183 Value = &Info.CurrentCall->
5184 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005185 Result.set(E, Info.CurrentCall->Index);
5186 }
5187
Richard Smithea4ad5d2013-06-06 08:19:16 +00005188 QualType Type = Inner->getType();
5189
Richard Smith84401042013-06-03 05:03:02 +00005190 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005191 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5192 (E->getStorageDuration() == SD_Static &&
5193 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5194 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005195 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005196 }
Richard Smith84401042013-06-03 05:03:02 +00005197
5198 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005199 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5200 --I;
5201 switch (Adjustments[I].Kind) {
5202 case SubobjectAdjustment::DerivedToBaseAdjustment:
5203 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5204 Type, Result))
5205 return false;
5206 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5207 break;
5208
5209 case SubobjectAdjustment::FieldAdjustment:
5210 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5211 return false;
5212 Type = Adjustments[I].Field->getType();
5213 break;
5214
5215 case SubobjectAdjustment::MemberPointerAdjustment:
5216 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5217 Adjustments[I].Ptr.RHS))
5218 return false;
5219 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5220 break;
5221 }
5222 }
5223
5224 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005225}
5226
Peter Collingbournee9200682011-05-13 03:29:01 +00005227bool
5228LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005229 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5230 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005231 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5232 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005233 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005234}
5235
Richard Smith6e525142011-12-27 12:18:28 +00005236bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005237 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005238 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005239
Faisal Valie690b7a2016-07-02 22:34:24 +00005240 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005241 << E->getExprOperand()->getType()
5242 << E->getExprOperand()->getSourceRange();
5243 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005244}
5245
Francois Pichet0066db92012-04-16 04:08:35 +00005246bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5247 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005248}
Francois Pichet0066db92012-04-16 04:08:35 +00005249
Peter Collingbournee9200682011-05-13 03:29:01 +00005250bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005251 // Handle static data members.
5252 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005253 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005254 return VisitVarDecl(E, VD);
5255 }
5256
Richard Smith254a73d2011-10-28 22:34:42 +00005257 // Handle static member functions.
5258 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5259 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005260 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005261 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005262 }
5263 }
5264
Richard Smithd62306a2011-11-10 06:34:14 +00005265 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005266 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005267}
5268
Peter Collingbournee9200682011-05-13 03:29:01 +00005269bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005270 // FIXME: Deal with vectors as array subscript bases.
5271 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005272 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005273
Nick Lewyckyad888682017-04-27 07:27:36 +00005274 bool Success = true;
5275 if (!evaluatePointer(E->getBase(), Result)) {
5276 if (!Info.noteFailure())
5277 return false;
5278 Success = false;
5279 }
Mike Stump11289f42009-09-09 15:08:12 +00005280
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005281 APSInt Index;
5282 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005283 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005284
Nick Lewyckyad888682017-04-27 07:27:36 +00005285 return Success &&
5286 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005287}
Eli Friedman9a156e52008-11-12 09:44:48 +00005288
Peter Collingbournee9200682011-05-13 03:29:01 +00005289bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005290 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005291}
5292
Richard Smith66c96992012-02-18 22:04:06 +00005293bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5294 if (!Visit(E->getSubExpr()))
5295 return false;
5296 // __real is a no-op on scalar lvalues.
5297 if (E->getSubExpr()->getType()->isAnyComplexType())
5298 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5299 return true;
5300}
5301
5302bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5303 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5304 "lvalue __imag__ on scalar?");
5305 if (!Visit(E->getSubExpr()))
5306 return false;
5307 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5308 return true;
5309}
5310
Richard Smith243ef902013-05-05 23:31:59 +00005311bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005312 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005313 return Error(UO);
5314
5315 if (!this->Visit(UO->getSubExpr()))
5316 return false;
5317
Richard Smith243ef902013-05-05 23:31:59 +00005318 return handleIncDec(
5319 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005320 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005321}
5322
5323bool LValueExprEvaluator::VisitCompoundAssignOperator(
5324 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005325 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005326 return Error(CAO);
5327
Richard Smith3229b742013-05-05 21:17:10 +00005328 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005329
5330 // The overall lvalue result is the result of evaluating the LHS.
5331 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005332 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005333 Evaluate(RHS, this->Info, CAO->getRHS());
5334 return false;
5335 }
5336
Richard Smith3229b742013-05-05 21:17:10 +00005337 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5338 return false;
5339
Richard Smith43e77732013-05-07 04:50:00 +00005340 return handleCompoundAssignment(
5341 this->Info, CAO,
5342 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5343 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005344}
5345
5346bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005347 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005348 return Error(E);
5349
Richard Smith3229b742013-05-05 21:17:10 +00005350 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005351
5352 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005353 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005354 Evaluate(NewVal, this->Info, E->getRHS());
5355 return false;
5356 }
5357
Richard Smith3229b742013-05-05 21:17:10 +00005358 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5359 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005360
5361 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005362 NewVal);
5363}
5364
Eli Friedman9a156e52008-11-12 09:44:48 +00005365//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005366// Pointer Evaluation
5367//===----------------------------------------------------------------------===//
5368
George Burgess IVe3763372016-12-22 02:50:20 +00005369/// \brief Attempts to compute the number of bytes available at the pointer
5370/// returned by a function with the alloc_size attribute. Returns true if we
5371/// were successful. Places an unsigned number into `Result`.
5372///
5373/// This expects the given CallExpr to be a call to a function with an
5374/// alloc_size attribute.
5375static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5376 const CallExpr *Call,
5377 llvm::APInt &Result) {
5378 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5379
5380 // alloc_size args are 1-indexed, 0 means not present.
5381 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5382 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5383 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5384 if (Call->getNumArgs() <= SizeArgNo)
5385 return false;
5386
5387 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5388 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5389 return false;
5390 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5391 return false;
5392 Into = Into.zextOrSelf(BitsInSizeT);
5393 return true;
5394 };
5395
5396 APSInt SizeOfElem;
5397 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5398 return false;
5399
5400 if (!AllocSize->getNumElemsParam()) {
5401 Result = std::move(SizeOfElem);
5402 return true;
5403 }
5404
5405 APSInt NumberOfElems;
5406 // Argument numbers start at 1
5407 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5408 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5409 return false;
5410
5411 bool Overflow;
5412 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5413 if (Overflow)
5414 return false;
5415
5416 Result = std::move(BytesAvailable);
5417 return true;
5418}
5419
5420/// \brief Convenience function. LVal's base must be a call to an alloc_size
5421/// function.
5422static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5423 const LValue &LVal,
5424 llvm::APInt &Result) {
5425 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5426 "Can't get the size of a non alloc_size function");
5427 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5428 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5429 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5430}
5431
5432/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5433/// a function with the alloc_size attribute. If it was possible to do so, this
5434/// function will return true, make Result's Base point to said function call,
5435/// and mark Result's Base as invalid.
5436static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5437 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005438 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005439 return false;
5440
5441 // Because we do no form of static analysis, we only support const variables.
5442 //
5443 // Additionally, we can't support parameters, nor can we support static
5444 // variables (in the latter case, use-before-assign isn't UB; in the former,
5445 // we have no clue what they'll be assigned to).
5446 const auto *VD =
5447 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5448 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5449 return false;
5450
5451 const Expr *Init = VD->getAnyInitializer();
5452 if (!Init)
5453 return false;
5454
5455 const Expr *E = Init->IgnoreParens();
5456 if (!tryUnwrapAllocSizeCall(E))
5457 return false;
5458
5459 // Store E instead of E unwrapped so that the type of the LValue's base is
5460 // what the user wanted.
5461 Result.setInvalid(E);
5462
5463 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Daniel Jasperffdee092017-05-02 19:21:42 +00005464 Result.addUnsizedArray(Info, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005465 return true;
5466}
5467
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005468namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005469class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005470 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005471 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005472 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005473
Peter Collingbournee9200682011-05-13 03:29:01 +00005474 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005475 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005476 return true;
5477 }
George Burgess IVe3763372016-12-22 02:50:20 +00005478
George Burgess IVf9013bf2017-02-10 22:52:29 +00005479 bool evaluateLValue(const Expr *E, LValue &Result) {
5480 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5481 }
5482
5483 bool evaluatePointer(const Expr *E, LValue &Result) {
5484 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5485 }
5486
George Burgess IVe3763372016-12-22 02:50:20 +00005487 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005488public:
Mike Stump11289f42009-09-09 15:08:12 +00005489
George Burgess IVf9013bf2017-02-10 22:52:29 +00005490 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5491 : ExprEvaluatorBaseTy(info), Result(Result),
5492 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005493
Richard Smith2e312c82012-03-03 22:46:17 +00005494 bool Success(const APValue &V, const Expr *E) {
5495 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005496 return true;
5497 }
Richard Smithfddd3842011-12-30 21:15:51 +00005498 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005499 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5500 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005501 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005502 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005503
John McCall45d55e42010-05-07 21:00:08 +00005504 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005505 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005506 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005507 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005508 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005509 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5510 if (Info.noteFailure())
5511 EvaluateIgnoredValue(Info, E->getSubExpr());
5512 return Error(E);
5513 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005514 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005515 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005516 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005517 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005518 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005519 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005520 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005521 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005522 }
Richard Smithd62306a2011-11-10 06:34:14 +00005523 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005524 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005525 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005526 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005527 if (!Info.CurrentCall->This) {
5528 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005529 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005530 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005531 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005532 return false;
5533 }
Richard Smithd62306a2011-11-10 06:34:14 +00005534 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005535 // If we are inside a lambda's call operator, the 'this' expression refers
5536 // to the enclosing '*this' object (either by value or reference) which is
5537 // either copied into the closure object's field that represents the '*this'
5538 // or refers to '*this'.
5539 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5540 // Update 'Result' to refer to the data member/field of the closure object
5541 // that represents the '*this' capture.
5542 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005543 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005544 return false;
5545 // If we captured '*this' by reference, replace the field with its referent.
5546 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5547 ->isPointerType()) {
5548 APValue RVal;
5549 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5550 RVal))
5551 return false;
5552
5553 Result.setFrom(Info.Ctx, RVal);
5554 }
5555 }
Richard Smithd62306a2011-11-10 06:34:14 +00005556 return true;
5557 }
John McCallc07a0c72011-02-17 10:25:35 +00005558
Eli Friedman449fe542009-03-23 04:56:01 +00005559 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005560};
Chris Lattner05706e882008-07-11 18:11:29 +00005561} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005562
George Burgess IVf9013bf2017-02-10 22:52:29 +00005563static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5564 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005565 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005566 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005567}
5568
John McCall45d55e42010-05-07 21:00:08 +00005569bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005570 if (E->getOpcode() != BO_Add &&
5571 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005572 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005573
Chris Lattner05706e882008-07-11 18:11:29 +00005574 const Expr *PExp = E->getLHS();
5575 const Expr *IExp = E->getRHS();
5576 if (IExp->getType()->isPointerType())
5577 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005578
George Burgess IVf9013bf2017-02-10 22:52:29 +00005579 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005580 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005581 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005582
John McCall45d55e42010-05-07 21:00:08 +00005583 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005584 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005585 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005586
Richard Smith96e0c102011-11-04 02:25:55 +00005587 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005588 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005589
Ted Kremenek28831752012-08-23 20:46:57 +00005590 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005591 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005592}
Eli Friedman9a156e52008-11-12 09:44:48 +00005593
John McCall45d55e42010-05-07 21:00:08 +00005594bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005595 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005596}
Mike Stump11289f42009-09-09 15:08:12 +00005597
Peter Collingbournee9200682011-05-13 03:29:01 +00005598bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5599 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005600
Eli Friedman847a2bc2009-12-27 05:43:15 +00005601 switch (E->getCastKind()) {
5602 default:
5603 break;
5604
John McCalle3027922010-08-25 11:45:40 +00005605 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005606 case CK_CPointerToObjCPointerCast:
5607 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005608 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005609 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005610 if (!Visit(SubExpr))
5611 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005612 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5613 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5614 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005615 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005616 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005617 if (SubExpr->getType()->isVoidPointerType())
5618 CCEDiag(E, diag::note_constexpr_invalid_cast)
5619 << 3 << SubExpr->getType();
5620 else
5621 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5622 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005623 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5624 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005625 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005626
Anders Carlsson18275092010-10-31 20:41:46 +00005627 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005628 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005629 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005630 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005631 if (!Result.Base && Result.Offset.isZero())
5632 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005633
Richard Smithd62306a2011-11-10 06:34:14 +00005634 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005635 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005636 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5637 castAs<PointerType>()->getPointeeType(),
5638 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005639
Richard Smith027bf112011-11-17 22:56:20 +00005640 case CK_BaseToDerived:
5641 if (!Visit(E->getSubExpr()))
5642 return false;
5643 if (!Result.Base && Result.Offset.isZero())
5644 return true;
5645 return HandleBaseToDerivedCast(Info, E, Result);
5646
Richard Smith0b0a0b62011-10-29 20:57:55 +00005647 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005648 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005649 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005650
John McCalle3027922010-08-25 11:45:40 +00005651 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005652 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5653
Richard Smith2e312c82012-03-03 22:46:17 +00005654 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005655 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005656 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005657
John McCall45d55e42010-05-07 21:00:08 +00005658 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005659 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5660 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005661 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005662 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005663 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005664 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005665 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005666 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005667 return true;
5668 } else {
5669 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005670 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005671 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005672 }
5673 }
John McCalle3027922010-08-25 11:45:40 +00005674 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005675 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005676 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005677 return false;
5678 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005679 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005680 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005681 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005682 return false;
5683 }
Richard Smith96e0c102011-11-04 02:25:55 +00005684 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005685 if (const ConstantArrayType *CAT
5686 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5687 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005688 else
5689 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005690 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005691
John McCalle3027922010-08-25 11:45:40 +00005692 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005693 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005694
5695 case CK_LValueToRValue: {
5696 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005697 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005698 return false;
5699
5700 APValue RVal;
5701 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5702 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5703 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005704 return InvalidBaseOK &&
5705 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005706 return Success(RVal, E);
5707 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005708 }
5709
Richard Smith11562c52011-10-28 17:51:58 +00005710 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005711}
Chris Lattner05706e882008-07-11 18:11:29 +00005712
Hal Finkel0dd05d42014-10-03 17:18:37 +00005713static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5714 // C++ [expr.alignof]p3:
5715 // When alignof is applied to a reference type, the result is the
5716 // alignment of the referenced type.
5717 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5718 T = Ref->getPointeeType();
5719
5720 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005721 if (T.getQualifiers().hasUnaligned())
5722 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005723 return Info.Ctx.toCharUnitsFromBits(
5724 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5725}
5726
5727static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5728 E = E->IgnoreParens();
5729
5730 // The kinds of expressions that we have special-case logic here for
5731 // should be kept up to date with the special checks for those
5732 // expressions in Sema.
5733
5734 // alignof decl is always accepted, even if it doesn't make sense: we default
5735 // to 1 in those cases.
5736 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5737 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5738 /*RefAsPointee*/true);
5739
5740 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5741 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5742 /*RefAsPointee*/true);
5743
5744 return GetAlignOfType(Info, E->getType());
5745}
5746
George Burgess IVe3763372016-12-22 02:50:20 +00005747// To be clear: this happily visits unsupported builtins. Better name welcomed.
5748bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5749 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5750 return true;
5751
George Burgess IVf9013bf2017-02-10 22:52:29 +00005752 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005753 return false;
5754
5755 Result.setInvalid(E);
5756 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Daniel Jasperffdee092017-05-02 19:21:42 +00005757 Result.addUnsizedArray(Info, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005758 return true;
5759}
5760
Peter Collingbournee9200682011-05-13 03:29:01 +00005761bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005762 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005763 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005764
Richard Smith6328cbd2016-11-16 00:57:23 +00005765 if (unsigned BuiltinOp = E->getBuiltinCallee())
5766 return VisitBuiltinCallExpr(E, BuiltinOp);
5767
George Burgess IVe3763372016-12-22 02:50:20 +00005768 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005769}
5770
5771bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5772 unsigned BuiltinOp) {
5773 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005774 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005775 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005776 case Builtin::BI__builtin_assume_aligned: {
5777 // We need to be very careful here because: if the pointer does not have the
5778 // asserted alignment, then the behavior is undefined, and undefined
5779 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005780 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005781 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005782
Hal Finkel0dd05d42014-10-03 17:18:37 +00005783 LValue OffsetResult(Result);
5784 APSInt Alignment;
5785 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5786 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005787 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005788
5789 if (E->getNumArgs() > 2) {
5790 APSInt Offset;
5791 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5792 return false;
5793
Richard Smith642a2362017-01-30 23:30:26 +00005794 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005795 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5796 }
5797
5798 // If there is a base object, then it must have the correct alignment.
5799 if (OffsetResult.Base) {
5800 CharUnits BaseAlignment;
5801 if (const ValueDecl *VD =
5802 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5803 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5804 } else {
5805 BaseAlignment =
5806 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5807 }
5808
5809 if (BaseAlignment < Align) {
5810 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005811 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005812 CCEDiag(E->getArg(0),
5813 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005814 << (unsigned)BaseAlignment.getQuantity()
5815 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005816 return false;
5817 }
5818 }
5819
5820 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005821 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005822 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005823
Richard Smith642a2362017-01-30 23:30:26 +00005824 (OffsetResult.Base
5825 ? CCEDiag(E->getArg(0),
5826 diag::note_constexpr_baa_insufficient_alignment) << 1
5827 : CCEDiag(E->getArg(0),
5828 diag::note_constexpr_baa_value_insufficient_alignment))
5829 << (int)OffsetResult.Offset.getQuantity()
5830 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005831 return false;
5832 }
5833
5834 return true;
5835 }
Richard Smithe9507952016-11-12 01:39:56 +00005836
5837 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005838 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005839 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005840 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005841 if (Info.getLangOpts().CPlusPlus11)
5842 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5843 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005844 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005845 else
5846 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5847 // Fall through.
5848 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005849 case Builtin::BI__builtin_wcschr:
5850 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005851 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005852 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005853 if (!Visit(E->getArg(0)))
5854 return false;
5855 APSInt Desired;
5856 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5857 return false;
5858 uint64_t MaxLength = uint64_t(-1);
5859 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005860 BuiltinOp != Builtin::BIwcschr &&
5861 BuiltinOp != Builtin::BI__builtin_strchr &&
5862 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005863 APSInt N;
5864 if (!EvaluateInteger(E->getArg(2), N, Info))
5865 return false;
5866 MaxLength = N.getExtValue();
5867 }
5868
Richard Smith8110c9d2016-11-29 19:45:17 +00005869 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005870
Richard Smith8110c9d2016-11-29 19:45:17 +00005871 // Figure out what value we're actually looking for (after converting to
5872 // the corresponding unsigned type if necessary).
5873 uint64_t DesiredVal;
5874 bool StopAtNull = false;
5875 switch (BuiltinOp) {
5876 case Builtin::BIstrchr:
5877 case Builtin::BI__builtin_strchr:
5878 // strchr compares directly to the passed integer, and therefore
5879 // always fails if given an int that is not a char.
5880 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5881 E->getArg(1)->getType(),
5882 Desired),
5883 Desired))
5884 return ZeroInitialization(E);
5885 StopAtNull = true;
5886 // Fall through.
5887 case Builtin::BImemchr:
5888 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005889 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005890 // memchr compares by converting both sides to unsigned char. That's also
5891 // correct for strchr if we get this far (to cope with plain char being
5892 // unsigned in the strchr case).
5893 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5894 break;
Richard Smithe9507952016-11-12 01:39:56 +00005895
Richard Smith8110c9d2016-11-29 19:45:17 +00005896 case Builtin::BIwcschr:
5897 case Builtin::BI__builtin_wcschr:
5898 StopAtNull = true;
5899 // Fall through.
5900 case Builtin::BIwmemchr:
5901 case Builtin::BI__builtin_wmemchr:
5902 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5903 DesiredVal = Desired.getZExtValue();
5904 break;
5905 }
Richard Smithe9507952016-11-12 01:39:56 +00005906
5907 for (; MaxLength; --MaxLength) {
5908 APValue Char;
5909 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5910 !Char.isInt())
5911 return false;
5912 if (Char.getInt().getZExtValue() == DesiredVal)
5913 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005914 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005915 break;
5916 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5917 return false;
5918 }
5919 // Not found: return nullptr.
5920 return ZeroInitialization(E);
5921 }
5922
Richard Smith6cbd65d2013-07-11 02:27:57 +00005923 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005924 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005925 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005926}
Chris Lattner05706e882008-07-11 18:11:29 +00005927
5928//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005929// Member Pointer Evaluation
5930//===----------------------------------------------------------------------===//
5931
5932namespace {
5933class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005934 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005935 MemberPtr &Result;
5936
5937 bool Success(const ValueDecl *D) {
5938 Result = MemberPtr(D);
5939 return true;
5940 }
5941public:
5942
5943 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5944 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5945
Richard Smith2e312c82012-03-03 22:46:17 +00005946 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005947 Result.setFrom(V);
5948 return true;
5949 }
Richard Smithfddd3842011-12-30 21:15:51 +00005950 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005951 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005952 }
5953
5954 bool VisitCastExpr(const CastExpr *E);
5955 bool VisitUnaryAddrOf(const UnaryOperator *E);
5956};
5957} // end anonymous namespace
5958
5959static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5960 EvalInfo &Info) {
5961 assert(E->isRValue() && E->getType()->isMemberPointerType());
5962 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5963}
5964
5965bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5966 switch (E->getCastKind()) {
5967 default:
5968 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5969
5970 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005971 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005972 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005973
5974 case CK_BaseToDerivedMemberPointer: {
5975 if (!Visit(E->getSubExpr()))
5976 return false;
5977 if (E->path_empty())
5978 return true;
5979 // Base-to-derived member pointer casts store the path in derived-to-base
5980 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5981 // the wrong end of the derived->base arc, so stagger the path by one class.
5982 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5983 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5984 PathI != PathE; ++PathI) {
5985 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5986 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5987 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005988 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005989 }
5990 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5991 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005992 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005993 return true;
5994 }
5995
5996 case CK_DerivedToBaseMemberPointer:
5997 if (!Visit(E->getSubExpr()))
5998 return false;
5999 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6000 PathE = E->path_end(); PathI != PathE; ++PathI) {
6001 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6002 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6003 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006004 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006005 }
6006 return true;
6007 }
6008}
6009
6010bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6011 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6012 // member can be formed.
6013 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6014}
6015
6016//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006017// Record Evaluation
6018//===----------------------------------------------------------------------===//
6019
6020namespace {
6021 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006022 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006023 const LValue &This;
6024 APValue &Result;
6025 public:
6026
6027 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6028 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6029
Richard Smith2e312c82012-03-03 22:46:17 +00006030 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006031 Result = V;
6032 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006033 }
Richard Smithb8348f52016-05-12 22:16:28 +00006034 bool ZeroInitialization(const Expr *E) {
6035 return ZeroInitialization(E, E->getType());
6036 }
6037 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006038
Richard Smith52a980a2015-08-28 02:43:42 +00006039 bool VisitCallExpr(const CallExpr *E) {
6040 return handleCallExpr(E, Result, &This);
6041 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006042 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006043 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006044 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6045 return VisitCXXConstructExpr(E, E->getType());
6046 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006047 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006048 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006049 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006050 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006051 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006052}
Richard Smithd62306a2011-11-10 06:34:14 +00006053
Richard Smithfddd3842011-12-30 21:15:51 +00006054/// Perform zero-initialization on an object of non-union class type.
6055/// C++11 [dcl.init]p5:
6056/// To zero-initialize an object or reference of type T means:
6057/// [...]
6058/// -- if T is a (possibly cv-qualified) non-union class type,
6059/// each non-static data member and each base-class subobject is
6060/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006061static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6062 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006063 const LValue &This, APValue &Result) {
6064 assert(!RD->isUnion() && "Expected non-union class type");
6065 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6066 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006067 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006068
John McCalld7bca762012-05-01 00:38:49 +00006069 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006070 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6071
6072 if (CD) {
6073 unsigned Index = 0;
6074 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006075 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006076 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6077 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006078 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6079 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006080 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006081 Result.getStructBase(Index)))
6082 return false;
6083 }
6084 }
6085
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006086 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006087 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006088 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006089 continue;
6090
6091 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006092 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006093 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006094
David Blaikie2d7c57e2012-04-30 02:36:29 +00006095 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006096 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006097 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006098 return false;
6099 }
6100
6101 return true;
6102}
6103
Richard Smithb8348f52016-05-12 22:16:28 +00006104bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6105 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006106 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006107 if (RD->isUnion()) {
6108 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6109 // object's first non-static named data member is zero-initialized
6110 RecordDecl::field_iterator I = RD->field_begin();
6111 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006112 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006113 return true;
6114 }
6115
6116 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006117 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006118 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006119 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006120 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006121 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006122 }
6123
Richard Smith5d108602012-02-17 00:44:16 +00006124 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006125 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006126 return false;
6127 }
6128
Richard Smitha8105bc2012-01-06 16:39:00 +00006129 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006130}
6131
Richard Smithe97cbd72011-11-11 04:05:33 +00006132bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6133 switch (E->getCastKind()) {
6134 default:
6135 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6136
6137 case CK_ConstructorConversion:
6138 return Visit(E->getSubExpr());
6139
6140 case CK_DerivedToBase:
6141 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006142 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006143 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006144 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006145 if (!DerivedObject.isStruct())
6146 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006147
6148 // Derived-to-base rvalue conversion: just slice off the derived part.
6149 APValue *Value = &DerivedObject;
6150 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6151 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6152 PathE = E->path_end(); PathI != PathE; ++PathI) {
6153 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6154 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6155 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6156 RD = Base;
6157 }
6158 Result = *Value;
6159 return true;
6160 }
6161 }
6162}
6163
Richard Smithd62306a2011-11-10 06:34:14 +00006164bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006165 if (E->isTransparent())
6166 return Visit(E->getInit(0));
6167
Richard Smithd62306a2011-11-10 06:34:14 +00006168 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006169 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006170 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6171
6172 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006173 const FieldDecl *Field = E->getInitializedFieldInUnion();
6174 Result = APValue(Field);
6175 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006176 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006177
6178 // If the initializer list for a union does not contain any elements, the
6179 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006180 // FIXME: The element should be initialized from an initializer list.
6181 // Is this difference ever observable for initializer lists which
6182 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006183 ImplicitValueInitExpr VIE(Field->getType());
6184 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6185
Richard Smithd62306a2011-11-10 06:34:14 +00006186 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006187 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6188 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006189
6190 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6191 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6192 isa<CXXDefaultInitExpr>(InitExpr));
6193
Richard Smithb228a862012-02-15 02:18:13 +00006194 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006195 }
6196
Richard Smith872307e2016-03-08 22:17:41 +00006197 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006198 if (Result.isUninit())
6199 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6200 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006201 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006202 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006203
6204 // Initialize base classes.
6205 if (CXXRD) {
6206 for (const auto &Base : CXXRD->bases()) {
6207 assert(ElementNo < E->getNumInits() && "missing init for base class");
6208 const Expr *Init = E->getInit(ElementNo);
6209
6210 LValue Subobject = This;
6211 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6212 return false;
6213
6214 APValue &FieldVal = Result.getStructBase(ElementNo);
6215 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006216 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006217 return false;
6218 Success = false;
6219 }
6220 ++ElementNo;
6221 }
6222 }
6223
6224 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006225 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006226 // Anonymous bit-fields are not considered members of the class for
6227 // purposes of aggregate initialization.
6228 if (Field->isUnnamedBitfield())
6229 continue;
6230
6231 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006232
Richard Smith253c2a32012-01-27 01:14:48 +00006233 bool HaveInit = ElementNo < E->getNumInits();
6234
6235 // FIXME: Diagnostics here should point to the end of the initializer
6236 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006237 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006238 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006239 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006240
6241 // Perform an implicit value-initialization for members beyond the end of
6242 // the initializer list.
6243 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006244 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006245
Richard Smith852c9db2013-04-20 22:23:05 +00006246 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6247 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6248 isa<CXXDefaultInitExpr>(Init));
6249
Richard Smith49ca8aa2013-08-06 07:09:20 +00006250 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6251 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6252 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006253 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006254 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006255 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006256 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006257 }
6258 }
6259
Richard Smith253c2a32012-01-27 01:14:48 +00006260 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006261}
6262
Richard Smithb8348f52016-05-12 22:16:28 +00006263bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6264 QualType T) {
6265 // Note that E's type is not necessarily the type of our class here; we might
6266 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006267 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006268 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6269
Richard Smithfddd3842011-12-30 21:15:51 +00006270 bool ZeroInit = E->requiresZeroInitialization();
6271 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006272 // If we've already performed zero-initialization, we're already done.
6273 if (!Result.isUninit())
6274 return true;
6275
Richard Smithda3f4fd2014-03-05 23:32:50 +00006276 // We can get here in two different ways:
6277 // 1) We're performing value-initialization, and should zero-initialize
6278 // the object, or
6279 // 2) We're performing default-initialization of an object with a trivial
6280 // constexpr default constructor, in which case we should start the
6281 // lifetimes of all the base subobjects (there can be no data member
6282 // subobjects in this case) per [basic.life]p1.
6283 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006284 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006285 }
6286
Craig Topper36250ad2014-05-12 05:36:57 +00006287 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006288 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006289
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006290 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006291 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006292
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006293 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006294 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006295 if (const MaterializeTemporaryExpr *ME
6296 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6297 return Visit(ME->GetTemporaryExpr());
6298
Richard Smithb8348f52016-05-12 22:16:28 +00006299 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006300 return false;
6301
Craig Topper5fc8fc22014-08-27 06:28:36 +00006302 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006303 return HandleConstructorCall(E, This, Args,
6304 cast<CXXConstructorDecl>(Definition), Info,
6305 Result);
6306}
6307
6308bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6309 const CXXInheritedCtorInitExpr *E) {
6310 if (!Info.CurrentCall) {
6311 assert(Info.checkingPotentialConstantExpression());
6312 return false;
6313 }
6314
6315 const CXXConstructorDecl *FD = E->getConstructor();
6316 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6317 return false;
6318
6319 const FunctionDecl *Definition = nullptr;
6320 auto Body = FD->getBody(Definition);
6321
6322 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6323 return false;
6324
6325 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006326 cast<CXXConstructorDecl>(Definition), Info,
6327 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006328}
6329
Richard Smithcc1b96d2013-06-12 22:31:48 +00006330bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6331 const CXXStdInitializerListExpr *E) {
6332 const ConstantArrayType *ArrayType =
6333 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6334
6335 LValue Array;
6336 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6337 return false;
6338
6339 // Get a pointer to the first element of the array.
6340 Array.addArray(Info, E, ArrayType);
6341
6342 // FIXME: Perform the checks on the field types in SemaInit.
6343 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6344 RecordDecl::field_iterator Field = Record->field_begin();
6345 if (Field == Record->field_end())
6346 return Error(E);
6347
6348 // Start pointer.
6349 if (!Field->getType()->isPointerType() ||
6350 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6351 ArrayType->getElementType()))
6352 return Error(E);
6353
6354 // FIXME: What if the initializer_list type has base classes, etc?
6355 Result = APValue(APValue::UninitStruct(), 0, 2);
6356 Array.moveInto(Result.getStructField(0));
6357
6358 if (++Field == Record->field_end())
6359 return Error(E);
6360
6361 if (Field->getType()->isPointerType() &&
6362 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6363 ArrayType->getElementType())) {
6364 // End pointer.
6365 if (!HandleLValueArrayAdjustment(Info, E, Array,
6366 ArrayType->getElementType(),
6367 ArrayType->getSize().getZExtValue()))
6368 return false;
6369 Array.moveInto(Result.getStructField(1));
6370 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6371 // Length.
6372 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6373 else
6374 return Error(E);
6375
6376 if (++Field != Record->field_end())
6377 return Error(E);
6378
6379 return true;
6380}
6381
Faisal Valic72a08c2017-01-09 03:02:53 +00006382bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6383 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6384 if (ClosureClass->isInvalidDecl()) return false;
6385
6386 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006387
Faisal Vali051e3a22017-02-16 04:12:21 +00006388 const size_t NumFields =
6389 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006390
6391 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6392 E->capture_init_end()) &&
6393 "The number of lambda capture initializers should equal the number of "
6394 "fields within the closure type");
6395
Faisal Vali051e3a22017-02-16 04:12:21 +00006396 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6397 // Iterate through all the lambda's closure object's fields and initialize
6398 // them.
6399 auto *CaptureInitIt = E->capture_init_begin();
6400 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6401 bool Success = true;
6402 for (const auto *Field : ClosureClass->fields()) {
6403 assert(CaptureInitIt != E->capture_init_end());
6404 // Get the initializer for this field
6405 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006406
Faisal Vali051e3a22017-02-16 04:12:21 +00006407 // If there is no initializer, either this is a VLA or an error has
6408 // occurred.
6409 if (!CurFieldInit)
6410 return Error(E);
6411
6412 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6413 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6414 if (!Info.keepEvaluatingAfterFailure())
6415 return false;
6416 Success = false;
6417 }
6418 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006419 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006420 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006421}
6422
Richard Smithd62306a2011-11-10 06:34:14 +00006423static bool EvaluateRecord(const Expr *E, const LValue &This,
6424 APValue &Result, EvalInfo &Info) {
6425 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006426 "can't evaluate expression as a record rvalue");
6427 return RecordExprEvaluator(Info, This, Result).Visit(E);
6428}
6429
6430//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006431// Temporary Evaluation
6432//
6433// Temporaries are represented in the AST as rvalues, but generally behave like
6434// lvalues. The full-object of which the temporary is a subobject is implicitly
6435// materialized so that a reference can bind to it.
6436//===----------------------------------------------------------------------===//
6437namespace {
6438class TemporaryExprEvaluator
6439 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6440public:
6441 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006442 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006443
6444 /// Visit an expression which constructs the value of this temporary.
6445 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006446 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006447 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6448 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006449 }
6450
6451 bool VisitCastExpr(const CastExpr *E) {
6452 switch (E->getCastKind()) {
6453 default:
6454 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6455
6456 case CK_ConstructorConversion:
6457 return VisitConstructExpr(E->getSubExpr());
6458 }
6459 }
6460 bool VisitInitListExpr(const InitListExpr *E) {
6461 return VisitConstructExpr(E);
6462 }
6463 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6464 return VisitConstructExpr(E);
6465 }
6466 bool VisitCallExpr(const CallExpr *E) {
6467 return VisitConstructExpr(E);
6468 }
Richard Smith513955c2014-12-17 19:24:30 +00006469 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6470 return VisitConstructExpr(E);
6471 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006472 bool VisitLambdaExpr(const LambdaExpr *E) {
6473 return VisitConstructExpr(E);
6474 }
Richard Smith027bf112011-11-17 22:56:20 +00006475};
6476} // end anonymous namespace
6477
6478/// Evaluate an expression of record type as a temporary.
6479static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006480 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006481 return TemporaryExprEvaluator(Info, Result).Visit(E);
6482}
6483
6484//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006485// Vector Evaluation
6486//===----------------------------------------------------------------------===//
6487
6488namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006489 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006490 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006491 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006492 public:
Mike Stump11289f42009-09-09 15:08:12 +00006493
Richard Smith2d406342011-10-22 21:10:00 +00006494 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6495 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006496
Craig Topper9798b932015-09-29 04:30:05 +00006497 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006498 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6499 // FIXME: remove this APValue copy.
6500 Result = APValue(V.data(), V.size());
6501 return true;
6502 }
Richard Smith2e312c82012-03-03 22:46:17 +00006503 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006504 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006505 Result = V;
6506 return true;
6507 }
Richard Smithfddd3842011-12-30 21:15:51 +00006508 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006509
Richard Smith2d406342011-10-22 21:10:00 +00006510 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006511 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006512 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006513 bool VisitInitListExpr(const InitListExpr *E);
6514 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006515 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006516 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006517 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006518 };
6519} // end anonymous namespace
6520
6521static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006522 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006523 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006524}
6525
George Burgess IV533ff002015-12-11 00:23:35 +00006526bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006527 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006528 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006529
Richard Smith161f09a2011-12-06 22:44:34 +00006530 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006531 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006532
Eli Friedmanc757de22011-03-25 00:43:55 +00006533 switch (E->getCastKind()) {
6534 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006535 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006536 if (SETy->isIntegerType()) {
6537 APSInt IntResult;
6538 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006539 return false;
6540 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006541 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006542 APFloat FloatResult(0.0);
6543 if (!EvaluateFloat(SE, FloatResult, Info))
6544 return false;
6545 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006546 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006547 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006548 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006549
6550 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006551 SmallVector<APValue, 4> Elts(NElts, Val);
6552 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006553 }
Eli Friedman803acb32011-12-22 03:51:45 +00006554 case CK_BitCast: {
6555 // Evaluate the operand into an APInt we can extract from.
6556 llvm::APInt SValInt;
6557 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6558 return false;
6559 // Extract the elements
6560 QualType EltTy = VTy->getElementType();
6561 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6562 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6563 SmallVector<APValue, 4> Elts;
6564 if (EltTy->isRealFloatingType()) {
6565 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006566 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006567 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006568 FloatEltSize = 80;
6569 for (unsigned i = 0; i < NElts; i++) {
6570 llvm::APInt Elt;
6571 if (BigEndian)
6572 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6573 else
6574 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006575 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006576 }
6577 } else if (EltTy->isIntegerType()) {
6578 for (unsigned i = 0; i < NElts; i++) {
6579 llvm::APInt Elt;
6580 if (BigEndian)
6581 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6582 else
6583 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6584 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6585 }
6586 } else {
6587 return Error(E);
6588 }
6589 return Success(Elts, E);
6590 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006591 default:
Richard Smith11562c52011-10-28 17:51:58 +00006592 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006593 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006594}
6595
Richard Smith2d406342011-10-22 21:10:00 +00006596bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006597VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006598 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006599 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006600 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006601
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006602 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006603 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006604
Eli Friedmanb9c71292012-01-03 23:24:20 +00006605 // The number of initializers can be less than the number of
6606 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006607 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006608 // should be initialized with zeroes.
6609 unsigned CountInits = 0, CountElts = 0;
6610 while (CountElts < NumElements) {
6611 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006612 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006613 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006614 APValue v;
6615 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6616 return Error(E);
6617 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006618 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006619 Elements.push_back(v.getVectorElt(j));
6620 CountElts += vlen;
6621 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006622 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006623 if (CountInits < NumInits) {
6624 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006625 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006626 } else // trailing integer zero.
6627 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6628 Elements.push_back(APValue(sInt));
6629 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006630 } else {
6631 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006632 if (CountInits < NumInits) {
6633 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006634 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006635 } else // trailing float zero.
6636 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6637 Elements.push_back(APValue(f));
6638 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006639 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006640 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006641 }
Richard Smith2d406342011-10-22 21:10:00 +00006642 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006643}
6644
Richard Smith2d406342011-10-22 21:10:00 +00006645bool
Richard Smithfddd3842011-12-30 21:15:51 +00006646VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006647 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006648 QualType EltTy = VT->getElementType();
6649 APValue ZeroElement;
6650 if (EltTy->isIntegerType())
6651 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6652 else
6653 ZeroElement =
6654 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6655
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006656 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006657 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006658}
6659
Richard Smith2d406342011-10-22 21:10:00 +00006660bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006661 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006662 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006663}
6664
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006665//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006666// Array Evaluation
6667//===----------------------------------------------------------------------===//
6668
6669namespace {
6670 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006671 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006672 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006673 APValue &Result;
6674 public:
6675
Richard Smithd62306a2011-11-10 06:34:14 +00006676 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6677 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006678
6679 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006680 assert((V.isArray() || V.isLValue()) &&
6681 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006682 Result = V;
6683 return true;
6684 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006685
Richard Smithfddd3842011-12-30 21:15:51 +00006686 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006687 const ConstantArrayType *CAT =
6688 Info.Ctx.getAsConstantArrayType(E->getType());
6689 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006690 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006691
6692 Result = APValue(APValue::UninitArray(), 0,
6693 CAT->getSize().getZExtValue());
6694 if (!Result.hasArrayFiller()) return true;
6695
Richard Smithfddd3842011-12-30 21:15:51 +00006696 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006697 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006698 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006699 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006700 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006701 }
6702
Richard Smith52a980a2015-08-28 02:43:42 +00006703 bool VisitCallExpr(const CallExpr *E) {
6704 return handleCallExpr(E, Result, &This);
6705 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006706 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006707 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006708 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006709 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6710 const LValue &Subobject,
6711 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006712 };
6713} // end anonymous namespace
6714
Richard Smithd62306a2011-11-10 06:34:14 +00006715static bool EvaluateArray(const Expr *E, const LValue &This,
6716 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006717 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006718 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006719}
6720
6721bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6722 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6723 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006724 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006725
Richard Smithca2cfbf2011-12-22 01:07:19 +00006726 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6727 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006728 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006729 LValue LV;
6730 if (!EvaluateLValue(E->getInit(0), LV, Info))
6731 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006732 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006733 LV.moveInto(Val);
6734 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006735 }
6736
Richard Smith253c2a32012-01-27 01:14:48 +00006737 bool Success = true;
6738
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006739 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6740 "zero-initialized array shouldn't have any initialized elts");
6741 APValue Filler;
6742 if (Result.isArray() && Result.hasArrayFiller())
6743 Filler = Result.getArrayFiller();
6744
Richard Smith9543c5e2013-04-22 14:44:29 +00006745 unsigned NumEltsToInit = E->getNumInits();
6746 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006747 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006748
6749 // If the initializer might depend on the array index, run it for each
6750 // array element. For now, just whitelist non-class value-initialization.
6751 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6752 NumEltsToInit = NumElts;
6753
6754 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006755
6756 // If the array was previously zero-initialized, preserve the
6757 // zero-initialized values.
6758 if (!Filler.isUninit()) {
6759 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6760 Result.getArrayInitializedElt(I) = Filler;
6761 if (Result.hasArrayFiller())
6762 Result.getArrayFiller() = Filler;
6763 }
6764
Richard Smithd62306a2011-11-10 06:34:14 +00006765 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006766 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006767 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6768 const Expr *Init =
6769 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006770 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006771 Info, Subobject, Init) ||
6772 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006773 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006774 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006775 return false;
6776 Success = false;
6777 }
Richard Smithd62306a2011-11-10 06:34:14 +00006778 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006779
Richard Smith9543c5e2013-04-22 14:44:29 +00006780 if (!Result.hasArrayFiller())
6781 return Success;
6782
6783 // If we get here, we have a trivial filler, which we can just evaluate
6784 // once and splat over the rest of the array elements.
6785 assert(FillerExpr && "no array filler for incomplete init list");
6786 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6787 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006788}
6789
Richard Smith410306b2016-12-12 02:53:20 +00006790bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6791 if (E->getCommonExpr() &&
6792 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6793 Info, E->getCommonExpr()->getSourceExpr()))
6794 return false;
6795
6796 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6797
6798 uint64_t Elements = CAT->getSize().getZExtValue();
6799 Result = APValue(APValue::UninitArray(), Elements, Elements);
6800
6801 LValue Subobject = This;
6802 Subobject.addArray(Info, E, CAT);
6803
6804 bool Success = true;
6805 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6806 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6807 Info, Subobject, E->getSubExpr()) ||
6808 !HandleLValueArrayAdjustment(Info, E, Subobject,
6809 CAT->getElementType(), 1)) {
6810 if (!Info.noteFailure())
6811 return false;
6812 Success = false;
6813 }
6814 }
6815
6816 return Success;
6817}
6818
Richard Smith027bf112011-11-17 22:56:20 +00006819bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006820 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6821}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006822
Richard Smith9543c5e2013-04-22 14:44:29 +00006823bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6824 const LValue &Subobject,
6825 APValue *Value,
6826 QualType Type) {
6827 bool HadZeroInit = !Value->isUninit();
6828
6829 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6830 unsigned N = CAT->getSize().getZExtValue();
6831
6832 // Preserve the array filler if we had prior zero-initialization.
6833 APValue Filler =
6834 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6835 : APValue();
6836
6837 *Value = APValue(APValue::UninitArray(), N, N);
6838
6839 if (HadZeroInit)
6840 for (unsigned I = 0; I != N; ++I)
6841 Value->getArrayInitializedElt(I) = Filler;
6842
6843 // Initialize the elements.
6844 LValue ArrayElt = Subobject;
6845 ArrayElt.addArray(Info, E, CAT);
6846 for (unsigned I = 0; I != N; ++I)
6847 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6848 CAT->getElementType()) ||
6849 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6850 CAT->getElementType(), 1))
6851 return false;
6852
6853 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006854 }
Richard Smith027bf112011-11-17 22:56:20 +00006855
Richard Smith9543c5e2013-04-22 14:44:29 +00006856 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006857 return Error(E);
6858
Richard Smithb8348f52016-05-12 22:16:28 +00006859 return RecordExprEvaluator(Info, Subobject, *Value)
6860 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006861}
6862
Richard Smithf3e9e432011-11-07 09:22:26 +00006863//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006864// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006865//
6866// As a GNU extension, we support casting pointers to sufficiently-wide integer
6867// types and back in constant folding. Integer values are thus represented
6868// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006869//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006870
6871namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006872class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006873 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006874 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006875public:
Richard Smith2e312c82012-03-03 22:46:17 +00006876 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006877 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006878
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006879 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006880 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006881 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006882 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006883 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006884 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006885 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006886 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006887 return true;
6888 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006889 bool Success(const llvm::APSInt &SI, const Expr *E) {
6890 return Success(SI, E, Result);
6891 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006892
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006893 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006894 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006895 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006896 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006897 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006898 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006899 Result.getInt().setIsUnsigned(
6900 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006901 return true;
6902 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006903 bool Success(const llvm::APInt &I, const Expr *E) {
6904 return Success(I, E, Result);
6905 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006906
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006907 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006908 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006909 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006910 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006911 return true;
6912 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006913 bool Success(uint64_t Value, const Expr *E) {
6914 return Success(Value, E, Result);
6915 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006916
Ken Dyckdbc01912011-03-11 02:13:43 +00006917 bool Success(CharUnits Size, const Expr *E) {
6918 return Success(Size.getQuantity(), E);
6919 }
6920
Richard Smith2e312c82012-03-03 22:46:17 +00006921 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006922 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006923 Result = V;
6924 return true;
6925 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006926 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006927 }
Mike Stump11289f42009-09-09 15:08:12 +00006928
Richard Smithfddd3842011-12-30 21:15:51 +00006929 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006930
Peter Collingbournee9200682011-05-13 03:29:01 +00006931 //===--------------------------------------------------------------------===//
6932 // Visitor Methods
6933 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006934
Chris Lattner7174bf32008-07-12 00:38:25 +00006935 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006936 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006937 }
6938 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006939 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006940 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006941
6942 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6943 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006944 if (CheckReferencedDecl(E, E->getDecl()))
6945 return true;
6946
6947 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006948 }
6949 bool VisitMemberExpr(const MemberExpr *E) {
6950 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006951 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006952 return true;
6953 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006954
6955 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006956 }
6957
Peter Collingbournee9200682011-05-13 03:29:01 +00006958 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006959 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006960 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006961 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006962 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006963
Peter Collingbournee9200682011-05-13 03:29:01 +00006964 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006965 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006966
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006967 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006968 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006969 }
Mike Stump11289f42009-09-09 15:08:12 +00006970
Ted Kremeneke65b0862012-03-06 20:05:56 +00006971 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6972 return Success(E->getValue(), E);
6973 }
Richard Smith410306b2016-12-12 02:53:20 +00006974
6975 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6976 if (Info.ArrayInitIndex == uint64_t(-1)) {
6977 // We were asked to evaluate this subexpression independent of the
6978 // enclosing ArrayInitLoopExpr. We can't do that.
6979 Info.FFDiag(E);
6980 return false;
6981 }
6982 return Success(Info.ArrayInitIndex, E);
6983 }
Daniel Jasperffdee092017-05-02 19:21:42 +00006984
Richard Smith4ce706a2011-10-11 21:43:33 +00006985 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006986 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006987 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006988 }
6989
Douglas Gregor29c42f22012-02-24 07:38:34 +00006990 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6991 return Success(E->getValue(), E);
6992 }
6993
John Wiegley6242b6a2011-04-28 00:16:57 +00006994 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6995 return Success(E->getValue(), E);
6996 }
6997
John Wiegleyf9f65842011-04-25 06:54:41 +00006998 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6999 return Success(E->getValue(), E);
7000 }
7001
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007002 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007003 bool VisitUnaryImag(const UnaryOperator *E);
7004
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007005 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007006 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007007
Eli Friedman4e7a2412009-02-27 04:45:43 +00007008 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007009};
Chris Lattner05706e882008-07-11 18:11:29 +00007010} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007011
Richard Smith11562c52011-10-28 17:51:58 +00007012/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7013/// produce either the integer value or a pointer.
7014///
7015/// GCC has a heinous extension which folds casts between pointer types and
7016/// pointer-sized integral types. We support this by allowing the evaluation of
7017/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7018/// Some simple arithmetic on such values is supported (they are treated much
7019/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007020static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007021 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007022 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007023 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007024}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007025
Richard Smithf57d8cb2011-12-09 22:58:01 +00007026static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007027 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007028 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007029 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007030 if (!Val.isInt()) {
7031 // FIXME: It would be better to produce the diagnostic for casting
7032 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007033 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007034 return false;
7035 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007036 Result = Val.getInt();
7037 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007038}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007039
Richard Smithf57d8cb2011-12-09 22:58:01 +00007040/// Check whether the given declaration can be directly converted to an integral
7041/// rvalue. If not, no diagnostic is produced; there are other things we can
7042/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007043bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007044 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007045 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007046 // Check for signedness/width mismatches between E type and ECD value.
7047 bool SameSign = (ECD->getInitVal().isSigned()
7048 == E->getType()->isSignedIntegerOrEnumerationType());
7049 bool SameWidth = (ECD->getInitVal().getBitWidth()
7050 == Info.Ctx.getIntWidth(E->getType()));
7051 if (SameSign && SameWidth)
7052 return Success(ECD->getInitVal(), E);
7053 else {
7054 // Get rid of mismatch (otherwise Success assertions will fail)
7055 // by computing a new value matching the type of E.
7056 llvm::APSInt Val = ECD->getInitVal();
7057 if (!SameSign)
7058 Val.setIsSigned(!ECD->getInitVal().isSigned());
7059 if (!SameWidth)
7060 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7061 return Success(Val, E);
7062 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007063 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007064 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007065}
7066
Chris Lattner86ee2862008-10-06 06:40:35 +00007067/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7068/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007069static int EvaluateBuiltinClassifyType(const CallExpr *E,
7070 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007071 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007072 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007073 enum gcc_type_class {
7074 no_type_class = -1,
7075 void_type_class, integer_type_class, char_type_class,
7076 enumeral_type_class, boolean_type_class,
7077 pointer_type_class, reference_type_class, offset_type_class,
7078 real_type_class, complex_type_class,
7079 function_type_class, method_type_class,
7080 record_type_class, union_type_class,
7081 array_type_class, string_type_class,
7082 lang_type_class
7083 };
Mike Stump11289f42009-09-09 15:08:12 +00007084
7085 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007086 // ideal, however it is what gcc does.
7087 if (E->getNumArgs() == 0)
7088 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007089
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007090 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7091 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7092
7093 switch (CanTy->getTypeClass()) {
7094#define TYPE(ID, BASE)
7095#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7096#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7097#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7098#include "clang/AST/TypeNodes.def"
7099 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7100
7101 case Type::Builtin:
7102 switch (BT->getKind()) {
7103#define BUILTIN_TYPE(ID, SINGLETON_ID)
7104#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7105#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7106#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7107#include "clang/AST/BuiltinTypes.def"
7108 case BuiltinType::Void:
7109 return void_type_class;
7110
7111 case BuiltinType::Bool:
7112 return boolean_type_class;
7113
7114 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7115 case BuiltinType::UChar:
7116 case BuiltinType::UShort:
7117 case BuiltinType::UInt:
7118 case BuiltinType::ULong:
7119 case BuiltinType::ULongLong:
7120 case BuiltinType::UInt128:
7121 return integer_type_class;
7122
7123 case BuiltinType::NullPtr:
7124 return pointer_type_class;
7125
7126 case BuiltinType::WChar_U:
7127 case BuiltinType::Char16:
7128 case BuiltinType::Char32:
7129 case BuiltinType::ObjCId:
7130 case BuiltinType::ObjCClass:
7131 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007132#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7133 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007134#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007135 case BuiltinType::OCLSampler:
7136 case BuiltinType::OCLEvent:
7137 case BuiltinType::OCLClkEvent:
7138 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007139 case BuiltinType::OCLReserveID:
7140 case BuiltinType::Dependent:
7141 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7142 };
7143
7144 case Type::Enum:
7145 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7146 break;
7147
7148 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007149 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007150 break;
7151
7152 case Type::MemberPointer:
7153 if (CanTy->isMemberDataPointerType())
7154 return offset_type_class;
7155 else {
7156 // We expect member pointers to be either data or function pointers,
7157 // nothing else.
7158 assert(CanTy->isMemberFunctionPointerType());
7159 return method_type_class;
7160 }
7161
7162 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007163 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007164
7165 case Type::FunctionNoProto:
7166 case Type::FunctionProto:
7167 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7168
7169 case Type::Record:
7170 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7171 switch (RT->getDecl()->getTagKind()) {
7172 case TagTypeKind::TTK_Struct:
7173 case TagTypeKind::TTK_Class:
7174 case TagTypeKind::TTK_Interface:
7175 return record_type_class;
7176
7177 case TagTypeKind::TTK_Enum:
7178 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7179
7180 case TagTypeKind::TTK_Union:
7181 return union_type_class;
7182 }
7183 }
David Blaikie83d382b2011-09-23 05:06:16 +00007184 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007185
7186 case Type::ConstantArray:
7187 case Type::VariableArray:
7188 case Type::IncompleteArray:
7189 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7190
7191 case Type::BlockPointer:
7192 case Type::LValueReference:
7193 case Type::RValueReference:
7194 case Type::Vector:
7195 case Type::ExtVector:
7196 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007197 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007198 case Type::ObjCObject:
7199 case Type::ObjCInterface:
7200 case Type::ObjCObjectPointer:
7201 case Type::Pipe:
7202 case Type::Atomic:
7203 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7204 }
7205
7206 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007207}
7208
Richard Smith5fab0c92011-12-28 19:48:30 +00007209/// EvaluateBuiltinConstantPForLValue - Determine the result of
7210/// __builtin_constant_p when applied to the given lvalue.
7211///
7212/// An lvalue is only "constant" if it is a pointer or reference to the first
7213/// character of a string literal.
7214template<typename LValue>
7215static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007216 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007217 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7218}
7219
7220/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7221/// GCC as we can manage.
7222static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7223 QualType ArgType = Arg->getType();
7224
7225 // __builtin_constant_p always has one operand. The rules which gcc follows
7226 // are not precisely documented, but are as follows:
7227 //
7228 // - If the operand is of integral, floating, complex or enumeration type,
7229 // and can be folded to a known value of that type, it returns 1.
7230 // - If the operand and can be folded to a pointer to the first character
7231 // of a string literal (or such a pointer cast to an integral type), it
7232 // returns 1.
7233 //
7234 // Otherwise, it returns 0.
7235 //
7236 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7237 // its support for this does not currently work.
7238 if (ArgType->isIntegralOrEnumerationType()) {
7239 Expr::EvalResult Result;
7240 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7241 return false;
7242
7243 APValue &V = Result.Val;
7244 if (V.getKind() == APValue::Int)
7245 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007246 if (V.getKind() == APValue::LValue)
7247 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007248 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7249 return Arg->isEvaluatable(Ctx);
7250 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7251 LValue LV;
7252 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007253 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007254 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7255 : EvaluatePointer(Arg, LV, Info)) &&
7256 !Status.HasSideEffects)
7257 return EvaluateBuiltinConstantPForLValue(LV);
7258 }
7259
7260 // Anything else isn't considered to be sufficiently constant.
7261 return false;
7262}
7263
John McCall95007602010-05-10 23:27:23 +00007264/// Retrieves the "underlying object type" of the given expression,
7265/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007266static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007267 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7268 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007269 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007270 } else if (const Expr *E = B.get<const Expr*>()) {
7271 if (isa<CompoundLiteralExpr>(E))
7272 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007273 }
7274
7275 return QualType();
7276}
7277
George Burgess IV3a03fab2015-09-04 21:28:13 +00007278/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007279/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007280/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007281/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7282///
7283/// Always returns an RValue with a pointer representation.
7284static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7285 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7286
7287 auto *NoParens = E->IgnoreParens();
7288 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007289 if (Cast == nullptr)
7290 return NoParens;
7291
7292 // We only conservatively allow a few kinds of casts, because this code is
7293 // inherently a simple solution that seeks to support the common case.
7294 auto CastKind = Cast->getCastKind();
7295 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7296 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007297 return NoParens;
7298
7299 auto *SubExpr = Cast->getSubExpr();
7300 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7301 return NoParens;
7302 return ignorePointerCastsAndParens(SubExpr);
7303}
7304
George Burgess IVa51c4072015-10-16 01:49:01 +00007305/// Checks to see if the given LValue's Designator is at the end of the LValue's
7306/// record layout. e.g.
7307/// struct { struct { int a, b; } fst, snd; } obj;
7308/// obj.fst // no
7309/// obj.snd // yes
7310/// obj.fst.a // no
7311/// obj.fst.b // no
7312/// obj.snd.a // no
7313/// obj.snd.b // yes
7314///
7315/// Please note: this function is specialized for how __builtin_object_size
7316/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007317///
7318/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007319static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7320 assert(!LVal.Designator.Invalid);
7321
George Burgess IV4168d752016-06-27 19:40:41 +00007322 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7323 const RecordDecl *Parent = FD->getParent();
7324 Invalid = Parent->isInvalidDecl();
7325 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007326 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007327 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007328 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7329 };
7330
7331 auto &Base = LVal.getLValueBase();
7332 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7333 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007334 bool Invalid;
7335 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7336 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007337 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007338 for (auto *FD : IFD->chain()) {
7339 bool Invalid;
7340 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7341 return Invalid;
7342 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007343 }
7344 }
7345
George Burgess IVe3763372016-12-22 02:50:20 +00007346 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007347 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007348 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7349 assert(isBaseAnAllocSizeCall(Base) &&
7350 "Unsized array in non-alloc_size call?");
7351 // If this is an alloc_size base, we should ignore the initial array index
George Burgess IVe3763372016-12-22 02:50:20 +00007352 ++I;
7353 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7354 }
7355
7356 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7357 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007358 if (BaseType->isArrayType()) {
7359 // Because __builtin_object_size treats arrays as objects, we can ignore
7360 // the index iff this is the last array in the Designator.
7361 if (I + 1 == E)
7362 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007363 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7364 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007365 if (Index + 1 != CAT->getSize())
7366 return false;
7367 BaseType = CAT->getElementType();
7368 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007369 const auto *CT = BaseType->castAs<ComplexType>();
7370 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007371 if (Index != 1)
7372 return false;
7373 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007374 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007375 bool Invalid;
7376 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7377 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007378 BaseType = FD->getType();
7379 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007380 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007381 return false;
7382 }
7383 }
7384 return true;
7385}
7386
George Burgess IVe3763372016-12-22 02:50:20 +00007387/// Tests to see if the LValue has a user-specified designator (that isn't
7388/// necessarily valid). Note that this always returns 'true' if the LValue has
7389/// an unsized array as its first designator entry, because there's currently no
7390/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007391static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007392 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007393 return false;
7394
George Burgess IVe3763372016-12-22 02:50:20 +00007395 if (!LVal.Designator.Entries.empty())
7396 return LVal.Designator.isMostDerivedAnUnsizedArray();
7397
George Burgess IVa51c4072015-10-16 01:49:01 +00007398 if (!LVal.InvalidBase)
7399 return true;
7400
George Burgess IVe3763372016-12-22 02:50:20 +00007401 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7402 // the LValueBase.
7403 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7404 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007405}
7406
George Burgess IVe3763372016-12-22 02:50:20 +00007407/// Attempts to detect a user writing into a piece of memory that's impossible
7408/// to figure out the size of by just using types.
7409static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7410 const SubobjectDesignator &Designator = LVal.Designator;
7411 // Notes:
7412 // - Users can only write off of the end when we have an invalid base. Invalid
7413 // bases imply we don't know where the memory came from.
7414 // - We used to be a bit more aggressive here; we'd only be conservative if
7415 // the array at the end was flexible, or if it had 0 or 1 elements. This
7416 // broke some common standard library extensions (PR30346), but was
7417 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7418 // with some sort of whitelist. OTOH, it seems that GCC is always
7419 // conservative with the last element in structs (if it's an array), so our
7420 // current behavior is more compatible than a whitelisting approach would
7421 // be.
7422 return LVal.InvalidBase &&
7423 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7424 Designator.MostDerivedIsArrayElement &&
7425 isDesignatorAtObjectEnd(Ctx, LVal);
7426}
7427
7428/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7429/// Fails if the conversion would cause loss of precision.
7430static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7431 CharUnits &Result) {
7432 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7433 if (Int.ugt(CharUnitsMax))
7434 return false;
7435 Result = CharUnits::fromQuantity(Int.getZExtValue());
7436 return true;
7437}
7438
7439/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7440/// determine how many bytes exist from the beginning of the object to either
7441/// the end of the current subobject, or the end of the object itself, depending
7442/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007443///
George Burgess IVe3763372016-12-22 02:50:20 +00007444/// If this returns false, the value of Result is undefined.
7445static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7446 unsigned Type, const LValue &LVal,
7447 CharUnits &EndOffset) {
7448 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007449
George Burgess IV7fb7e362017-01-03 23:35:19 +00007450 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7451 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7452 return false;
7453 return HandleSizeof(Info, ExprLoc, Ty, Result);
7454 };
7455
George Burgess IVe3763372016-12-22 02:50:20 +00007456 // We want to evaluate the size of the entire object. This is a valid fallback
7457 // for when Type=1 and the designator is invalid, because we're asked for an
7458 // upper-bound.
7459 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7460 // Type=3 wants a lower bound, so we can't fall back to this.
7461 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007462 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007463
7464 llvm::APInt APEndOffset;
7465 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7466 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7467 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7468
7469 if (LVal.InvalidBase)
7470 return false;
7471
7472 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007473 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007474 }
7475
George Burgess IVe3763372016-12-22 02:50:20 +00007476 // We want to evaluate the size of a subobject.
7477 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007478
7479 // The following is a moderately common idiom in C:
7480 //
7481 // struct Foo { int a; char c[1]; };
7482 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7483 // strcpy(&F->c[0], Bar);
7484 //
George Burgess IVe3763372016-12-22 02:50:20 +00007485 // In order to not break too much legacy code, we need to support it.
7486 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7487 // If we can resolve this to an alloc_size call, we can hand that back,
7488 // because we know for certain how many bytes there are to write to.
7489 llvm::APInt APEndOffset;
7490 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7491 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7492 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7493
7494 // If we cannot determine the size of the initial allocation, then we can't
7495 // given an accurate upper-bound. However, we are still able to give
7496 // conservative lower-bounds for Type=3.
7497 if (Type == 1)
7498 return false;
7499 }
7500
7501 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007502 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007503 return false;
7504
George Burgess IVe3763372016-12-22 02:50:20 +00007505 // According to the GCC documentation, we want the size of the subobject
7506 // denoted by the pointer. But that's not quite right -- what we actually
7507 // want is the size of the immediately-enclosing array, if there is one.
7508 int64_t ElemsRemaining;
7509 if (Designator.MostDerivedIsArrayElement &&
7510 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7511 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7512 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7513 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7514 } else {
7515 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7516 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007517
George Burgess IVe3763372016-12-22 02:50:20 +00007518 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7519 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007520}
7521
George Burgess IVe3763372016-12-22 02:50:20 +00007522/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7523/// returns true and stores the result in @p Size.
7524///
7525/// If @p WasError is non-null, this will report whether the failure to evaluate
7526/// is to be treated as an Error in IntExprEvaluator.
7527static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7528 EvalInfo &Info, uint64_t &Size) {
7529 // Determine the denoted object.
7530 LValue LVal;
7531 {
7532 // The operand of __builtin_object_size is never evaluated for side-effects.
7533 // If there are any, but we can determine the pointed-to object anyway, then
7534 // ignore the side-effects.
7535 SpeculativeEvaluationRAII SpeculativeEval(Info);
7536 FoldOffsetRAII Fold(Info);
7537
7538 if (E->isGLValue()) {
7539 // It's possible for us to be given GLValues if we're called via
7540 // Expr::tryEvaluateObjectSize.
7541 APValue RVal;
7542 if (!EvaluateAsRValue(Info, E, RVal))
7543 return false;
7544 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007545 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7546 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007547 return false;
7548 }
7549
7550 // If we point to before the start of the object, there are no accessible
7551 // bytes.
7552 if (LVal.getLValueOffset().isNegative()) {
7553 Size = 0;
7554 return true;
7555 }
7556
7557 CharUnits EndOffset;
7558 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7559 return false;
7560
7561 // If we've fallen outside of the end offset, just pretend there's nothing to
7562 // write to/read from.
7563 if (EndOffset <= LVal.getLValueOffset())
7564 Size = 0;
7565 else
7566 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7567 return true;
John McCall95007602010-05-10 23:27:23 +00007568}
7569
Peter Collingbournee9200682011-05-13 03:29:01 +00007570bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007571 if (unsigned BuiltinOp = E->getBuiltinCallee())
7572 return VisitBuiltinCallExpr(E, BuiltinOp);
7573
7574 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7575}
7576
7577bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7578 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007579 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007580 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007581 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007582
7583 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007584 // The type was checked when we built the expression.
7585 unsigned Type =
7586 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7587 assert(Type <= 3 && "unexpected type");
7588
George Burgess IVe3763372016-12-22 02:50:20 +00007589 uint64_t Size;
7590 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7591 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007592
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007593 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007594 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007595
Richard Smith01ade172012-05-23 04:13:20 +00007596 // Expression had no side effects, but we couldn't statically determine the
7597 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007598 switch (Info.EvalMode) {
7599 case EvalInfo::EM_ConstantExpression:
7600 case EvalInfo::EM_PotentialConstantExpression:
7601 case EvalInfo::EM_ConstantFold:
7602 case EvalInfo::EM_EvaluateForOverflow:
7603 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007604 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007605 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007606 return Error(E);
7607 case EvalInfo::EM_ConstantExpressionUnevaluated:
7608 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007609 // Reduce it to a constant now.
7610 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007611 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007612
7613 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007614 }
7615
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007616 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007617 case Builtin::BI__builtin_bswap32:
7618 case Builtin::BI__builtin_bswap64: {
7619 APSInt Val;
7620 if (!EvaluateInteger(E->getArg(0), Val, Info))
7621 return false;
7622
7623 return Success(Val.byteSwap(), E);
7624 }
7625
Richard Smith8889a3d2013-06-13 06:26:32 +00007626 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007627 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007628
7629 // FIXME: BI__builtin_clrsb
7630 // FIXME: BI__builtin_clrsbl
7631 // FIXME: BI__builtin_clrsbll
7632
Richard Smith80b3c8e2013-06-13 05:04:16 +00007633 case Builtin::BI__builtin_clz:
7634 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007635 case Builtin::BI__builtin_clzll:
7636 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007637 APSInt Val;
7638 if (!EvaluateInteger(E->getArg(0), Val, Info))
7639 return false;
7640 if (!Val)
7641 return Error(E);
7642
7643 return Success(Val.countLeadingZeros(), E);
7644 }
7645
Richard Smith8889a3d2013-06-13 06:26:32 +00007646 case Builtin::BI__builtin_constant_p:
7647 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7648
Richard Smith80b3c8e2013-06-13 05:04:16 +00007649 case Builtin::BI__builtin_ctz:
7650 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007651 case Builtin::BI__builtin_ctzll:
7652 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007653 APSInt Val;
7654 if (!EvaluateInteger(E->getArg(0), Val, Info))
7655 return false;
7656 if (!Val)
7657 return Error(E);
7658
7659 return Success(Val.countTrailingZeros(), E);
7660 }
7661
Richard Smith8889a3d2013-06-13 06:26:32 +00007662 case Builtin::BI__builtin_eh_return_data_regno: {
7663 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7664 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7665 return Success(Operand, E);
7666 }
7667
7668 case Builtin::BI__builtin_expect:
7669 return Visit(E->getArg(0));
7670
7671 case Builtin::BI__builtin_ffs:
7672 case Builtin::BI__builtin_ffsl:
7673 case Builtin::BI__builtin_ffsll: {
7674 APSInt Val;
7675 if (!EvaluateInteger(E->getArg(0), Val, Info))
7676 return false;
7677
7678 unsigned N = Val.countTrailingZeros();
7679 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7680 }
7681
7682 case Builtin::BI__builtin_fpclassify: {
7683 APFloat Val(0.0);
7684 if (!EvaluateFloat(E->getArg(5), Val, Info))
7685 return false;
7686 unsigned Arg;
7687 switch (Val.getCategory()) {
7688 case APFloat::fcNaN: Arg = 0; break;
7689 case APFloat::fcInfinity: Arg = 1; break;
7690 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7691 case APFloat::fcZero: Arg = 4; break;
7692 }
7693 return Visit(E->getArg(Arg));
7694 }
7695
7696 case Builtin::BI__builtin_isinf_sign: {
7697 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007698 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007699 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7700 }
7701
Richard Smithea3019d2013-10-15 19:07:14 +00007702 case Builtin::BI__builtin_isinf: {
7703 APFloat Val(0.0);
7704 return EvaluateFloat(E->getArg(0), Val, Info) &&
7705 Success(Val.isInfinity() ? 1 : 0, E);
7706 }
7707
7708 case Builtin::BI__builtin_isfinite: {
7709 APFloat Val(0.0);
7710 return EvaluateFloat(E->getArg(0), Val, Info) &&
7711 Success(Val.isFinite() ? 1 : 0, E);
7712 }
7713
7714 case Builtin::BI__builtin_isnan: {
7715 APFloat Val(0.0);
7716 return EvaluateFloat(E->getArg(0), Val, Info) &&
7717 Success(Val.isNaN() ? 1 : 0, E);
7718 }
7719
7720 case Builtin::BI__builtin_isnormal: {
7721 APFloat Val(0.0);
7722 return EvaluateFloat(E->getArg(0), Val, Info) &&
7723 Success(Val.isNormal() ? 1 : 0, E);
7724 }
7725
Richard Smith8889a3d2013-06-13 06:26:32 +00007726 case Builtin::BI__builtin_parity:
7727 case Builtin::BI__builtin_parityl:
7728 case Builtin::BI__builtin_parityll: {
7729 APSInt Val;
7730 if (!EvaluateInteger(E->getArg(0), Val, Info))
7731 return false;
7732
7733 return Success(Val.countPopulation() % 2, E);
7734 }
7735
Richard Smith80b3c8e2013-06-13 05:04:16 +00007736 case Builtin::BI__builtin_popcount:
7737 case Builtin::BI__builtin_popcountl:
7738 case Builtin::BI__builtin_popcountll: {
7739 APSInt Val;
7740 if (!EvaluateInteger(E->getArg(0), Val, Info))
7741 return false;
7742
7743 return Success(Val.countPopulation(), E);
7744 }
7745
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007746 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007747 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007748 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007749 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007750 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007751 << /*isConstexpr*/0 << /*isConstructor*/0
7752 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007753 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007754 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007755 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007756 case Builtin::BI__builtin_strlen:
7757 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007758 // As an extension, we support __builtin_strlen() as a constant expression,
7759 // and support folding strlen() to a constant.
7760 LValue String;
7761 if (!EvaluatePointer(E->getArg(0), String, Info))
7762 return false;
7763
Richard Smith8110c9d2016-11-29 19:45:17 +00007764 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7765
Richard Smithe6c19f22013-11-15 02:10:04 +00007766 // Fast path: if it's a string literal, search the string value.
7767 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7768 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007769 // The string literal may have embedded null characters. Find the first
7770 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007771 StringRef Str = S->getBytes();
7772 int64_t Off = String.Offset.getQuantity();
7773 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007774 S->getCharByteWidth() == 1 &&
7775 // FIXME: Add fast-path for wchar_t too.
7776 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007777 Str = Str.substr(Off);
7778
7779 StringRef::size_type Pos = Str.find(0);
7780 if (Pos != StringRef::npos)
7781 Str = Str.substr(0, Pos);
7782
7783 return Success(Str.size(), E);
7784 }
7785
7786 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007787 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007788
7789 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007790 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7791 APValue Char;
7792 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7793 !Char.isInt())
7794 return false;
7795 if (!Char.getInt())
7796 return Success(Strlen, E);
7797 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7798 return false;
7799 }
7800 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007801
Richard Smithe151bab2016-11-11 23:43:35 +00007802 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007803 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007804 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007805 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007806 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007807 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007808 // A call to strlen is not a constant expression.
7809 if (Info.getLangOpts().CPlusPlus11)
7810 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7811 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007812 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007813 else
7814 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7815 // Fall through.
7816 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007817 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007818 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007819 case Builtin::BI__builtin_wcsncmp:
7820 case Builtin::BI__builtin_memcmp:
7821 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007822 LValue String1, String2;
7823 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7824 !EvaluatePointer(E->getArg(1), String2, Info))
7825 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007826
7827 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7828
Richard Smithe151bab2016-11-11 23:43:35 +00007829 uint64_t MaxLength = uint64_t(-1);
7830 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007831 BuiltinOp != Builtin::BIwcscmp &&
7832 BuiltinOp != Builtin::BI__builtin_strcmp &&
7833 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007834 APSInt N;
7835 if (!EvaluateInteger(E->getArg(2), N, Info))
7836 return false;
7837 MaxLength = N.getExtValue();
7838 }
7839 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007840 BuiltinOp != Builtin::BIwmemcmp &&
7841 BuiltinOp != Builtin::BI__builtin_memcmp &&
7842 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007843 for (; MaxLength; --MaxLength) {
7844 APValue Char1, Char2;
7845 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7846 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7847 !Char1.isInt() || !Char2.isInt())
7848 return false;
7849 if (Char1.getInt() != Char2.getInt())
7850 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7851 if (StopAtNull && !Char1.getInt())
7852 return Success(0, E);
7853 assert(!(StopAtNull && !Char2.getInt()));
7854 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7855 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7856 return false;
7857 }
7858 // We hit the strncmp / memcmp limit.
7859 return Success(0, E);
7860 }
7861
Richard Smith01ba47d2012-04-13 00:45:38 +00007862 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007863 case Builtin::BI__atomic_is_lock_free:
7864 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007865 APSInt SizeVal;
7866 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7867 return false;
7868
7869 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7870 // of two less than the maximum inline atomic width, we know it is
7871 // lock-free. If the size isn't a power of two, or greater than the
7872 // maximum alignment where we promote atomics, we know it is not lock-free
7873 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7874 // the answer can only be determined at runtime; for example, 16-byte
7875 // atomics have lock-free implementations on some, but not all,
7876 // x86-64 processors.
7877
7878 // Check power-of-two.
7879 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007880 if (Size.isPowerOfTwo()) {
7881 // Check against inlining width.
7882 unsigned InlineWidthBits =
7883 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7884 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7885 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7886 Size == CharUnits::One() ||
7887 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7888 Expr::NPC_NeverValueDependent))
7889 // OK, we will inline appropriately-aligned operations of this size,
7890 // and _Atomic(T) is appropriately-aligned.
7891 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007892
Richard Smith01ba47d2012-04-13 00:45:38 +00007893 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7894 castAs<PointerType>()->getPointeeType();
7895 if (!PointeeType->isIncompleteType() &&
7896 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7897 // OK, we will inline operations on this object.
7898 return Success(1, E);
7899 }
7900 }
7901 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007902
Richard Smith01ba47d2012-04-13 00:45:38 +00007903 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7904 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007905 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007906 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007907}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007908
Richard Smith8b3497e2011-10-31 01:37:14 +00007909static bool HasSameBase(const LValue &A, const LValue &B) {
7910 if (!A.getLValueBase())
7911 return !B.getLValueBase();
7912 if (!B.getLValueBase())
7913 return false;
7914
Richard Smithce40ad62011-11-12 22:28:03 +00007915 if (A.getLValueBase().getOpaqueValue() !=
7916 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007917 const Decl *ADecl = GetLValueBaseDecl(A);
7918 if (!ADecl)
7919 return false;
7920 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007921 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007922 return false;
7923 }
7924
7925 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007926 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007927}
7928
Richard Smithd20f1e62014-10-21 23:01:04 +00007929/// \brief Determine whether this is a pointer past the end of the complete
7930/// object referred to by the lvalue.
7931static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7932 const LValue &LV) {
7933 // A null pointer can be viewed as being "past the end" but we don't
7934 // choose to look at it that way here.
7935 if (!LV.getLValueBase())
7936 return false;
7937
7938 // If the designator is valid and refers to a subobject, we're not pointing
7939 // past the end.
7940 if (!LV.getLValueDesignator().Invalid &&
7941 !LV.getLValueDesignator().isOnePastTheEnd())
7942 return false;
7943
David Majnemerc378ca52015-08-29 08:32:55 +00007944 // A pointer to an incomplete type might be past-the-end if the type's size is
7945 // zero. We cannot tell because the type is incomplete.
7946 QualType Ty = getType(LV.getLValueBase());
7947 if (Ty->isIncompleteType())
7948 return true;
7949
Richard Smithd20f1e62014-10-21 23:01:04 +00007950 // We're a past-the-end pointer if we point to the byte after the object,
7951 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007952 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007953 return LV.getLValueOffset() == Size;
7954}
7955
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007956namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007957
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007958/// \brief Data recursive integer evaluator of certain binary operators.
7959///
7960/// We use a data recursive algorithm for binary operators so that we are able
7961/// to handle extreme cases of chained binary operators without causing stack
7962/// overflow.
7963class DataRecursiveIntBinOpEvaluator {
7964 struct EvalResult {
7965 APValue Val;
7966 bool Failed;
7967
7968 EvalResult() : Failed(false) { }
7969
7970 void swap(EvalResult &RHS) {
7971 Val.swap(RHS.Val);
7972 Failed = RHS.Failed;
7973 RHS.Failed = false;
7974 }
7975 };
7976
7977 struct Job {
7978 const Expr *E;
7979 EvalResult LHSResult; // meaningful only for binary operator expression.
7980 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007981
David Blaikie73726062015-08-12 23:09:24 +00007982 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007983 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007984
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007985 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007986 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007987 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007988
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007989 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007990 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007991 };
7992
7993 SmallVector<Job, 16> Queue;
7994
7995 IntExprEvaluator &IntEval;
7996 EvalInfo &Info;
7997 APValue &FinalResult;
7998
7999public:
8000 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8001 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8002
8003 /// \brief True if \param E is a binary operator that we are going to handle
8004 /// data recursively.
8005 /// We handle binary operators that are comma, logical, or that have operands
8006 /// with integral or enumeration type.
8007 static bool shouldEnqueue(const BinaryOperator *E) {
8008 return E->getOpcode() == BO_Comma ||
8009 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008010 (E->isRValue() &&
8011 E->getType()->isIntegralOrEnumerationType() &&
8012 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008013 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008014 }
8015
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008016 bool Traverse(const BinaryOperator *E) {
8017 enqueue(E);
8018 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008019 while (!Queue.empty())
8020 process(PrevResult);
8021
8022 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008023
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008024 FinalResult.swap(PrevResult.Val);
8025 return true;
8026 }
8027
8028private:
8029 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8030 return IntEval.Success(Value, E, Result);
8031 }
8032 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8033 return IntEval.Success(Value, E, Result);
8034 }
8035 bool Error(const Expr *E) {
8036 return IntEval.Error(E);
8037 }
8038 bool Error(const Expr *E, diag::kind D) {
8039 return IntEval.Error(E, D);
8040 }
8041
8042 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8043 return Info.CCEDiag(E, D);
8044 }
8045
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008046 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8047 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008048 bool &SuppressRHSDiags);
8049
8050 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8051 const BinaryOperator *E, APValue &Result);
8052
8053 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8054 Result.Failed = !Evaluate(Result.Val, Info, E);
8055 if (Result.Failed)
8056 Result.Val = APValue();
8057 }
8058
Richard Trieuba4d0872012-03-21 23:30:30 +00008059 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008060
8061 void enqueue(const Expr *E) {
8062 E = E->IgnoreParens();
8063 Queue.resize(Queue.size()+1);
8064 Queue.back().E = E;
8065 Queue.back().Kind = Job::AnyExprKind;
8066 }
8067};
8068
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008069}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008070
8071bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008072 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008073 bool &SuppressRHSDiags) {
8074 if (E->getOpcode() == BO_Comma) {
8075 // Ignore LHS but note if we could not evaluate it.
8076 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008077 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008078 return true;
8079 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008080
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008081 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008082 bool LHSAsBool;
8083 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008084 // We were able to evaluate the LHS, see if we can get away with not
8085 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008086 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8087 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008088 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008089 }
8090 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008091 LHSResult.Failed = true;
8092
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008093 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008094 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008095 if (!Info.noteSideEffect())
8096 return false;
8097
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008098 // We can't evaluate the LHS; however, sometimes the result
8099 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8100 // Don't ignore RHS and suppress diagnostics from this arm.
8101 SuppressRHSDiags = true;
8102 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008103
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008104 return true;
8105 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008106
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008107 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8108 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008109
George Burgess IVa145e252016-05-25 22:38:36 +00008110 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008111 return false; // Ignore RHS;
8112
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008113 return true;
8114}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008115
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008116static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8117 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008118 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8119 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8120 // offsets.
8121 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8122 CharUnits &Offset = LVal.getLValueOffset();
8123 uint64_t Offset64 = Offset.getQuantity();
8124 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8125 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8126 : Offset64 + Index64);
8127}
8128
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008129bool DataRecursiveIntBinOpEvaluator::
8130 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8131 const BinaryOperator *E, APValue &Result) {
8132 if (E->getOpcode() == BO_Comma) {
8133 if (RHSResult.Failed)
8134 return false;
8135 Result = RHSResult.Val;
8136 return true;
8137 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008138
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008139 if (E->isLogicalOp()) {
8140 bool lhsResult, rhsResult;
8141 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8142 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008143
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008144 if (LHSIsOK) {
8145 if (RHSIsOK) {
8146 if (E->getOpcode() == BO_LOr)
8147 return Success(lhsResult || rhsResult, E, Result);
8148 else
8149 return Success(lhsResult && rhsResult, E, Result);
8150 }
8151 } else {
8152 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008153 // We can't evaluate the LHS; however, sometimes the result
8154 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8155 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008156 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008157 }
8158 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008159
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008160 return false;
8161 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008162
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008163 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8164 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008165
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008166 if (LHSResult.Failed || RHSResult.Failed)
8167 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008168
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008169 const APValue &LHSVal = LHSResult.Val;
8170 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008171
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008172 // Handle cases like (unsigned long)&a + 4.
8173 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8174 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008175 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008176 return true;
8177 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008178
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008179 // Handle cases like 4 + (unsigned long)&a
8180 if (E->getOpcode() == BO_Add &&
8181 RHSVal.isLValue() && LHSVal.isInt()) {
8182 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008183 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008184 return true;
8185 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008186
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008187 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8188 // Handle (intptr_t)&&A - (intptr_t)&&B.
8189 if (!LHSVal.getLValueOffset().isZero() ||
8190 !RHSVal.getLValueOffset().isZero())
8191 return false;
8192 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8193 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8194 if (!LHSExpr || !RHSExpr)
8195 return false;
8196 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8197 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8198 if (!LHSAddrExpr || !RHSAddrExpr)
8199 return false;
8200 // Make sure both labels come from the same function.
8201 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8202 RHSAddrExpr->getLabel()->getDeclContext())
8203 return false;
8204 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8205 return true;
8206 }
Richard Smith43e77732013-05-07 04:50:00 +00008207
8208 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008209 if (!LHSVal.isInt() || !RHSVal.isInt())
8210 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008211
8212 // Set up the width and signedness manually, in case it can't be deduced
8213 // from the operation we're performing.
8214 // FIXME: Don't do this in the cases where we can deduce it.
8215 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8216 E->getType()->isUnsignedIntegerOrEnumerationType());
8217 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8218 RHSVal.getInt(), Value))
8219 return false;
8220 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008221}
8222
Richard Trieuba4d0872012-03-21 23:30:30 +00008223void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008224 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008225
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008226 switch (job.Kind) {
8227 case Job::AnyExprKind: {
8228 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8229 if (shouldEnqueue(Bop)) {
8230 job.Kind = Job::BinOpKind;
8231 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008232 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008233 }
8234 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008235
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008236 EvaluateExpr(job.E, Result);
8237 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008238 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008239 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008240
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008241 case Job::BinOpKind: {
8242 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008243 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008244 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008245 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008246 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008247 }
8248 if (SuppressRHSDiags)
8249 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008250 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008251 job.Kind = Job::BinOpVisitedLHSKind;
8252 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008253 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008254 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008255
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008256 case Job::BinOpVisitedLHSKind: {
8257 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8258 EvalResult RHS;
8259 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008260 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008261 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008262 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008263 }
8264 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008265
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008266 llvm_unreachable("Invalid Job::Kind!");
8267}
8268
George Burgess IV8c892b52016-05-25 22:31:54 +00008269namespace {
8270/// Used when we determine that we should fail, but can keep evaluating prior to
8271/// noting that we had a failure.
8272class DelayedNoteFailureRAII {
8273 EvalInfo &Info;
8274 bool NoteFailure;
8275
8276public:
8277 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8278 : Info(Info), NoteFailure(NoteFailure) {}
8279 ~DelayedNoteFailureRAII() {
8280 if (NoteFailure) {
8281 bool ContinueAfterFailure = Info.noteFailure();
8282 (void)ContinueAfterFailure;
8283 assert(ContinueAfterFailure &&
8284 "Shouldn't have kept evaluating on failure.");
8285 }
8286 }
8287};
8288}
8289
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008290bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008291 // We don't call noteFailure immediately because the assignment happens after
8292 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008293 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008294 return Error(E);
8295
George Burgess IV8c892b52016-05-25 22:31:54 +00008296 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008297 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8298 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008299
Anders Carlssonacc79812008-11-16 07:17:21 +00008300 QualType LHSTy = E->getLHS()->getType();
8301 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008302
Chandler Carruthb29a7432014-10-11 11:03:30 +00008303 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008304 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008305 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008306 if (E->isAssignmentOp()) {
8307 LValue LV;
8308 EvaluateLValue(E->getLHS(), LV, Info);
8309 LHSOK = false;
8310 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008311 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8312 if (LHSOK) {
8313 LHS.makeComplexFloat();
8314 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8315 }
8316 } else {
8317 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8318 }
George Burgess IVa145e252016-05-25 22:38:36 +00008319 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008320 return false;
8321
Chandler Carruthb29a7432014-10-11 11:03:30 +00008322 if (E->getRHS()->getType()->isRealFloatingType()) {
8323 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8324 return false;
8325 RHS.makeComplexFloat();
8326 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8327 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008328 return false;
8329
8330 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008331 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008332 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008333 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008334 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8335
John McCalle3027922010-08-25 11:45:40 +00008336 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008337 return Success((CR_r == APFloat::cmpEqual &&
8338 CR_i == APFloat::cmpEqual), E);
8339 else {
John McCalle3027922010-08-25 11:45:40 +00008340 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008341 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008342 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008343 CR_r == APFloat::cmpLessThan ||
8344 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008345 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008346 CR_i == APFloat::cmpLessThan ||
8347 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008348 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008349 } else {
John McCalle3027922010-08-25 11:45:40 +00008350 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008351 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8352 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8353 else {
John McCalle3027922010-08-25 11:45:40 +00008354 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008355 "Invalid compex comparison.");
8356 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8357 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8358 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008359 }
8360 }
Mike Stump11289f42009-09-09 15:08:12 +00008361
Anders Carlssonacc79812008-11-16 07:17:21 +00008362 if (LHSTy->isRealFloatingType() &&
8363 RHSTy->isRealFloatingType()) {
8364 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008365
Richard Smith253c2a32012-01-27 01:14:48 +00008366 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008367 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008368 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008369
Richard Smith253c2a32012-01-27 01:14:48 +00008370 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008371 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008372
Anders Carlssonacc79812008-11-16 07:17:21 +00008373 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008374
Anders Carlssonacc79812008-11-16 07:17:21 +00008375 switch (E->getOpcode()) {
8376 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008377 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008378 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008379 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008380 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008381 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008382 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008383 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008384 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008385 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008386 E);
John McCalle3027922010-08-25 11:45:40 +00008387 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008388 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008389 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008390 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008391 || CR == APFloat::cmpLessThan
8392 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008393 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008394 }
Mike Stump11289f42009-09-09 15:08:12 +00008395
Eli Friedmana38da572009-04-28 19:17:36 +00008396 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008397 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008398 LValue LHSValue, RHSValue;
8399
8400 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008401 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008402 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008403
Richard Smith253c2a32012-01-27 01:14:48 +00008404 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008405 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008406
Richard Smith8b3497e2011-10-31 01:37:14 +00008407 // Reject differing bases from the normal codepath; we special-case
8408 // comparisons to null.
8409 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008410 if (E->getOpcode() == BO_Sub) {
8411 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008412 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008413 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008414 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008415 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008416 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008417 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008418 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8419 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8420 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008421 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008422 // Make sure both labels come from the same function.
8423 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8424 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008425 return Error(E);
8426 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008427 }
Richard Smith83c68212011-10-31 05:11:32 +00008428 // Inequalities and subtractions between unrelated pointers have
8429 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008430 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008431 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008432 // A constant address may compare equal to the address of a symbol.
8433 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008434 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008435 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8436 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008437 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008438 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008439 // distinct addresses. In clang, the result of such a comparison is
8440 // unspecified, so it is not a constant expression. However, we do know
8441 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008442 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8443 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008444 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008445 // We can't tell whether weak symbols will end up pointing to the same
8446 // object.
8447 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008448 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008449 // We can't compare the address of the start of one object with the
8450 // past-the-end address of another object, per C++ DR1652.
8451 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8452 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8453 (RHSValue.Base && RHSValue.Offset.isZero() &&
8454 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8455 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008456 // We can't tell whether an object is at the same address as another
8457 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008458 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8459 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008460 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008461 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008462 // (Note that clang defaults to -fmerge-all-constants, which can
8463 // lead to inconsistent results for comparisons involving the address
8464 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008465 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008466 }
Eli Friedman64004332009-03-23 04:38:34 +00008467
Richard Smith1b470412012-02-01 08:10:20 +00008468 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8469 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8470
Richard Smith84f6dcf2012-02-02 01:16:57 +00008471 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8472 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8473
John McCalle3027922010-08-25 11:45:40 +00008474 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008475 // C++11 [expr.add]p6:
8476 // Unless both pointers point to elements of the same array object, or
8477 // one past the last element of the array object, the behavior is
8478 // undefined.
8479 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8480 !AreElementsOfSameArray(getType(LHSValue.Base),
8481 LHSDesignator, RHSDesignator))
8482 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8483
Chris Lattner882bdf22010-04-20 17:13:14 +00008484 QualType Type = E->getLHS()->getType();
8485 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008486
Richard Smithd62306a2011-11-10 06:34:14 +00008487 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008488 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008489 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008490
Richard Smith84c6b3d2013-09-10 21:34:14 +00008491 // As an extension, a type may have zero size (empty struct or union in
8492 // C, array of zero length). Pointer subtraction in such cases has
8493 // undefined behavior, so is not constant.
8494 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008495 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008496 << ElementType;
8497 return false;
8498 }
8499
Richard Smith1b470412012-02-01 08:10:20 +00008500 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8501 // and produce incorrect results when it overflows. Such behavior
8502 // appears to be non-conforming, but is common, so perhaps we should
8503 // assume the standard intended for such cases to be undefined behavior
8504 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008505
Richard Smith1b470412012-02-01 08:10:20 +00008506 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8507 // overflow in the final conversion to ptrdiff_t.
8508 APSInt LHS(
8509 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8510 APSInt RHS(
8511 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8512 APSInt ElemSize(
8513 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8514 APSInt TrueResult = (LHS - RHS) / ElemSize;
8515 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8516
Richard Smith0c6124b2015-12-03 01:36:22 +00008517 if (Result.extend(65) != TrueResult &&
8518 !HandleOverflow(Info, E, TrueResult, E->getType()))
8519 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008520 return Success(Result, E);
8521 }
Richard Smithde21b242012-01-31 06:41:30 +00008522
8523 // C++11 [expr.rel]p3:
8524 // Pointers to void (after pointer conversions) can be compared, with a
8525 // result defined as follows: If both pointers represent the same
8526 // address or are both the null pointer value, the result is true if the
8527 // operator is <= or >= and false otherwise; otherwise the result is
8528 // unspecified.
8529 // We interpret this as applying to pointers to *cv* void.
8530 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008531 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008532 CCEDiag(E, diag::note_constexpr_void_comparison);
8533
Richard Smith84f6dcf2012-02-02 01:16:57 +00008534 // C++11 [expr.rel]p2:
8535 // - If two pointers point to non-static data members of the same object,
8536 // or to subobjects or array elements fo such members, recursively, the
8537 // pointer to the later declared member compares greater provided the
8538 // two members have the same access control and provided their class is
8539 // not a union.
8540 // [...]
8541 // - Otherwise pointer comparisons are unspecified.
8542 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8543 E->isRelationalOp()) {
8544 bool WasArrayIndex;
8545 unsigned Mismatch =
8546 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8547 RHSDesignator, WasArrayIndex);
8548 // At the point where the designators diverge, the comparison has a
8549 // specified value if:
8550 // - we are comparing array indices
8551 // - we are comparing fields of a union, or fields with the same access
8552 // Otherwise, the result is unspecified and thus the comparison is not a
8553 // constant expression.
8554 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8555 Mismatch < RHSDesignator.Entries.size()) {
8556 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8557 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8558 if (!LF && !RF)
8559 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8560 else if (!LF)
8561 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8562 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8563 << RF->getParent() << RF;
8564 else if (!RF)
8565 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8566 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8567 << LF->getParent() << LF;
8568 else if (!LF->getParent()->isUnion() &&
8569 LF->getAccess() != RF->getAccess())
8570 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8571 << LF << LF->getAccess() << RF << RF->getAccess()
8572 << LF->getParent();
8573 }
8574 }
8575
Eli Friedman6c31cb42012-04-16 04:30:08 +00008576 // The comparison here must be unsigned, and performed with the same
8577 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008578 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8579 uint64_t CompareLHS = LHSOffset.getQuantity();
8580 uint64_t CompareRHS = RHSOffset.getQuantity();
8581 assert(PtrSize <= 64 && "Unexpected pointer width");
8582 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8583 CompareLHS &= Mask;
8584 CompareRHS &= Mask;
8585
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008586 // If there is a base and this is a relational operator, we can only
8587 // compare pointers within the object in question; otherwise, the result
8588 // depends on where the object is located in memory.
8589 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8590 QualType BaseTy = getType(LHSValue.Base);
8591 if (BaseTy->isIncompleteType())
8592 return Error(E);
8593 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8594 uint64_t OffsetLimit = Size.getQuantity();
8595 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8596 return Error(E);
8597 }
8598
Richard Smith8b3497e2011-10-31 01:37:14 +00008599 switch (E->getOpcode()) {
8600 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008601 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8602 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8603 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8604 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8605 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8606 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008607 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008608 }
8609 }
Richard Smith7bb00672012-02-01 01:42:44 +00008610
8611 if (LHSTy->isMemberPointerType()) {
8612 assert(E->isEqualityOp() && "unexpected member pointer operation");
8613 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8614
8615 MemberPtr LHSValue, RHSValue;
8616
8617 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008618 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008619 return false;
8620
8621 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8622 return false;
8623
8624 // C++11 [expr.eq]p2:
8625 // If both operands are null, they compare equal. Otherwise if only one is
8626 // null, they compare unequal.
8627 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8628 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8629 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8630 }
8631
8632 // Otherwise if either is a pointer to a virtual member function, the
8633 // result is unspecified.
8634 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8635 if (MD->isVirtual())
8636 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8637 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8638 if (MD->isVirtual())
8639 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8640
8641 // Otherwise they compare equal if and only if they would refer to the
8642 // same member of the same most derived object or the same subobject if
8643 // they were dereferenced with a hypothetical object of the associated
8644 // class type.
8645 bool Equal = LHSValue == RHSValue;
8646 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8647 }
8648
Richard Smithab44d9b2012-02-14 22:35:28 +00008649 if (LHSTy->isNullPtrType()) {
8650 assert(E->isComparisonOp() && "unexpected nullptr operation");
8651 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8652 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8653 // are compared, the result is true of the operator is <=, >= or ==, and
8654 // false otherwise.
8655 BinaryOperator::Opcode Opcode = E->getOpcode();
8656 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8657 }
8658
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008659 assert((!LHSTy->isIntegralOrEnumerationType() ||
8660 !RHSTy->isIntegralOrEnumerationType()) &&
8661 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8662 // We can't continue from here for non-integral types.
8663 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008664}
8665
Peter Collingbournee190dee2011-03-11 19:24:49 +00008666/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8667/// a result as the expression's type.
8668bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8669 const UnaryExprOrTypeTraitExpr *E) {
8670 switch(E->getKind()) {
8671 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008672 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008673 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008674 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008675 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008676 }
Eli Friedman64004332009-03-23 04:38:34 +00008677
Peter Collingbournee190dee2011-03-11 19:24:49 +00008678 case UETT_VecStep: {
8679 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008680
Peter Collingbournee190dee2011-03-11 19:24:49 +00008681 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008682 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008683
Peter Collingbournee190dee2011-03-11 19:24:49 +00008684 // The vec_step built-in functions that take a 3-component
8685 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8686 if (n == 3)
8687 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008688
Peter Collingbournee190dee2011-03-11 19:24:49 +00008689 return Success(n, E);
8690 } else
8691 return Success(1, E);
8692 }
8693
8694 case UETT_SizeOf: {
8695 QualType SrcTy = E->getTypeOfArgument();
8696 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8697 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008698 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8699 SrcTy = Ref->getPointeeType();
8700
Richard Smithd62306a2011-11-10 06:34:14 +00008701 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008702 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008703 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008704 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008705 }
Alexey Bataev00396512015-07-02 03:40:19 +00008706 case UETT_OpenMPRequiredSimdAlign:
8707 assert(E->isArgumentType());
8708 return Success(
8709 Info.Ctx.toCharUnitsFromBits(
8710 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8711 .getQuantity(),
8712 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008713 }
8714
8715 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008716}
8717
Peter Collingbournee9200682011-05-13 03:29:01 +00008718bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008719 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008720 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008721 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008722 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008723 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008724 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008725 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008726 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008727 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008728 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008729 APSInt IdxResult;
8730 if (!EvaluateInteger(Idx, IdxResult, Info))
8731 return false;
8732 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8733 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008734 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008735 CurrentType = AT->getElementType();
8736 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8737 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008738 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008739 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008740
James Y Knight7281c352015-12-29 22:31:18 +00008741 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008742 FieldDecl *MemberDecl = ON.getField();
8743 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008744 if (!RT)
8745 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008746 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008747 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008748 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008749 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008750 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008751 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008752 CurrentType = MemberDecl->getType().getNonReferenceType();
8753 break;
8754 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008755
James Y Knight7281c352015-12-29 22:31:18 +00008756 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008757 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008758
James Y Knight7281c352015-12-29 22:31:18 +00008759 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008760 CXXBaseSpecifier *BaseSpec = ON.getBase();
8761 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008762 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008763
8764 // Find the layout of the class whose base we are looking into.
8765 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008766 if (!RT)
8767 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008768 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008769 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008770 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8771
8772 // Find the base class itself.
8773 CurrentType = BaseSpec->getType();
8774 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8775 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008776 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008777
Douglas Gregord1702062010-04-29 00:18:15 +00008778 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008779 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008780 break;
8781 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008782 }
8783 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008784 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008785}
8786
Chris Lattnere13042c2008-07-11 19:10:17 +00008787bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008788 switch (E->getOpcode()) {
8789 default:
8790 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8791 // See C99 6.6p3.
8792 return Error(E);
8793 case UO_Extension:
8794 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8795 // If so, we could clear the diagnostic ID.
8796 return Visit(E->getSubExpr());
8797 case UO_Plus:
8798 // The result is just the value.
8799 return Visit(E->getSubExpr());
8800 case UO_Minus: {
8801 if (!Visit(E->getSubExpr()))
8802 return false;
8803 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008804 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008805 if (Value.isSigned() && Value.isMinSignedValue() &&
8806 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8807 E->getType()))
8808 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008809 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008810 }
8811 case UO_Not: {
8812 if (!Visit(E->getSubExpr()))
8813 return false;
8814 if (!Result.isInt()) return Error(E);
8815 return Success(~Result.getInt(), E);
8816 }
8817 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008818 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008819 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008820 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008821 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008822 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008823 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008824}
Mike Stump11289f42009-09-09 15:08:12 +00008825
Chris Lattner477c4be2008-07-12 01:15:53 +00008826/// HandleCast - This is used to evaluate implicit or explicit casts where the
8827/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008828bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8829 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008830 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008831 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008832
Eli Friedmanc757de22011-03-25 00:43:55 +00008833 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008834 case CK_BaseToDerived:
8835 case CK_DerivedToBase:
8836 case CK_UncheckedDerivedToBase:
8837 case CK_Dynamic:
8838 case CK_ToUnion:
8839 case CK_ArrayToPointerDecay:
8840 case CK_FunctionToPointerDecay:
8841 case CK_NullToPointer:
8842 case CK_NullToMemberPointer:
8843 case CK_BaseToDerivedMemberPointer:
8844 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008845 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008846 case CK_ConstructorConversion:
8847 case CK_IntegralToPointer:
8848 case CK_ToVoid:
8849 case CK_VectorSplat:
8850 case CK_IntegralToFloating:
8851 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008852 case CK_CPointerToObjCPointerCast:
8853 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008854 case CK_AnyPointerToBlockPointerCast:
8855 case CK_ObjCObjectLValueCast:
8856 case CK_FloatingRealToComplex:
8857 case CK_FloatingComplexToReal:
8858 case CK_FloatingComplexCast:
8859 case CK_FloatingComplexToIntegralComplex:
8860 case CK_IntegralRealToComplex:
8861 case CK_IntegralComplexCast:
8862 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008863 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008864 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008865 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008866 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008867 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008868 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008869 llvm_unreachable("invalid cast kind for integral value");
8870
Eli Friedman9faf2f92011-03-25 19:07:11 +00008871 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008872 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008873 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008874 case CK_ARCProduceObject:
8875 case CK_ARCConsumeObject:
8876 case CK_ARCReclaimReturnedObject:
8877 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008878 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008879 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008880
Richard Smith4ef685b2012-01-17 21:17:26 +00008881 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008882 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008883 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008884 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008885 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008886
8887 case CK_MemberPointerToBoolean:
8888 case CK_PointerToBoolean:
8889 case CK_IntegralToBoolean:
8890 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008891 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008892 case CK_FloatingComplexToBoolean:
8893 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008894 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008895 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008896 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008897 uint64_t IntResult = BoolResult;
8898 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8899 IntResult = (uint64_t)-1;
8900 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008901 }
8902
Eli Friedmanc757de22011-03-25 00:43:55 +00008903 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008904 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008905 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008906
Eli Friedman742421e2009-02-20 01:15:07 +00008907 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008908 // Allow casts of address-of-label differences if they are no-ops
8909 // or narrowing. (The narrowing case isn't actually guaranteed to
8910 // be constant-evaluatable except in some narrow cases which are hard
8911 // to detect here. We let it through on the assumption the user knows
8912 // what they are doing.)
8913 if (Result.isAddrLabelDiff())
8914 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008915 // Only allow casts of lvalues if they are lossless.
8916 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8917 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008918
Richard Smith911e1422012-01-30 22:27:01 +00008919 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8920 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008921 }
Mike Stump11289f42009-09-09 15:08:12 +00008922
Eli Friedmanc757de22011-03-25 00:43:55 +00008923 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008924 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8925
John McCall45d55e42010-05-07 21:00:08 +00008926 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008927 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008928 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008929
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008930 if (LV.getLValueBase()) {
8931 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008932 // FIXME: Allow a larger integer size than the pointer size, and allow
8933 // narrowing back down to pointer width in subsequent integral casts.
8934 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008935 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008936 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008937
Richard Smithcf74da72011-11-16 07:18:12 +00008938 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008939 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008940 return true;
8941 }
8942
Yaxun Liu402804b2016-12-15 08:09:08 +00008943 uint64_t V;
8944 if (LV.isNullPointer())
8945 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8946 else
8947 V = LV.getLValueOffset().getQuantity();
8948
8949 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008950 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008951 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008952
Eli Friedmanc757de22011-03-25 00:43:55 +00008953 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008954 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008955 if (!EvaluateComplex(SubExpr, C, Info))
8956 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008957 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008958 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008959
Eli Friedmanc757de22011-03-25 00:43:55 +00008960 case CK_FloatingToIntegral: {
8961 APFloat F(0.0);
8962 if (!EvaluateFloat(SubExpr, F, Info))
8963 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008964
Richard Smith357362d2011-12-13 06:39:58 +00008965 APSInt Value;
8966 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8967 return false;
8968 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008969 }
8970 }
Mike Stump11289f42009-09-09 15:08:12 +00008971
Eli Friedmanc757de22011-03-25 00:43:55 +00008972 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008973}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008974
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008975bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8976 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008977 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008978 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8979 return false;
8980 if (!LV.isComplexInt())
8981 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008982 return Success(LV.getComplexIntReal(), E);
8983 }
8984
8985 return Visit(E->getSubExpr());
8986}
8987
Eli Friedman4e7a2412009-02-27 04:45:43 +00008988bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008989 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008990 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008991 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8992 return false;
8993 if (!LV.isComplexInt())
8994 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008995 return Success(LV.getComplexIntImag(), E);
8996 }
8997
Richard Smith4a678122011-10-24 18:44:57 +00008998 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008999 return Success(0, E);
9000}
9001
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009002bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9003 return Success(E->getPackLength(), E);
9004}
9005
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009006bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9007 return Success(E->getValue(), E);
9008}
9009
Chris Lattner05706e882008-07-11 18:11:29 +00009010//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009011// Float Evaluation
9012//===----------------------------------------------------------------------===//
9013
9014namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009015class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009016 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009017 APFloat &Result;
9018public:
9019 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009020 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009021
Richard Smith2e312c82012-03-03 22:46:17 +00009022 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009023 Result = V.getFloat();
9024 return true;
9025 }
Eli Friedman24c01542008-08-22 00:06:13 +00009026
Richard Smithfddd3842011-12-30 21:15:51 +00009027 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009028 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9029 return true;
9030 }
9031
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009032 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009033
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009034 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009035 bool VisitBinaryOperator(const BinaryOperator *E);
9036 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009037 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009038
John McCallb1fb0d32010-05-07 22:08:54 +00009039 bool VisitUnaryReal(const UnaryOperator *E);
9040 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009041
Richard Smithfddd3842011-12-30 21:15:51 +00009042 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009043};
9044} // end anonymous namespace
9045
9046static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009047 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009048 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009049}
9050
Jay Foad39c79802011-01-12 09:06:06 +00009051static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009052 QualType ResultTy,
9053 const Expr *Arg,
9054 bool SNaN,
9055 llvm::APFloat &Result) {
9056 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9057 if (!S) return false;
9058
9059 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9060
9061 llvm::APInt fill;
9062
9063 // Treat empty strings as if they were zero.
9064 if (S->getString().empty())
9065 fill = llvm::APInt(32, 0);
9066 else if (S->getString().getAsInteger(0, fill))
9067 return false;
9068
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009069 if (Context.getTargetInfo().isNan2008()) {
9070 if (SNaN)
9071 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9072 else
9073 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9074 } else {
9075 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9076 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9077 // a different encoding to what became a standard in 2008, and for pre-
9078 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9079 // sNaN. This is now known as "legacy NaN" encoding.
9080 if (SNaN)
9081 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9082 else
9083 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9084 }
9085
John McCall16291492010-02-28 13:00:19 +00009086 return true;
9087}
9088
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009089bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009090 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009091 default:
9092 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9093
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009094 case Builtin::BI__builtin_huge_val:
9095 case Builtin::BI__builtin_huge_valf:
9096 case Builtin::BI__builtin_huge_vall:
9097 case Builtin::BI__builtin_inf:
9098 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009099 case Builtin::BI__builtin_infl: {
9100 const llvm::fltSemantics &Sem =
9101 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009102 Result = llvm::APFloat::getInf(Sem);
9103 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009104 }
Mike Stump11289f42009-09-09 15:08:12 +00009105
John McCall16291492010-02-28 13:00:19 +00009106 case Builtin::BI__builtin_nans:
9107 case Builtin::BI__builtin_nansf:
9108 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009109 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9110 true, Result))
9111 return Error(E);
9112 return true;
John McCall16291492010-02-28 13:00:19 +00009113
Chris Lattner0b7282e2008-10-06 06:31:58 +00009114 case Builtin::BI__builtin_nan:
9115 case Builtin::BI__builtin_nanf:
9116 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00009117 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009118 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009119 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9120 false, Result))
9121 return Error(E);
9122 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009123
9124 case Builtin::BI__builtin_fabs:
9125 case Builtin::BI__builtin_fabsf:
9126 case Builtin::BI__builtin_fabsl:
9127 if (!EvaluateFloat(E->getArg(0), Result, Info))
9128 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009129
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009130 if (Result.isNegative())
9131 Result.changeSign();
9132 return true;
9133
Richard Smith8889a3d2013-06-13 06:26:32 +00009134 // FIXME: Builtin::BI__builtin_powi
9135 // FIXME: Builtin::BI__builtin_powif
9136 // FIXME: Builtin::BI__builtin_powil
9137
Mike Stump11289f42009-09-09 15:08:12 +00009138 case Builtin::BI__builtin_copysign:
9139 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009140 case Builtin::BI__builtin_copysignl: {
9141 APFloat RHS(0.);
9142 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9143 !EvaluateFloat(E->getArg(1), RHS, Info))
9144 return false;
9145 Result.copySign(RHS);
9146 return true;
9147 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009148 }
9149}
9150
John McCallb1fb0d32010-05-07 22:08:54 +00009151bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009152 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9153 ComplexValue CV;
9154 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9155 return false;
9156 Result = CV.FloatReal;
9157 return true;
9158 }
9159
9160 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009161}
9162
9163bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009164 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9165 ComplexValue CV;
9166 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9167 return false;
9168 Result = CV.FloatImag;
9169 return true;
9170 }
9171
Richard Smith4a678122011-10-24 18:44:57 +00009172 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009173 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9174 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009175 return true;
9176}
9177
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009178bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009179 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009180 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009181 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009182 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009183 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009184 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9185 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009186 Result.changeSign();
9187 return true;
9188 }
9189}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009190
Eli Friedman24c01542008-08-22 00:06:13 +00009191bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009192 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9193 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009194
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009195 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009196 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009197 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009198 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009199 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9200 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009201}
9202
9203bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9204 Result = E->getValue();
9205 return true;
9206}
9207
Peter Collingbournee9200682011-05-13 03:29:01 +00009208bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9209 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009210
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009211 switch (E->getCastKind()) {
9212 default:
Richard Smith11562c52011-10-28 17:51:58 +00009213 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009214
9215 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009216 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009217 return EvaluateInteger(SubExpr, IntResult, Info) &&
9218 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9219 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009220 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009221
9222 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009223 if (!Visit(SubExpr))
9224 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009225 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9226 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009227 }
John McCalld7646252010-11-14 08:17:51 +00009228
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009229 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009230 ComplexValue V;
9231 if (!EvaluateComplex(SubExpr, V, Info))
9232 return false;
9233 Result = V.getComplexFloatReal();
9234 return true;
9235 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009236 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009237}
9238
Eli Friedman24c01542008-08-22 00:06:13 +00009239//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009240// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009241//===----------------------------------------------------------------------===//
9242
9243namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009244class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009245 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009246 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009247
Anders Carlsson537969c2008-11-16 20:27:53 +00009248public:
John McCall93d91dc2010-05-07 17:22:02 +00009249 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009250 : ExprEvaluatorBaseTy(info), Result(Result) {}
9251
Richard Smith2e312c82012-03-03 22:46:17 +00009252 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009253 Result.setFrom(V);
9254 return true;
9255 }
Mike Stump11289f42009-09-09 15:08:12 +00009256
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009257 bool ZeroInitialization(const Expr *E);
9258
Anders Carlsson537969c2008-11-16 20:27:53 +00009259 //===--------------------------------------------------------------------===//
9260 // Visitor Methods
9261 //===--------------------------------------------------------------------===//
9262
Peter Collingbournee9200682011-05-13 03:29:01 +00009263 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009264 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009265 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009266 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009267 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009268};
9269} // end anonymous namespace
9270
John McCall93d91dc2010-05-07 17:22:02 +00009271static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9272 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009273 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009274 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009275}
9276
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009277bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009278 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009279 if (ElemTy->isRealFloatingType()) {
9280 Result.makeComplexFloat();
9281 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9282 Result.FloatReal = Zero;
9283 Result.FloatImag = Zero;
9284 } else {
9285 Result.makeComplexInt();
9286 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9287 Result.IntReal = Zero;
9288 Result.IntImag = Zero;
9289 }
9290 return true;
9291}
9292
Peter Collingbournee9200682011-05-13 03:29:01 +00009293bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9294 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009295
9296 if (SubExpr->getType()->isRealFloatingType()) {
9297 Result.makeComplexFloat();
9298 APFloat &Imag = Result.FloatImag;
9299 if (!EvaluateFloat(SubExpr, Imag, Info))
9300 return false;
9301
9302 Result.FloatReal = APFloat(Imag.getSemantics());
9303 return true;
9304 } else {
9305 assert(SubExpr->getType()->isIntegerType() &&
9306 "Unexpected imaginary literal.");
9307
9308 Result.makeComplexInt();
9309 APSInt &Imag = Result.IntImag;
9310 if (!EvaluateInteger(SubExpr, Imag, Info))
9311 return false;
9312
9313 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9314 return true;
9315 }
9316}
9317
Peter Collingbournee9200682011-05-13 03:29:01 +00009318bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009319
John McCallfcef3cf2010-12-14 17:51:41 +00009320 switch (E->getCastKind()) {
9321 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009322 case CK_BaseToDerived:
9323 case CK_DerivedToBase:
9324 case CK_UncheckedDerivedToBase:
9325 case CK_Dynamic:
9326 case CK_ToUnion:
9327 case CK_ArrayToPointerDecay:
9328 case CK_FunctionToPointerDecay:
9329 case CK_NullToPointer:
9330 case CK_NullToMemberPointer:
9331 case CK_BaseToDerivedMemberPointer:
9332 case CK_DerivedToBaseMemberPointer:
9333 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009334 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009335 case CK_ConstructorConversion:
9336 case CK_IntegralToPointer:
9337 case CK_PointerToIntegral:
9338 case CK_PointerToBoolean:
9339 case CK_ToVoid:
9340 case CK_VectorSplat:
9341 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009342 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009343 case CK_IntegralToBoolean:
9344 case CK_IntegralToFloating:
9345 case CK_FloatingToIntegral:
9346 case CK_FloatingToBoolean:
9347 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009348 case CK_CPointerToObjCPointerCast:
9349 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009350 case CK_AnyPointerToBlockPointerCast:
9351 case CK_ObjCObjectLValueCast:
9352 case CK_FloatingComplexToReal:
9353 case CK_FloatingComplexToBoolean:
9354 case CK_IntegralComplexToReal:
9355 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009356 case CK_ARCProduceObject:
9357 case CK_ARCConsumeObject:
9358 case CK_ARCReclaimReturnedObject:
9359 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009360 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009361 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009362 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009363 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009364 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009365 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009366 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009367 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009368
John McCallfcef3cf2010-12-14 17:51:41 +00009369 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009370 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009371 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009372 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009373
9374 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009375 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009376 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009377 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009378
9379 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009380 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009381 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009382 return false;
9383
John McCallfcef3cf2010-12-14 17:51:41 +00009384 Result.makeComplexFloat();
9385 Result.FloatImag = APFloat(Real.getSemantics());
9386 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009387 }
9388
John McCallfcef3cf2010-12-14 17:51:41 +00009389 case CK_FloatingComplexCast: {
9390 if (!Visit(E->getSubExpr()))
9391 return false;
9392
9393 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9394 QualType From
9395 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9396
Richard Smith357362d2011-12-13 06:39:58 +00009397 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9398 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009399 }
9400
9401 case CK_FloatingComplexToIntegralComplex: {
9402 if (!Visit(E->getSubExpr()))
9403 return false;
9404
9405 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9406 QualType From
9407 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9408 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009409 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9410 To, Result.IntReal) &&
9411 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9412 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009413 }
9414
9415 case CK_IntegralRealToComplex: {
9416 APSInt &Real = Result.IntReal;
9417 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9418 return false;
9419
9420 Result.makeComplexInt();
9421 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9422 return true;
9423 }
9424
9425 case CK_IntegralComplexCast: {
9426 if (!Visit(E->getSubExpr()))
9427 return false;
9428
9429 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9430 QualType From
9431 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9432
Richard Smith911e1422012-01-30 22:27:01 +00009433 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9434 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009435 return true;
9436 }
9437
9438 case CK_IntegralComplexToFloatingComplex: {
9439 if (!Visit(E->getSubExpr()))
9440 return false;
9441
Ted Kremenek28831752012-08-23 20:46:57 +00009442 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009443 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009444 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009445 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009446 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9447 To, Result.FloatReal) &&
9448 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9449 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009450 }
9451 }
9452
9453 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009454}
9455
John McCall93d91dc2010-05-07 17:22:02 +00009456bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009457 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009458 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9459
Chandler Carrutha216cad2014-10-11 00:57:18 +00009460 // Track whether the LHS or RHS is real at the type system level. When this is
9461 // the case we can simplify our evaluation strategy.
9462 bool LHSReal = false, RHSReal = false;
9463
9464 bool LHSOK;
9465 if (E->getLHS()->getType()->isRealFloatingType()) {
9466 LHSReal = true;
9467 APFloat &Real = Result.FloatReal;
9468 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9469 if (LHSOK) {
9470 Result.makeComplexFloat();
9471 Result.FloatImag = APFloat(Real.getSemantics());
9472 }
9473 } else {
9474 LHSOK = Visit(E->getLHS());
9475 }
George Burgess IVa145e252016-05-25 22:38:36 +00009476 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009477 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009478
John McCall93d91dc2010-05-07 17:22:02 +00009479 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009480 if (E->getRHS()->getType()->isRealFloatingType()) {
9481 RHSReal = true;
9482 APFloat &Real = RHS.FloatReal;
9483 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9484 return false;
9485 RHS.makeComplexFloat();
9486 RHS.FloatImag = APFloat(Real.getSemantics());
9487 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009488 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009489
Chandler Carrutha216cad2014-10-11 00:57:18 +00009490 assert(!(LHSReal && RHSReal) &&
9491 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009492 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009493 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009494 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009495 if (Result.isComplexFloat()) {
9496 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9497 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009498 if (LHSReal)
9499 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9500 else if (!RHSReal)
9501 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9502 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009503 } else {
9504 Result.getComplexIntReal() += RHS.getComplexIntReal();
9505 Result.getComplexIntImag() += RHS.getComplexIntImag();
9506 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009507 break;
John McCalle3027922010-08-25 11:45:40 +00009508 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009509 if (Result.isComplexFloat()) {
9510 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9511 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009512 if (LHSReal) {
9513 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9514 Result.getComplexFloatImag().changeSign();
9515 } else if (!RHSReal) {
9516 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9517 APFloat::rmNearestTiesToEven);
9518 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009519 } else {
9520 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9521 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9522 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009523 break;
John McCalle3027922010-08-25 11:45:40 +00009524 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009525 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009526 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009527 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009528 // following naming scheme:
9529 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009530 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009531 APFloat &A = LHS.getComplexFloatReal();
9532 APFloat &B = LHS.getComplexFloatImag();
9533 APFloat &C = RHS.getComplexFloatReal();
9534 APFloat &D = RHS.getComplexFloatImag();
9535 APFloat &ResR = Result.getComplexFloatReal();
9536 APFloat &ResI = Result.getComplexFloatImag();
9537 if (LHSReal) {
9538 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9539 ResR = A * C;
9540 ResI = A * D;
9541 } else if (RHSReal) {
9542 ResR = C * A;
9543 ResI = C * B;
9544 } else {
9545 // In the fully general case, we need to handle NaNs and infinities
9546 // robustly.
9547 APFloat AC = A * C;
9548 APFloat BD = B * D;
9549 APFloat AD = A * D;
9550 APFloat BC = B * C;
9551 ResR = AC - BD;
9552 ResI = AD + BC;
9553 if (ResR.isNaN() && ResI.isNaN()) {
9554 bool Recalc = false;
9555 if (A.isInfinity() || B.isInfinity()) {
9556 A = APFloat::copySign(
9557 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9558 B = APFloat::copySign(
9559 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9560 if (C.isNaN())
9561 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9562 if (D.isNaN())
9563 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9564 Recalc = true;
9565 }
9566 if (C.isInfinity() || D.isInfinity()) {
9567 C = APFloat::copySign(
9568 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9569 D = APFloat::copySign(
9570 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9571 if (A.isNaN())
9572 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9573 if (B.isNaN())
9574 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9575 Recalc = true;
9576 }
9577 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9578 AD.isInfinity() || BC.isInfinity())) {
9579 if (A.isNaN())
9580 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9581 if (B.isNaN())
9582 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9583 if (C.isNaN())
9584 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9585 if (D.isNaN())
9586 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9587 Recalc = true;
9588 }
9589 if (Recalc) {
9590 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9591 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9592 }
9593 }
9594 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009595 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009596 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009597 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009598 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9599 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009600 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009601 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9602 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9603 }
9604 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009605 case BO_Div:
9606 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009607 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009608 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009609 // following naming scheme:
9610 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009611 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009612 APFloat &A = LHS.getComplexFloatReal();
9613 APFloat &B = LHS.getComplexFloatImag();
9614 APFloat &C = RHS.getComplexFloatReal();
9615 APFloat &D = RHS.getComplexFloatImag();
9616 APFloat &ResR = Result.getComplexFloatReal();
9617 APFloat &ResI = Result.getComplexFloatImag();
9618 if (RHSReal) {
9619 ResR = A / C;
9620 ResI = B / C;
9621 } else {
9622 if (LHSReal) {
9623 // No real optimizations we can do here, stub out with zero.
9624 B = APFloat::getZero(A.getSemantics());
9625 }
9626 int DenomLogB = 0;
9627 APFloat MaxCD = maxnum(abs(C), abs(D));
9628 if (MaxCD.isFinite()) {
9629 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009630 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9631 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009632 }
9633 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009634 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9635 APFloat::rmNearestTiesToEven);
9636 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9637 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009638 if (ResR.isNaN() && ResI.isNaN()) {
9639 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9640 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9641 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9642 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9643 D.isFinite()) {
9644 A = APFloat::copySign(
9645 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9646 B = APFloat::copySign(
9647 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9648 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9649 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9650 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9651 C = APFloat::copySign(
9652 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9653 D = APFloat::copySign(
9654 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9655 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9656 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9657 }
9658 }
9659 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009660 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009661 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9662 return Error(E, diag::note_expr_divide_by_zero);
9663
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009664 ComplexValue LHS = Result;
9665 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9666 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9667 Result.getComplexIntReal() =
9668 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9669 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9670 Result.getComplexIntImag() =
9671 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9672 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9673 }
9674 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009675 }
9676
John McCall93d91dc2010-05-07 17:22:02 +00009677 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009678}
9679
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009680bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9681 // Get the operand value into 'Result'.
9682 if (!Visit(E->getSubExpr()))
9683 return false;
9684
9685 switch (E->getOpcode()) {
9686 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009687 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009688 case UO_Extension:
9689 return true;
9690 case UO_Plus:
9691 // The result is always just the subexpr.
9692 return true;
9693 case UO_Minus:
9694 if (Result.isComplexFloat()) {
9695 Result.getComplexFloatReal().changeSign();
9696 Result.getComplexFloatImag().changeSign();
9697 }
9698 else {
9699 Result.getComplexIntReal() = -Result.getComplexIntReal();
9700 Result.getComplexIntImag() = -Result.getComplexIntImag();
9701 }
9702 return true;
9703 case UO_Not:
9704 if (Result.isComplexFloat())
9705 Result.getComplexFloatImag().changeSign();
9706 else
9707 Result.getComplexIntImag() = -Result.getComplexIntImag();
9708 return true;
9709 }
9710}
9711
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009712bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9713 if (E->getNumInits() == 2) {
9714 if (E->getType()->isComplexType()) {
9715 Result.makeComplexFloat();
9716 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9717 return false;
9718 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9719 return false;
9720 } else {
9721 Result.makeComplexInt();
9722 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9723 return false;
9724 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9725 return false;
9726 }
9727 return true;
9728 }
9729 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9730}
9731
Anders Carlsson537969c2008-11-16 20:27:53 +00009732//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009733// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9734// implicit conversion.
9735//===----------------------------------------------------------------------===//
9736
9737namespace {
9738class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009739 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009740 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009741 APValue &Result;
9742public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009743 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9744 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009745
9746 bool Success(const APValue &V, const Expr *E) {
9747 Result = V;
9748 return true;
9749 }
9750
9751 bool ZeroInitialization(const Expr *E) {
9752 ImplicitValueInitExpr VIE(
9753 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009754 // For atomic-qualified class (and array) types in C++, initialize the
9755 // _Atomic-wrapped subobject directly, in-place.
9756 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9757 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009758 }
9759
9760 bool VisitCastExpr(const CastExpr *E) {
9761 switch (E->getCastKind()) {
9762 default:
9763 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9764 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009765 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9766 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009767 }
9768 }
9769};
9770} // end anonymous namespace
9771
Richard Smith64cb9ca2017-02-22 22:09:50 +00009772static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9773 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009774 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009775 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009776}
9777
9778//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009779// Void expression evaluation, primarily for a cast to void on the LHS of a
9780// comma operator
9781//===----------------------------------------------------------------------===//
9782
9783namespace {
9784class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009785 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009786public:
9787 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9788
Richard Smith2e312c82012-03-03 22:46:17 +00009789 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009790
9791 bool VisitCastExpr(const CastExpr *E) {
9792 switch (E->getCastKind()) {
9793 default:
9794 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9795 case CK_ToVoid:
9796 VisitIgnoredValue(E->getSubExpr());
9797 return true;
9798 }
9799 }
Hal Finkela8443c32014-07-17 14:49:58 +00009800
9801 bool VisitCallExpr(const CallExpr *E) {
9802 switch (E->getBuiltinCallee()) {
9803 default:
9804 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9805 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009806 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009807 // The argument is not evaluated!
9808 return true;
9809 }
9810 }
Richard Smith42d3af92011-12-07 00:43:50 +00009811};
9812} // end anonymous namespace
9813
9814static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9815 assert(E->isRValue() && E->getType()->isVoidType());
9816 return VoidExprEvaluator(Info).Visit(E);
9817}
9818
9819//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009820// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009821//===----------------------------------------------------------------------===//
9822
Richard Smith2e312c82012-03-03 22:46:17 +00009823static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009824 // In C, function designators are not lvalues, but we evaluate them as if they
9825 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009826 QualType T = E->getType();
9827 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009828 LValue LV;
9829 if (!EvaluateLValue(E, LV, Info))
9830 return false;
9831 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009832 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009833 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009834 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009835 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009836 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009837 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009838 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009839 LValue LV;
9840 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009841 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009842 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009843 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009844 llvm::APFloat F(0.0);
9845 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009846 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009847 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009848 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009849 ComplexValue C;
9850 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009851 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009852 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009853 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009854 MemberPtr P;
9855 if (!EvaluateMemberPointer(E, P, Info))
9856 return false;
9857 P.moveInto(Result);
9858 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009859 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009860 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009861 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009862 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9863 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009864 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009865 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009866 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009867 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009868 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009869 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9870 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009871 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009872 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009873 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009874 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009875 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009876 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009877 if (!EvaluateVoid(E, Info))
9878 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009879 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009880 QualType Unqual = T.getAtomicUnqualifiedType();
9881 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9882 LValue LV;
9883 LV.set(E, Info.CurrentCall->Index);
9884 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9885 if (!EvaluateAtomic(E, &LV, Value, Info))
9886 return false;
9887 } else {
9888 if (!EvaluateAtomic(E, nullptr, Result, Info))
9889 return false;
9890 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009891 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009892 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009893 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009894 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009895 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009896 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009897 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009898
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009899 return true;
9900}
9901
Richard Smithb228a862012-02-15 02:18:13 +00009902/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9903/// cases, the in-place evaluation is essential, since later initializers for
9904/// an object can indirectly refer to subobjects which were initialized earlier.
9905static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009906 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009907 assert(!E->isValueDependent());
9908
Richard Smith7525ff62013-05-09 07:14:00 +00009909 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009910 return false;
9911
9912 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009913 // Evaluate arrays and record types in-place, so that later initializers can
9914 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +00009915 QualType T = E->getType();
9916 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +00009917 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009918 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +00009919 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009920 else if (T->isAtomicType()) {
9921 QualType Unqual = T.getAtomicUnqualifiedType();
9922 if (Unqual->isArrayType() || Unqual->isRecordType())
9923 return EvaluateAtomic(E, &This, Result, Info);
9924 }
Richard Smithed5165f2011-11-04 05:33:44 +00009925 }
9926
9927 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009928 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009929}
9930
Richard Smithf57d8cb2011-12-09 22:58:01 +00009931/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9932/// lvalue-to-rvalue cast if it is an lvalue.
9933static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009934 if (E->getType().isNull())
9935 return false;
9936
Nick Lewyckyc190f962017-05-02 01:06:16 +00009937 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00009938 return false;
9939
Richard Smith2e312c82012-03-03 22:46:17 +00009940 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009941 return false;
9942
9943 if (E->isGLValue()) {
9944 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009945 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009946 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009947 return false;
9948 }
9949
Richard Smith2e312c82012-03-03 22:46:17 +00009950 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009951 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009952}
Richard Smith11562c52011-10-28 17:51:58 +00009953
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009954static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +00009955 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009956 // Fast-path evaluations of integer literals, since we sometimes see files
9957 // containing vast quantities of these.
9958 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9959 Result.Val = APValue(APSInt(L->getValue(),
9960 L->getType()->isUnsignedIntegerType()));
9961 IsConst = true;
9962 return true;
9963 }
James Dennett0492ef02014-03-14 17:44:10 +00009964
9965 // This case should be rare, but we need to check it before we check on
9966 // the type below.
9967 if (Exp->getType().isNull()) {
9968 IsConst = false;
9969 return true;
9970 }
Daniel Jasperffdee092017-05-02 19:21:42 +00009971
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009972 // FIXME: Evaluating values of large array and record types can cause
9973 // performance problems. Only do so in C++11 for now.
9974 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9975 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +00009976 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009977 IsConst = false;
9978 return true;
9979 }
9980 return false;
9981}
9982
9983
Richard Smith7b553f12011-10-29 00:50:52 +00009984/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009985/// any crazy technique (that has nothing to do with language standards) that
9986/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009987/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9988/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009989bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009990 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +00009991 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009992 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +00009993
Richard Smith6d4c6582013-11-05 22:18:15 +00009994 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009995 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009996}
9997
Jay Foad39c79802011-01-12 09:06:06 +00009998bool Expr::EvaluateAsBooleanCondition(bool &Result,
9999 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010000 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010001 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010002 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010003}
10004
Richard Smithce8eca52015-12-08 03:21:47 +000010005static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10006 Expr::SideEffectsKind SEK) {
10007 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10008 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10009}
10010
Richard Smith5fab0c92011-12-28 19:48:30 +000010011bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10012 SideEffectsKind AllowSideEffects) const {
10013 if (!getType()->isIntegralOrEnumerationType())
10014 return false;
10015
Richard Smith11562c52011-10-28 17:51:58 +000010016 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010017 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010018 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010019 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010020
Richard Smith11562c52011-10-28 17:51:58 +000010021 Result = ExprResult.Val.getInt();
10022 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010023}
10024
Richard Trieube234c32016-04-21 21:04:55 +000010025bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10026 SideEffectsKind AllowSideEffects) const {
10027 if (!getType()->isRealFloatingType())
10028 return false;
10029
10030 EvalResult ExprResult;
10031 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10032 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10033 return false;
10034
10035 Result = ExprResult.Val.getFloat();
10036 return true;
10037}
10038
Jay Foad39c79802011-01-12 09:06:06 +000010039bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010040 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010041
John McCall45d55e42010-05-07 21:00:08 +000010042 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010043 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10044 !CheckLValueConstantExpression(Info, getExprLoc(),
10045 Ctx.getLValueReferenceType(getType()), LV))
10046 return false;
10047
Richard Smith2e312c82012-03-03 22:46:17 +000010048 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010049 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010050}
10051
Richard Smithd0b4dd62011-12-19 06:19:21 +000010052bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10053 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010054 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010055 // FIXME: Evaluating initializers for large array and record types can cause
10056 // performance problems. Only do so in C++11 for now.
10057 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010058 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010059 return false;
10060
Richard Smithd0b4dd62011-12-19 06:19:21 +000010061 Expr::EvalStatus EStatus;
10062 EStatus.Diag = &Notes;
10063
Richard Smith0c6124b2015-12-03 01:36:22 +000010064 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10065 ? EvalInfo::EM_ConstantExpression
10066 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010067 InitInfo.setEvaluatingDecl(VD, Value);
10068
10069 LValue LVal;
10070 LVal.set(VD);
10071
Richard Smithfddd3842011-12-30 21:15:51 +000010072 // C++11 [basic.start.init]p2:
10073 // Variables with static storage duration or thread storage duration shall be
10074 // zero-initialized before any other initialization takes place.
10075 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010076 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010077 !VD->getType()->isReferenceType()) {
10078 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010079 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010080 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010081 return false;
10082 }
10083
Richard Smith7525ff62013-05-09 07:14:00 +000010084 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10085 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010086 EStatus.HasSideEffects)
10087 return false;
10088
10089 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10090 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010091}
10092
Richard Smith7b553f12011-10-29 00:50:52 +000010093/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10094/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010095bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010096 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010097 return EvaluateAsRValue(Result, Ctx) &&
10098 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010099}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010100
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010101APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010102 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010103 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010104 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010105 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010106 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010107 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010108 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010109
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010110 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010111}
John McCall864e3962010-05-07 05:32:02 +000010112
Richard Smithe9ff7702013-11-05 22:23:30 +000010113void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010114 bool IsConst;
10115 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010116 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010117 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010118 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10119 }
10120}
10121
Richard Smithe6c01442013-06-05 00:46:14 +000010122bool Expr::EvalResult::isGlobalLValue() const {
10123 assert(Val.isLValue());
10124 return IsGlobalLValue(Val.getLValueBase());
10125}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010126
10127
John McCall864e3962010-05-07 05:32:02 +000010128/// isIntegerConstantExpr - this recursive routine will test if an expression is
10129/// an integer constant expression.
10130
10131/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10132/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010133
10134// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010135// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10136// and a (possibly null) SourceLocation indicating the location of the problem.
10137//
John McCall864e3962010-05-07 05:32:02 +000010138// Note that to reduce code duplication, this helper does no evaluation
10139// itself; the caller checks whether the expression is evaluatable, and
10140// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010141// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010142
Dan Gohman28ade552010-07-26 21:25:24 +000010143namespace {
10144
Richard Smith9e575da2012-12-28 13:25:52 +000010145enum ICEKind {
10146 /// This expression is an ICE.
10147 IK_ICE,
10148 /// This expression is not an ICE, but if it isn't evaluated, it's
10149 /// a legal subexpression for an ICE. This return value is used to handle
10150 /// the comma operator in C99 mode, and non-constant subexpressions.
10151 IK_ICEIfUnevaluated,
10152 /// This expression is not an ICE, and is not a legal subexpression for one.
10153 IK_NotICE
10154};
10155
John McCall864e3962010-05-07 05:32:02 +000010156struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010157 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010158 SourceLocation Loc;
10159
Richard Smith9e575da2012-12-28 13:25:52 +000010160 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010161};
10162
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010163}
Dan Gohman28ade552010-07-26 21:25:24 +000010164
Richard Smith9e575da2012-12-28 13:25:52 +000010165static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10166
10167static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010168
Craig Toppera31a8822013-08-22 07:09:37 +000010169static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010170 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010171 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010172 !EVResult.Val.isInt())
10173 return ICEDiag(IK_NotICE, E->getLocStart());
10174
John McCall864e3962010-05-07 05:32:02 +000010175 return NoDiag();
10176}
10177
Craig Toppera31a8822013-08-22 07:09:37 +000010178static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010179 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010180 if (!E->getType()->isIntegralOrEnumerationType())
10181 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010182
10183 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010184#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010185#define STMT(Node, Base) case Expr::Node##Class:
10186#define EXPR(Node, Base)
10187#include "clang/AST/StmtNodes.inc"
10188 case Expr::PredefinedExprClass:
10189 case Expr::FloatingLiteralClass:
10190 case Expr::ImaginaryLiteralClass:
10191 case Expr::StringLiteralClass:
10192 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010193 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010194 case Expr::MemberExprClass:
10195 case Expr::CompoundAssignOperatorClass:
10196 case Expr::CompoundLiteralExprClass:
10197 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010198 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010199 case Expr::ArrayInitLoopExprClass:
10200 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010201 case Expr::NoInitExprClass:
10202 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010203 case Expr::ImplicitValueInitExprClass:
10204 case Expr::ParenListExprClass:
10205 case Expr::VAArgExprClass:
10206 case Expr::AddrLabelExprClass:
10207 case Expr::StmtExprClass:
10208 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010209 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010210 case Expr::CXXDynamicCastExprClass:
10211 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010212 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010213 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010214 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010215 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010216 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010217 case Expr::CXXThisExprClass:
10218 case Expr::CXXThrowExprClass:
10219 case Expr::CXXNewExprClass:
10220 case Expr::CXXDeleteExprClass:
10221 case Expr::CXXPseudoDestructorExprClass:
10222 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010223 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010224 case Expr::DependentScopeDeclRefExprClass:
10225 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010226 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010227 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010228 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010229 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010230 case Expr::CXXTemporaryObjectExprClass:
10231 case Expr::CXXUnresolvedConstructExprClass:
10232 case Expr::CXXDependentScopeMemberExprClass:
10233 case Expr::UnresolvedMemberExprClass:
10234 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010235 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010236 case Expr::ObjCArrayLiteralClass:
10237 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010238 case Expr::ObjCEncodeExprClass:
10239 case Expr::ObjCMessageExprClass:
10240 case Expr::ObjCSelectorExprClass:
10241 case Expr::ObjCProtocolExprClass:
10242 case Expr::ObjCIvarRefExprClass:
10243 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010244 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010245 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010246 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010247 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010248 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010249 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010250 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010251 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010252 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010253 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010254 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010255 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010256 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010257 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010258 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010259 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010260 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010261 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010262 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010263 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010264 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010265 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010266
Richard Smithf137f932014-01-25 20:50:08 +000010267 case Expr::InitListExprClass: {
10268 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10269 // form "T x = { a };" is equivalent to "T x = a;".
10270 // Unless we're initializing a reference, T is a scalar as it is known to be
10271 // of integral or enumeration type.
10272 if (E->isRValue())
10273 if (cast<InitListExpr>(E)->getNumInits() == 1)
10274 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10275 return ICEDiag(IK_NotICE, E->getLocStart());
10276 }
10277
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010278 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010279 case Expr::GNUNullExprClass:
10280 // GCC considers the GNU __null value to be an integral constant expression.
10281 return NoDiag();
10282
John McCall7c454bb2011-07-15 05:09:51 +000010283 case Expr::SubstNonTypeTemplateParmExprClass:
10284 return
10285 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10286
John McCall864e3962010-05-07 05:32:02 +000010287 case Expr::ParenExprClass:
10288 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010289 case Expr::GenericSelectionExprClass:
10290 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010291 case Expr::IntegerLiteralClass:
10292 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010293 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010294 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010295 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010296 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010297 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010298 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010299 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010300 return NoDiag();
10301 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010302 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010303 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10304 // constant expressions, but they can never be ICEs because an ICE cannot
10305 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010306 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010307 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010308 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010309 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010310 }
Richard Smith6365c912012-02-24 22:12:32 +000010311 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010312 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10313 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010314 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010315 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010316 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010317 // Parameter variables are never constants. Without this check,
10318 // getAnyInitializer() can find a default argument, which leads
10319 // to chaos.
10320 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010321 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010322
10323 // C++ 7.1.5.1p2
10324 // A variable of non-volatile const-qualified integral or enumeration
10325 // type initialized by an ICE can be used in ICEs.
10326 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010327 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010328 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010329
Richard Smithd0b4dd62011-12-19 06:19:21 +000010330 const VarDecl *VD;
10331 // Look for a declaration of this variable that has an initializer, and
10332 // check whether it is an ICE.
10333 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10334 return NoDiag();
10335 else
Richard Smith9e575da2012-12-28 13:25:52 +000010336 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010337 }
10338 }
Richard Smith9e575da2012-12-28 13:25:52 +000010339 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010340 }
John McCall864e3962010-05-07 05:32:02 +000010341 case Expr::UnaryOperatorClass: {
10342 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10343 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010344 case UO_PostInc:
10345 case UO_PostDec:
10346 case UO_PreInc:
10347 case UO_PreDec:
10348 case UO_AddrOf:
10349 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010350 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010351 // C99 6.6/3 allows increment and decrement within unevaluated
10352 // subexpressions of constant expressions, but they can never be ICEs
10353 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010354 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010355 case UO_Extension:
10356 case UO_LNot:
10357 case UO_Plus:
10358 case UO_Minus:
10359 case UO_Not:
10360 case UO_Real:
10361 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010362 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010363 }
Richard Smith9e575da2012-12-28 13:25:52 +000010364
John McCall864e3962010-05-07 05:32:02 +000010365 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010366 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010367 }
10368 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010369 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10370 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10371 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10372 // compliance: we should warn earlier for offsetof expressions with
10373 // array subscripts that aren't ICEs, and if the array subscripts
10374 // are ICEs, the value of the offsetof must be an integer constant.
10375 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010376 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010377 case Expr::UnaryExprOrTypeTraitExprClass: {
10378 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10379 if ((Exp->getKind() == UETT_SizeOf) &&
10380 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010381 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010382 return NoDiag();
10383 }
10384 case Expr::BinaryOperatorClass: {
10385 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10386 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010387 case BO_PtrMemD:
10388 case BO_PtrMemI:
10389 case BO_Assign:
10390 case BO_MulAssign:
10391 case BO_DivAssign:
10392 case BO_RemAssign:
10393 case BO_AddAssign:
10394 case BO_SubAssign:
10395 case BO_ShlAssign:
10396 case BO_ShrAssign:
10397 case BO_AndAssign:
10398 case BO_XorAssign:
10399 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010400 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10401 // constant expressions, but they can never be ICEs because an ICE cannot
10402 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010403 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010404
John McCalle3027922010-08-25 11:45:40 +000010405 case BO_Mul:
10406 case BO_Div:
10407 case BO_Rem:
10408 case BO_Add:
10409 case BO_Sub:
10410 case BO_Shl:
10411 case BO_Shr:
10412 case BO_LT:
10413 case BO_GT:
10414 case BO_LE:
10415 case BO_GE:
10416 case BO_EQ:
10417 case BO_NE:
10418 case BO_And:
10419 case BO_Xor:
10420 case BO_Or:
10421 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010422 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10423 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010424 if (Exp->getOpcode() == BO_Div ||
10425 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010426 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010427 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010428 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010429 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010430 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010431 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010432 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010433 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010434 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010435 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010436 }
10437 }
10438 }
John McCalle3027922010-08-25 11:45:40 +000010439 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010440 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010441 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10442 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010443 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10444 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010445 } else {
10446 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010447 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010448 }
10449 }
Richard Smith9e575da2012-12-28 13:25:52 +000010450 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010451 }
John McCalle3027922010-08-25 11:45:40 +000010452 case BO_LAnd:
10453 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010454 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10455 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010456 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010457 // Rare case where the RHS has a comma "side-effect"; we need
10458 // to actually check the condition to see whether the side
10459 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010460 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010461 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010462 return RHSResult;
10463 return NoDiag();
10464 }
10465
Richard Smith9e575da2012-12-28 13:25:52 +000010466 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010467 }
10468 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010469 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010470 }
10471 case Expr::ImplicitCastExprClass:
10472 case Expr::CStyleCastExprClass:
10473 case Expr::CXXFunctionalCastExprClass:
10474 case Expr::CXXStaticCastExprClass:
10475 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010476 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010477 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010478 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010479 if (isa<ExplicitCastExpr>(E)) {
10480 if (const FloatingLiteral *FL
10481 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10482 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10483 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10484 APSInt IgnoredVal(DestWidth, !DestSigned);
10485 bool Ignored;
10486 // If the value does not fit in the destination type, the behavior is
10487 // undefined, so we are not required to treat it as a constant
10488 // expression.
10489 if (FL->getValue().convertToInteger(IgnoredVal,
10490 llvm::APFloat::rmTowardZero,
10491 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010492 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010493 return NoDiag();
10494 }
10495 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010496 switch (cast<CastExpr>(E)->getCastKind()) {
10497 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010498 case CK_AtomicToNonAtomic:
10499 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010500 case CK_NoOp:
10501 case CK_IntegralToBoolean:
10502 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010503 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010504 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010505 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010506 }
John McCall864e3962010-05-07 05:32:02 +000010507 }
John McCallc07a0c72011-02-17 10:25:35 +000010508 case Expr::BinaryConditionalOperatorClass: {
10509 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10510 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010511 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010512 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010513 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10514 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10515 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010516 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010517 return FalseResult;
10518 }
John McCall864e3962010-05-07 05:32:02 +000010519 case Expr::ConditionalOperatorClass: {
10520 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10521 // If the condition (ignoring parens) is a __builtin_constant_p call,
10522 // then only the true side is actually considered in an integer constant
10523 // expression, and it is fully evaluated. This is an important GNU
10524 // extension. See GCC PR38377 for discussion.
10525 if (const CallExpr *CallCE
10526 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010527 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010528 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010529 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010530 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010531 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010532
Richard Smithf57d8cb2011-12-09 22:58:01 +000010533 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10534 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010535
Richard Smith9e575da2012-12-28 13:25:52 +000010536 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010537 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010538 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010539 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010540 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010541 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010542 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010543 return NoDiag();
10544 // Rare case where the diagnostics depend on which side is evaluated
10545 // Note that if we get here, CondResult is 0, and at least one of
10546 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010547 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010548 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010549 return TrueResult;
10550 }
10551 case Expr::CXXDefaultArgExprClass:
10552 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010553 case Expr::CXXDefaultInitExprClass:
10554 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010555 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010556 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010557 }
10558 }
10559
David Blaikiee4d798f2012-01-20 21:50:17 +000010560 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010561}
10562
Richard Smithf57d8cb2011-12-09 22:58:01 +000010563/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010564static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010565 const Expr *E,
10566 llvm::APSInt *Value,
10567 SourceLocation *Loc) {
10568 if (!E->getType()->isIntegralOrEnumerationType()) {
10569 if (Loc) *Loc = E->getExprLoc();
10570 return false;
10571 }
10572
Richard Smith66e05fe2012-01-18 05:21:49 +000010573 APValue Result;
10574 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010575 return false;
10576
Richard Smith98710fc2014-11-13 23:03:19 +000010577 if (!Result.isInt()) {
10578 if (Loc) *Loc = E->getExprLoc();
10579 return false;
10580 }
10581
Richard Smith66e05fe2012-01-18 05:21:49 +000010582 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010583 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010584}
10585
Craig Toppera31a8822013-08-22 07:09:37 +000010586bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10587 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010588 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010589 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010590
Richard Smith9e575da2012-12-28 13:25:52 +000010591 ICEDiag D = CheckICE(this, Ctx);
10592 if (D.Kind != IK_ICE) {
10593 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010594 return false;
10595 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010596 return true;
10597}
10598
Craig Toppera31a8822013-08-22 07:09:37 +000010599bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010600 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010601 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010602 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10603
10604 if (!isIntegerConstantExpr(Ctx, Loc))
10605 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010606 // The only possible side-effects here are due to UB discovered in the
10607 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10608 // required to treat the expression as an ICE, so we produce the folded
10609 // value.
10610 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010611 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010612 return true;
10613}
Richard Smith66e05fe2012-01-18 05:21:49 +000010614
Craig Toppera31a8822013-08-22 07:09:37 +000010615bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010616 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010617}
10618
Craig Toppera31a8822013-08-22 07:09:37 +000010619bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010620 SourceLocation *Loc) const {
10621 // We support this checking in C++98 mode in order to diagnose compatibility
10622 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010623 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010624
Richard Smith98a0a492012-02-14 21:38:30 +000010625 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010626 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010627 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010628 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010629 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010630
10631 APValue Scratch;
10632 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10633
10634 if (!Diags.empty()) {
10635 IsConstExpr = false;
10636 if (Loc) *Loc = Diags[0].first;
10637 } else if (!IsConstExpr) {
10638 // FIXME: This shouldn't happen.
10639 if (Loc) *Loc = getExprLoc();
10640 }
10641
10642 return IsConstExpr;
10643}
Richard Smith253c2a32012-01-27 01:14:48 +000010644
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010645bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10646 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010647 ArrayRef<const Expr*> Args,
10648 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010649 Expr::EvalStatus Status;
10650 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10651
George Burgess IV177399e2017-01-09 04:12:14 +000010652 LValue ThisVal;
10653 const LValue *ThisPtr = nullptr;
10654 if (This) {
10655#ifndef NDEBUG
10656 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10657 assert(MD && "Don't provide `this` for non-methods.");
10658 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10659#endif
10660 if (EvaluateObjectArgument(Info, This, ThisVal))
10661 ThisPtr = &ThisVal;
10662 if (Info.EvalStatus.HasSideEffects)
10663 return false;
10664 }
10665
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010666 ArgVector ArgValues(Args.size());
10667 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10668 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010669 if ((*I)->isValueDependent() ||
10670 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010671 // If evaluation fails, throw away the argument entirely.
10672 ArgValues[I - Args.begin()] = APValue();
10673 if (Info.EvalStatus.HasSideEffects)
10674 return false;
10675 }
10676
10677 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010678 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010679 ArgValues.data());
10680 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10681}
10682
Richard Smith253c2a32012-01-27 01:14:48 +000010683bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010684 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010685 PartialDiagnosticAt> &Diags) {
10686 // FIXME: It would be useful to check constexpr function templates, but at the
10687 // moment the constant expression evaluator cannot cope with the non-rigorous
10688 // ASTs which we build for dependent expressions.
10689 if (FD->isDependentContext())
10690 return true;
10691
10692 Expr::EvalStatus Status;
10693 Status.Diag = &Diags;
10694
Richard Smith6d4c6582013-11-05 22:18:15 +000010695 EvalInfo Info(FD->getASTContext(), Status,
10696 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010697
10698 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010699 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010700
Richard Smith7525ff62013-05-09 07:14:00 +000010701 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010702 // is a temporary being used as the 'this' pointer.
10703 LValue This;
10704 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010705 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010706
Richard Smith253c2a32012-01-27 01:14:48 +000010707 ArrayRef<const Expr*> Args;
10708
Richard Smith2e312c82012-03-03 22:46:17 +000010709 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010710 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10711 // Evaluate the call as a constant initializer, to allow the construction
10712 // of objects of non-literal types.
10713 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010714 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10715 } else {
10716 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010717 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010718 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010719 }
Richard Smith253c2a32012-01-27 01:14:48 +000010720
10721 return Diags.empty();
10722}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010723
10724bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10725 const FunctionDecl *FD,
10726 SmallVectorImpl<
10727 PartialDiagnosticAt> &Diags) {
10728 Expr::EvalStatus Status;
10729 Status.Diag = &Diags;
10730
10731 EvalInfo Info(FD->getASTContext(), Status,
10732 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10733
10734 // Fabricate a call stack frame to give the arguments a plausible cover story.
10735 ArrayRef<const Expr*> Args;
10736 ArgVector ArgValues(0);
10737 bool Success = EvaluateArgs(Args, ArgValues, Info);
10738 (void)Success;
10739 assert(Success &&
10740 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010741 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010742
10743 APValue ResultScratch;
10744 Evaluate(ResultScratch, Info, E);
10745 return Diags.empty();
10746}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010747
10748bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10749 unsigned Type) const {
10750 if (!getType()->isPointerType())
10751 return false;
10752
10753 Expr::EvalStatus Status;
10754 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010755 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010756}