blob: 17d0ce67dcf9a63b872c9d1fd88ae53b1f025721 [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
Richard Smithfddd3842011-12-30 21:15:51 +00001668/// Check that this core constant expression is of literal type, and if not,
1669/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001670static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001671 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001672 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001673 return true;
1674
Richard Smith7525ff62013-05-09 07:14:00 +00001675 // C++1y: A constant initializer for an object o [...] may also invoke
1676 // constexpr constructors for o and its subobjects even if those objects
1677 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001678 //
1679 // C++11 missed this detail for aggregates, so classes like this:
1680 // struct foo_t { union { int i; volatile int j; } u; };
1681 // are not (obviously) initializable like so:
1682 // __attribute__((__require_constant_initialization__))
1683 // static const foo_t x = {{0}};
1684 // because "i" is a subobject with non-literal initialization (due to the
1685 // volatile member of the union). See:
1686 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1687 // Therefore, we use the C++1y behavior.
1688 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001689 return true;
1690
Richard Smithfddd3842011-12-30 21:15:51 +00001691 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001692 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001693 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001694 << E->getType();
1695 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001696 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001697 return false;
1698}
1699
Richard Smith0b0a0b62011-10-29 20:57:55 +00001700/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001701/// constant expression. If not, report an appropriate diagnostic. Does not
1702/// check that the expression is of literal type.
1703static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1704 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001705 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001706 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001707 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001708 return false;
1709 }
1710
Richard Smith77be48a2014-07-31 06:31:19 +00001711 // We allow _Atomic(T) to be initialized from anything that T can be
1712 // initialized from.
1713 if (const AtomicType *AT = Type->getAs<AtomicType>())
1714 Type = AT->getValueType();
1715
Richard Smithb228a862012-02-15 02:18:13 +00001716 // Core issue 1454: For a literal constant expression of array or class type,
1717 // each subobject of its value shall have been initialized by a constant
1718 // expression.
1719 if (Value.isArray()) {
1720 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1721 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1722 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1723 Value.getArrayInitializedElt(I)))
1724 return false;
1725 }
1726 if (!Value.hasArrayFiller())
1727 return true;
1728 return CheckConstantExpression(Info, DiagLoc, EltTy,
1729 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001730 }
Richard Smithb228a862012-02-15 02:18:13 +00001731 if (Value.isUnion() && Value.getUnionField()) {
1732 return CheckConstantExpression(Info, DiagLoc,
1733 Value.getUnionField()->getType(),
1734 Value.getUnionValue());
1735 }
1736 if (Value.isStruct()) {
1737 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1738 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1739 unsigned BaseIndex = 0;
1740 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1741 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1742 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1743 Value.getStructBase(BaseIndex)))
1744 return false;
1745 }
1746 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001747 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001748 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1749 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001750 return false;
1751 }
1752 }
1753
1754 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001755 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001756 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001757 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1758 }
1759
1760 // Everything else is fine.
1761 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001762}
1763
Benjamin Kramer8407df72015-03-09 16:47:52 +00001764static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001765 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001766}
1767
1768static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001769 if (Value.CallIndex)
1770 return false;
1771 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1772 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001773}
1774
Richard Smithcecf1842011-11-01 21:06:14 +00001775static bool IsWeakLValue(const LValue &Value) {
1776 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001777 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001778}
1779
David Majnemerb5116032014-12-09 23:32:34 +00001780static bool isZeroSized(const LValue &Value) {
1781 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001782 if (Decl && isa<VarDecl>(Decl)) {
1783 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001784 if (Ty->isArrayType())
1785 return Ty->isIncompleteType() ||
1786 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001787 }
1788 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001789}
1790
Richard Smith2e312c82012-03-03 22:46:17 +00001791static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001792 // A null base expression indicates a null pointer. These are always
1793 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001794 if (!Value.getLValueBase()) {
1795 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001796 return true;
1797 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001798
Richard Smith027bf112011-11-17 22:56:20 +00001799 // We have a non-null base. These are generally known to be true, but if it's
1800 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001801 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001802 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001803 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001804}
1805
Richard Smith2e312c82012-03-03 22:46:17 +00001806static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001807 switch (Val.getKind()) {
1808 case APValue::Uninitialized:
1809 return false;
1810 case APValue::Int:
1811 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001812 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001813 case APValue::Float:
1814 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001815 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001816 case APValue::ComplexInt:
1817 Result = Val.getComplexIntReal().getBoolValue() ||
1818 Val.getComplexIntImag().getBoolValue();
1819 return true;
1820 case APValue::ComplexFloat:
1821 Result = !Val.getComplexFloatReal().isZero() ||
1822 !Val.getComplexFloatImag().isZero();
1823 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001824 case APValue::LValue:
1825 return EvalPointerValueAsBool(Val, Result);
1826 case APValue::MemberPointer:
1827 Result = Val.getMemberPointerDecl();
1828 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001829 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001830 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001831 case APValue::Struct:
1832 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001833 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001834 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001835 }
1836
Richard Smith11562c52011-10-28 17:51:58 +00001837 llvm_unreachable("unknown APValue kind");
1838}
1839
1840static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1841 EvalInfo &Info) {
1842 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001843 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001844 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001845 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001846 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001847}
1848
Richard Smith357362d2011-12-13 06:39:58 +00001849template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001850static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001851 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001852 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001853 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001854 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001855}
1856
1857static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1858 QualType SrcType, const APFloat &Value,
1859 QualType DestType, APSInt &Result) {
1860 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001861 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001862 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001863
Richard Smith357362d2011-12-13 06:39:58 +00001864 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001865 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001866 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1867 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001868 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001869 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001870}
1871
Richard Smith357362d2011-12-13 06:39:58 +00001872static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1873 QualType SrcType, QualType DestType,
1874 APFloat &Result) {
1875 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001876 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001877 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1878 APFloat::rmNearestTiesToEven, &ignored)
1879 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001880 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001881 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001882}
1883
Richard Smith911e1422012-01-30 22:27:01 +00001884static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1885 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001886 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001887 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001888 APSInt Result = Value;
1889 // Figure out if this is a truncate, extend or noop cast.
1890 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001891 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001892 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001893 return Result;
1894}
1895
Richard Smith357362d2011-12-13 06:39:58 +00001896static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1897 QualType SrcType, const APSInt &Value,
1898 QualType DestType, APFloat &Result) {
1899 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1900 if (Result.convertFromAPInt(Value, Value.isSigned(),
1901 APFloat::rmNearestTiesToEven)
1902 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001903 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001904 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001905}
1906
Richard Smith49ca8aa2013-08-06 07:09:20 +00001907static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1908 APValue &Value, const FieldDecl *FD) {
1909 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1910
1911 if (!Value.isInt()) {
1912 // Trying to store a pointer-cast-to-integer into a bitfield.
1913 // FIXME: In this case, we should provide the diagnostic for casting
1914 // a pointer to an integer.
1915 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001916 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001917 return false;
1918 }
1919
1920 APSInt &Int = Value.getInt();
1921 unsigned OldBitWidth = Int.getBitWidth();
1922 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1923 if (NewBitWidth < OldBitWidth)
1924 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1925 return true;
1926}
1927
Eli Friedman803acb32011-12-22 03:51:45 +00001928static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1929 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001930 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001931 if (!Evaluate(SVal, Info, E))
1932 return false;
1933 if (SVal.isInt()) {
1934 Res = SVal.getInt();
1935 return true;
1936 }
1937 if (SVal.isFloat()) {
1938 Res = SVal.getFloat().bitcastToAPInt();
1939 return true;
1940 }
1941 if (SVal.isVector()) {
1942 QualType VecTy = E->getType();
1943 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1944 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1945 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1946 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1947 Res = llvm::APInt::getNullValue(VecSize);
1948 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1949 APValue &Elt = SVal.getVectorElt(i);
1950 llvm::APInt EltAsInt;
1951 if (Elt.isInt()) {
1952 EltAsInt = Elt.getInt();
1953 } else if (Elt.isFloat()) {
1954 EltAsInt = Elt.getFloat().bitcastToAPInt();
1955 } else {
1956 // Don't try to handle vectors of anything other than int or float
1957 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001958 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001959 return false;
1960 }
1961 unsigned BaseEltSize = EltAsInt.getBitWidth();
1962 if (BigEndian)
1963 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1964 else
1965 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1966 }
1967 return true;
1968 }
1969 // Give up if the input isn't an int, float, or vector. For example, we
1970 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001971 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001972 return false;
1973}
1974
Richard Smith43e77732013-05-07 04:50:00 +00001975/// Perform the given integer operation, which is known to need at most BitWidth
1976/// bits, and check for overflow in the original type (if that type was not an
1977/// unsigned type).
1978template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001979static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1980 const APSInt &LHS, const APSInt &RHS,
1981 unsigned BitWidth, Operation Op,
1982 APSInt &Result) {
1983 if (LHS.isUnsigned()) {
1984 Result = Op(LHS, RHS);
1985 return true;
1986 }
Richard Smith43e77732013-05-07 04:50:00 +00001987
1988 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001989 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001990 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001991 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001992 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001993 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001994 << Result.toString(10) << E->getType();
1995 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001996 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001997 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001998 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001999}
2000
2001/// Perform the given binary integer operation.
2002static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2003 BinaryOperatorKind Opcode, APSInt RHS,
2004 APSInt &Result) {
2005 switch (Opcode) {
2006 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002007 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002008 return false;
2009 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002010 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2011 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002012 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002013 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2014 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002015 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002016 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2017 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002018 case BO_And: Result = LHS & RHS; return true;
2019 case BO_Xor: Result = LHS ^ RHS; return true;
2020 case BO_Or: Result = LHS | RHS; return true;
2021 case BO_Div:
2022 case BO_Rem:
2023 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002024 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002025 return false;
2026 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002027 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2028 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2029 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002030 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2031 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002032 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2033 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002034 return true;
2035 case BO_Shl: {
2036 if (Info.getLangOpts().OpenCL)
2037 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2038 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2039 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2040 RHS.isUnsigned());
2041 else if (RHS.isSigned() && RHS.isNegative()) {
2042 // During constant-folding, a negative shift is an opposite shift. Such
2043 // a shift is not a constant expression.
2044 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2045 RHS = -RHS;
2046 goto shift_right;
2047 }
2048 shift_left:
2049 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2050 // the shifted type.
2051 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2052 if (SA != RHS) {
2053 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2054 << RHS << E->getType() << LHS.getBitWidth();
2055 } else if (LHS.isSigned()) {
2056 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2057 // operand, and must not overflow the corresponding unsigned type.
2058 if (LHS.isNegative())
2059 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2060 else if (LHS.countLeadingZeros() < SA)
2061 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2062 }
2063 Result = LHS << SA;
2064 return true;
2065 }
2066 case BO_Shr: {
2067 if (Info.getLangOpts().OpenCL)
2068 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2069 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2070 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2071 RHS.isUnsigned());
2072 else if (RHS.isSigned() && RHS.isNegative()) {
2073 // During constant-folding, a negative shift is an opposite shift. Such a
2074 // shift is not a constant expression.
2075 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2076 RHS = -RHS;
2077 goto shift_left;
2078 }
2079 shift_right:
2080 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2081 // shifted type.
2082 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2083 if (SA != RHS)
2084 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2085 << RHS << E->getType() << LHS.getBitWidth();
2086 Result = LHS >> SA;
2087 return true;
2088 }
2089
2090 case BO_LT: Result = LHS < RHS; return true;
2091 case BO_GT: Result = LHS > RHS; return true;
2092 case BO_LE: Result = LHS <= RHS; return true;
2093 case BO_GE: Result = LHS >= RHS; return true;
2094 case BO_EQ: Result = LHS == RHS; return true;
2095 case BO_NE: Result = LHS != RHS; return true;
2096 }
2097}
2098
Richard Smith861b5b52013-05-07 23:34:45 +00002099/// Perform the given binary floating-point operation, in-place, on LHS.
2100static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2101 APFloat &LHS, BinaryOperatorKind Opcode,
2102 const APFloat &RHS) {
2103 switch (Opcode) {
2104 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002105 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002106 return false;
2107 case BO_Mul:
2108 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2109 break;
2110 case BO_Add:
2111 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2112 break;
2113 case BO_Sub:
2114 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2115 break;
2116 case BO_Div:
2117 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2118 break;
2119 }
2120
Richard Smith0c6124b2015-12-03 01:36:22 +00002121 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002122 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002123 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002124 }
Richard Smith861b5b52013-05-07 23:34:45 +00002125 return true;
2126}
2127
Richard Smitha8105bc2012-01-06 16:39:00 +00002128/// Cast an lvalue referring to a base subobject to a derived class, by
2129/// truncating the lvalue's path to the given length.
2130static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2131 const RecordDecl *TruncatedType,
2132 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002133 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002134
2135 // Check we actually point to a derived class object.
2136 if (TruncatedElements == D.Entries.size())
2137 return true;
2138 assert(TruncatedElements >= D.MostDerivedPathLength &&
2139 "not casting to a derived class");
2140 if (!Result.checkSubobject(Info, E, CSK_Derived))
2141 return false;
2142
2143 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002144 const RecordDecl *RD = TruncatedType;
2145 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002146 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002147 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2148 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002149 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002150 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002151 else
Richard Smithd62306a2011-11-10 06:34:14 +00002152 Result.Offset -= Layout.getBaseClassOffset(Base);
2153 RD = Base;
2154 }
Richard Smith027bf112011-11-17 22:56:20 +00002155 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002156 return true;
2157}
2158
John McCalld7bca762012-05-01 00:38:49 +00002159static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002160 const CXXRecordDecl *Derived,
2161 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002162 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002163 if (!RL) {
2164 if (Derived->isInvalidDecl()) return false;
2165 RL = &Info.Ctx.getASTRecordLayout(Derived);
2166 }
2167
Richard Smithd62306a2011-11-10 06:34:14 +00002168 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002169 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002170 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002171}
2172
Richard Smitha8105bc2012-01-06 16:39:00 +00002173static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002174 const CXXRecordDecl *DerivedDecl,
2175 const CXXBaseSpecifier *Base) {
2176 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2177
John McCalld7bca762012-05-01 00:38:49 +00002178 if (!Base->isVirtual())
2179 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002180
Richard Smitha8105bc2012-01-06 16:39:00 +00002181 SubobjectDesignator &D = Obj.Designator;
2182 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002183 return false;
2184
Richard Smitha8105bc2012-01-06 16:39:00 +00002185 // Extract most-derived object and corresponding type.
2186 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2187 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2188 return false;
2189
2190 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002191 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002192 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2193 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002194 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002195 return true;
2196}
2197
Richard Smith84401042013-06-03 05:03:02 +00002198static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2199 QualType Type, LValue &Result) {
2200 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2201 PathE = E->path_end();
2202 PathI != PathE; ++PathI) {
2203 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2204 *PathI))
2205 return false;
2206 Type = (*PathI)->getType();
2207 }
2208 return true;
2209}
2210
Richard Smithd62306a2011-11-10 06:34:14 +00002211/// Update LVal to refer to the given field, which must be a member of the type
2212/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002213static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002214 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002215 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002216 if (!RL) {
2217 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002218 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002219 }
Richard Smithd62306a2011-11-10 06:34:14 +00002220
2221 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002222 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002223 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002224 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002225}
2226
Richard Smith1b78b3d2012-01-25 22:15:11 +00002227/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002228static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002229 LValue &LVal,
2230 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002231 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002232 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002233 return false;
2234 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002235}
2236
Richard Smithd62306a2011-11-10 06:34:14 +00002237/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002238static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2239 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002240 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2241 // extension.
2242 if (Type->isVoidType() || Type->isFunctionType()) {
2243 Size = CharUnits::One();
2244 return true;
2245 }
2246
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002247 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002248 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002249 return false;
2250 }
2251
Richard Smithd62306a2011-11-10 06:34:14 +00002252 if (!Type->isConstantSizeType()) {
2253 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002254 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002255 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002256 return false;
2257 }
2258
2259 Size = Info.Ctx.getTypeSizeInChars(Type);
2260 return true;
2261}
2262
2263/// Update a pointer value to model pointer arithmetic.
2264/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002265/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002266/// \param LVal - The pointer value to be updated.
2267/// \param EltTy - The pointee type represented by LVal.
2268/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002269static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2270 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002271 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002272 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002273 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002274 return false;
2275
Yaxun Liu402804b2016-12-15 08:09:08 +00002276 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002277 return true;
2278}
2279
Richard Smithd6cc1982017-01-31 02:23:02 +00002280static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2281 LValue &LVal, QualType EltTy,
2282 int64_t Adjustment) {
2283 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2284 APSInt::get(Adjustment));
2285}
2286
Richard Smith66c96992012-02-18 22:04:06 +00002287/// Update an lvalue to refer to a component of a complex number.
2288/// \param Info - Information about the ongoing evaluation.
2289/// \param LVal - The lvalue to be updated.
2290/// \param EltTy - The complex number's component type.
2291/// \param Imag - False for the real component, true for the imaginary.
2292static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2293 LValue &LVal, QualType EltTy,
2294 bool Imag) {
2295 if (Imag) {
2296 CharUnits SizeOfComponent;
2297 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2298 return false;
2299 LVal.Offset += SizeOfComponent;
2300 }
2301 LVal.addComplex(Info, E, EltTy, Imag);
2302 return true;
2303}
2304
Faisal Vali051e3a22017-02-16 04:12:21 +00002305static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2306 QualType Type, const LValue &LVal,
2307 APValue &RVal);
2308
Richard Smith27908702011-10-24 17:54:18 +00002309/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002310///
2311/// \param Info Information about the ongoing evaluation.
2312/// \param E An expression to be used when printing diagnostics.
2313/// \param VD The variable whose initializer should be obtained.
2314/// \param Frame The frame in which the variable was created. Must be null
2315/// if this variable is not local to the evaluation.
2316/// \param Result Filled in with a pointer to the value of the variable.
2317static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2318 const VarDecl *VD, CallStackFrame *Frame,
2319 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002320
Richard Smith254a73d2011-10-28 22:34:42 +00002321 // If this is a parameter to an active constexpr function call, perform
2322 // argument substitution.
2323 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002324 // Assume arguments of a potential constant expression are unknown
2325 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002326 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002327 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002328 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002329 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002330 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002331 }
Richard Smith3229b742013-05-05 21:17:10 +00002332 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002333 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002334 }
Richard Smith27908702011-10-24 17:54:18 +00002335
Richard Smithd9f663b2013-04-22 15:31:51 +00002336 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002337 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002338 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002339 if (!Result) {
2340 // Assume variables referenced within a lambda's call operator that were
2341 // not declared within the call operator are captures and during checking
2342 // of a potential constant expression, assume they are unknown constant
2343 // expressions.
2344 assert(isLambdaCallOperator(Frame->Callee) &&
2345 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2346 "missing value for local variable");
2347 if (Info.checkingPotentialConstantExpression())
2348 return false;
2349 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002350 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002351 diag::note_unimplemented_constexpr_lambda_feature_ast)
2352 << "captures not currently allowed";
2353 return false;
2354 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002355 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002356 }
2357
Richard Smithd0b4dd62011-12-19 06:19:21 +00002358 // Dig out the initializer, and use the declaration which it's attached to.
2359 const Expr *Init = VD->getAnyInitializer(VD);
2360 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002361 // If we're checking a potential constant expression, the variable could be
2362 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002363 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002364 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002365 return false;
2366 }
2367
Richard Smithd62306a2011-11-10 06:34:14 +00002368 // If we're currently evaluating the initializer of this declaration, use that
2369 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002370 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002371 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002372 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002373 }
2374
Richard Smithcecf1842011-11-01 21:06:14 +00002375 // Never evaluate the initializer of a weak variable. We can't be sure that
2376 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002377 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002378 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002379 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002380 }
Richard Smithcecf1842011-11-01 21:06:14 +00002381
Richard Smithd0b4dd62011-12-19 06:19:21 +00002382 // Check that we can fold the initializer. In C++, we will have already done
2383 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002384 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002385 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002386 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002387 Notes.size() + 1) << VD;
2388 Info.Note(VD->getLocation(), diag::note_declared_at);
2389 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002390 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002391 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002392 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002393 Notes.size() + 1) << VD;
2394 Info.Note(VD->getLocation(), diag::note_declared_at);
2395 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002396 }
Richard Smith27908702011-10-24 17:54:18 +00002397
Richard Smith3229b742013-05-05 21:17:10 +00002398 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002399 return true;
Richard Smith27908702011-10-24 17:54:18 +00002400}
2401
Richard Smith11562c52011-10-28 17:51:58 +00002402static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002403 Qualifiers Quals = T.getQualifiers();
2404 return Quals.hasConst() && !Quals.hasVolatile();
2405}
2406
Richard Smithe97cbd72011-11-11 04:05:33 +00002407/// Get the base index of the given base class within an APValue representing
2408/// the given derived class.
2409static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2410 const CXXRecordDecl *Base) {
2411 Base = Base->getCanonicalDecl();
2412 unsigned Index = 0;
2413 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2414 E = Derived->bases_end(); I != E; ++I, ++Index) {
2415 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2416 return Index;
2417 }
2418
2419 llvm_unreachable("base class missing from derived class's bases list");
2420}
2421
Richard Smith3da88fa2013-04-26 14:36:30 +00002422/// Extract the value of a character from a string literal.
2423static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2424 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002425 // FIXME: Support MakeStringConstant
2426 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2427 std::string Str;
2428 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2429 assert(Index <= Str.size() && "Index too large");
2430 return APSInt::getUnsigned(Str.c_str()[Index]);
2431 }
2432
Alexey Bataevec474782014-10-09 08:45:04 +00002433 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2434 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002435 const StringLiteral *S = cast<StringLiteral>(Lit);
2436 const ConstantArrayType *CAT =
2437 Info.Ctx.getAsConstantArrayType(S->getType());
2438 assert(CAT && "string literal isn't an array");
2439 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002440 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002441
2442 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002443 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002444 if (Index < S->getLength())
2445 Value = S->getCodeUnit(Index);
2446 return Value;
2447}
2448
Richard Smith3da88fa2013-04-26 14:36:30 +00002449// Expand a string literal into an array of characters.
2450static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2451 APValue &Result) {
2452 const StringLiteral *S = cast<StringLiteral>(Lit);
2453 const ConstantArrayType *CAT =
2454 Info.Ctx.getAsConstantArrayType(S->getType());
2455 assert(CAT && "string literal isn't an array");
2456 QualType CharType = CAT->getElementType();
2457 assert(CharType->isIntegerType() && "unexpected character type");
2458
2459 unsigned Elts = CAT->getSize().getZExtValue();
2460 Result = APValue(APValue::UninitArray(),
2461 std::min(S->getLength(), Elts), Elts);
2462 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2463 CharType->isUnsignedIntegerType());
2464 if (Result.hasArrayFiller())
2465 Result.getArrayFiller() = APValue(Value);
2466 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2467 Value = S->getCodeUnit(I);
2468 Result.getArrayInitializedElt(I) = APValue(Value);
2469 }
2470}
2471
2472// Expand an array so that it has more than Index filled elements.
2473static void expandArray(APValue &Array, unsigned Index) {
2474 unsigned Size = Array.getArraySize();
2475 assert(Index < Size);
2476
2477 // Always at least double the number of elements for which we store a value.
2478 unsigned OldElts = Array.getArrayInitializedElts();
2479 unsigned NewElts = std::max(Index+1, OldElts * 2);
2480 NewElts = std::min(Size, std::max(NewElts, 8u));
2481
2482 // Copy the data across.
2483 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2484 for (unsigned I = 0; I != OldElts; ++I)
2485 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2486 for (unsigned I = OldElts; I != NewElts; ++I)
2487 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2488 if (NewValue.hasArrayFiller())
2489 NewValue.getArrayFiller() = Array.getArrayFiller();
2490 Array.swap(NewValue);
2491}
2492
Richard Smithb01fe402014-09-16 01:24:02 +00002493/// Determine whether a type would actually be read by an lvalue-to-rvalue
2494/// conversion. If it's of class type, we may assume that the copy operation
2495/// is trivial. Note that this is never true for a union type with fields
2496/// (because the copy always "reads" the active member) and always true for
2497/// a non-class type.
2498static bool isReadByLvalueToRvalueConversion(QualType T) {
2499 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2500 if (!RD || (RD->isUnion() && !RD->field_empty()))
2501 return true;
2502 if (RD->isEmpty())
2503 return false;
2504
2505 for (auto *Field : RD->fields())
2506 if (isReadByLvalueToRvalueConversion(Field->getType()))
2507 return true;
2508
2509 for (auto &BaseSpec : RD->bases())
2510 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2511 return true;
2512
2513 return false;
2514}
2515
2516/// Diagnose an attempt to read from any unreadable field within the specified
2517/// type, which might be a class type.
2518static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2519 QualType T) {
2520 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2521 if (!RD)
2522 return false;
2523
2524 if (!RD->hasMutableFields())
2525 return false;
2526
2527 for (auto *Field : RD->fields()) {
2528 // If we're actually going to read this field in some way, then it can't
2529 // be mutable. If we're in a union, then assigning to a mutable field
2530 // (even an empty one) can change the active member, so that's not OK.
2531 // FIXME: Add core issue number for the union case.
2532 if (Field->isMutable() &&
2533 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002534 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002535 Info.Note(Field->getLocation(), diag::note_declared_at);
2536 return true;
2537 }
2538
2539 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2540 return true;
2541 }
2542
2543 for (auto &BaseSpec : RD->bases())
2544 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2545 return true;
2546
2547 // All mutable fields were empty, and thus not actually read.
2548 return false;
2549}
2550
Richard Smith861b5b52013-05-07 23:34:45 +00002551/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002552enum AccessKinds {
2553 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002554 AK_Assign,
2555 AK_Increment,
2556 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002557};
2558
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002559namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002560/// A handle to a complete object (an object that is not a subobject of
2561/// another object).
2562struct CompleteObject {
2563 /// The value of the complete object.
2564 APValue *Value;
2565 /// The type of the complete object.
2566 QualType Type;
2567
Craig Topper36250ad2014-05-12 05:36:57 +00002568 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002569 CompleteObject(APValue *Value, QualType Type)
2570 : Value(Value), Type(Type) {
2571 assert(Value && "missing value for complete object");
2572 }
2573
Aaron Ballman67347662015-02-15 22:00:28 +00002574 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002575};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002576} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002577
Richard Smith3da88fa2013-04-26 14:36:30 +00002578/// Find the designated sub-object of an rvalue.
2579template<typename SubobjectHandler>
2580typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002581findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002582 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002583 if (Sub.Invalid)
2584 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002585 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002586 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002587 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002588 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002589 << handler.AccessKind;
2590 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002591 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002592 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002593 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002594
Richard Smith3229b742013-05-05 21:17:10 +00002595 APValue *O = Obj.Value;
2596 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002597 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002598
Richard Smithd62306a2011-11-10 06:34:14 +00002599 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002600 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2601 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002602 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002603 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002604 return handler.failed();
2605 }
2606
Richard Smith49ca8aa2013-08-06 07:09:20 +00002607 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002608 // If we are reading an object of class type, there may still be more
2609 // things we need to check: if there are any mutable subobjects, we
2610 // cannot perform this read. (This only happens when performing a trivial
2611 // copy or assignment.)
2612 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2613 diagnoseUnreadableFields(Info, E, ObjType))
2614 return handler.failed();
2615
Richard Smith49ca8aa2013-08-06 07:09:20 +00002616 if (!handler.found(*O, ObjType))
2617 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002618
Richard Smith49ca8aa2013-08-06 07:09:20 +00002619 // If we modified a bit-field, truncate it to the right width.
2620 if (handler.AccessKind != AK_Read &&
2621 LastField && LastField->isBitField() &&
2622 !truncateBitfieldValue(Info, E, *O, LastField))
2623 return false;
2624
2625 return true;
2626 }
2627
Craig Topper36250ad2014-05-12 05:36:57 +00002628 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002629 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002630 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002631 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002632 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002633 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002634 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002635 // Note, it should not be possible to form a pointer with a valid
2636 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002637 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002638 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002639 << handler.AccessKind;
2640 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002641 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002642 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002643 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002644
2645 ObjType = CAT->getElementType();
2646
Richard Smith14a94132012-02-17 03:35:37 +00002647 // An array object is represented as either an Array APValue or as an
2648 // LValue which refers to a string literal.
2649 if (O->isLValue()) {
2650 assert(I == N - 1 && "extracting subobject of character?");
2651 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002652 if (handler.AccessKind != AK_Read)
2653 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2654 *O);
2655 else
2656 return handler.foundString(*O, ObjType, Index);
2657 }
2658
2659 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002660 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002661 else if (handler.AccessKind != AK_Read) {
2662 expandArray(*O, Index);
2663 O = &O->getArrayInitializedElt(Index);
2664 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002665 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002666 } else if (ObjType->isAnyComplexType()) {
2667 // Next subobject is a complex number.
2668 uint64_t Index = Sub.Entries[I].ArrayIndex;
2669 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002670 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002671 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002672 << handler.AccessKind;
2673 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002674 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002675 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002676 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002677
2678 bool WasConstQualified = ObjType.isConstQualified();
2679 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2680 if (WasConstQualified)
2681 ObjType.addConst();
2682
Richard Smith66c96992012-02-18 22:04:06 +00002683 assert(I == N - 1 && "extracting subobject of scalar?");
2684 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002685 return handler.found(Index ? O->getComplexIntImag()
2686 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002687 } else {
2688 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002689 return handler.found(Index ? O->getComplexFloatImag()
2690 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002691 }
Richard Smithd62306a2011-11-10 06:34:14 +00002692 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002693 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002694 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002695 << Field;
2696 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002697 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002698 }
2699
Richard Smithd62306a2011-11-10 06:34:14 +00002700 // Next subobject is a class, struct or union field.
2701 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2702 if (RD->isUnion()) {
2703 const FieldDecl *UnionField = O->getUnionField();
2704 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002705 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002706 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002707 << handler.AccessKind << Field << !UnionField << UnionField;
2708 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002709 }
Richard Smithd62306a2011-11-10 06:34:14 +00002710 O = &O->getUnionValue();
2711 } else
2712 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002713
2714 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002715 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002716 if (WasConstQualified && !Field->isMutable())
2717 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002718
2719 if (ObjType.isVolatileQualified()) {
2720 if (Info.getLangOpts().CPlusPlus) {
2721 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002722 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002723 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002724 Info.Note(Field->getLocation(), diag::note_declared_at);
2725 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002726 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002727 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002728 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002729 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002730
2731 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002732 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002733 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002734 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2735 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2736 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002737
2738 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002739 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002740 if (WasConstQualified)
2741 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002742 }
2743 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002744}
2745
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002746namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002747struct ExtractSubobjectHandler {
2748 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002749 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002750
2751 static const AccessKinds AccessKind = AK_Read;
2752
2753 typedef bool result_type;
2754 bool failed() { return false; }
2755 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002756 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002757 return true;
2758 }
2759 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002760 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002761 return true;
2762 }
2763 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002764 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002765 return true;
2766 }
2767 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002768 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002769 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2770 return true;
2771 }
2772};
Richard Smith3229b742013-05-05 21:17:10 +00002773} // end anonymous namespace
2774
Richard Smith3da88fa2013-04-26 14:36:30 +00002775const AccessKinds ExtractSubobjectHandler::AccessKind;
2776
2777/// Extract the designated sub-object of an rvalue.
2778static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002779 const CompleteObject &Obj,
2780 const SubobjectDesignator &Sub,
2781 APValue &Result) {
2782 ExtractSubobjectHandler Handler = { Info, Result };
2783 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002784}
2785
Richard Smith3229b742013-05-05 21:17:10 +00002786namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002787struct ModifySubobjectHandler {
2788 EvalInfo &Info;
2789 APValue &NewVal;
2790 const Expr *E;
2791
2792 typedef bool result_type;
2793 static const AccessKinds AccessKind = AK_Assign;
2794
2795 bool checkConst(QualType QT) {
2796 // Assigning to a const object has undefined behavior.
2797 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002798 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002799 return false;
2800 }
2801 return true;
2802 }
2803
2804 bool failed() { return false; }
2805 bool found(APValue &Subobj, QualType SubobjType) {
2806 if (!checkConst(SubobjType))
2807 return false;
2808 // We've been given ownership of NewVal, so just swap it in.
2809 Subobj.swap(NewVal);
2810 return true;
2811 }
2812 bool found(APSInt &Value, QualType SubobjType) {
2813 if (!checkConst(SubobjType))
2814 return false;
2815 if (!NewVal.isInt()) {
2816 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002817 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002818 return false;
2819 }
2820 Value = NewVal.getInt();
2821 return true;
2822 }
2823 bool found(APFloat &Value, QualType SubobjType) {
2824 if (!checkConst(SubobjType))
2825 return false;
2826 Value = NewVal.getFloat();
2827 return true;
2828 }
2829 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2830 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2831 }
2832};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002833} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002834
Richard Smith3229b742013-05-05 21:17:10 +00002835const AccessKinds ModifySubobjectHandler::AccessKind;
2836
Richard Smith3da88fa2013-04-26 14:36:30 +00002837/// Update the designated sub-object of an rvalue to the given value.
2838static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002839 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002840 const SubobjectDesignator &Sub,
2841 APValue &NewVal) {
2842 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002843 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002844}
2845
Richard Smith84f6dcf2012-02-02 01:16:57 +00002846/// Find the position where two subobject designators diverge, or equivalently
2847/// the length of the common initial subsequence.
2848static unsigned FindDesignatorMismatch(QualType ObjType,
2849 const SubobjectDesignator &A,
2850 const SubobjectDesignator &B,
2851 bool &WasArrayIndex) {
2852 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2853 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002854 if (!ObjType.isNull() &&
2855 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002856 // Next subobject is an array element.
2857 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2858 WasArrayIndex = true;
2859 return I;
2860 }
Richard Smith66c96992012-02-18 22:04:06 +00002861 if (ObjType->isAnyComplexType())
2862 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2863 else
2864 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002865 } else {
2866 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2867 WasArrayIndex = false;
2868 return I;
2869 }
2870 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2871 // Next subobject is a field.
2872 ObjType = FD->getType();
2873 else
2874 // Next subobject is a base class.
2875 ObjType = QualType();
2876 }
2877 }
2878 WasArrayIndex = false;
2879 return I;
2880}
2881
2882/// Determine whether the given subobject designators refer to elements of the
2883/// same array object.
2884static bool AreElementsOfSameArray(QualType ObjType,
2885 const SubobjectDesignator &A,
2886 const SubobjectDesignator &B) {
2887 if (A.Entries.size() != B.Entries.size())
2888 return false;
2889
George Burgess IVa51c4072015-10-16 01:49:01 +00002890 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002891 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2892 // A is a subobject of the array element.
2893 return false;
2894
2895 // If A (and B) designates an array element, the last entry will be the array
2896 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2897 // of length 1' case, and the entire path must match.
2898 bool WasArrayIndex;
2899 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2900 return CommonLength >= A.Entries.size() - IsArray;
2901}
2902
Richard Smith3229b742013-05-05 21:17:10 +00002903/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002904static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2905 AccessKinds AK, const LValue &LVal,
2906 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002907 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002908 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002909 return CompleteObject();
2910 }
2911
Craig Topper36250ad2014-05-12 05:36:57 +00002912 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002913 if (LVal.CallIndex) {
2914 Frame = Info.getCallFrame(LVal.CallIndex);
2915 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002916 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002917 << AK << LVal.Base.is<const ValueDecl*>();
2918 NoteLValueLocation(Info, LVal.Base);
2919 return CompleteObject();
2920 }
Richard Smith3229b742013-05-05 21:17:10 +00002921 }
2922
2923 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2924 // is not a constant expression (even if the object is non-volatile). We also
2925 // apply this rule to C++98, in order to conform to the expected 'volatile'
2926 // semantics.
2927 if (LValType.isVolatileQualified()) {
2928 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002929 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002930 << AK << LValType;
2931 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002932 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002933 return CompleteObject();
2934 }
2935
2936 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002937 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002938 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002939
2940 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2941 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2942 // In C++11, constexpr, non-volatile variables initialized with constant
2943 // expressions are constant expressions too. Inside constexpr functions,
2944 // parameters are constant expressions even if they're non-const.
2945 // In C++1y, objects local to a constant expression (those with a Frame) are
2946 // both readable and writable inside constant expressions.
2947 // In C, such things can also be folded, although they are not ICEs.
2948 const VarDecl *VD = dyn_cast<VarDecl>(D);
2949 if (VD) {
2950 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2951 VD = VDef;
2952 }
2953 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002954 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002955 return CompleteObject();
2956 }
2957
2958 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002959 if (BaseType.isVolatileQualified()) {
2960 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002961 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002962 << AK << 1 << VD;
2963 Info.Note(VD->getLocation(), diag::note_declared_at);
2964 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002965 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002966 }
2967 return CompleteObject();
2968 }
2969
2970 // Unless we're looking at a local variable or argument in a constexpr call,
2971 // the variable we're reading must be const.
2972 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002973 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002974 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2975 // OK, we can read and modify an object if we're in the process of
2976 // evaluating its initializer, because its lifetime began in this
2977 // evaluation.
2978 } else if (AK != AK_Read) {
2979 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002980 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002981 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00002982 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002983 // OK, we can read this variable.
2984 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002985 // In OpenCL if a variable is in constant address space it is a const value.
2986 if (!(BaseType.isConstQualified() ||
2987 (Info.getLangOpts().OpenCL &&
2988 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002989 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002990 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002991 Info.Note(VD->getLocation(), diag::note_declared_at);
2992 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002993 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002994 }
2995 return CompleteObject();
2996 }
2997 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2998 // We support folding of const floating-point types, in order to make
2999 // static const data members of such types (supported as an extension)
3000 // more useful.
3001 if (Info.getLangOpts().CPlusPlus11) {
3002 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3003 Info.Note(VD->getLocation(), diag::note_declared_at);
3004 } else {
3005 Info.CCEDiag(E);
3006 }
George Burgess IVb5316982016-12-27 05:33:20 +00003007 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3008 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3009 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003010 } else {
3011 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003012 if (Info.checkingPotentialConstantExpression() &&
3013 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3014 // The definition of this variable could be constexpr. We can't
3015 // access it right now, but may be able to in future.
3016 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003017 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003018 Info.Note(VD->getLocation(), diag::note_declared_at);
3019 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003020 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003021 }
3022 return CompleteObject();
3023 }
3024 }
3025
3026 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3027 return CompleteObject();
3028 } else {
3029 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3030
3031 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003032 if (const MaterializeTemporaryExpr *MTE =
3033 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3034 assert(MTE->getStorageDuration() == SD_Static &&
3035 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003036
Richard Smithe6c01442013-06-05 00:46:14 +00003037 // Per C++1y [expr.const]p2:
3038 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3039 // - a [...] glvalue of integral or enumeration type that refers to
3040 // a non-volatile const object [...]
3041 // [...]
3042 // - a [...] glvalue of literal type that refers to a non-volatile
3043 // object whose lifetime began within the evaluation of e.
3044 //
3045 // C++11 misses the 'began within the evaluation of e' check and
3046 // instead allows all temporaries, including things like:
3047 // int &&r = 1;
3048 // int x = ++r;
3049 // constexpr int k = r;
3050 // Therefore we use the C++1y rules in C++11 too.
3051 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3052 const ValueDecl *ED = MTE->getExtendingDecl();
3053 if (!(BaseType.isConstQualified() &&
3054 BaseType->isIntegralOrEnumerationType()) &&
3055 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003056 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003057 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3058 return CompleteObject();
3059 }
3060
3061 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3062 assert(BaseVal && "got reference to unevaluated temporary");
3063 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003064 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003065 return CompleteObject();
3066 }
3067 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003068 BaseVal = Frame->getTemporary(Base);
3069 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003070 }
Richard Smith3229b742013-05-05 21:17:10 +00003071
3072 // Volatile temporary objects cannot be accessed in constant expressions.
3073 if (BaseType.isVolatileQualified()) {
3074 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003075 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003076 << AK << 0;
3077 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3078 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003079 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003080 }
3081 return CompleteObject();
3082 }
3083 }
3084
Richard Smith7525ff62013-05-09 07:14:00 +00003085 // During the construction of an object, it is not yet 'const'.
3086 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3087 // and this doesn't do quite the right thing for const subobjects of the
3088 // object under construction.
3089 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3090 BaseType = Info.Ctx.getCanonicalType(BaseType);
3091 BaseType.removeLocalConst();
3092 }
3093
Richard Smith6d4c6582013-11-05 22:18:15 +00003094 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003095 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003096 //
3097 // FIXME: Not all local state is mutable. Allow local constant subobjects
3098 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003099 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3100 Info.EvalStatus.HasSideEffects) ||
3101 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003102 return CompleteObject();
3103
3104 return CompleteObject(BaseVal, BaseType);
3105}
3106
Richard Smith243ef902013-05-05 23:31:59 +00003107/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3108/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3109/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003110///
3111/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003112/// \param Conv - The expression for which we are performing the conversion.
3113/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003114/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3115/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003116/// \param LVal - The glvalue on which we are attempting to perform this action.
3117/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003118static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003119 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003120 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003121 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003122 return false;
3123
Richard Smith3229b742013-05-05 21:17:10 +00003124 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003125 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003126 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003127 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3128 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3129 // initializer until now for such expressions. Such an expression can't be
3130 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003131 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003132 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003133 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003134 }
Richard Smith3229b742013-05-05 21:17:10 +00003135 APValue Lit;
3136 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3137 return false;
3138 CompleteObject LitObj(&Lit, Base->getType());
3139 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003140 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003141 // We represent a string literal array as an lvalue pointing at the
3142 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003143 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003144 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3145 CompleteObject StrObj(&Str, Base->getType());
3146 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003147 }
Richard Smith11562c52011-10-28 17:51:58 +00003148 }
3149
Richard Smith3229b742013-05-05 21:17:10 +00003150 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3151 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003152}
3153
3154/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003155static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003156 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003157 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003158 return false;
3159
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003160 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003161 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003162 return false;
3163 }
3164
Richard Smith3229b742013-05-05 21:17:10 +00003165 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3166 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003167}
3168
Richard Smith243ef902013-05-05 23:31:59 +00003169static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3170 return T->isSignedIntegerType() &&
3171 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3172}
3173
3174namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003175struct CompoundAssignSubobjectHandler {
3176 EvalInfo &Info;
3177 const Expr *E;
3178 QualType PromotedLHSType;
3179 BinaryOperatorKind Opcode;
3180 const APValue &RHS;
3181
3182 static const AccessKinds AccessKind = AK_Assign;
3183
3184 typedef bool result_type;
3185
3186 bool checkConst(QualType QT) {
3187 // Assigning to a const object has undefined behavior.
3188 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003189 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003190 return false;
3191 }
3192 return true;
3193 }
3194
3195 bool failed() { return false; }
3196 bool found(APValue &Subobj, QualType SubobjType) {
3197 switch (Subobj.getKind()) {
3198 case APValue::Int:
3199 return found(Subobj.getInt(), SubobjType);
3200 case APValue::Float:
3201 return found(Subobj.getFloat(), SubobjType);
3202 case APValue::ComplexInt:
3203 case APValue::ComplexFloat:
3204 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003205 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003206 return false;
3207 case APValue::LValue:
3208 return foundPointer(Subobj, SubobjType);
3209 default:
3210 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003211 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003212 return false;
3213 }
3214 }
3215 bool found(APSInt &Value, QualType SubobjType) {
3216 if (!checkConst(SubobjType))
3217 return false;
3218
3219 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3220 // We don't support compound assignment on integer-cast-to-pointer
3221 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003222 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003223 return false;
3224 }
3225
3226 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3227 SubobjType, Value);
3228 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3229 return false;
3230 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3231 return true;
3232 }
3233 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003234 return checkConst(SubobjType) &&
3235 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3236 Value) &&
3237 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3238 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003239 }
3240 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3241 if (!checkConst(SubobjType))
3242 return false;
3243
3244 QualType PointeeType;
3245 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3246 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003247
3248 if (PointeeType.isNull() || !RHS.isInt() ||
3249 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003250 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003251 return false;
3252 }
3253
Richard Smithd6cc1982017-01-31 02:23:02 +00003254 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003255 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003256 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003257
3258 LValue LVal;
3259 LVal.setFrom(Info.Ctx, Subobj);
3260 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3261 return false;
3262 LVal.moveInto(Subobj);
3263 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003264 }
3265 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3266 llvm_unreachable("shouldn't encounter string elements here");
3267 }
3268};
3269} // end anonymous namespace
3270
3271const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3272
3273/// Perform a compound assignment of LVal <op>= RVal.
3274static bool handleCompoundAssignment(
3275 EvalInfo &Info, const Expr *E,
3276 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3277 BinaryOperatorKind Opcode, const APValue &RVal) {
3278 if (LVal.Designator.Invalid)
3279 return false;
3280
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003281 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003282 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003283 return false;
3284 }
3285
3286 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3287 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3288 RVal };
3289 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3290}
3291
3292namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003293struct IncDecSubobjectHandler {
3294 EvalInfo &Info;
3295 const Expr *E;
3296 AccessKinds AccessKind;
3297 APValue *Old;
3298
3299 typedef bool result_type;
3300
3301 bool checkConst(QualType QT) {
3302 // Assigning to a const object has undefined behavior.
3303 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003304 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003305 return false;
3306 }
3307 return true;
3308 }
3309
3310 bool failed() { return false; }
3311 bool found(APValue &Subobj, QualType SubobjType) {
3312 // Stash the old value. Also clear Old, so we don't clobber it later
3313 // if we're post-incrementing a complex.
3314 if (Old) {
3315 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003316 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003317 }
3318
3319 switch (Subobj.getKind()) {
3320 case APValue::Int:
3321 return found(Subobj.getInt(), SubobjType);
3322 case APValue::Float:
3323 return found(Subobj.getFloat(), SubobjType);
3324 case APValue::ComplexInt:
3325 return found(Subobj.getComplexIntReal(),
3326 SubobjType->castAs<ComplexType>()->getElementType()
3327 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3328 case APValue::ComplexFloat:
3329 return found(Subobj.getComplexFloatReal(),
3330 SubobjType->castAs<ComplexType>()->getElementType()
3331 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3332 case APValue::LValue:
3333 return foundPointer(Subobj, SubobjType);
3334 default:
3335 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003336 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003337 return false;
3338 }
3339 }
3340 bool found(APSInt &Value, QualType SubobjType) {
3341 if (!checkConst(SubobjType))
3342 return false;
3343
3344 if (!SubobjType->isIntegerType()) {
3345 // We don't support increment / decrement on integer-cast-to-pointer
3346 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003347 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003348 return false;
3349 }
3350
3351 if (Old) *Old = APValue(Value);
3352
3353 // bool arithmetic promotes to int, and the conversion back to bool
3354 // doesn't reduce mod 2^n, so special-case it.
3355 if (SubobjType->isBooleanType()) {
3356 if (AccessKind == AK_Increment)
3357 Value = 1;
3358 else
3359 Value = !Value;
3360 return true;
3361 }
3362
3363 bool WasNegative = Value.isNegative();
3364 if (AccessKind == AK_Increment) {
3365 ++Value;
3366
3367 if (!WasNegative && Value.isNegative() &&
3368 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3369 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003370 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003371 }
3372 } else {
3373 --Value;
3374
3375 if (WasNegative && !Value.isNegative() &&
3376 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3377 unsigned BitWidth = Value.getBitWidth();
3378 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3379 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003380 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003381 }
3382 }
3383 return true;
3384 }
3385 bool found(APFloat &Value, QualType SubobjType) {
3386 if (!checkConst(SubobjType))
3387 return false;
3388
3389 if (Old) *Old = APValue(Value);
3390
3391 APFloat One(Value.getSemantics(), 1);
3392 if (AccessKind == AK_Increment)
3393 Value.add(One, APFloat::rmNearestTiesToEven);
3394 else
3395 Value.subtract(One, APFloat::rmNearestTiesToEven);
3396 return true;
3397 }
3398 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3399 if (!checkConst(SubobjType))
3400 return false;
3401
3402 QualType PointeeType;
3403 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3404 PointeeType = PT->getPointeeType();
3405 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003406 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003407 return false;
3408 }
3409
3410 LValue LVal;
3411 LVal.setFrom(Info.Ctx, Subobj);
3412 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3413 AccessKind == AK_Increment ? 1 : -1))
3414 return false;
3415 LVal.moveInto(Subobj);
3416 return true;
3417 }
3418 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3419 llvm_unreachable("shouldn't encounter string elements here");
3420 }
3421};
3422} // end anonymous namespace
3423
3424/// Perform an increment or decrement on LVal.
3425static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3426 QualType LValType, bool IsIncrement, APValue *Old) {
3427 if (LVal.Designator.Invalid)
3428 return false;
3429
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003430 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003431 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003432 return false;
3433 }
3434
3435 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3436 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3437 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3438 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3439}
3440
Richard Smithe97cbd72011-11-11 04:05:33 +00003441/// Build an lvalue for the object argument of a member function call.
3442static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3443 LValue &This) {
3444 if (Object->getType()->isPointerType())
3445 return EvaluatePointer(Object, This, Info);
3446
3447 if (Object->isGLValue())
3448 return EvaluateLValue(Object, This, Info);
3449
Richard Smithd9f663b2013-04-22 15:31:51 +00003450 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003451 return EvaluateTemporary(Object, This, Info);
3452
Faisal Valie690b7a2016-07-02 22:34:24 +00003453 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003454 return false;
3455}
3456
3457/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3458/// lvalue referring to the result.
3459///
3460/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003461/// \param LV - An lvalue referring to the base of the member pointer.
3462/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003463/// \param IncludeMember - Specifies whether the member itself is included in
3464/// the resulting LValue subobject designator. This is not possible when
3465/// creating a bound member function.
3466/// \return The field or method declaration to which the member pointer refers,
3467/// or 0 if evaluation fails.
3468static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003469 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003470 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003471 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003472 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003473 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003474 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003475 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003476
3477 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3478 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003479 if (!MemPtr.getDecl()) {
3480 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003481 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003482 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003483 }
Richard Smith253c2a32012-01-27 01:14:48 +00003484
Richard Smith027bf112011-11-17 22:56:20 +00003485 if (MemPtr.isDerivedMember()) {
3486 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003487 // The end of the derived-to-base path for the base object must match the
3488 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003489 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003490 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003491 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003492 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003493 }
Richard Smith027bf112011-11-17 22:56:20 +00003494 unsigned PathLengthToMember =
3495 LV.Designator.Entries.size() - MemPtr.Path.size();
3496 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3497 const CXXRecordDecl *LVDecl = getAsBaseClass(
3498 LV.Designator.Entries[PathLengthToMember + I]);
3499 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003500 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003501 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003502 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003503 }
Richard Smith027bf112011-11-17 22:56:20 +00003504 }
3505
3506 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003507 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003508 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003509 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003510 } else if (!MemPtr.Path.empty()) {
3511 // Extend the LValue path with the member pointer's path.
3512 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3513 MemPtr.Path.size() + IncludeMember);
3514
3515 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003516 if (const PointerType *PT = LVType->getAs<PointerType>())
3517 LVType = PT->getPointeeType();
3518 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3519 assert(RD && "member pointer access on non-class-type expression");
3520 // The first class in the path is that of the lvalue.
3521 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3522 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003523 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003524 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003525 RD = Base;
3526 }
3527 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003528 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3529 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003530 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003531 }
3532
3533 // Add the member. Note that we cannot build bound member functions here.
3534 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003535 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003536 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003537 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003538 } else if (const IndirectFieldDecl *IFD =
3539 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003540 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003541 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003542 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003543 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003544 }
Richard Smith027bf112011-11-17 22:56:20 +00003545 }
3546
3547 return MemPtr.getDecl();
3548}
3549
Richard Smith84401042013-06-03 05:03:02 +00003550static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3551 const BinaryOperator *BO,
3552 LValue &LV,
3553 bool IncludeMember = true) {
3554 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3555
3556 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003557 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003558 MemberPtr MemPtr;
3559 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3560 }
Craig Topper36250ad2014-05-12 05:36:57 +00003561 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003562 }
3563
3564 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3565 BO->getRHS(), IncludeMember);
3566}
3567
Richard Smith027bf112011-11-17 22:56:20 +00003568/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3569/// the provided lvalue, which currently refers to the base object.
3570static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3571 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003572 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003573 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003574 return false;
3575
Richard Smitha8105bc2012-01-06 16:39:00 +00003576 QualType TargetQT = E->getType();
3577 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3578 TargetQT = PT->getPointeeType();
3579
3580 // Check this cast lands within the final derived-to-base subobject path.
3581 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003582 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003583 << D.MostDerivedType << TargetQT;
3584 return false;
3585 }
3586
Richard Smith027bf112011-11-17 22:56:20 +00003587 // Check the type of the final cast. We don't need to check the path,
3588 // since a cast can only be formed if the path is unique.
3589 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003590 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3591 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003592 if (NewEntriesSize == D.MostDerivedPathLength)
3593 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3594 else
Richard Smith027bf112011-11-17 22:56:20 +00003595 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003596 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003597 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003598 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003599 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003600 }
Richard Smith027bf112011-11-17 22:56:20 +00003601
3602 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003603 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003604}
3605
Mike Stump876387b2009-10-27 22:09:17 +00003606namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003607enum EvalStmtResult {
3608 /// Evaluation failed.
3609 ESR_Failed,
3610 /// Hit a 'return' statement.
3611 ESR_Returned,
3612 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003613 ESR_Succeeded,
3614 /// Hit a 'continue' statement.
3615 ESR_Continue,
3616 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003617 ESR_Break,
3618 /// Still scanning for 'case' or 'default' statement.
3619 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003620};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003621}
Richard Smith254a73d2011-10-28 22:34:42 +00003622
Richard Smith97fcf4b2016-08-14 23:15:52 +00003623static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3624 // We don't need to evaluate the initializer for a static local.
3625 if (!VD->hasLocalStorage())
3626 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003627
Richard Smith97fcf4b2016-08-14 23:15:52 +00003628 LValue Result;
3629 Result.set(VD, Info.CurrentCall->Index);
3630 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003631
Richard Smith97fcf4b2016-08-14 23:15:52 +00003632 const Expr *InitE = VD->getInit();
3633 if (!InitE) {
3634 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3635 << false << VD->getType();
3636 Val = APValue();
3637 return false;
3638 }
Richard Smith51f03172013-06-20 03:00:05 +00003639
Richard Smith97fcf4b2016-08-14 23:15:52 +00003640 if (InitE->isValueDependent())
3641 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003642
Richard Smith97fcf4b2016-08-14 23:15:52 +00003643 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3644 // Wipe out any partially-computed value, to allow tracking that this
3645 // evaluation failed.
3646 Val = APValue();
3647 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003648 }
3649
3650 return true;
3651}
3652
Richard Smith97fcf4b2016-08-14 23:15:52 +00003653static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3654 bool OK = true;
3655
3656 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3657 OK &= EvaluateVarDecl(Info, VD);
3658
3659 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3660 for (auto *BD : DD->bindings())
3661 if (auto *VD = BD->getHoldingVar())
3662 OK &= EvaluateDecl(Info, VD);
3663
3664 return OK;
3665}
3666
3667
Richard Smith4e18ca52013-05-06 05:56:11 +00003668/// Evaluate a condition (either a variable declaration or an expression).
3669static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3670 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003671 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003672 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3673 return false;
3674 return EvaluateAsBooleanCondition(Cond, Result, Info);
3675}
3676
Richard Smith89210072016-04-04 23:29:43 +00003677namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003678/// \brief A location where the result (returned value) of evaluating a
3679/// statement should be stored.
3680struct StmtResult {
3681 /// The APValue that should be filled in with the returned value.
3682 APValue &Value;
3683 /// The location containing the result, if any (used to support RVO).
3684 const LValue *Slot;
3685};
Richard Smith89210072016-04-04 23:29:43 +00003686}
Richard Smith52a980a2015-08-28 02:43:42 +00003687
3688static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003689 const Stmt *S,
3690 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003691
3692/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003693static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003694 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003695 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003696 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003697 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003698 case ESR_Break:
3699 return ESR_Succeeded;
3700 case ESR_Succeeded:
3701 case ESR_Continue:
3702 return ESR_Continue;
3703 case ESR_Failed:
3704 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003705 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003706 return ESR;
3707 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003708 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003709}
3710
Richard Smith496ddcf2013-05-12 17:32:42 +00003711/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003712static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003713 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003714 BlockScopeRAII Scope(Info);
3715
Richard Smith496ddcf2013-05-12 17:32:42 +00003716 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003717 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003718 {
3719 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003720 if (const Stmt *Init = SS->getInit()) {
3721 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3722 if (ESR != ESR_Succeeded)
3723 return ESR;
3724 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003725 if (SS->getConditionVariable() &&
3726 !EvaluateDecl(Info, SS->getConditionVariable()))
3727 return ESR_Failed;
3728 if (!EvaluateInteger(SS->getCond(), Value, Info))
3729 return ESR_Failed;
3730 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003731
3732 // Find the switch case corresponding to the value of the condition.
3733 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003734 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003735 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3736 SC = SC->getNextSwitchCase()) {
3737 if (isa<DefaultStmt>(SC)) {
3738 Found = SC;
3739 continue;
3740 }
3741
3742 const CaseStmt *CS = cast<CaseStmt>(SC);
3743 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3744 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3745 : LHS;
3746 if (LHS <= Value && Value <= RHS) {
3747 Found = SC;
3748 break;
3749 }
3750 }
3751
3752 if (!Found)
3753 return ESR_Succeeded;
3754
3755 // Search the switch body for the switch case and evaluate it from there.
3756 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3757 case ESR_Break:
3758 return ESR_Succeeded;
3759 case ESR_Succeeded:
3760 case ESR_Continue:
3761 case ESR_Failed:
3762 case ESR_Returned:
3763 return ESR;
3764 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003765 // This can only happen if the switch case is nested within a statement
3766 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003767 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003768 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003769 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003770 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003771}
3772
Richard Smith254a73d2011-10-28 22:34:42 +00003773// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003774static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003775 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003776 if (!Info.nextStep(S))
3777 return ESR_Failed;
3778
Richard Smith496ddcf2013-05-12 17:32:42 +00003779 // If we're hunting down a 'case' or 'default' label, recurse through
3780 // substatements until we hit the label.
3781 if (Case) {
3782 // FIXME: We don't start the lifetime of objects whose initialization we
3783 // jump over. However, such objects must be of class type with a trivial
3784 // default constructor that initialize all subobjects, so must be empty,
3785 // so this almost never matters.
3786 switch (S->getStmtClass()) {
3787 case Stmt::CompoundStmtClass:
3788 // FIXME: Precompute which substatement of a compound statement we
3789 // would jump to, and go straight there rather than performing a
3790 // linear scan each time.
3791 case Stmt::LabelStmtClass:
3792 case Stmt::AttributedStmtClass:
3793 case Stmt::DoStmtClass:
3794 break;
3795
3796 case Stmt::CaseStmtClass:
3797 case Stmt::DefaultStmtClass:
3798 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003799 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003800 break;
3801
3802 case Stmt::IfStmtClass: {
3803 // FIXME: Precompute which side of an 'if' we would jump to, and go
3804 // straight there rather than scanning both sides.
3805 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003806
3807 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3808 // preceded by our switch label.
3809 BlockScopeRAII Scope(Info);
3810
Richard Smith496ddcf2013-05-12 17:32:42 +00003811 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3812 if (ESR != ESR_CaseNotFound || !IS->getElse())
3813 return ESR;
3814 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3815 }
3816
3817 case Stmt::WhileStmtClass: {
3818 EvalStmtResult ESR =
3819 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3820 if (ESR != ESR_Continue)
3821 return ESR;
3822 break;
3823 }
3824
3825 case Stmt::ForStmtClass: {
3826 const ForStmt *FS = cast<ForStmt>(S);
3827 EvalStmtResult ESR =
3828 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3829 if (ESR != ESR_Continue)
3830 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003831 if (FS->getInc()) {
3832 FullExpressionRAII IncScope(Info);
3833 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3834 return ESR_Failed;
3835 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003836 break;
3837 }
3838
3839 case Stmt::DeclStmtClass:
3840 // FIXME: If the variable has initialization that can't be jumped over,
3841 // bail out of any immediately-surrounding compound-statement too.
3842 default:
3843 return ESR_CaseNotFound;
3844 }
3845 }
3846
Richard Smith254a73d2011-10-28 22:34:42 +00003847 switch (S->getStmtClass()) {
3848 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003849 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003850 // Don't bother evaluating beyond an expression-statement which couldn't
3851 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003852 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003853 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003854 return ESR_Failed;
3855 return ESR_Succeeded;
3856 }
3857
Faisal Valie690b7a2016-07-02 22:34:24 +00003858 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003859 return ESR_Failed;
3860
3861 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003862 return ESR_Succeeded;
3863
Richard Smithd9f663b2013-04-22 15:31:51 +00003864 case Stmt::DeclStmtClass: {
3865 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003866 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003867 // Each declaration initialization is its own full-expression.
3868 // FIXME: This isn't quite right; if we're performing aggregate
3869 // initialization, each braced subexpression is its own full-expression.
3870 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003871 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003872 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003873 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003874 return ESR_Succeeded;
3875 }
3876
Richard Smith357362d2011-12-13 06:39:58 +00003877 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003878 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003879 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003880 if (RetExpr &&
3881 !(Result.Slot
3882 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3883 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003884 return ESR_Failed;
3885 return ESR_Returned;
3886 }
Richard Smith254a73d2011-10-28 22:34:42 +00003887
3888 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003889 BlockScopeRAII Scope(Info);
3890
Richard Smith254a73d2011-10-28 22:34:42 +00003891 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003892 for (const auto *BI : CS->body()) {
3893 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003894 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003895 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003896 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003897 return ESR;
3898 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003899 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003900 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003901
3902 case Stmt::IfStmtClass: {
3903 const IfStmt *IS = cast<IfStmt>(S);
3904
3905 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003906 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003907 if (const Stmt *Init = IS->getInit()) {
3908 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3909 if (ESR != ESR_Succeeded)
3910 return ESR;
3911 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003912 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003913 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003914 return ESR_Failed;
3915
3916 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3917 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3918 if (ESR != ESR_Succeeded)
3919 return ESR;
3920 }
3921 return ESR_Succeeded;
3922 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003923
3924 case Stmt::WhileStmtClass: {
3925 const WhileStmt *WS = cast<WhileStmt>(S);
3926 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003927 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003928 bool Continue;
3929 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3930 Continue))
3931 return ESR_Failed;
3932 if (!Continue)
3933 break;
3934
3935 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3936 if (ESR != ESR_Continue)
3937 return ESR;
3938 }
3939 return ESR_Succeeded;
3940 }
3941
3942 case Stmt::DoStmtClass: {
3943 const DoStmt *DS = cast<DoStmt>(S);
3944 bool Continue;
3945 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003946 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003947 if (ESR != ESR_Continue)
3948 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003949 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003950
Richard Smith08d6a2c2013-07-24 07:11:57 +00003951 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003952 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3953 return ESR_Failed;
3954 } while (Continue);
3955 return ESR_Succeeded;
3956 }
3957
3958 case Stmt::ForStmtClass: {
3959 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003960 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003961 if (FS->getInit()) {
3962 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3963 if (ESR != ESR_Succeeded)
3964 return ESR;
3965 }
3966 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003967 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003968 bool Continue = true;
3969 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3970 FS->getCond(), Continue))
3971 return ESR_Failed;
3972 if (!Continue)
3973 break;
3974
3975 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3976 if (ESR != ESR_Continue)
3977 return ESR;
3978
Richard Smith08d6a2c2013-07-24 07:11:57 +00003979 if (FS->getInc()) {
3980 FullExpressionRAII IncScope(Info);
3981 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3982 return ESR_Failed;
3983 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003984 }
3985 return ESR_Succeeded;
3986 }
3987
Richard Smith896e0d72013-05-06 06:51:17 +00003988 case Stmt::CXXForRangeStmtClass: {
3989 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003990 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003991
3992 // Initialize the __range variable.
3993 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3994 if (ESR != ESR_Succeeded)
3995 return ESR;
3996
3997 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003998 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3999 if (ESR != ESR_Succeeded)
4000 return ESR;
4001 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004002 if (ESR != ESR_Succeeded)
4003 return ESR;
4004
4005 while (true) {
4006 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004007 {
4008 bool Continue = true;
4009 FullExpressionRAII CondExpr(Info);
4010 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4011 return ESR_Failed;
4012 if (!Continue)
4013 break;
4014 }
Richard Smith896e0d72013-05-06 06:51:17 +00004015
4016 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004017 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004018 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4019 if (ESR != ESR_Succeeded)
4020 return ESR;
4021
4022 // Loop body.
4023 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4024 if (ESR != ESR_Continue)
4025 return ESR;
4026
4027 // Increment: ++__begin
4028 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4029 return ESR_Failed;
4030 }
4031
4032 return ESR_Succeeded;
4033 }
4034
Richard Smith496ddcf2013-05-12 17:32:42 +00004035 case Stmt::SwitchStmtClass:
4036 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4037
Richard Smith4e18ca52013-05-06 05:56:11 +00004038 case Stmt::ContinueStmtClass:
4039 return ESR_Continue;
4040
4041 case Stmt::BreakStmtClass:
4042 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004043
4044 case Stmt::LabelStmtClass:
4045 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4046
4047 case Stmt::AttributedStmtClass:
4048 // As a general principle, C++11 attributes can be ignored without
4049 // any semantic impact.
4050 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4051 Case);
4052
4053 case Stmt::CaseStmtClass:
4054 case Stmt::DefaultStmtClass:
4055 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004056 }
4057}
4058
Richard Smithcc36f692011-12-22 02:22:31 +00004059/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4060/// default constructor. If so, we'll fold it whether or not it's marked as
4061/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4062/// so we need special handling.
4063static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004064 const CXXConstructorDecl *CD,
4065 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004066 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4067 return false;
4068
Richard Smith66e05fe2012-01-18 05:21:49 +00004069 // Value-initialization does not call a trivial default constructor, so such a
4070 // call is a core constant expression whether or not the constructor is
4071 // constexpr.
4072 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004073 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004074 // FIXME: If DiagDecl is an implicitly-declared special member function,
4075 // we should be much more explicit about why it's not constexpr.
4076 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4077 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4078 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004079 } else {
4080 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4081 }
4082 }
4083 return true;
4084}
4085
Richard Smith357362d2011-12-13 06:39:58 +00004086/// CheckConstexprFunction - Check that a function can be called in a constant
4087/// expression.
4088static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4089 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004090 const FunctionDecl *Definition,
4091 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004092 // Potential constant expressions can contain calls to declared, but not yet
4093 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004094 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004095 Declaration->isConstexpr())
4096 return false;
4097
Richard Smith0838f3a2013-05-14 05:18:44 +00004098 // Bail out with no diagnostic if the function declaration itself is invalid.
4099 // We will have produced a relevant diagnostic while parsing it.
4100 if (Declaration->isInvalidDecl())
4101 return false;
4102
Richard Smith357362d2011-12-13 06:39:58 +00004103 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004104 if (Definition && Definition->isConstexpr() &&
4105 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004106 return true;
4107
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004108 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004109 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004110
Richard Smith5179eb72016-06-28 19:03:57 +00004111 // If this function is not constexpr because it is an inherited
4112 // non-constexpr constructor, diagnose that directly.
4113 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4114 if (CD && CD->isInheritingConstructor()) {
4115 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004116 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004117 DiagDecl = CD = Inherited;
4118 }
4119
4120 // FIXME: If DiagDecl is an implicitly-declared special member function
4121 // or an inheriting constructor, we should be much more explicit about why
4122 // it's not constexpr.
4123 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004124 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004125 << CD->getInheritedConstructor().getConstructor()->getParent();
4126 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004127 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004128 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004129 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4130 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004131 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004132 }
4133 return false;
4134}
4135
Richard Smithbe6dd812014-11-19 21:27:17 +00004136/// Determine if a class has any fields that might need to be copied by a
4137/// trivial copy or move operation.
4138static bool hasFields(const CXXRecordDecl *RD) {
4139 if (!RD || RD->isEmpty())
4140 return false;
4141 for (auto *FD : RD->fields()) {
4142 if (FD->isUnnamedBitfield())
4143 continue;
4144 return true;
4145 }
4146 for (auto &Base : RD->bases())
4147 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4148 return true;
4149 return false;
4150}
4151
Richard Smithd62306a2011-11-10 06:34:14 +00004152namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004153typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004154}
4155
4156/// EvaluateArgs - Evaluate the arguments to a function call.
4157static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4158 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004159 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004160 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004161 I != E; ++I) {
4162 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4163 // If we're checking for a potential constant expression, evaluate all
4164 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004165 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004166 return false;
4167 Success = false;
4168 }
4169 }
4170 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004171}
4172
Richard Smith254a73d2011-10-28 22:34:42 +00004173/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004174static bool HandleFunctionCall(SourceLocation CallLoc,
4175 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004176 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004177 EvalInfo &Info, APValue &Result,
4178 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004179 ArgVector ArgValues(Args.size());
4180 if (!EvaluateArgs(Args, ArgValues, Info))
4181 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004182
Richard Smith253c2a32012-01-27 01:14:48 +00004183 if (!Info.CheckCallLimit(CallLoc))
4184 return false;
4185
4186 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004187
4188 // For a trivial copy or move assignment, perform an APValue copy. This is
4189 // essential for unions, where the operations performed by the assignment
4190 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004191 //
4192 // Skip this for non-union classes with no fields; in that case, the defaulted
4193 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004194 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004195 if (MD && MD->isDefaulted() &&
4196 (MD->getParent()->isUnion() ||
4197 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004198 assert(This &&
4199 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4200 LValue RHS;
4201 RHS.setFrom(Info.Ctx, ArgValues[0]);
4202 APValue RHSValue;
4203 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4204 RHS, RHSValue))
4205 return false;
4206 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4207 RHSValue))
4208 return false;
4209 This->moveInto(Result);
4210 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004211 } else if (MD && isLambdaCallOperator(MD)) {
4212 // We're in a lambda; determine the lambda capture field maps.
4213 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4214 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004215 }
4216
Richard Smith52a980a2015-08-28 02:43:42 +00004217 StmtResult Ret = {Result, ResultSlot};
4218 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004219 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004220 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004221 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004222 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004223 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004224 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004225}
4226
Richard Smithd62306a2011-11-10 06:34:14 +00004227/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004228static bool HandleConstructorCall(const Expr *E, const LValue &This,
4229 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004230 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004231 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004232 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004233 if (!Info.CheckCallLimit(CallLoc))
4234 return false;
4235
Richard Smith3607ffe2012-02-13 03:54:03 +00004236 const CXXRecordDecl *RD = Definition->getParent();
4237 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004238 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004239 return false;
4240 }
4241
Richard Smith5179eb72016-06-28 19:03:57 +00004242 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004243
Richard Smith52a980a2015-08-28 02:43:42 +00004244 // FIXME: Creating an APValue just to hold a nonexistent return value is
4245 // wasteful.
4246 APValue RetVal;
4247 StmtResult Ret = {RetVal, nullptr};
4248
Richard Smith5179eb72016-06-28 19:03:57 +00004249 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004250 if (Definition->isDelegatingConstructor()) {
4251 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004252 {
4253 FullExpressionRAII InitScope(Info);
4254 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4255 return false;
4256 }
Richard Smith52a980a2015-08-28 02:43:42 +00004257 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004258 }
4259
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004260 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004261 // essential for unions (or classes with anonymous union members), where the
4262 // operations performed by the constructor cannot be represented by
4263 // ctor-initializers.
4264 //
4265 // Skip this for empty non-union classes; we should not perform an
4266 // lvalue-to-rvalue conversion on them because their copy constructor does not
4267 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004268 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004269 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004270 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004271 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004272 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004273 return handleLValueToRValueConversion(
4274 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4275 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004276 }
4277
4278 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004279 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004280 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004281 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004282
John McCalld7bca762012-05-01 00:38:49 +00004283 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004284 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4285
Richard Smith08d6a2c2013-07-24 07:11:57 +00004286 // A scope for temporaries lifetime-extended by reference members.
4287 BlockScopeRAII LifetimeExtendedScope(Info);
4288
Richard Smith253c2a32012-01-27 01:14:48 +00004289 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004290 unsigned BasesSeen = 0;
4291#ifndef NDEBUG
4292 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4293#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004294 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004295 LValue Subobject = This;
4296 APValue *Value = &Result;
4297
4298 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004299 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004300 if (I->isBaseInitializer()) {
4301 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004302#ifndef NDEBUG
4303 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004304 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004305 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4306 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4307 "base class initializers not in expected order");
4308 ++BaseIt;
4309#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004310 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004311 BaseType->getAsCXXRecordDecl(), &Layout))
4312 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004313 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004314 } else if ((FD = I->getMember())) {
4315 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004316 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004317 if (RD->isUnion()) {
4318 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004319 Value = &Result.getUnionValue();
4320 } else {
4321 Value = &Result.getStructField(FD->getFieldIndex());
4322 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004323 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004324 // Walk the indirect field decl's chain to find the object to initialize,
4325 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004326 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004327 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004328 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4329 // Switch the union field if it differs. This happens if we had
4330 // preceding zero-initialization, and we're now initializing a union
4331 // subobject other than the first.
4332 // FIXME: In this case, the values of the other subobjects are
4333 // specified, since zero-initialization sets all padding bits to zero.
4334 if (Value->isUninit() ||
4335 (Value->isUnion() && Value->getUnionField() != FD)) {
4336 if (CD->isUnion())
4337 *Value = APValue(FD);
4338 else
4339 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004340 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004341 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004342 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004343 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004344 if (CD->isUnion())
4345 Value = &Value->getUnionValue();
4346 else
4347 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004348 }
Richard Smithd62306a2011-11-10 06:34:14 +00004349 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004350 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004351 }
Richard Smith253c2a32012-01-27 01:14:48 +00004352
Richard Smith08d6a2c2013-07-24 07:11:57 +00004353 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004354 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4355 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004356 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004357 // If we're checking for a potential constant expression, evaluate all
4358 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004359 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004360 return false;
4361 Success = false;
4362 }
Richard Smithd62306a2011-11-10 06:34:14 +00004363 }
4364
Richard Smithd9f663b2013-04-22 15:31:51 +00004365 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004366 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004367}
4368
Richard Smith5179eb72016-06-28 19:03:57 +00004369static bool HandleConstructorCall(const Expr *E, const LValue &This,
4370 ArrayRef<const Expr*> Args,
4371 const CXXConstructorDecl *Definition,
4372 EvalInfo &Info, APValue &Result) {
4373 ArgVector ArgValues(Args.size());
4374 if (!EvaluateArgs(Args, ArgValues, Info))
4375 return false;
4376
4377 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4378 Info, Result);
4379}
4380
Eli Friedman9a156e52008-11-12 09:44:48 +00004381//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004382// Generic Evaluation
4383//===----------------------------------------------------------------------===//
4384namespace {
4385
Aaron Ballman68af21c2014-01-03 19:26:43 +00004386template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004387class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004388 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004389private:
Richard Smith52a980a2015-08-28 02:43:42 +00004390 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004391 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004392 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004393 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004394 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004395 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004396 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004397
Richard Smith17100ba2012-02-16 02:46:34 +00004398 // Check whether a conditional operator with a non-constant condition is a
4399 // potential constant expression. If neither arm is a potential constant
4400 // expression, then the conditional operator is not either.
4401 template<typename ConditionalOperator>
4402 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004403 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004404
4405 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004406 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004407 {
Richard Smith17100ba2012-02-16 02:46:34 +00004408 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004409 StmtVisitorTy::Visit(E->getFalseExpr());
4410 if (Diag.empty())
4411 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004412 }
Richard Smith17100ba2012-02-16 02:46:34 +00004413
George Burgess IV8c892b52016-05-25 22:31:54 +00004414 {
4415 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004416 Diag.clear();
4417 StmtVisitorTy::Visit(E->getTrueExpr());
4418 if (Diag.empty())
4419 return;
4420 }
4421
4422 Error(E, diag::note_constexpr_conditional_never_const);
4423 }
4424
4425
4426 template<typename ConditionalOperator>
4427 bool HandleConditionalOperator(const ConditionalOperator *E) {
4428 bool BoolResult;
4429 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004430 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004431 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004432 return false;
4433 }
4434 if (Info.noteFailure()) {
4435 StmtVisitorTy::Visit(E->getTrueExpr());
4436 StmtVisitorTy::Visit(E->getFalseExpr());
4437 }
Richard Smith17100ba2012-02-16 02:46:34 +00004438 return false;
4439 }
4440
4441 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4442 return StmtVisitorTy::Visit(EvalExpr);
4443 }
4444
Peter Collingbournee9200682011-05-13 03:29:01 +00004445protected:
4446 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004447 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004448 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4449
Richard Smith92b1ce02011-12-12 09:28:41 +00004450 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004451 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004452 }
4453
Aaron Ballman68af21c2014-01-03 19:26:43 +00004454 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004455
4456public:
4457 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4458
4459 EvalInfo &getEvalInfo() { return Info; }
4460
Richard Smithf57d8cb2011-12-09 22:58:01 +00004461 /// Report an evaluation error. This should only be called when an error is
4462 /// first discovered. When propagating an error, just return false.
4463 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004464 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004465 return false;
4466 }
4467 bool Error(const Expr *E) {
4468 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4469 }
4470
Aaron Ballman68af21c2014-01-03 19:26:43 +00004471 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004472 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004473 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004474 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004475 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004476 }
4477
Aaron Ballman68af21c2014-01-03 19:26:43 +00004478 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004479 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004480 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004481 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004482 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004483 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004484 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004485 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004486 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004487 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004488 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004489 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004490 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004491 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004492 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004493 // The initializer may not have been parsed yet, or might be erroneous.
4494 if (!E->getExpr())
4495 return Error(E);
4496 return StmtVisitorTy::Visit(E->getExpr());
4497 }
Richard Smith5894a912011-12-19 22:12:41 +00004498 // We cannot create any objects for which cleanups are required, so there is
4499 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004500 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004501 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004502
Aaron Ballman68af21c2014-01-03 19:26:43 +00004503 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004504 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4505 return static_cast<Derived*>(this)->VisitCastExpr(E);
4506 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004507 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004508 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4509 return static_cast<Derived*>(this)->VisitCastExpr(E);
4510 }
4511
Aaron Ballman68af21c2014-01-03 19:26:43 +00004512 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004513 switch (E->getOpcode()) {
4514 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004515 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004516
4517 case BO_Comma:
4518 VisitIgnoredValue(E->getLHS());
4519 return StmtVisitorTy::Visit(E->getRHS());
4520
4521 case BO_PtrMemD:
4522 case BO_PtrMemI: {
4523 LValue Obj;
4524 if (!HandleMemberPointerAccess(Info, E, Obj))
4525 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004526 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004527 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004528 return false;
4529 return DerivedSuccess(Result, E);
4530 }
4531 }
4532 }
4533
Aaron Ballman68af21c2014-01-03 19:26:43 +00004534 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004535 // Evaluate and cache the common expression. We treat it as a temporary,
4536 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004537 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004538 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004539 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004540
Richard Smith17100ba2012-02-16 02:46:34 +00004541 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004542 }
4543
Aaron Ballman68af21c2014-01-03 19:26:43 +00004544 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004545 bool IsBcpCall = false;
4546 // If the condition (ignoring parens) is a __builtin_constant_p call,
4547 // the result is a constant expression if it can be folded without
4548 // side-effects. This is an important GNU extension. See GCC PR38377
4549 // for discussion.
4550 if (const CallExpr *CallCE =
4551 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004552 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004553 IsBcpCall = true;
4554
4555 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4556 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004557 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004558 return false;
4559
Richard Smith6d4c6582013-11-05 22:18:15 +00004560 FoldConstant Fold(Info, IsBcpCall);
4561 if (!HandleConditionalOperator(E)) {
4562 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004563 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004564 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004565
4566 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004567 }
4568
Aaron Ballman68af21c2014-01-03 19:26:43 +00004569 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004570 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4571 return DerivedSuccess(*Value, E);
4572
4573 const Expr *Source = E->getSourceExpr();
4574 if (!Source)
4575 return Error(E);
4576 if (Source == E) { // sanity checking.
4577 assert(0 && "OpaqueValueExpr recursively refers to itself");
4578 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004579 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004580 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004581 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004582
Aaron Ballman68af21c2014-01-03 19:26:43 +00004583 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004584 APValue Result;
4585 if (!handleCallExpr(E, Result, nullptr))
4586 return false;
4587 return DerivedSuccess(Result, E);
4588 }
4589
4590 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky9add1592017-05-17 23:56:54 +00004591 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004592 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004593 QualType CalleeType = Callee->getType();
4594
Craig Topper36250ad2014-05-12 05:36:57 +00004595 const FunctionDecl *FD = nullptr;
4596 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004597 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004598 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004599
Nick Lewycky9add1592017-05-17 23:56:54 +00004600 struct EvaluateIgnoredRAII {
4601 public:
4602 EvaluateIgnoredRAII(EvalInfo &Info, llvm::ArrayRef<const Expr*> ToEval)
4603 : Info(Info), ToEval(ToEval) {}
4604 ~EvaluateIgnoredRAII() {
4605 if (Info.noteFailure()) {
4606 for (auto E : ToEval)
4607 EvaluateIgnoredValue(Info, E);
4608 }
4609 }
4610 void cancel() { ToEval = {}; }
4611 void drop_front() { ToEval = ToEval.drop_front(); }
4612 private:
4613 EvalInfo &Info;
4614 llvm::ArrayRef<const Expr*> ToEval;
4615 } EvalArguments(Info, Args);
4616
Richard Smithe97cbd72011-11-11 04:05:33 +00004617 // Extract function decl and 'this' pointer from the callee.
4618 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004619 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004620 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4621 // Explicit bound member calls, such as x.f() or p->g();
4622 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004623 return false;
4624 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004625 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004626 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004627 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4628 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004629 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4630 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004631 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004632 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004633 return Error(Callee);
4634
4635 FD = dyn_cast<FunctionDecl>(Member);
4636 if (!FD)
4637 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004638 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004639 LValue Call;
4640 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004641 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004642
Richard Smitha8105bc2012-01-06 16:39:00 +00004643 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004644 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004645 FD = dyn_cast_or_null<FunctionDecl>(
4646 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004647 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004648 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004649 // Don't call function pointers which have been cast to some other type.
4650 // Per DR (no number yet), the caller and callee can differ in noexcept.
4651 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4652 CalleeType->getPointeeType(), FD->getType())) {
4653 return Error(E);
4654 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004655
4656 // Overloaded operator calls to member functions are represented as normal
4657 // calls with '*this' as the first argument.
4658 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4659 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004660 // FIXME: When selecting an implicit conversion for an overloaded
4661 // operator delete, we sometimes try to evaluate calls to conversion
4662 // operators without a 'this' parameter!
4663 if (Args.empty())
4664 return Error(E);
4665
Nick Lewycky9add1592017-05-17 23:56:54 +00004666 const Expr *FirstArg = Args[0];
4667 Args = Args.drop_front();
4668 EvalArguments.drop_front();
4669 if (!EvaluateObjectArgument(Info, FirstArg, ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004670 return false;
4671 This = &ThisVal;
Daniel Jasperffdee092017-05-02 19:21:42 +00004672 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004673 // Map the static invoker for the lambda back to the call operator.
4674 // Conveniently, we don't have to slice out the 'this' argument (as is
4675 // being done for the non-static case), since a static member function
4676 // doesn't have an implicit argument passed in.
4677 const CXXRecordDecl *ClosureClass = MD->getParent();
4678 assert(
4679 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4680 "Number of captures must be zero for conversion to function-ptr");
4681
4682 const CXXMethodDecl *LambdaCallOp =
4683 ClosureClass->getLambdaCallOperator();
4684
4685 // Set 'FD', the function that will be called below, to the call
4686 // operator. If the closure object represents a generic lambda, find
4687 // the corresponding specialization of the call operator.
4688
4689 if (ClosureClass->isGenericLambda()) {
4690 assert(MD->isFunctionTemplateSpecialization() &&
4691 "A generic lambda's static-invoker function must be a "
4692 "template specialization");
4693 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4694 FunctionTemplateDecl *CallOpTemplate =
4695 LambdaCallOp->getDescribedFunctionTemplate();
4696 void *InsertPos = nullptr;
4697 FunctionDecl *CorrespondingCallOpSpecialization =
4698 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4699 assert(CorrespondingCallOpSpecialization &&
4700 "We must always have a function call operator specialization "
4701 "that corresponds to our static invoker specialization");
4702 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4703 } else
4704 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004705 }
4706
Daniel Jasperffdee092017-05-02 19:21:42 +00004707
Richard Smithe97cbd72011-11-11 04:05:33 +00004708 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004709 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004710
Richard Smith47b34932012-02-01 02:39:43 +00004711 if (This && !This->checkSubobject(Info, E, CSK_This))
4712 return false;
4713
Richard Smith3607ffe2012-02-13 03:54:03 +00004714 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4715 // calls to such functions in constant expressions.
4716 if (This && !HasQualifier &&
4717 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4718 return Error(E, diag::note_constexpr_virtual_call);
4719
Craig Topper36250ad2014-05-12 05:36:57 +00004720 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004721 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004722
Nick Lewycky9add1592017-05-17 23:56:54 +00004723 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
4724 return false;
4725
4726 EvalArguments.cancel();
4727
4728 if (!HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004729 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004730 return false;
4731
Richard Smith52a980a2015-08-28 02:43:42 +00004732 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004733 }
4734
Aaron Ballman68af21c2014-01-03 19:26:43 +00004735 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004736 return StmtVisitorTy::Visit(E->getInitializer());
4737 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004738 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004739 if (E->getNumInits() == 0)
4740 return DerivedZeroInitialization(E);
4741 if (E->getNumInits() == 1)
4742 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004743 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004744 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004745 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004746 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004747 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004748 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004749 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004750 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004751 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004752 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004753 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004754
Richard Smithd62306a2011-11-10 06:34:14 +00004755 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004756 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004757 assert(!E->isArrow() && "missing call to bound member function?");
4758
Richard Smith2e312c82012-03-03 22:46:17 +00004759 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004760 if (!Evaluate(Val, Info, E->getBase()))
4761 return false;
4762
4763 QualType BaseTy = E->getBase()->getType();
4764
4765 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004766 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004767 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004768 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004769 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4770
Richard Smith3229b742013-05-05 21:17:10 +00004771 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004772 SubobjectDesignator Designator(BaseTy);
4773 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004774
Richard Smith3229b742013-05-05 21:17:10 +00004775 APValue Result;
4776 return extractSubobject(Info, E, Obj, Designator, Result) &&
4777 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004778 }
4779
Aaron Ballman68af21c2014-01-03 19:26:43 +00004780 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004781 switch (E->getCastKind()) {
4782 default:
4783 break;
4784
Richard Smitha23ab512013-05-23 00:30:41 +00004785 case CK_AtomicToNonAtomic: {
4786 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004787 // This does not need to be done in place even for class/array types:
4788 // atomic-to-non-atomic conversion implies copying the object
4789 // representation.
4790 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004791 return false;
4792 return DerivedSuccess(AtomicVal, E);
4793 }
4794
Richard Smith11562c52011-10-28 17:51:58 +00004795 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004796 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004797 return StmtVisitorTy::Visit(E->getSubExpr());
4798
4799 case CK_LValueToRValue: {
4800 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004801 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4802 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004803 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004804 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004805 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004806 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004807 return false;
4808 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004809 }
4810 }
4811
Richard Smithf57d8cb2011-12-09 22:58:01 +00004812 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004813 }
4814
Aaron Ballman68af21c2014-01-03 19:26:43 +00004815 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004816 return VisitUnaryPostIncDec(UO);
4817 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004818 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004819 return VisitUnaryPostIncDec(UO);
4820 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004821 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004822 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004823 return Error(UO);
4824
4825 LValue LVal;
4826 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4827 return false;
4828 APValue RVal;
4829 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4830 UO->isIncrementOp(), &RVal))
4831 return false;
4832 return DerivedSuccess(RVal, UO);
4833 }
4834
Aaron Ballman68af21c2014-01-03 19:26:43 +00004835 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004836 // We will have checked the full-expressions inside the statement expression
4837 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004838 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004839 return Error(E);
4840
Richard Smith08d6a2c2013-07-24 07:11:57 +00004841 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004842 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004843 if (CS->body_empty())
4844 return true;
4845
Richard Smith51f03172013-06-20 03:00:05 +00004846 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4847 BE = CS->body_end();
4848 /**/; ++BI) {
4849 if (BI + 1 == BE) {
4850 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4851 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004852 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004853 diag::note_constexpr_stmt_expr_unsupported);
4854 return false;
4855 }
4856 return this->Visit(FinalExpr);
4857 }
4858
4859 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004860 StmtResult Result = { ReturnValue, nullptr };
4861 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004862 if (ESR != ESR_Succeeded) {
4863 // FIXME: If the statement-expression terminated due to 'return',
4864 // 'break', or 'continue', it would be nice to propagate that to
4865 // the outer statement evaluation rather than bailing out.
4866 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004867 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004868 diag::note_constexpr_stmt_expr_unsupported);
4869 return false;
4870 }
4871 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004872
4873 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004874 }
4875
Richard Smith4a678122011-10-24 18:44:57 +00004876 /// Visit a value which is evaluated, but whose value is ignored.
4877 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004878 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004879 }
David Majnemere9807b22016-02-26 04:23:19 +00004880
4881 /// Potentially visit a MemberExpr's base expression.
4882 void VisitIgnoredBaseExpression(const Expr *E) {
4883 // While MSVC doesn't evaluate the base expression, it does diagnose the
4884 // presence of side-effecting behavior.
4885 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4886 return;
4887 VisitIgnoredValue(E);
4888 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004889};
4890
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004891}
Peter Collingbournee9200682011-05-13 03:29:01 +00004892
4893//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004894// Common base class for lvalue and temporary evaluation.
4895//===----------------------------------------------------------------------===//
4896namespace {
4897template<class Derived>
4898class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004899 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004900protected:
4901 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004902 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004903 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004904 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004905
4906 bool Success(APValue::LValueBase B) {
4907 Result.set(B);
4908 return true;
4909 }
4910
George Burgess IVf9013bf2017-02-10 22:52:29 +00004911 bool evaluatePointer(const Expr *E, LValue &Result) {
4912 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4913 }
4914
Richard Smith027bf112011-11-17 22:56:20 +00004915public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004916 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4917 : ExprEvaluatorBaseTy(Info), Result(Result),
4918 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00004919
Richard Smith2e312c82012-03-03 22:46:17 +00004920 bool Success(const APValue &V, const Expr *E) {
4921 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004922 return true;
4923 }
Richard Smith027bf112011-11-17 22:56:20 +00004924
Richard Smith027bf112011-11-17 22:56:20 +00004925 bool VisitMemberExpr(const MemberExpr *E) {
4926 // Handle non-static data members.
4927 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004928 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004929 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004930 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00004931 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004932 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004933 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004934 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004935 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004936 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004937 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004938 BaseTy = E->getBase()->getType();
4939 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004940 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004941 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004942 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004943 Result.setInvalid(E);
4944 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004945 }
Richard Smith027bf112011-11-17 22:56:20 +00004946
Richard Smith1b78b3d2012-01-25 22:15:11 +00004947 const ValueDecl *MD = E->getMemberDecl();
4948 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4949 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4950 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4951 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004952 if (!HandleLValueMember(this->Info, E, Result, FD))
4953 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004954 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004955 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4956 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004957 } else
4958 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004959
Richard Smith1b78b3d2012-01-25 22:15:11 +00004960 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004961 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004962 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004963 RefValue))
4964 return false;
4965 return Success(RefValue, E);
4966 }
4967 return true;
4968 }
4969
4970 bool VisitBinaryOperator(const BinaryOperator *E) {
4971 switch (E->getOpcode()) {
4972 default:
4973 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4974
4975 case BO_PtrMemD:
4976 case BO_PtrMemI:
4977 return HandleMemberPointerAccess(this->Info, E, Result);
4978 }
4979 }
4980
4981 bool VisitCastExpr(const CastExpr *E) {
4982 switch (E->getCastKind()) {
4983 default:
4984 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4985
4986 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004987 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004988 if (!this->Visit(E->getSubExpr()))
4989 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004990
4991 // Now figure out the necessary offset to add to the base LV to get from
4992 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004993 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4994 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004995 }
4996 }
4997};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004998}
Richard Smith027bf112011-11-17 22:56:20 +00004999
5000//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005001// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005002//
5003// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5004// function designators (in C), decl references to void objects (in C), and
5005// temporaries (if building with -Wno-address-of-temporary).
5006//
5007// LValue evaluation produces values comprising a base expression of one of the
5008// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005009// - Declarations
5010// * VarDecl
5011// * FunctionDecl
5012// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005013// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005014// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005015// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005016// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005017// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005018// * ObjCEncodeExpr
5019// * AddrLabelExpr
5020// * BlockExpr
5021// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005022// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005023// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005024// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005025// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5026// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005027// * A MaterializeTemporaryExpr that has static storage duration, with no
5028// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005029// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005030//===----------------------------------------------------------------------===//
5031namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005032class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005033 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005034public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005035 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5036 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005037
Richard Smith11562c52011-10-28 17:51:58 +00005038 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005039 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005040
Peter Collingbournee9200682011-05-13 03:29:01 +00005041 bool VisitDeclRefExpr(const DeclRefExpr *E);
5042 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005043 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005044 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5045 bool VisitMemberExpr(const MemberExpr *E);
5046 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5047 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005048 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005049 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005050 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5051 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005052 bool VisitUnaryReal(const UnaryOperator *E);
5053 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005054 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5055 return VisitUnaryPreIncDec(UO);
5056 }
5057 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5058 return VisitUnaryPreIncDec(UO);
5059 }
Richard Smith3229b742013-05-05 21:17:10 +00005060 bool VisitBinAssign(const BinaryOperator *BO);
5061 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005062
Peter Collingbournee9200682011-05-13 03:29:01 +00005063 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005064 switch (E->getCastKind()) {
5065 default:
Richard Smith027bf112011-11-17 22:56:20 +00005066 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005067
Eli Friedmance3e02a2011-10-11 00:13:24 +00005068 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005069 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005070 if (!Visit(E->getSubExpr()))
5071 return false;
5072 Result.Designator.setInvalid();
5073 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005074
Richard Smith027bf112011-11-17 22:56:20 +00005075 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005076 if (!Visit(E->getSubExpr()))
5077 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005078 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005079 }
5080 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005081};
5082} // end anonymous namespace
5083
Richard Smith11562c52011-10-28 17:51:58 +00005084/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005085/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005086/// * function designators in C, and
5087/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005088/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005089static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5090 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005091 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005092 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005093 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005094}
5095
Peter Collingbournee9200682011-05-13 03:29:01 +00005096bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005097 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005098 return Success(FD);
5099 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005100 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005101 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005102 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005103 return Error(E);
5104}
Richard Smith733237d2011-10-24 23:14:33 +00005105
Faisal Vali0528a312016-11-13 06:09:16 +00005106
Richard Smith11562c52011-10-28 17:51:58 +00005107bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005108
5109 // If we are within a lambda's call operator, check whether the 'VD' referred
5110 // to within 'E' actually represents a lambda-capture that maps to a
5111 // data-member/field within the closure object, and if so, evaluate to the
5112 // field or what the field refers to.
5113 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5114 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5115 if (Info.checkingPotentialConstantExpression())
5116 return false;
5117 // Start with 'Result' referring to the complete closure object...
5118 Result = *Info.CurrentCall->This;
5119 // ... then update it to refer to the field of the closure object
5120 // that represents the capture.
5121 if (!HandleLValueMember(Info, E, Result, FD))
5122 return false;
5123 // And if the field is of reference type, update 'Result' to refer to what
5124 // the field refers to.
5125 if (FD->getType()->isReferenceType()) {
5126 APValue RVal;
5127 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5128 RVal))
5129 return false;
5130 Result.setFrom(Info.Ctx, RVal);
5131 }
5132 return true;
5133 }
5134 }
Craig Topper36250ad2014-05-12 05:36:57 +00005135 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005136 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5137 // Only if a local variable was declared in the function currently being
5138 // evaluated, do we expect to be able to find its value in the current
5139 // frame. (Otherwise it was likely declared in an enclosing context and
5140 // could either have a valid evaluatable value (for e.g. a constexpr
5141 // variable) or be ill-formed (and trigger an appropriate evaluation
5142 // diagnostic)).
5143 if (Info.CurrentCall->Callee &&
5144 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5145 Frame = Info.CurrentCall;
5146 }
5147 }
Richard Smith3229b742013-05-05 21:17:10 +00005148
Richard Smithfec09922011-11-01 16:57:24 +00005149 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005150 if (Frame) {
5151 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005152 return true;
5153 }
Richard Smithce40ad62011-11-12 22:28:03 +00005154 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005155 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005156
Richard Smith3229b742013-05-05 21:17:10 +00005157 APValue *V;
5158 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005159 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005160 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005161 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005162 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005163 return false;
5164 }
Richard Smith3229b742013-05-05 21:17:10 +00005165 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005166}
5167
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005168bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5169 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005170 // Walk through the expression to find the materialized temporary itself.
5171 SmallVector<const Expr *, 2> CommaLHSs;
5172 SmallVector<SubobjectAdjustment, 2> Adjustments;
5173 const Expr *Inner = E->GetTemporaryExpr()->
5174 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005175
Richard Smith84401042013-06-03 05:03:02 +00005176 // If we passed any comma operators, evaluate their LHSs.
5177 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5178 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5179 return false;
5180
Richard Smithe6c01442013-06-05 00:46:14 +00005181 // A materialized temporary with static storage duration can appear within the
5182 // result of a constant expression evaluation, so we need to preserve its
5183 // value for use outside this evaluation.
5184 APValue *Value;
5185 if (E->getStorageDuration() == SD_Static) {
5186 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005187 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005188 Result.set(E);
5189 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005190 Value = &Info.CurrentCall->
5191 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005192 Result.set(E, Info.CurrentCall->Index);
5193 }
5194
Richard Smithea4ad5d2013-06-06 08:19:16 +00005195 QualType Type = Inner->getType();
5196
Richard Smith84401042013-06-03 05:03:02 +00005197 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005198 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5199 (E->getStorageDuration() == SD_Static &&
5200 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5201 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005202 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005203 }
Richard Smith84401042013-06-03 05:03:02 +00005204
5205 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005206 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5207 --I;
5208 switch (Adjustments[I].Kind) {
5209 case SubobjectAdjustment::DerivedToBaseAdjustment:
5210 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5211 Type, Result))
5212 return false;
5213 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5214 break;
5215
5216 case SubobjectAdjustment::FieldAdjustment:
5217 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5218 return false;
5219 Type = Adjustments[I].Field->getType();
5220 break;
5221
5222 case SubobjectAdjustment::MemberPointerAdjustment:
5223 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5224 Adjustments[I].Ptr.RHS))
5225 return false;
5226 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5227 break;
5228 }
5229 }
5230
5231 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005232}
5233
Peter Collingbournee9200682011-05-13 03:29:01 +00005234bool
5235LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005236 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5237 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005238 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5239 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005240 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005241}
5242
Richard Smith6e525142011-12-27 12:18:28 +00005243bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005244 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005245 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005246
Faisal Valie690b7a2016-07-02 22:34:24 +00005247 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005248 << E->getExprOperand()->getType()
5249 << E->getExprOperand()->getSourceRange();
5250 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005251}
5252
Francois Pichet0066db92012-04-16 04:08:35 +00005253bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5254 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005255}
Francois Pichet0066db92012-04-16 04:08:35 +00005256
Peter Collingbournee9200682011-05-13 03:29:01 +00005257bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005258 // Handle static data members.
5259 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005260 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005261 return VisitVarDecl(E, VD);
5262 }
5263
Richard Smith254a73d2011-10-28 22:34:42 +00005264 // Handle static member functions.
5265 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5266 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005267 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005268 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005269 }
5270 }
5271
Richard Smithd62306a2011-11-10 06:34:14 +00005272 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005273 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005274}
5275
Peter Collingbournee9200682011-05-13 03:29:01 +00005276bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005277 // FIXME: Deal with vectors as array subscript bases.
5278 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005279 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005280
Nick Lewyckyad888682017-04-27 07:27:36 +00005281 bool Success = true;
5282 if (!evaluatePointer(E->getBase(), Result)) {
5283 if (!Info.noteFailure())
5284 return false;
5285 Success = false;
5286 }
Mike Stump11289f42009-09-09 15:08:12 +00005287
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005288 APSInt Index;
5289 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005290 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005291
Nick Lewyckyad888682017-04-27 07:27:36 +00005292 return Success &&
5293 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005294}
Eli Friedman9a156e52008-11-12 09:44:48 +00005295
Peter Collingbournee9200682011-05-13 03:29:01 +00005296bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005297 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005298}
5299
Richard Smith66c96992012-02-18 22:04:06 +00005300bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5301 if (!Visit(E->getSubExpr()))
5302 return false;
5303 // __real is a no-op on scalar lvalues.
5304 if (E->getSubExpr()->getType()->isAnyComplexType())
5305 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5306 return true;
5307}
5308
5309bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5310 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5311 "lvalue __imag__ on scalar?");
5312 if (!Visit(E->getSubExpr()))
5313 return false;
5314 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5315 return true;
5316}
5317
Richard Smith243ef902013-05-05 23:31:59 +00005318bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005319 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005320 return Error(UO);
5321
5322 if (!this->Visit(UO->getSubExpr()))
5323 return false;
5324
Richard Smith243ef902013-05-05 23:31:59 +00005325 return handleIncDec(
5326 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005327 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005328}
5329
5330bool LValueExprEvaluator::VisitCompoundAssignOperator(
5331 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005332 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005333 return Error(CAO);
5334
Richard Smith3229b742013-05-05 21:17:10 +00005335 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005336
5337 // The overall lvalue result is the result of evaluating the LHS.
5338 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005339 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005340 Evaluate(RHS, this->Info, CAO->getRHS());
5341 return false;
5342 }
5343
Richard Smith3229b742013-05-05 21:17:10 +00005344 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5345 return false;
5346
Richard Smith43e77732013-05-07 04:50:00 +00005347 return handleCompoundAssignment(
5348 this->Info, CAO,
5349 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5350 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005351}
5352
5353bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005354 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005355 return Error(E);
5356
Richard Smith3229b742013-05-05 21:17:10 +00005357 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005358
5359 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005360 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005361 Evaluate(NewVal, this->Info, E->getRHS());
5362 return false;
5363 }
5364
Richard Smith3229b742013-05-05 21:17:10 +00005365 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5366 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005367
5368 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005369 NewVal);
5370}
5371
Eli Friedman9a156e52008-11-12 09:44:48 +00005372//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005373// Pointer Evaluation
5374//===----------------------------------------------------------------------===//
5375
George Burgess IVe3763372016-12-22 02:50:20 +00005376/// \brief Attempts to compute the number of bytes available at the pointer
5377/// returned by a function with the alloc_size attribute. Returns true if we
5378/// were successful. Places an unsigned number into `Result`.
5379///
5380/// This expects the given CallExpr to be a call to a function with an
5381/// alloc_size attribute.
5382static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5383 const CallExpr *Call,
5384 llvm::APInt &Result) {
5385 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5386
5387 // alloc_size args are 1-indexed, 0 means not present.
5388 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5389 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5390 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5391 if (Call->getNumArgs() <= SizeArgNo)
5392 return false;
5393
5394 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5395 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5396 return false;
5397 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5398 return false;
5399 Into = Into.zextOrSelf(BitsInSizeT);
5400 return true;
5401 };
5402
5403 APSInt SizeOfElem;
5404 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5405 return false;
5406
5407 if (!AllocSize->getNumElemsParam()) {
5408 Result = std::move(SizeOfElem);
5409 return true;
5410 }
5411
5412 APSInt NumberOfElems;
5413 // Argument numbers start at 1
5414 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5415 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5416 return false;
5417
5418 bool Overflow;
5419 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5420 if (Overflow)
5421 return false;
5422
5423 Result = std::move(BytesAvailable);
5424 return true;
5425}
5426
5427/// \brief Convenience function. LVal's base must be a call to an alloc_size
5428/// function.
5429static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5430 const LValue &LVal,
5431 llvm::APInt &Result) {
5432 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5433 "Can't get the size of a non alloc_size function");
5434 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5435 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5436 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5437}
5438
5439/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5440/// a function with the alloc_size attribute. If it was possible to do so, this
5441/// function will return true, make Result's Base point to said function call,
5442/// and mark Result's Base as invalid.
5443static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5444 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005445 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005446 return false;
5447
5448 // Because we do no form of static analysis, we only support const variables.
5449 //
5450 // Additionally, we can't support parameters, nor can we support static
5451 // variables (in the latter case, use-before-assign isn't UB; in the former,
5452 // we have no clue what they'll be assigned to).
5453 const auto *VD =
5454 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5455 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5456 return false;
5457
5458 const Expr *Init = VD->getAnyInitializer();
5459 if (!Init)
5460 return false;
5461
5462 const Expr *E = Init->IgnoreParens();
5463 if (!tryUnwrapAllocSizeCall(E))
5464 return false;
5465
5466 // Store E instead of E unwrapped so that the type of the LValue's base is
5467 // what the user wanted.
5468 Result.setInvalid(E);
5469
5470 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Daniel Jasperffdee092017-05-02 19:21:42 +00005471 Result.addUnsizedArray(Info, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005472 return true;
5473}
5474
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005475namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005476class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005477 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005478 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005479 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005480
Peter Collingbournee9200682011-05-13 03:29:01 +00005481 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005482 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005483 return true;
5484 }
George Burgess IVe3763372016-12-22 02:50:20 +00005485
George Burgess IVf9013bf2017-02-10 22:52:29 +00005486 bool evaluateLValue(const Expr *E, LValue &Result) {
5487 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5488 }
5489
5490 bool evaluatePointer(const Expr *E, LValue &Result) {
5491 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5492 }
5493
George Burgess IVe3763372016-12-22 02:50:20 +00005494 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005495public:
Mike Stump11289f42009-09-09 15:08:12 +00005496
George Burgess IVf9013bf2017-02-10 22:52:29 +00005497 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5498 : ExprEvaluatorBaseTy(info), Result(Result),
5499 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005500
Richard Smith2e312c82012-03-03 22:46:17 +00005501 bool Success(const APValue &V, const Expr *E) {
5502 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005503 return true;
5504 }
Richard Smithfddd3842011-12-30 21:15:51 +00005505 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005506 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5507 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005508 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005509 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005510
John McCall45d55e42010-05-07 21:00:08 +00005511 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005512 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005513 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005514 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005515 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005516 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5517 if (Info.noteFailure())
5518 EvaluateIgnoredValue(Info, E->getSubExpr());
5519 return Error(E);
5520 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005521 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005522 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005523 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005524 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005525 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005526 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005527 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005528 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005529 }
Richard Smithd62306a2011-11-10 06:34:14 +00005530 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005531 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005532 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005533 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005534 if (!Info.CurrentCall->This) {
5535 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005536 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005537 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005538 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005539 return false;
5540 }
Richard Smithd62306a2011-11-10 06:34:14 +00005541 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005542 // If we are inside a lambda's call operator, the 'this' expression refers
5543 // to the enclosing '*this' object (either by value or reference) which is
5544 // either copied into the closure object's field that represents the '*this'
5545 // or refers to '*this'.
5546 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5547 // Update 'Result' to refer to the data member/field of the closure object
5548 // that represents the '*this' capture.
5549 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005550 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005551 return false;
5552 // If we captured '*this' by reference, replace the field with its referent.
5553 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5554 ->isPointerType()) {
5555 APValue RVal;
5556 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5557 RVal))
5558 return false;
5559
5560 Result.setFrom(Info.Ctx, RVal);
5561 }
5562 }
Richard Smithd62306a2011-11-10 06:34:14 +00005563 return true;
5564 }
John McCallc07a0c72011-02-17 10:25:35 +00005565
Eli Friedman449fe542009-03-23 04:56:01 +00005566 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005567};
Chris Lattner05706e882008-07-11 18:11:29 +00005568} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005569
George Burgess IVf9013bf2017-02-10 22:52:29 +00005570static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5571 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005572 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005573 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005574}
5575
John McCall45d55e42010-05-07 21:00:08 +00005576bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005577 if (E->getOpcode() != BO_Add &&
5578 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005579 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005580
Chris Lattner05706e882008-07-11 18:11:29 +00005581 const Expr *PExp = E->getLHS();
5582 const Expr *IExp = E->getRHS();
5583 if (IExp->getType()->isPointerType())
5584 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005585
George Burgess IVf9013bf2017-02-10 22:52:29 +00005586 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005587 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005588 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005589
John McCall45d55e42010-05-07 21:00:08 +00005590 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005591 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005592 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005593
Richard Smith96e0c102011-11-04 02:25:55 +00005594 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005595 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005596
Ted Kremenek28831752012-08-23 20:46:57 +00005597 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005598 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005599}
Eli Friedman9a156e52008-11-12 09:44:48 +00005600
John McCall45d55e42010-05-07 21:00:08 +00005601bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005602 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005603}
Mike Stump11289f42009-09-09 15:08:12 +00005604
Peter Collingbournee9200682011-05-13 03:29:01 +00005605bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5606 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005607
Eli Friedman847a2bc2009-12-27 05:43:15 +00005608 switch (E->getCastKind()) {
5609 default:
5610 break;
5611
John McCalle3027922010-08-25 11:45:40 +00005612 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005613 case CK_CPointerToObjCPointerCast:
5614 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005615 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005616 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005617 if (!Visit(SubExpr))
5618 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005619 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5620 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5621 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005622 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005623 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005624 if (SubExpr->getType()->isVoidPointerType())
5625 CCEDiag(E, diag::note_constexpr_invalid_cast)
5626 << 3 << SubExpr->getType();
5627 else
5628 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5629 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005630 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5631 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005632 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005633
Anders Carlsson18275092010-10-31 20:41:46 +00005634 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005635 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005636 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005637 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005638 if (!Result.Base && Result.Offset.isZero())
5639 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005640
Richard Smithd62306a2011-11-10 06:34:14 +00005641 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005642 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005643 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5644 castAs<PointerType>()->getPointeeType(),
5645 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005646
Richard Smith027bf112011-11-17 22:56:20 +00005647 case CK_BaseToDerived:
5648 if (!Visit(E->getSubExpr()))
5649 return false;
5650 if (!Result.Base && Result.Offset.isZero())
5651 return true;
5652 return HandleBaseToDerivedCast(Info, E, Result);
5653
Richard Smith0b0a0b62011-10-29 20:57:55 +00005654 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005655 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005656 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005657
John McCalle3027922010-08-25 11:45:40 +00005658 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005659 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5660
Richard Smith2e312c82012-03-03 22:46:17 +00005661 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005662 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005663 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005664
John McCall45d55e42010-05-07 21:00:08 +00005665 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005666 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5667 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005668 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005669 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005670 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005671 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005672 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005673 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005674 return true;
5675 } else {
5676 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005677 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005678 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005679 }
5680 }
John McCalle3027922010-08-25 11:45:40 +00005681 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005682 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005683 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005684 return false;
5685 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005686 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005687 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005688 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005689 return false;
5690 }
Richard Smith96e0c102011-11-04 02:25:55 +00005691 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005692 if (const ConstantArrayType *CAT
5693 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5694 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005695 else
5696 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005697 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005698
John McCalle3027922010-08-25 11:45:40 +00005699 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005700 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005701
5702 case CK_LValueToRValue: {
5703 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005704 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005705 return false;
5706
5707 APValue RVal;
5708 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5709 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5710 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005711 return InvalidBaseOK &&
5712 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005713 return Success(RVal, E);
5714 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005715 }
5716
Richard Smith11562c52011-10-28 17:51:58 +00005717 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005718}
Chris Lattner05706e882008-07-11 18:11:29 +00005719
Hal Finkel0dd05d42014-10-03 17:18:37 +00005720static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5721 // C++ [expr.alignof]p3:
5722 // When alignof is applied to a reference type, the result is the
5723 // alignment of the referenced type.
5724 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5725 T = Ref->getPointeeType();
5726
5727 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005728 if (T.getQualifiers().hasUnaligned())
5729 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005730 return Info.Ctx.toCharUnitsFromBits(
5731 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5732}
5733
5734static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5735 E = E->IgnoreParens();
5736
5737 // The kinds of expressions that we have special-case logic here for
5738 // should be kept up to date with the special checks for those
5739 // expressions in Sema.
5740
5741 // alignof decl is always accepted, even if it doesn't make sense: we default
5742 // to 1 in those cases.
5743 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5744 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5745 /*RefAsPointee*/true);
5746
5747 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5748 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5749 /*RefAsPointee*/true);
5750
5751 return GetAlignOfType(Info, E->getType());
5752}
5753
George Burgess IVe3763372016-12-22 02:50:20 +00005754// To be clear: this happily visits unsupported builtins. Better name welcomed.
5755bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5756 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5757 return true;
5758
George Burgess IVf9013bf2017-02-10 22:52:29 +00005759 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005760 return false;
5761
5762 Result.setInvalid(E);
5763 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Daniel Jasperffdee092017-05-02 19:21:42 +00005764 Result.addUnsizedArray(Info, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005765 return true;
5766}
5767
Peter Collingbournee9200682011-05-13 03:29:01 +00005768bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005769 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005770 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005771
Richard Smith6328cbd2016-11-16 00:57:23 +00005772 if (unsigned BuiltinOp = E->getBuiltinCallee())
5773 return VisitBuiltinCallExpr(E, BuiltinOp);
5774
George Burgess IVe3763372016-12-22 02:50:20 +00005775 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005776}
5777
5778bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5779 unsigned BuiltinOp) {
5780 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005781 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005782 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005783 case Builtin::BI__builtin_assume_aligned: {
5784 // We need to be very careful here because: if the pointer does not have the
5785 // asserted alignment, then the behavior is undefined, and undefined
5786 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005787 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005788 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005789
Hal Finkel0dd05d42014-10-03 17:18:37 +00005790 LValue OffsetResult(Result);
5791 APSInt Alignment;
5792 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5793 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005794 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005795
5796 if (E->getNumArgs() > 2) {
5797 APSInt Offset;
5798 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5799 return false;
5800
Richard Smith642a2362017-01-30 23:30:26 +00005801 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005802 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5803 }
5804
5805 // If there is a base object, then it must have the correct alignment.
5806 if (OffsetResult.Base) {
5807 CharUnits BaseAlignment;
5808 if (const ValueDecl *VD =
5809 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5810 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5811 } else {
5812 BaseAlignment =
5813 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5814 }
5815
5816 if (BaseAlignment < Align) {
5817 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005818 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005819 CCEDiag(E->getArg(0),
5820 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005821 << (unsigned)BaseAlignment.getQuantity()
5822 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005823 return false;
5824 }
5825 }
5826
5827 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005828 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005829 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005830
Richard Smith642a2362017-01-30 23:30:26 +00005831 (OffsetResult.Base
5832 ? CCEDiag(E->getArg(0),
5833 diag::note_constexpr_baa_insufficient_alignment) << 1
5834 : CCEDiag(E->getArg(0),
5835 diag::note_constexpr_baa_value_insufficient_alignment))
5836 << (int)OffsetResult.Offset.getQuantity()
5837 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005838 return false;
5839 }
5840
5841 return true;
5842 }
Richard Smithe9507952016-11-12 01:39:56 +00005843
5844 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005845 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005846 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005847 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005848 if (Info.getLangOpts().CPlusPlus11)
5849 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5850 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005851 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005852 else
5853 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5854 // Fall through.
5855 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005856 case Builtin::BI__builtin_wcschr:
5857 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005858 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005859 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005860 if (!Visit(E->getArg(0)))
5861 return false;
5862 APSInt Desired;
5863 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5864 return false;
5865 uint64_t MaxLength = uint64_t(-1);
5866 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005867 BuiltinOp != Builtin::BIwcschr &&
5868 BuiltinOp != Builtin::BI__builtin_strchr &&
5869 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005870 APSInt N;
5871 if (!EvaluateInteger(E->getArg(2), N, Info))
5872 return false;
5873 MaxLength = N.getExtValue();
5874 }
5875
Richard Smith8110c9d2016-11-29 19:45:17 +00005876 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005877
Richard Smith8110c9d2016-11-29 19:45:17 +00005878 // Figure out what value we're actually looking for (after converting to
5879 // the corresponding unsigned type if necessary).
5880 uint64_t DesiredVal;
5881 bool StopAtNull = false;
5882 switch (BuiltinOp) {
5883 case Builtin::BIstrchr:
5884 case Builtin::BI__builtin_strchr:
5885 // strchr compares directly to the passed integer, and therefore
5886 // always fails if given an int that is not a char.
5887 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5888 E->getArg(1)->getType(),
5889 Desired),
5890 Desired))
5891 return ZeroInitialization(E);
5892 StopAtNull = true;
5893 // Fall through.
5894 case Builtin::BImemchr:
5895 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005896 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005897 // memchr compares by converting both sides to unsigned char. That's also
5898 // correct for strchr if we get this far (to cope with plain char being
5899 // unsigned in the strchr case).
5900 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5901 break;
Richard Smithe9507952016-11-12 01:39:56 +00005902
Richard Smith8110c9d2016-11-29 19:45:17 +00005903 case Builtin::BIwcschr:
5904 case Builtin::BI__builtin_wcschr:
5905 StopAtNull = true;
5906 // Fall through.
5907 case Builtin::BIwmemchr:
5908 case Builtin::BI__builtin_wmemchr:
5909 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5910 DesiredVal = Desired.getZExtValue();
5911 break;
5912 }
Richard Smithe9507952016-11-12 01:39:56 +00005913
5914 for (; MaxLength; --MaxLength) {
5915 APValue Char;
5916 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5917 !Char.isInt())
5918 return false;
5919 if (Char.getInt().getZExtValue() == DesiredVal)
5920 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005921 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005922 break;
5923 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5924 return false;
5925 }
5926 // Not found: return nullptr.
5927 return ZeroInitialization(E);
5928 }
5929
Richard Smith6cbd65d2013-07-11 02:27:57 +00005930 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005931 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005932 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005933}
Chris Lattner05706e882008-07-11 18:11:29 +00005934
5935//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005936// Member Pointer Evaluation
5937//===----------------------------------------------------------------------===//
5938
5939namespace {
5940class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005941 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005942 MemberPtr &Result;
5943
5944 bool Success(const ValueDecl *D) {
5945 Result = MemberPtr(D);
5946 return true;
5947 }
5948public:
5949
5950 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5951 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5952
Richard Smith2e312c82012-03-03 22:46:17 +00005953 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005954 Result.setFrom(V);
5955 return true;
5956 }
Richard Smithfddd3842011-12-30 21:15:51 +00005957 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005958 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005959 }
5960
5961 bool VisitCastExpr(const CastExpr *E);
5962 bool VisitUnaryAddrOf(const UnaryOperator *E);
5963};
5964} // end anonymous namespace
5965
5966static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5967 EvalInfo &Info) {
5968 assert(E->isRValue() && E->getType()->isMemberPointerType());
5969 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5970}
5971
5972bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5973 switch (E->getCastKind()) {
5974 default:
5975 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5976
5977 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005978 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005979 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005980
5981 case CK_BaseToDerivedMemberPointer: {
5982 if (!Visit(E->getSubExpr()))
5983 return false;
5984 if (E->path_empty())
5985 return true;
5986 // Base-to-derived member pointer casts store the path in derived-to-base
5987 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5988 // the wrong end of the derived->base arc, so stagger the path by one class.
5989 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5990 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5991 PathI != PathE; ++PathI) {
5992 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5993 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5994 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005995 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005996 }
5997 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5998 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005999 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006000 return true;
6001 }
6002
6003 case CK_DerivedToBaseMemberPointer:
6004 if (!Visit(E->getSubExpr()))
6005 return false;
6006 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6007 PathE = E->path_end(); PathI != PathE; ++PathI) {
6008 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6009 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6010 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006011 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006012 }
6013 return true;
6014 }
6015}
6016
6017bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6018 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6019 // member can be formed.
6020 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6021}
6022
6023//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006024// Record Evaluation
6025//===----------------------------------------------------------------------===//
6026
6027namespace {
6028 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006029 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006030 const LValue &This;
6031 APValue &Result;
6032 public:
6033
6034 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6035 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6036
Richard Smith2e312c82012-03-03 22:46:17 +00006037 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006038 Result = V;
6039 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006040 }
Richard Smithb8348f52016-05-12 22:16:28 +00006041 bool ZeroInitialization(const Expr *E) {
6042 return ZeroInitialization(E, E->getType());
6043 }
6044 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006045
Richard Smith52a980a2015-08-28 02:43:42 +00006046 bool VisitCallExpr(const CallExpr *E) {
6047 return handleCallExpr(E, Result, &This);
6048 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006049 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006050 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006051 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6052 return VisitCXXConstructExpr(E, E->getType());
6053 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006054 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006055 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006056 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006057 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006058 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006059}
Richard Smithd62306a2011-11-10 06:34:14 +00006060
Richard Smithfddd3842011-12-30 21:15:51 +00006061/// Perform zero-initialization on an object of non-union class type.
6062/// C++11 [dcl.init]p5:
6063/// To zero-initialize an object or reference of type T means:
6064/// [...]
6065/// -- if T is a (possibly cv-qualified) non-union class type,
6066/// each non-static data member and each base-class subobject is
6067/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006068static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6069 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006070 const LValue &This, APValue &Result) {
6071 assert(!RD->isUnion() && "Expected non-union class type");
6072 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6073 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006074 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006075
John McCalld7bca762012-05-01 00:38:49 +00006076 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006077 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6078
6079 if (CD) {
6080 unsigned Index = 0;
6081 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006082 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006083 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6084 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006085 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6086 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006087 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006088 Result.getStructBase(Index)))
6089 return false;
6090 }
6091 }
6092
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006093 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006094 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006095 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006096 continue;
6097
6098 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006099 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006100 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006101
David Blaikie2d7c57e2012-04-30 02:36:29 +00006102 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006103 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006104 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006105 return false;
6106 }
6107
6108 return true;
6109}
6110
Richard Smithb8348f52016-05-12 22:16:28 +00006111bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6112 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006113 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006114 if (RD->isUnion()) {
6115 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6116 // object's first non-static named data member is zero-initialized
6117 RecordDecl::field_iterator I = RD->field_begin();
6118 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006119 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006120 return true;
6121 }
6122
6123 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006124 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006125 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006126 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006127 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006128 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006129 }
6130
Richard Smith5d108602012-02-17 00:44:16 +00006131 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006132 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006133 return false;
6134 }
6135
Richard Smitha8105bc2012-01-06 16:39:00 +00006136 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006137}
6138
Richard Smithe97cbd72011-11-11 04:05:33 +00006139bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6140 switch (E->getCastKind()) {
6141 default:
6142 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6143
6144 case CK_ConstructorConversion:
6145 return Visit(E->getSubExpr());
6146
6147 case CK_DerivedToBase:
6148 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006149 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006150 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006151 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006152 if (!DerivedObject.isStruct())
6153 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006154
6155 // Derived-to-base rvalue conversion: just slice off the derived part.
6156 APValue *Value = &DerivedObject;
6157 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6158 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6159 PathE = E->path_end(); PathI != PathE; ++PathI) {
6160 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6161 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6162 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6163 RD = Base;
6164 }
6165 Result = *Value;
6166 return true;
6167 }
6168 }
6169}
6170
Richard Smithd62306a2011-11-10 06:34:14 +00006171bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006172 if (E->isTransparent())
6173 return Visit(E->getInit(0));
6174
Richard Smithd62306a2011-11-10 06:34:14 +00006175 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006176 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006177 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6178
6179 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006180 const FieldDecl *Field = E->getInitializedFieldInUnion();
6181 Result = APValue(Field);
6182 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006183 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006184
6185 // If the initializer list for a union does not contain any elements, the
6186 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006187 // FIXME: The element should be initialized from an initializer list.
6188 // Is this difference ever observable for initializer lists which
6189 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006190 ImplicitValueInitExpr VIE(Field->getType());
6191 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6192
Richard Smithd62306a2011-11-10 06:34:14 +00006193 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006194 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6195 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006196
6197 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6198 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6199 isa<CXXDefaultInitExpr>(InitExpr));
6200
Richard Smithb228a862012-02-15 02:18:13 +00006201 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006202 }
6203
Richard Smith872307e2016-03-08 22:17:41 +00006204 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006205 if (Result.isUninit())
6206 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6207 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006208 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006209 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006210
6211 // Initialize base classes.
6212 if (CXXRD) {
6213 for (const auto &Base : CXXRD->bases()) {
6214 assert(ElementNo < E->getNumInits() && "missing init for base class");
6215 const Expr *Init = E->getInit(ElementNo);
6216
6217 LValue Subobject = This;
6218 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6219 return false;
6220
6221 APValue &FieldVal = Result.getStructBase(ElementNo);
6222 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006223 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006224 return false;
6225 Success = false;
6226 }
6227 ++ElementNo;
6228 }
6229 }
6230
6231 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006232 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006233 // Anonymous bit-fields are not considered members of the class for
6234 // purposes of aggregate initialization.
6235 if (Field->isUnnamedBitfield())
6236 continue;
6237
6238 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006239
Richard Smith253c2a32012-01-27 01:14:48 +00006240 bool HaveInit = ElementNo < E->getNumInits();
6241
6242 // FIXME: Diagnostics here should point to the end of the initializer
6243 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006244 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006245 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006246 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006247
6248 // Perform an implicit value-initialization for members beyond the end of
6249 // the initializer list.
6250 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006251 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Nick Lewyckye7d6fbd2017-04-29 09:33:46 +00006252 if (Init->isValueDependent()) {
6253 Success = false;
6254 continue;
6255 }
Richard Smith253c2a32012-01-27 01:14:48 +00006256
Richard Smith852c9db2013-04-20 22:23:05 +00006257 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6258 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6259 isa<CXXDefaultInitExpr>(Init));
6260
Richard Smith49ca8aa2013-08-06 07:09:20 +00006261 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6262 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6263 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006264 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006265 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006266 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006267 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006268 }
6269 }
6270
Richard Smith253c2a32012-01-27 01:14:48 +00006271 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006272}
6273
Richard Smithb8348f52016-05-12 22:16:28 +00006274bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6275 QualType T) {
6276 // Note that E's type is not necessarily the type of our class here; we might
6277 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006278 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006279 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6280
Richard Smithfddd3842011-12-30 21:15:51 +00006281 bool ZeroInit = E->requiresZeroInitialization();
6282 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006283 // If we've already performed zero-initialization, we're already done.
6284 if (!Result.isUninit())
6285 return true;
6286
Richard Smithda3f4fd2014-03-05 23:32:50 +00006287 // We can get here in two different ways:
6288 // 1) We're performing value-initialization, and should zero-initialize
6289 // the object, or
6290 // 2) We're performing default-initialization of an object with a trivial
6291 // constexpr default constructor, in which case we should start the
6292 // lifetimes of all the base subobjects (there can be no data member
6293 // subobjects in this case) per [basic.life]p1.
6294 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006295 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006296 }
6297
Craig Topper36250ad2014-05-12 05:36:57 +00006298 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006299 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006300
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006301 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006302 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006303
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006304 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006305 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006306 if (const MaterializeTemporaryExpr *ME
6307 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6308 return Visit(ME->GetTemporaryExpr());
6309
Richard Smithb8348f52016-05-12 22:16:28 +00006310 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006311 return false;
6312
Craig Topper5fc8fc22014-08-27 06:28:36 +00006313 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006314 return HandleConstructorCall(E, This, Args,
6315 cast<CXXConstructorDecl>(Definition), Info,
6316 Result);
6317}
6318
6319bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6320 const CXXInheritedCtorInitExpr *E) {
6321 if (!Info.CurrentCall) {
6322 assert(Info.checkingPotentialConstantExpression());
6323 return false;
6324 }
6325
6326 const CXXConstructorDecl *FD = E->getConstructor();
6327 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6328 return false;
6329
6330 const FunctionDecl *Definition = nullptr;
6331 auto Body = FD->getBody(Definition);
6332
6333 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6334 return false;
6335
6336 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006337 cast<CXXConstructorDecl>(Definition), Info,
6338 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006339}
6340
Richard Smithcc1b96d2013-06-12 22:31:48 +00006341bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6342 const CXXStdInitializerListExpr *E) {
6343 const ConstantArrayType *ArrayType =
6344 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6345
6346 LValue Array;
6347 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6348 return false;
6349
6350 // Get a pointer to the first element of the array.
6351 Array.addArray(Info, E, ArrayType);
6352
6353 // FIXME: Perform the checks on the field types in SemaInit.
6354 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6355 RecordDecl::field_iterator Field = Record->field_begin();
6356 if (Field == Record->field_end())
6357 return Error(E);
6358
6359 // Start pointer.
6360 if (!Field->getType()->isPointerType() ||
6361 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6362 ArrayType->getElementType()))
6363 return Error(E);
6364
6365 // FIXME: What if the initializer_list type has base classes, etc?
6366 Result = APValue(APValue::UninitStruct(), 0, 2);
6367 Array.moveInto(Result.getStructField(0));
6368
6369 if (++Field == Record->field_end())
6370 return Error(E);
6371
6372 if (Field->getType()->isPointerType() &&
6373 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6374 ArrayType->getElementType())) {
6375 // End pointer.
6376 if (!HandleLValueArrayAdjustment(Info, E, Array,
6377 ArrayType->getElementType(),
6378 ArrayType->getSize().getZExtValue()))
6379 return false;
6380 Array.moveInto(Result.getStructField(1));
6381 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6382 // Length.
6383 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6384 else
6385 return Error(E);
6386
6387 if (++Field != Record->field_end())
6388 return Error(E);
6389
6390 return true;
6391}
6392
Faisal Valic72a08c2017-01-09 03:02:53 +00006393bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6394 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6395 if (ClosureClass->isInvalidDecl()) return false;
6396
6397 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006398
Faisal Vali051e3a22017-02-16 04:12:21 +00006399 const size_t NumFields =
6400 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006401
6402 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6403 E->capture_init_end()) &&
6404 "The number of lambda capture initializers should equal the number of "
6405 "fields within the closure type");
6406
Faisal Vali051e3a22017-02-16 04:12:21 +00006407 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6408 // Iterate through all the lambda's closure object's fields and initialize
6409 // them.
6410 auto *CaptureInitIt = E->capture_init_begin();
6411 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6412 bool Success = true;
6413 for (const auto *Field : ClosureClass->fields()) {
6414 assert(CaptureInitIt != E->capture_init_end());
6415 // Get the initializer for this field
6416 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006417
Faisal Vali051e3a22017-02-16 04:12:21 +00006418 // If there is no initializer, either this is a VLA or an error has
6419 // occurred.
6420 if (!CurFieldInit)
6421 return Error(E);
6422
6423 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6424 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6425 if (!Info.keepEvaluatingAfterFailure())
6426 return false;
6427 Success = false;
6428 }
6429 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006430 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006431 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006432}
6433
Richard Smithd62306a2011-11-10 06:34:14 +00006434static bool EvaluateRecord(const Expr *E, const LValue &This,
6435 APValue &Result, EvalInfo &Info) {
6436 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006437 "can't evaluate expression as a record rvalue");
6438 return RecordExprEvaluator(Info, This, Result).Visit(E);
6439}
6440
6441//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006442// Temporary Evaluation
6443//
6444// Temporaries are represented in the AST as rvalues, but generally behave like
6445// lvalues. The full-object of which the temporary is a subobject is implicitly
6446// materialized so that a reference can bind to it.
6447//===----------------------------------------------------------------------===//
6448namespace {
6449class TemporaryExprEvaluator
6450 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6451public:
6452 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006453 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006454
6455 /// Visit an expression which constructs the value of this temporary.
6456 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006457 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006458 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6459 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006460 }
6461
6462 bool VisitCastExpr(const CastExpr *E) {
6463 switch (E->getCastKind()) {
6464 default:
6465 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6466
6467 case CK_ConstructorConversion:
6468 return VisitConstructExpr(E->getSubExpr());
6469 }
6470 }
6471 bool VisitInitListExpr(const InitListExpr *E) {
6472 return VisitConstructExpr(E);
6473 }
6474 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6475 return VisitConstructExpr(E);
6476 }
6477 bool VisitCallExpr(const CallExpr *E) {
6478 return VisitConstructExpr(E);
6479 }
Richard Smith513955c2014-12-17 19:24:30 +00006480 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6481 return VisitConstructExpr(E);
6482 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006483 bool VisitLambdaExpr(const LambdaExpr *E) {
6484 return VisitConstructExpr(E);
6485 }
Richard Smith027bf112011-11-17 22:56:20 +00006486};
6487} // end anonymous namespace
6488
6489/// Evaluate an expression of record type as a temporary.
6490static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006491 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006492 return TemporaryExprEvaluator(Info, Result).Visit(E);
6493}
6494
6495//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006496// Vector Evaluation
6497//===----------------------------------------------------------------------===//
6498
6499namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006500 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006501 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006502 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006503 public:
Mike Stump11289f42009-09-09 15:08:12 +00006504
Richard Smith2d406342011-10-22 21:10:00 +00006505 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6506 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006507
Craig Topper9798b932015-09-29 04:30:05 +00006508 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006509 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6510 // FIXME: remove this APValue copy.
6511 Result = APValue(V.data(), V.size());
6512 return true;
6513 }
Richard Smith2e312c82012-03-03 22:46:17 +00006514 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006515 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006516 Result = V;
6517 return true;
6518 }
Richard Smithfddd3842011-12-30 21:15:51 +00006519 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006520
Richard Smith2d406342011-10-22 21:10:00 +00006521 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006522 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006523 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006524 bool VisitInitListExpr(const InitListExpr *E);
6525 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006526 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006527 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006528 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006529 };
6530} // end anonymous namespace
6531
6532static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006533 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006534 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006535}
6536
George Burgess IV533ff002015-12-11 00:23:35 +00006537bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006538 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006539 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006540
Richard Smith161f09a2011-12-06 22:44:34 +00006541 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006542 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006543
Eli Friedmanc757de22011-03-25 00:43:55 +00006544 switch (E->getCastKind()) {
6545 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006546 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006547 if (SETy->isIntegerType()) {
6548 APSInt IntResult;
6549 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006550 return false;
6551 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006552 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006553 APFloat FloatResult(0.0);
6554 if (!EvaluateFloat(SE, FloatResult, Info))
6555 return false;
6556 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006557 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006558 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006559 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006560
6561 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006562 SmallVector<APValue, 4> Elts(NElts, Val);
6563 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006564 }
Eli Friedman803acb32011-12-22 03:51:45 +00006565 case CK_BitCast: {
6566 // Evaluate the operand into an APInt we can extract from.
6567 llvm::APInt SValInt;
6568 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6569 return false;
6570 // Extract the elements
6571 QualType EltTy = VTy->getElementType();
6572 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6573 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6574 SmallVector<APValue, 4> Elts;
6575 if (EltTy->isRealFloatingType()) {
6576 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006577 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006578 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006579 FloatEltSize = 80;
6580 for (unsigned i = 0; i < NElts; i++) {
6581 llvm::APInt Elt;
6582 if (BigEndian)
6583 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6584 else
6585 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006586 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006587 }
6588 } else if (EltTy->isIntegerType()) {
6589 for (unsigned i = 0; i < NElts; i++) {
6590 llvm::APInt Elt;
6591 if (BigEndian)
6592 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6593 else
6594 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6595 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6596 }
6597 } else {
6598 return Error(E);
6599 }
6600 return Success(Elts, E);
6601 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006602 default:
Richard Smith11562c52011-10-28 17:51:58 +00006603 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006604 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006605}
6606
Richard Smith2d406342011-10-22 21:10:00 +00006607bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006608VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006609 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006610 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006611 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006612
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006613 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006614 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006615
Eli Friedmanb9c71292012-01-03 23:24:20 +00006616 // The number of initializers can be less than the number of
6617 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006618 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006619 // should be initialized with zeroes.
6620 unsigned CountInits = 0, CountElts = 0;
6621 while (CountElts < NumElements) {
6622 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006623 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006624 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006625 APValue v;
6626 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6627 return Error(E);
6628 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006629 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006630 Elements.push_back(v.getVectorElt(j));
6631 CountElts += vlen;
6632 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006633 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006634 if (CountInits < NumInits) {
6635 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006636 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006637 } else // trailing integer zero.
6638 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6639 Elements.push_back(APValue(sInt));
6640 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006641 } else {
6642 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006643 if (CountInits < NumInits) {
6644 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006645 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006646 } else // trailing float zero.
6647 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6648 Elements.push_back(APValue(f));
6649 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006650 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006651 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006652 }
Richard Smith2d406342011-10-22 21:10:00 +00006653 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006654}
6655
Richard Smith2d406342011-10-22 21:10:00 +00006656bool
Richard Smithfddd3842011-12-30 21:15:51 +00006657VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006658 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006659 QualType EltTy = VT->getElementType();
6660 APValue ZeroElement;
6661 if (EltTy->isIntegerType())
6662 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6663 else
6664 ZeroElement =
6665 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6666
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006667 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006668 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006669}
6670
Richard Smith2d406342011-10-22 21:10:00 +00006671bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006672 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006673 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006674}
6675
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006676//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006677// Array Evaluation
6678//===----------------------------------------------------------------------===//
6679
6680namespace {
6681 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006682 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006683 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006684 APValue &Result;
6685 public:
6686
Richard Smithd62306a2011-11-10 06:34:14 +00006687 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6688 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006689
6690 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006691 assert((V.isArray() || V.isLValue()) &&
6692 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006693 Result = V;
6694 return true;
6695 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006696
Richard Smithfddd3842011-12-30 21:15:51 +00006697 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006698 const ConstantArrayType *CAT =
6699 Info.Ctx.getAsConstantArrayType(E->getType());
6700 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006701 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006702
6703 Result = APValue(APValue::UninitArray(), 0,
6704 CAT->getSize().getZExtValue());
6705 if (!Result.hasArrayFiller()) return true;
6706
Richard Smithfddd3842011-12-30 21:15:51 +00006707 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006708 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006709 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006710 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006711 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006712 }
6713
Richard Smith52a980a2015-08-28 02:43:42 +00006714 bool VisitCallExpr(const CallExpr *E) {
6715 return handleCallExpr(E, Result, &This);
6716 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006717 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006718 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006719 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006720 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6721 const LValue &Subobject,
6722 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006723 };
6724} // end anonymous namespace
6725
Richard Smithd62306a2011-11-10 06:34:14 +00006726static bool EvaluateArray(const Expr *E, const LValue &This,
6727 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006728 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006729 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006730}
6731
6732bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6733 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6734 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006735 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006736
Richard Smithca2cfbf2011-12-22 01:07:19 +00006737 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6738 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006739 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006740 LValue LV;
6741 if (!EvaluateLValue(E->getInit(0), LV, Info))
6742 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006743 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006744 LV.moveInto(Val);
6745 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006746 }
6747
Richard Smith253c2a32012-01-27 01:14:48 +00006748 bool Success = true;
6749
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006750 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6751 "zero-initialized array shouldn't have any initialized elts");
6752 APValue Filler;
6753 if (Result.isArray() && Result.hasArrayFiller())
6754 Filler = Result.getArrayFiller();
6755
Richard Smith9543c5e2013-04-22 14:44:29 +00006756 unsigned NumEltsToInit = E->getNumInits();
6757 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006758 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006759
6760 // If the initializer might depend on the array index, run it for each
6761 // array element. For now, just whitelist non-class value-initialization.
6762 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6763 NumEltsToInit = NumElts;
6764
6765 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006766
6767 // If the array was previously zero-initialized, preserve the
6768 // zero-initialized values.
6769 if (!Filler.isUninit()) {
6770 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6771 Result.getArrayInitializedElt(I) = Filler;
6772 if (Result.hasArrayFiller())
6773 Result.getArrayFiller() = Filler;
6774 }
6775
Richard Smithd62306a2011-11-10 06:34:14 +00006776 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006777 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006778 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6779 const Expr *Init =
6780 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006781 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006782 Info, Subobject, Init) ||
6783 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006784 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006785 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006786 return false;
6787 Success = false;
6788 }
Richard Smithd62306a2011-11-10 06:34:14 +00006789 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006790
Richard Smith9543c5e2013-04-22 14:44:29 +00006791 if (!Result.hasArrayFiller())
6792 return Success;
6793
6794 // If we get here, we have a trivial filler, which we can just evaluate
6795 // once and splat over the rest of the array elements.
6796 assert(FillerExpr && "no array filler for incomplete init list");
6797 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6798 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006799}
6800
Richard Smith410306b2016-12-12 02:53:20 +00006801bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6802 if (E->getCommonExpr() &&
6803 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6804 Info, E->getCommonExpr()->getSourceExpr()))
6805 return false;
6806
6807 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6808
6809 uint64_t Elements = CAT->getSize().getZExtValue();
6810 Result = APValue(APValue::UninitArray(), Elements, Elements);
6811
6812 LValue Subobject = This;
6813 Subobject.addArray(Info, E, CAT);
6814
6815 bool Success = true;
6816 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6817 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6818 Info, Subobject, E->getSubExpr()) ||
6819 !HandleLValueArrayAdjustment(Info, E, Subobject,
6820 CAT->getElementType(), 1)) {
6821 if (!Info.noteFailure())
6822 return false;
6823 Success = false;
6824 }
6825 }
6826
6827 return Success;
6828}
6829
Richard Smith027bf112011-11-17 22:56:20 +00006830bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006831 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6832}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006833
Richard Smith9543c5e2013-04-22 14:44:29 +00006834bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6835 const LValue &Subobject,
6836 APValue *Value,
6837 QualType Type) {
6838 bool HadZeroInit = !Value->isUninit();
6839
6840 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6841 unsigned N = CAT->getSize().getZExtValue();
6842
6843 // Preserve the array filler if we had prior zero-initialization.
6844 APValue Filler =
6845 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6846 : APValue();
6847
6848 *Value = APValue(APValue::UninitArray(), N, N);
6849
6850 if (HadZeroInit)
6851 for (unsigned I = 0; I != N; ++I)
6852 Value->getArrayInitializedElt(I) = Filler;
6853
6854 // Initialize the elements.
6855 LValue ArrayElt = Subobject;
6856 ArrayElt.addArray(Info, E, CAT);
6857 for (unsigned I = 0; I != N; ++I)
6858 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6859 CAT->getElementType()) ||
6860 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6861 CAT->getElementType(), 1))
6862 return false;
6863
6864 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006865 }
Richard Smith027bf112011-11-17 22:56:20 +00006866
Richard Smith9543c5e2013-04-22 14:44:29 +00006867 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006868 return Error(E);
6869
Richard Smithb8348f52016-05-12 22:16:28 +00006870 return RecordExprEvaluator(Info, Subobject, *Value)
6871 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006872}
6873
Richard Smithf3e9e432011-11-07 09:22:26 +00006874//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006875// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006876//
6877// As a GNU extension, we support casting pointers to sufficiently-wide integer
6878// types and back in constant folding. Integer values are thus represented
6879// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006880//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006881
6882namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006883class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006884 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006885 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006886public:
Richard Smith2e312c82012-03-03 22:46:17 +00006887 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006888 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006889
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006890 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006891 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006892 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006893 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006894 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006895 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006896 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006897 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006898 return true;
6899 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006900 bool Success(const llvm::APSInt &SI, const Expr *E) {
6901 return Success(SI, E, Result);
6902 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006903
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006904 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006905 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006906 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006907 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006908 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006909 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006910 Result.getInt().setIsUnsigned(
6911 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006912 return true;
6913 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006914 bool Success(const llvm::APInt &I, const Expr *E) {
6915 return Success(I, E, Result);
6916 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006917
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006918 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006919 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006920 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006921 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006922 return true;
6923 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006924 bool Success(uint64_t Value, const Expr *E) {
6925 return Success(Value, E, Result);
6926 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006927
Ken Dyckdbc01912011-03-11 02:13:43 +00006928 bool Success(CharUnits Size, const Expr *E) {
6929 return Success(Size.getQuantity(), E);
6930 }
6931
Richard Smith2e312c82012-03-03 22:46:17 +00006932 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006933 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006934 Result = V;
6935 return true;
6936 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006937 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006938 }
Mike Stump11289f42009-09-09 15:08:12 +00006939
Richard Smithfddd3842011-12-30 21:15:51 +00006940 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006941
Peter Collingbournee9200682011-05-13 03:29:01 +00006942 //===--------------------------------------------------------------------===//
6943 // Visitor Methods
6944 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006945
Chris Lattner7174bf32008-07-12 00:38:25 +00006946 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006947 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006948 }
6949 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006950 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006951 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006952
6953 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6954 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006955 if (CheckReferencedDecl(E, E->getDecl()))
6956 return true;
6957
6958 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006959 }
6960 bool VisitMemberExpr(const MemberExpr *E) {
6961 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006962 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006963 return true;
6964 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006965
6966 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006967 }
6968
Peter Collingbournee9200682011-05-13 03:29:01 +00006969 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006970 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006971 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006972 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006973 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006974
Peter Collingbournee9200682011-05-13 03:29:01 +00006975 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006976 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006977
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006978 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006979 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006980 }
Mike Stump11289f42009-09-09 15:08:12 +00006981
Ted Kremeneke65b0862012-03-06 20:05:56 +00006982 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6983 return Success(E->getValue(), E);
6984 }
Richard Smith410306b2016-12-12 02:53:20 +00006985
6986 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6987 if (Info.ArrayInitIndex == uint64_t(-1)) {
6988 // We were asked to evaluate this subexpression independent of the
6989 // enclosing ArrayInitLoopExpr. We can't do that.
6990 Info.FFDiag(E);
6991 return false;
6992 }
6993 return Success(Info.ArrayInitIndex, E);
6994 }
Daniel Jasperffdee092017-05-02 19:21:42 +00006995
Richard Smith4ce706a2011-10-11 21:43:33 +00006996 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006997 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006998 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006999 }
7000
Douglas Gregor29c42f22012-02-24 07:38:34 +00007001 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7002 return Success(E->getValue(), E);
7003 }
7004
John Wiegley6242b6a2011-04-28 00:16:57 +00007005 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7006 return Success(E->getValue(), E);
7007 }
7008
John Wiegleyf9f65842011-04-25 06:54:41 +00007009 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7010 return Success(E->getValue(), E);
7011 }
7012
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007013 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007014 bool VisitUnaryImag(const UnaryOperator *E);
7015
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007016 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007017 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007018
Eli Friedman4e7a2412009-02-27 04:45:43 +00007019 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007020};
Chris Lattner05706e882008-07-11 18:11:29 +00007021} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007022
Richard Smith11562c52011-10-28 17:51:58 +00007023/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7024/// produce either the integer value or a pointer.
7025///
7026/// GCC has a heinous extension which folds casts between pointer types and
7027/// pointer-sized integral types. We support this by allowing the evaluation of
7028/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7029/// Some simple arithmetic on such values is supported (they are treated much
7030/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007031static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007032 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007033 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007034 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007035}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007036
Richard Smithf57d8cb2011-12-09 22:58:01 +00007037static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007038 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007039 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007040 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007041 if (!Val.isInt()) {
7042 // FIXME: It would be better to produce the diagnostic for casting
7043 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007044 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007045 return false;
7046 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007047 Result = Val.getInt();
7048 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007049}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007050
Richard Smithf57d8cb2011-12-09 22:58:01 +00007051/// Check whether the given declaration can be directly converted to an integral
7052/// rvalue. If not, no diagnostic is produced; there are other things we can
7053/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007054bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007055 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007056 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007057 // Check for signedness/width mismatches between E type and ECD value.
7058 bool SameSign = (ECD->getInitVal().isSigned()
7059 == E->getType()->isSignedIntegerOrEnumerationType());
7060 bool SameWidth = (ECD->getInitVal().getBitWidth()
7061 == Info.Ctx.getIntWidth(E->getType()));
7062 if (SameSign && SameWidth)
7063 return Success(ECD->getInitVal(), E);
7064 else {
7065 // Get rid of mismatch (otherwise Success assertions will fail)
7066 // by computing a new value matching the type of E.
7067 llvm::APSInt Val = ECD->getInitVal();
7068 if (!SameSign)
7069 Val.setIsSigned(!ECD->getInitVal().isSigned());
7070 if (!SameWidth)
7071 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7072 return Success(Val, E);
7073 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007074 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007075 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007076}
7077
Chris Lattner86ee2862008-10-06 06:40:35 +00007078/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7079/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007080static int EvaluateBuiltinClassifyType(const CallExpr *E,
7081 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007082 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007083 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007084 enum gcc_type_class {
7085 no_type_class = -1,
7086 void_type_class, integer_type_class, char_type_class,
7087 enumeral_type_class, boolean_type_class,
7088 pointer_type_class, reference_type_class, offset_type_class,
7089 real_type_class, complex_type_class,
7090 function_type_class, method_type_class,
7091 record_type_class, union_type_class,
7092 array_type_class, string_type_class,
7093 lang_type_class
7094 };
Mike Stump11289f42009-09-09 15:08:12 +00007095
7096 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007097 // ideal, however it is what gcc does.
7098 if (E->getNumArgs() == 0)
7099 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007100
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007101 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7102 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7103
7104 switch (CanTy->getTypeClass()) {
7105#define TYPE(ID, BASE)
7106#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7107#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7108#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7109#include "clang/AST/TypeNodes.def"
7110 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7111
7112 case Type::Builtin:
7113 switch (BT->getKind()) {
7114#define BUILTIN_TYPE(ID, SINGLETON_ID)
7115#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7116#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7117#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7118#include "clang/AST/BuiltinTypes.def"
7119 case BuiltinType::Void:
7120 return void_type_class;
7121
7122 case BuiltinType::Bool:
7123 return boolean_type_class;
7124
7125 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7126 case BuiltinType::UChar:
7127 case BuiltinType::UShort:
7128 case BuiltinType::UInt:
7129 case BuiltinType::ULong:
7130 case BuiltinType::ULongLong:
7131 case BuiltinType::UInt128:
7132 return integer_type_class;
7133
7134 case BuiltinType::NullPtr:
7135 return pointer_type_class;
7136
7137 case BuiltinType::WChar_U:
7138 case BuiltinType::Char16:
7139 case BuiltinType::Char32:
7140 case BuiltinType::ObjCId:
7141 case BuiltinType::ObjCClass:
7142 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007143#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7144 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007145#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007146 case BuiltinType::OCLSampler:
7147 case BuiltinType::OCLEvent:
7148 case BuiltinType::OCLClkEvent:
7149 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007150 case BuiltinType::OCLReserveID:
7151 case BuiltinType::Dependent:
7152 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7153 };
7154
7155 case Type::Enum:
7156 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7157 break;
7158
7159 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007160 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007161 break;
7162
7163 case Type::MemberPointer:
7164 if (CanTy->isMemberDataPointerType())
7165 return offset_type_class;
7166 else {
7167 // We expect member pointers to be either data or function pointers,
7168 // nothing else.
7169 assert(CanTy->isMemberFunctionPointerType());
7170 return method_type_class;
7171 }
7172
7173 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007174 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007175
7176 case Type::FunctionNoProto:
7177 case Type::FunctionProto:
7178 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7179
7180 case Type::Record:
7181 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7182 switch (RT->getDecl()->getTagKind()) {
7183 case TagTypeKind::TTK_Struct:
7184 case TagTypeKind::TTK_Class:
7185 case TagTypeKind::TTK_Interface:
7186 return record_type_class;
7187
7188 case TagTypeKind::TTK_Enum:
7189 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7190
7191 case TagTypeKind::TTK_Union:
7192 return union_type_class;
7193 }
7194 }
David Blaikie83d382b2011-09-23 05:06:16 +00007195 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007196
7197 case Type::ConstantArray:
7198 case Type::VariableArray:
7199 case Type::IncompleteArray:
7200 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7201
7202 case Type::BlockPointer:
7203 case Type::LValueReference:
7204 case Type::RValueReference:
7205 case Type::Vector:
7206 case Type::ExtVector:
7207 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007208 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007209 case Type::ObjCObject:
7210 case Type::ObjCInterface:
7211 case Type::ObjCObjectPointer:
7212 case Type::Pipe:
7213 case Type::Atomic:
7214 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7215 }
7216
7217 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007218}
7219
Richard Smith5fab0c92011-12-28 19:48:30 +00007220/// EvaluateBuiltinConstantPForLValue - Determine the result of
7221/// __builtin_constant_p when applied to the given lvalue.
7222///
7223/// An lvalue is only "constant" if it is a pointer or reference to the first
7224/// character of a string literal.
7225template<typename LValue>
7226static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007227 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007228 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7229}
7230
7231/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7232/// GCC as we can manage.
7233static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7234 QualType ArgType = Arg->getType();
7235
7236 // __builtin_constant_p always has one operand. The rules which gcc follows
7237 // are not precisely documented, but are as follows:
7238 //
7239 // - If the operand is of integral, floating, complex or enumeration type,
7240 // and can be folded to a known value of that type, it returns 1.
7241 // - If the operand and can be folded to a pointer to the first character
7242 // of a string literal (or such a pointer cast to an integral type), it
7243 // returns 1.
7244 //
7245 // Otherwise, it returns 0.
7246 //
7247 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7248 // its support for this does not currently work.
7249 if (ArgType->isIntegralOrEnumerationType()) {
7250 Expr::EvalResult Result;
7251 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7252 return false;
7253
7254 APValue &V = Result.Val;
7255 if (V.getKind() == APValue::Int)
7256 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007257 if (V.getKind() == APValue::LValue)
7258 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007259 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7260 return Arg->isEvaluatable(Ctx);
7261 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7262 LValue LV;
7263 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007264 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007265 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7266 : EvaluatePointer(Arg, LV, Info)) &&
7267 !Status.HasSideEffects)
7268 return EvaluateBuiltinConstantPForLValue(LV);
7269 }
7270
7271 // Anything else isn't considered to be sufficiently constant.
7272 return false;
7273}
7274
John McCall95007602010-05-10 23:27:23 +00007275/// Retrieves the "underlying object type" of the given expression,
7276/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007277static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007278 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7279 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007280 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007281 } else if (const Expr *E = B.get<const Expr*>()) {
7282 if (isa<CompoundLiteralExpr>(E))
7283 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007284 }
7285
7286 return QualType();
7287}
7288
George Burgess IV3a03fab2015-09-04 21:28:13 +00007289/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007290/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007291/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007292/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7293///
7294/// Always returns an RValue with a pointer representation.
7295static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7296 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7297
7298 auto *NoParens = E->IgnoreParens();
7299 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007300 if (Cast == nullptr)
7301 return NoParens;
7302
7303 // We only conservatively allow a few kinds of casts, because this code is
7304 // inherently a simple solution that seeks to support the common case.
7305 auto CastKind = Cast->getCastKind();
7306 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7307 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007308 return NoParens;
7309
7310 auto *SubExpr = Cast->getSubExpr();
7311 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7312 return NoParens;
7313 return ignorePointerCastsAndParens(SubExpr);
7314}
7315
George Burgess IVa51c4072015-10-16 01:49:01 +00007316/// Checks to see if the given LValue's Designator is at the end of the LValue's
7317/// record layout. e.g.
7318/// struct { struct { int a, b; } fst, snd; } obj;
7319/// obj.fst // no
7320/// obj.snd // yes
7321/// obj.fst.a // no
7322/// obj.fst.b // no
7323/// obj.snd.a // no
7324/// obj.snd.b // yes
7325///
7326/// Please note: this function is specialized for how __builtin_object_size
7327/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007328///
7329/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007330static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7331 assert(!LVal.Designator.Invalid);
7332
George Burgess IV4168d752016-06-27 19:40:41 +00007333 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7334 const RecordDecl *Parent = FD->getParent();
7335 Invalid = Parent->isInvalidDecl();
7336 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007337 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007338 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007339 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7340 };
7341
7342 auto &Base = LVal.getLValueBase();
7343 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7344 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007345 bool Invalid;
7346 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7347 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007348 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007349 for (auto *FD : IFD->chain()) {
7350 bool Invalid;
7351 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7352 return Invalid;
7353 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007354 }
7355 }
7356
George Burgess IVe3763372016-12-22 02:50:20 +00007357 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007358 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007359 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7360 assert(isBaseAnAllocSizeCall(Base) &&
7361 "Unsized array in non-alloc_size call?");
7362 // If this is an alloc_size base, we should ignore the initial array index
George Burgess IVe3763372016-12-22 02:50:20 +00007363 ++I;
7364 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7365 }
7366
7367 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7368 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007369 if (BaseType->isArrayType()) {
7370 // Because __builtin_object_size treats arrays as objects, we can ignore
7371 // the index iff this is the last array in the Designator.
7372 if (I + 1 == E)
7373 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007374 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7375 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007376 if (Index + 1 != CAT->getSize())
7377 return false;
7378 BaseType = CAT->getElementType();
7379 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007380 const auto *CT = BaseType->castAs<ComplexType>();
7381 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007382 if (Index != 1)
7383 return false;
7384 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007385 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007386 bool Invalid;
7387 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7388 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007389 BaseType = FD->getType();
7390 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007391 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007392 return false;
7393 }
7394 }
7395 return true;
7396}
7397
George Burgess IVe3763372016-12-22 02:50:20 +00007398/// Tests to see if the LValue has a user-specified designator (that isn't
7399/// necessarily valid). Note that this always returns 'true' if the LValue has
7400/// an unsized array as its first designator entry, because there's currently no
7401/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007402static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007403 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007404 return false;
7405
George Burgess IVe3763372016-12-22 02:50:20 +00007406 if (!LVal.Designator.Entries.empty())
7407 return LVal.Designator.isMostDerivedAnUnsizedArray();
7408
George Burgess IVa51c4072015-10-16 01:49:01 +00007409 if (!LVal.InvalidBase)
7410 return true;
7411
George Burgess IVe3763372016-12-22 02:50:20 +00007412 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7413 // the LValueBase.
7414 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7415 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007416}
7417
George Burgess IVe3763372016-12-22 02:50:20 +00007418/// Attempts to detect a user writing into a piece of memory that's impossible
7419/// to figure out the size of by just using types.
7420static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7421 const SubobjectDesignator &Designator = LVal.Designator;
7422 // Notes:
7423 // - Users can only write off of the end when we have an invalid base. Invalid
7424 // bases imply we don't know where the memory came from.
7425 // - We used to be a bit more aggressive here; we'd only be conservative if
7426 // the array at the end was flexible, or if it had 0 or 1 elements. This
7427 // broke some common standard library extensions (PR30346), but was
7428 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7429 // with some sort of whitelist. OTOH, it seems that GCC is always
7430 // conservative with the last element in structs (if it's an array), so our
7431 // current behavior is more compatible than a whitelisting approach would
7432 // be.
7433 return LVal.InvalidBase &&
7434 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7435 Designator.MostDerivedIsArrayElement &&
7436 isDesignatorAtObjectEnd(Ctx, LVal);
7437}
7438
7439/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7440/// Fails if the conversion would cause loss of precision.
7441static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7442 CharUnits &Result) {
7443 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7444 if (Int.ugt(CharUnitsMax))
7445 return false;
7446 Result = CharUnits::fromQuantity(Int.getZExtValue());
7447 return true;
7448}
7449
7450/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7451/// determine how many bytes exist from the beginning of the object to either
7452/// the end of the current subobject, or the end of the object itself, depending
7453/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007454///
George Burgess IVe3763372016-12-22 02:50:20 +00007455/// If this returns false, the value of Result is undefined.
7456static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7457 unsigned Type, const LValue &LVal,
7458 CharUnits &EndOffset) {
7459 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007460
George Burgess IV7fb7e362017-01-03 23:35:19 +00007461 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7462 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7463 return false;
7464 return HandleSizeof(Info, ExprLoc, Ty, Result);
7465 };
7466
George Burgess IVe3763372016-12-22 02:50:20 +00007467 // We want to evaluate the size of the entire object. This is a valid fallback
7468 // for when Type=1 and the designator is invalid, because we're asked for an
7469 // upper-bound.
7470 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7471 // Type=3 wants a lower bound, so we can't fall back to this.
7472 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007473 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007474
7475 llvm::APInt APEndOffset;
7476 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7477 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7478 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7479
7480 if (LVal.InvalidBase)
7481 return false;
7482
7483 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007484 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007485 }
7486
George Burgess IVe3763372016-12-22 02:50:20 +00007487 // We want to evaluate the size of a subobject.
7488 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007489
7490 // The following is a moderately common idiom in C:
7491 //
7492 // struct Foo { int a; char c[1]; };
7493 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7494 // strcpy(&F->c[0], Bar);
7495 //
George Burgess IVe3763372016-12-22 02:50:20 +00007496 // In order to not break too much legacy code, we need to support it.
7497 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7498 // If we can resolve this to an alloc_size call, we can hand that back,
7499 // because we know for certain how many bytes there are to write to.
7500 llvm::APInt APEndOffset;
7501 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7502 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7503 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7504
7505 // If we cannot determine the size of the initial allocation, then we can't
7506 // given an accurate upper-bound. However, we are still able to give
7507 // conservative lower-bounds for Type=3.
7508 if (Type == 1)
7509 return false;
7510 }
7511
7512 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007513 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007514 return false;
7515
George Burgess IVe3763372016-12-22 02:50:20 +00007516 // According to the GCC documentation, we want the size of the subobject
7517 // denoted by the pointer. But that's not quite right -- what we actually
7518 // want is the size of the immediately-enclosing array, if there is one.
7519 int64_t ElemsRemaining;
7520 if (Designator.MostDerivedIsArrayElement &&
7521 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7522 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7523 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7524 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7525 } else {
7526 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7527 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007528
George Burgess IVe3763372016-12-22 02:50:20 +00007529 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7530 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007531}
7532
George Burgess IVe3763372016-12-22 02:50:20 +00007533/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7534/// returns true and stores the result in @p Size.
7535///
7536/// If @p WasError is non-null, this will report whether the failure to evaluate
7537/// is to be treated as an Error in IntExprEvaluator.
7538static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7539 EvalInfo &Info, uint64_t &Size) {
7540 // Determine the denoted object.
7541 LValue LVal;
7542 {
7543 // The operand of __builtin_object_size is never evaluated for side-effects.
7544 // If there are any, but we can determine the pointed-to object anyway, then
7545 // ignore the side-effects.
7546 SpeculativeEvaluationRAII SpeculativeEval(Info);
7547 FoldOffsetRAII Fold(Info);
7548
7549 if (E->isGLValue()) {
7550 // It's possible for us to be given GLValues if we're called via
7551 // Expr::tryEvaluateObjectSize.
7552 APValue RVal;
7553 if (!EvaluateAsRValue(Info, E, RVal))
7554 return false;
7555 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007556 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7557 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007558 return false;
7559 }
7560
7561 // If we point to before the start of the object, there are no accessible
7562 // bytes.
7563 if (LVal.getLValueOffset().isNegative()) {
7564 Size = 0;
7565 return true;
7566 }
7567
7568 CharUnits EndOffset;
7569 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7570 return false;
7571
7572 // If we've fallen outside of the end offset, just pretend there's nothing to
7573 // write to/read from.
7574 if (EndOffset <= LVal.getLValueOffset())
7575 Size = 0;
7576 else
7577 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7578 return true;
John McCall95007602010-05-10 23:27:23 +00007579}
7580
Peter Collingbournee9200682011-05-13 03:29:01 +00007581bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007582 if (unsigned BuiltinOp = E->getBuiltinCallee())
7583 return VisitBuiltinCallExpr(E, BuiltinOp);
7584
7585 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7586}
7587
7588bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7589 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007590 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007591 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007592 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007593
7594 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007595 // The type was checked when we built the expression.
7596 unsigned Type =
7597 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7598 assert(Type <= 3 && "unexpected type");
7599
George Burgess IVe3763372016-12-22 02:50:20 +00007600 uint64_t Size;
7601 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7602 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007603
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007604 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007605 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007606
Richard Smith01ade172012-05-23 04:13:20 +00007607 // Expression had no side effects, but we couldn't statically determine the
7608 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007609 switch (Info.EvalMode) {
7610 case EvalInfo::EM_ConstantExpression:
7611 case EvalInfo::EM_PotentialConstantExpression:
7612 case EvalInfo::EM_ConstantFold:
7613 case EvalInfo::EM_EvaluateForOverflow:
7614 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007615 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007616 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007617 return Error(E);
7618 case EvalInfo::EM_ConstantExpressionUnevaluated:
7619 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007620 // Reduce it to a constant now.
7621 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007622 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007623
7624 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007625 }
7626
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007627 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007628 case Builtin::BI__builtin_bswap32:
7629 case Builtin::BI__builtin_bswap64: {
7630 APSInt Val;
7631 if (!EvaluateInteger(E->getArg(0), Val, Info))
7632 return false;
7633
7634 return Success(Val.byteSwap(), E);
7635 }
7636
Richard Smith8889a3d2013-06-13 06:26:32 +00007637 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007638 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007639
7640 // FIXME: BI__builtin_clrsb
7641 // FIXME: BI__builtin_clrsbl
7642 // FIXME: BI__builtin_clrsbll
7643
Richard Smith80b3c8e2013-06-13 05:04:16 +00007644 case Builtin::BI__builtin_clz:
7645 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007646 case Builtin::BI__builtin_clzll:
7647 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007648 APSInt Val;
7649 if (!EvaluateInteger(E->getArg(0), Val, Info))
7650 return false;
7651 if (!Val)
7652 return Error(E);
7653
7654 return Success(Val.countLeadingZeros(), E);
7655 }
7656
Richard Smith8889a3d2013-06-13 06:26:32 +00007657 case Builtin::BI__builtin_constant_p:
7658 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7659
Richard Smith80b3c8e2013-06-13 05:04:16 +00007660 case Builtin::BI__builtin_ctz:
7661 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007662 case Builtin::BI__builtin_ctzll:
7663 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007664 APSInt Val;
7665 if (!EvaluateInteger(E->getArg(0), Val, Info))
7666 return false;
7667 if (!Val)
7668 return Error(E);
7669
7670 return Success(Val.countTrailingZeros(), E);
7671 }
7672
Richard Smith8889a3d2013-06-13 06:26:32 +00007673 case Builtin::BI__builtin_eh_return_data_regno: {
7674 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7675 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7676 return Success(Operand, E);
7677 }
7678
7679 case Builtin::BI__builtin_expect:
7680 return Visit(E->getArg(0));
7681
7682 case Builtin::BI__builtin_ffs:
7683 case Builtin::BI__builtin_ffsl:
7684 case Builtin::BI__builtin_ffsll: {
7685 APSInt Val;
7686 if (!EvaluateInteger(E->getArg(0), Val, Info))
7687 return false;
7688
7689 unsigned N = Val.countTrailingZeros();
7690 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7691 }
7692
7693 case Builtin::BI__builtin_fpclassify: {
7694 APFloat Val(0.0);
7695 if (!EvaluateFloat(E->getArg(5), Val, Info))
7696 return false;
7697 unsigned Arg;
7698 switch (Val.getCategory()) {
7699 case APFloat::fcNaN: Arg = 0; break;
7700 case APFloat::fcInfinity: Arg = 1; break;
7701 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7702 case APFloat::fcZero: Arg = 4; break;
7703 }
7704 return Visit(E->getArg(Arg));
7705 }
7706
7707 case Builtin::BI__builtin_isinf_sign: {
7708 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007709 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007710 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7711 }
7712
Richard Smithea3019d2013-10-15 19:07:14 +00007713 case Builtin::BI__builtin_isinf: {
7714 APFloat Val(0.0);
7715 return EvaluateFloat(E->getArg(0), Val, Info) &&
7716 Success(Val.isInfinity() ? 1 : 0, E);
7717 }
7718
7719 case Builtin::BI__builtin_isfinite: {
7720 APFloat Val(0.0);
7721 return EvaluateFloat(E->getArg(0), Val, Info) &&
7722 Success(Val.isFinite() ? 1 : 0, E);
7723 }
7724
7725 case Builtin::BI__builtin_isnan: {
7726 APFloat Val(0.0);
7727 return EvaluateFloat(E->getArg(0), Val, Info) &&
7728 Success(Val.isNaN() ? 1 : 0, E);
7729 }
7730
7731 case Builtin::BI__builtin_isnormal: {
7732 APFloat Val(0.0);
7733 return EvaluateFloat(E->getArg(0), Val, Info) &&
7734 Success(Val.isNormal() ? 1 : 0, E);
7735 }
7736
Richard Smith8889a3d2013-06-13 06:26:32 +00007737 case Builtin::BI__builtin_parity:
7738 case Builtin::BI__builtin_parityl:
7739 case Builtin::BI__builtin_parityll: {
7740 APSInt Val;
7741 if (!EvaluateInteger(E->getArg(0), Val, Info))
7742 return false;
7743
7744 return Success(Val.countPopulation() % 2, E);
7745 }
7746
Richard Smith80b3c8e2013-06-13 05:04:16 +00007747 case Builtin::BI__builtin_popcount:
7748 case Builtin::BI__builtin_popcountl:
7749 case Builtin::BI__builtin_popcountll: {
7750 APSInt Val;
7751 if (!EvaluateInteger(E->getArg(0), Val, Info))
7752 return false;
7753
7754 return Success(Val.countPopulation(), E);
7755 }
7756
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007757 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007758 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007759 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007760 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007761 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007762 << /*isConstexpr*/0 << /*isConstructor*/0
7763 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007764 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007765 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007766 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007767 case Builtin::BI__builtin_strlen:
7768 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007769 // As an extension, we support __builtin_strlen() as a constant expression,
7770 // and support folding strlen() to a constant.
7771 LValue String;
7772 if (!EvaluatePointer(E->getArg(0), String, Info))
7773 return false;
7774
Richard Smith8110c9d2016-11-29 19:45:17 +00007775 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7776
Richard Smithe6c19f22013-11-15 02:10:04 +00007777 // Fast path: if it's a string literal, search the string value.
7778 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7779 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007780 // The string literal may have embedded null characters. Find the first
7781 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007782 StringRef Str = S->getBytes();
7783 int64_t Off = String.Offset.getQuantity();
7784 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007785 S->getCharByteWidth() == 1 &&
7786 // FIXME: Add fast-path for wchar_t too.
7787 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007788 Str = Str.substr(Off);
7789
7790 StringRef::size_type Pos = Str.find(0);
7791 if (Pos != StringRef::npos)
7792 Str = Str.substr(0, Pos);
7793
7794 return Success(Str.size(), E);
7795 }
7796
7797 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007798 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007799
7800 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007801 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7802 APValue Char;
7803 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7804 !Char.isInt())
7805 return false;
7806 if (!Char.getInt())
7807 return Success(Strlen, E);
7808 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7809 return false;
7810 }
7811 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007812
Richard Smithe151bab2016-11-11 23:43:35 +00007813 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007814 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007815 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007816 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007817 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007818 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007819 // A call to strlen is not a constant expression.
7820 if (Info.getLangOpts().CPlusPlus11)
7821 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7822 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007823 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007824 else
7825 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7826 // Fall through.
7827 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007828 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007829 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007830 case Builtin::BI__builtin_wcsncmp:
7831 case Builtin::BI__builtin_memcmp:
7832 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007833 LValue String1, String2;
7834 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7835 !EvaluatePointer(E->getArg(1), String2, Info))
7836 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007837
7838 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7839
Richard Smithe151bab2016-11-11 23:43:35 +00007840 uint64_t MaxLength = uint64_t(-1);
7841 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007842 BuiltinOp != Builtin::BIwcscmp &&
7843 BuiltinOp != Builtin::BI__builtin_strcmp &&
7844 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007845 APSInt N;
7846 if (!EvaluateInteger(E->getArg(2), N, Info))
7847 return false;
7848 MaxLength = N.getExtValue();
7849 }
7850 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007851 BuiltinOp != Builtin::BIwmemcmp &&
7852 BuiltinOp != Builtin::BI__builtin_memcmp &&
7853 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007854 for (; MaxLength; --MaxLength) {
7855 APValue Char1, Char2;
7856 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7857 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7858 !Char1.isInt() || !Char2.isInt())
7859 return false;
7860 if (Char1.getInt() != Char2.getInt())
7861 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7862 if (StopAtNull && !Char1.getInt())
7863 return Success(0, E);
7864 assert(!(StopAtNull && !Char2.getInt()));
7865 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7866 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7867 return false;
7868 }
7869 // We hit the strncmp / memcmp limit.
7870 return Success(0, E);
7871 }
7872
Richard Smith01ba47d2012-04-13 00:45:38 +00007873 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007874 case Builtin::BI__atomic_is_lock_free:
7875 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007876 APSInt SizeVal;
7877 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7878 return false;
7879
7880 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7881 // of two less than the maximum inline atomic width, we know it is
7882 // lock-free. If the size isn't a power of two, or greater than the
7883 // maximum alignment where we promote atomics, we know it is not lock-free
7884 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7885 // the answer can only be determined at runtime; for example, 16-byte
7886 // atomics have lock-free implementations on some, but not all,
7887 // x86-64 processors.
7888
7889 // Check power-of-two.
7890 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007891 if (Size.isPowerOfTwo()) {
7892 // Check against inlining width.
7893 unsigned InlineWidthBits =
7894 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7895 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7896 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7897 Size == CharUnits::One() ||
7898 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7899 Expr::NPC_NeverValueDependent))
7900 // OK, we will inline appropriately-aligned operations of this size,
7901 // and _Atomic(T) is appropriately-aligned.
7902 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007903
Richard Smith01ba47d2012-04-13 00:45:38 +00007904 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7905 castAs<PointerType>()->getPointeeType();
7906 if (!PointeeType->isIncompleteType() &&
7907 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7908 // OK, we will inline operations on this object.
7909 return Success(1, E);
7910 }
7911 }
7912 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007913
Richard Smith01ba47d2012-04-13 00:45:38 +00007914 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7915 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007916 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007917 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007918}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007919
Richard Smith8b3497e2011-10-31 01:37:14 +00007920static bool HasSameBase(const LValue &A, const LValue &B) {
7921 if (!A.getLValueBase())
7922 return !B.getLValueBase();
7923 if (!B.getLValueBase())
7924 return false;
7925
Richard Smithce40ad62011-11-12 22:28:03 +00007926 if (A.getLValueBase().getOpaqueValue() !=
7927 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007928 const Decl *ADecl = GetLValueBaseDecl(A);
7929 if (!ADecl)
7930 return false;
7931 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007932 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007933 return false;
7934 }
7935
7936 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007937 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007938}
7939
Richard Smithd20f1e62014-10-21 23:01:04 +00007940/// \brief Determine whether this is a pointer past the end of the complete
7941/// object referred to by the lvalue.
7942static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7943 const LValue &LV) {
7944 // A null pointer can be viewed as being "past the end" but we don't
7945 // choose to look at it that way here.
7946 if (!LV.getLValueBase())
7947 return false;
7948
7949 // If the designator is valid and refers to a subobject, we're not pointing
7950 // past the end.
7951 if (!LV.getLValueDesignator().Invalid &&
7952 !LV.getLValueDesignator().isOnePastTheEnd())
7953 return false;
7954
David Majnemerc378ca52015-08-29 08:32:55 +00007955 // A pointer to an incomplete type might be past-the-end if the type's size is
7956 // zero. We cannot tell because the type is incomplete.
7957 QualType Ty = getType(LV.getLValueBase());
7958 if (Ty->isIncompleteType())
7959 return true;
7960
Richard Smithd20f1e62014-10-21 23:01:04 +00007961 // We're a past-the-end pointer if we point to the byte after the object,
7962 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007963 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007964 return LV.getLValueOffset() == Size;
7965}
7966
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007967namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007968
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007969/// \brief Data recursive integer evaluator of certain binary operators.
7970///
7971/// We use a data recursive algorithm for binary operators so that we are able
7972/// to handle extreme cases of chained binary operators without causing stack
7973/// overflow.
7974class DataRecursiveIntBinOpEvaluator {
7975 struct EvalResult {
7976 APValue Val;
7977 bool Failed;
7978
7979 EvalResult() : Failed(false) { }
7980
7981 void swap(EvalResult &RHS) {
7982 Val.swap(RHS.Val);
7983 Failed = RHS.Failed;
7984 RHS.Failed = false;
7985 }
7986 };
7987
7988 struct Job {
7989 const Expr *E;
7990 EvalResult LHSResult; // meaningful only for binary operator expression.
7991 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007992
David Blaikie73726062015-08-12 23:09:24 +00007993 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007994 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007995
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007996 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007997 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007998 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007999
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008000 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008001 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008002 };
8003
8004 SmallVector<Job, 16> Queue;
8005
8006 IntExprEvaluator &IntEval;
8007 EvalInfo &Info;
8008 APValue &FinalResult;
8009
8010public:
8011 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8012 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8013
8014 /// \brief True if \param E is a binary operator that we are going to handle
8015 /// data recursively.
8016 /// We handle binary operators that are comma, logical, or that have operands
8017 /// with integral or enumeration type.
8018 static bool shouldEnqueue(const BinaryOperator *E) {
8019 return E->getOpcode() == BO_Comma ||
8020 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008021 (E->isRValue() &&
8022 E->getType()->isIntegralOrEnumerationType() &&
8023 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008024 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008025 }
8026
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008027 bool Traverse(const BinaryOperator *E) {
8028 enqueue(E);
8029 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008030 while (!Queue.empty())
8031 process(PrevResult);
8032
8033 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008034
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008035 FinalResult.swap(PrevResult.Val);
8036 return true;
8037 }
8038
8039private:
8040 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8041 return IntEval.Success(Value, E, Result);
8042 }
8043 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8044 return IntEval.Success(Value, E, Result);
8045 }
8046 bool Error(const Expr *E) {
8047 return IntEval.Error(E);
8048 }
8049 bool Error(const Expr *E, diag::kind D) {
8050 return IntEval.Error(E, D);
8051 }
8052
8053 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8054 return Info.CCEDiag(E, D);
8055 }
8056
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008057 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8058 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008059 bool &SuppressRHSDiags);
8060
8061 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8062 const BinaryOperator *E, APValue &Result);
8063
8064 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8065 Result.Failed = !Evaluate(Result.Val, Info, E);
8066 if (Result.Failed)
8067 Result.Val = APValue();
8068 }
8069
Richard Trieuba4d0872012-03-21 23:30:30 +00008070 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008071
8072 void enqueue(const Expr *E) {
8073 E = E->IgnoreParens();
8074 Queue.resize(Queue.size()+1);
8075 Queue.back().E = E;
8076 Queue.back().Kind = Job::AnyExprKind;
8077 }
8078};
8079
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008080}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008081
8082bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008083 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008084 bool &SuppressRHSDiags) {
8085 if (E->getOpcode() == BO_Comma) {
8086 // Ignore LHS but note if we could not evaluate it.
8087 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008088 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008089 return true;
8090 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008091
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008092 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008093 bool LHSAsBool;
8094 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008095 // We were able to evaluate the LHS, see if we can get away with not
8096 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008097 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8098 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008099 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008100 }
8101 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008102 LHSResult.Failed = true;
8103
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008104 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008105 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008106 if (!Info.noteSideEffect())
8107 return false;
8108
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008109 // We can't evaluate the LHS; however, sometimes the result
8110 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8111 // Don't ignore RHS and suppress diagnostics from this arm.
8112 SuppressRHSDiags = true;
8113 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008114
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008115 return true;
8116 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008117
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008118 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8119 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008120
George Burgess IVa145e252016-05-25 22:38:36 +00008121 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008122 return false; // Ignore RHS;
8123
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008124 return true;
8125}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008126
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008127static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8128 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008129 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8130 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8131 // offsets.
8132 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8133 CharUnits &Offset = LVal.getLValueOffset();
8134 uint64_t Offset64 = Offset.getQuantity();
8135 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8136 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8137 : Offset64 + Index64);
8138}
8139
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008140bool DataRecursiveIntBinOpEvaluator::
8141 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8142 const BinaryOperator *E, APValue &Result) {
8143 if (E->getOpcode() == BO_Comma) {
8144 if (RHSResult.Failed)
8145 return false;
8146 Result = RHSResult.Val;
8147 return true;
8148 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008149
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008150 if (E->isLogicalOp()) {
8151 bool lhsResult, rhsResult;
8152 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8153 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008154
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008155 if (LHSIsOK) {
8156 if (RHSIsOK) {
8157 if (E->getOpcode() == BO_LOr)
8158 return Success(lhsResult || rhsResult, E, Result);
8159 else
8160 return Success(lhsResult && rhsResult, E, Result);
8161 }
8162 } else {
8163 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008164 // We can't evaluate the LHS; however, sometimes the result
8165 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8166 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008167 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008168 }
8169 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008170
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008171 return false;
8172 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008173
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008174 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8175 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008176
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008177 if (LHSResult.Failed || RHSResult.Failed)
8178 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008179
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008180 const APValue &LHSVal = LHSResult.Val;
8181 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008182
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008183 // Handle cases like (unsigned long)&a + 4.
8184 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8185 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008186 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008187 return true;
8188 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008189
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008190 // Handle cases like 4 + (unsigned long)&a
8191 if (E->getOpcode() == BO_Add &&
8192 RHSVal.isLValue() && LHSVal.isInt()) {
8193 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008194 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008195 return true;
8196 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008197
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008198 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8199 // Handle (intptr_t)&&A - (intptr_t)&&B.
8200 if (!LHSVal.getLValueOffset().isZero() ||
8201 !RHSVal.getLValueOffset().isZero())
8202 return false;
8203 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8204 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8205 if (!LHSExpr || !RHSExpr)
8206 return false;
8207 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8208 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8209 if (!LHSAddrExpr || !RHSAddrExpr)
8210 return false;
8211 // Make sure both labels come from the same function.
8212 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8213 RHSAddrExpr->getLabel()->getDeclContext())
8214 return false;
8215 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8216 return true;
8217 }
Richard Smith43e77732013-05-07 04:50:00 +00008218
8219 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008220 if (!LHSVal.isInt() || !RHSVal.isInt())
8221 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008222
8223 // Set up the width and signedness manually, in case it can't be deduced
8224 // from the operation we're performing.
8225 // FIXME: Don't do this in the cases where we can deduce it.
8226 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8227 E->getType()->isUnsignedIntegerOrEnumerationType());
8228 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8229 RHSVal.getInt(), Value))
8230 return false;
8231 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008232}
8233
Richard Trieuba4d0872012-03-21 23:30:30 +00008234void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008235 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008236
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008237 switch (job.Kind) {
8238 case Job::AnyExprKind: {
8239 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8240 if (shouldEnqueue(Bop)) {
8241 job.Kind = Job::BinOpKind;
8242 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008243 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008244 }
8245 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008246
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008247 EvaluateExpr(job.E, Result);
8248 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008249 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008250 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008251
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008252 case Job::BinOpKind: {
8253 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008254 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008255 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008256 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008257 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008258 }
8259 if (SuppressRHSDiags)
8260 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008261 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008262 job.Kind = Job::BinOpVisitedLHSKind;
8263 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008264 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008265 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008266
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008267 case Job::BinOpVisitedLHSKind: {
8268 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8269 EvalResult RHS;
8270 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008271 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008272 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008273 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008274 }
8275 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008276
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008277 llvm_unreachable("Invalid Job::Kind!");
8278}
8279
George Burgess IV8c892b52016-05-25 22:31:54 +00008280namespace {
8281/// Used when we determine that we should fail, but can keep evaluating prior to
8282/// noting that we had a failure.
8283class DelayedNoteFailureRAII {
8284 EvalInfo &Info;
8285 bool NoteFailure;
8286
8287public:
8288 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8289 : Info(Info), NoteFailure(NoteFailure) {}
8290 ~DelayedNoteFailureRAII() {
8291 if (NoteFailure) {
8292 bool ContinueAfterFailure = Info.noteFailure();
8293 (void)ContinueAfterFailure;
8294 assert(ContinueAfterFailure &&
8295 "Shouldn't have kept evaluating on failure.");
8296 }
8297 }
8298};
8299}
8300
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008301bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008302 // We don't call noteFailure immediately because the assignment happens after
8303 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008304 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008305 return Error(E);
8306
George Burgess IV8c892b52016-05-25 22:31:54 +00008307 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008308 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8309 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008310
Anders Carlssonacc79812008-11-16 07:17:21 +00008311 QualType LHSTy = E->getLHS()->getType();
8312 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008313
Chandler Carruthb29a7432014-10-11 11:03:30 +00008314 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008315 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008316 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008317 if (E->isAssignmentOp()) {
8318 LValue LV;
8319 EvaluateLValue(E->getLHS(), LV, Info);
8320 LHSOK = false;
8321 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008322 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8323 if (LHSOK) {
8324 LHS.makeComplexFloat();
8325 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8326 }
8327 } else {
8328 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8329 }
George Burgess IVa145e252016-05-25 22:38:36 +00008330 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008331 return false;
8332
Chandler Carruthb29a7432014-10-11 11:03:30 +00008333 if (E->getRHS()->getType()->isRealFloatingType()) {
8334 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8335 return false;
8336 RHS.makeComplexFloat();
8337 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8338 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008339 return false;
8340
8341 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008342 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008343 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008344 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008345 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8346
John McCalle3027922010-08-25 11:45:40 +00008347 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008348 return Success((CR_r == APFloat::cmpEqual &&
8349 CR_i == APFloat::cmpEqual), E);
8350 else {
John McCalle3027922010-08-25 11:45:40 +00008351 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008352 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008353 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008354 CR_r == APFloat::cmpLessThan ||
8355 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008356 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008357 CR_i == APFloat::cmpLessThan ||
8358 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008359 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008360 } else {
John McCalle3027922010-08-25 11:45:40 +00008361 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008362 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8363 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8364 else {
John McCalle3027922010-08-25 11:45:40 +00008365 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008366 "Invalid compex comparison.");
8367 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8368 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8369 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008370 }
8371 }
Mike Stump11289f42009-09-09 15:08:12 +00008372
Anders Carlssonacc79812008-11-16 07:17:21 +00008373 if (LHSTy->isRealFloatingType() &&
8374 RHSTy->isRealFloatingType()) {
8375 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008376
Richard Smith253c2a32012-01-27 01:14:48 +00008377 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008378 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008379 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008380
Richard Smith253c2a32012-01-27 01:14:48 +00008381 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008382 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008383
Anders Carlssonacc79812008-11-16 07:17:21 +00008384 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008385
Anders Carlssonacc79812008-11-16 07:17:21 +00008386 switch (E->getOpcode()) {
8387 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008388 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008389 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008390 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008391 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008392 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008393 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008394 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008395 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008396 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008397 E);
John McCalle3027922010-08-25 11:45:40 +00008398 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008399 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008400 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008401 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008402 || CR == APFloat::cmpLessThan
8403 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008404 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008405 }
Mike Stump11289f42009-09-09 15:08:12 +00008406
Eli Friedmana38da572009-04-28 19:17:36 +00008407 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008408 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008409 LValue LHSValue, RHSValue;
8410
8411 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008412 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008413 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008414
Richard Smith253c2a32012-01-27 01:14:48 +00008415 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008416 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008417
Richard Smith8b3497e2011-10-31 01:37:14 +00008418 // Reject differing bases from the normal codepath; we special-case
8419 // comparisons to null.
8420 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008421 if (E->getOpcode() == BO_Sub) {
8422 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008423 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008424 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008425 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008426 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008427 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008428 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008429 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8430 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8431 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008432 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008433 // Make sure both labels come from the same function.
8434 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8435 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008436 return Error(E);
8437 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008438 }
Richard Smith83c68212011-10-31 05:11:32 +00008439 // Inequalities and subtractions between unrelated pointers have
8440 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008441 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008442 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008443 // A constant address may compare equal to the address of a symbol.
8444 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008445 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008446 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8447 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008448 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008449 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008450 // distinct addresses. In clang, the result of such a comparison is
8451 // unspecified, so it is not a constant expression. However, we do know
8452 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008453 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8454 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008455 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008456 // We can't tell whether weak symbols will end up pointing to the same
8457 // object.
8458 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008459 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008460 // We can't compare the address of the start of one object with the
8461 // past-the-end address of another object, per C++ DR1652.
8462 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8463 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8464 (RHSValue.Base && RHSValue.Offset.isZero() &&
8465 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8466 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008467 // We can't tell whether an object is at the same address as another
8468 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008469 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8470 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008471 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008472 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008473 // (Note that clang defaults to -fmerge-all-constants, which can
8474 // lead to inconsistent results for comparisons involving the address
8475 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008476 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008477 }
Eli Friedman64004332009-03-23 04:38:34 +00008478
Richard Smith1b470412012-02-01 08:10:20 +00008479 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8480 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8481
Richard Smith84f6dcf2012-02-02 01:16:57 +00008482 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8483 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8484
John McCalle3027922010-08-25 11:45:40 +00008485 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008486 // C++11 [expr.add]p6:
8487 // Unless both pointers point to elements of the same array object, or
8488 // one past the last element of the array object, the behavior is
8489 // undefined.
8490 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8491 !AreElementsOfSameArray(getType(LHSValue.Base),
8492 LHSDesignator, RHSDesignator))
8493 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8494
Chris Lattner882bdf22010-04-20 17:13:14 +00008495 QualType Type = E->getLHS()->getType();
8496 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008497
Richard Smithd62306a2011-11-10 06:34:14 +00008498 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008499 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008500 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008501
Richard Smith84c6b3d2013-09-10 21:34:14 +00008502 // As an extension, a type may have zero size (empty struct or union in
8503 // C, array of zero length). Pointer subtraction in such cases has
8504 // undefined behavior, so is not constant.
8505 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008506 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008507 << ElementType;
8508 return false;
8509 }
8510
Richard Smith1b470412012-02-01 08:10:20 +00008511 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8512 // and produce incorrect results when it overflows. Such behavior
8513 // appears to be non-conforming, but is common, so perhaps we should
8514 // assume the standard intended for such cases to be undefined behavior
8515 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008516
Richard Smith1b470412012-02-01 08:10:20 +00008517 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8518 // overflow in the final conversion to ptrdiff_t.
8519 APSInt LHS(
8520 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8521 APSInt RHS(
8522 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8523 APSInt ElemSize(
8524 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8525 APSInt TrueResult = (LHS - RHS) / ElemSize;
8526 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8527
Richard Smith0c6124b2015-12-03 01:36:22 +00008528 if (Result.extend(65) != TrueResult &&
8529 !HandleOverflow(Info, E, TrueResult, E->getType()))
8530 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008531 return Success(Result, E);
8532 }
Richard Smithde21b242012-01-31 06:41:30 +00008533
8534 // C++11 [expr.rel]p3:
8535 // Pointers to void (after pointer conversions) can be compared, with a
8536 // result defined as follows: If both pointers represent the same
8537 // address or are both the null pointer value, the result is true if the
8538 // operator is <= or >= and false otherwise; otherwise the result is
8539 // unspecified.
8540 // We interpret this as applying to pointers to *cv* void.
8541 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008542 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008543 CCEDiag(E, diag::note_constexpr_void_comparison);
8544
Richard Smith84f6dcf2012-02-02 01:16:57 +00008545 // C++11 [expr.rel]p2:
8546 // - If two pointers point to non-static data members of the same object,
8547 // or to subobjects or array elements fo such members, recursively, the
8548 // pointer to the later declared member compares greater provided the
8549 // two members have the same access control and provided their class is
8550 // not a union.
8551 // [...]
8552 // - Otherwise pointer comparisons are unspecified.
8553 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8554 E->isRelationalOp()) {
8555 bool WasArrayIndex;
8556 unsigned Mismatch =
8557 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8558 RHSDesignator, WasArrayIndex);
8559 // At the point where the designators diverge, the comparison has a
8560 // specified value if:
8561 // - we are comparing array indices
8562 // - we are comparing fields of a union, or fields with the same access
8563 // Otherwise, the result is unspecified and thus the comparison is not a
8564 // constant expression.
8565 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8566 Mismatch < RHSDesignator.Entries.size()) {
8567 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8568 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8569 if (!LF && !RF)
8570 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8571 else if (!LF)
8572 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8573 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8574 << RF->getParent() << RF;
8575 else if (!RF)
8576 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8577 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8578 << LF->getParent() << LF;
8579 else if (!LF->getParent()->isUnion() &&
8580 LF->getAccess() != RF->getAccess())
8581 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8582 << LF << LF->getAccess() << RF << RF->getAccess()
8583 << LF->getParent();
8584 }
8585 }
8586
Eli Friedman6c31cb42012-04-16 04:30:08 +00008587 // The comparison here must be unsigned, and performed with the same
8588 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008589 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8590 uint64_t CompareLHS = LHSOffset.getQuantity();
8591 uint64_t CompareRHS = RHSOffset.getQuantity();
8592 assert(PtrSize <= 64 && "Unexpected pointer width");
8593 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8594 CompareLHS &= Mask;
8595 CompareRHS &= Mask;
8596
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008597 // If there is a base and this is a relational operator, we can only
8598 // compare pointers within the object in question; otherwise, the result
8599 // depends on where the object is located in memory.
8600 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8601 QualType BaseTy = getType(LHSValue.Base);
8602 if (BaseTy->isIncompleteType())
8603 return Error(E);
8604 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8605 uint64_t OffsetLimit = Size.getQuantity();
8606 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8607 return Error(E);
8608 }
8609
Richard Smith8b3497e2011-10-31 01:37:14 +00008610 switch (E->getOpcode()) {
8611 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008612 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8613 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8614 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8615 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8616 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8617 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008618 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008619 }
8620 }
Richard Smith7bb00672012-02-01 01:42:44 +00008621
8622 if (LHSTy->isMemberPointerType()) {
8623 assert(E->isEqualityOp() && "unexpected member pointer operation");
8624 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8625
8626 MemberPtr LHSValue, RHSValue;
8627
8628 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008629 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008630 return false;
8631
8632 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8633 return false;
8634
8635 // C++11 [expr.eq]p2:
8636 // If both operands are null, they compare equal. Otherwise if only one is
8637 // null, they compare unequal.
8638 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8639 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8640 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8641 }
8642
8643 // Otherwise if either is a pointer to a virtual member function, the
8644 // result is unspecified.
8645 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8646 if (MD->isVirtual())
8647 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8648 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8649 if (MD->isVirtual())
8650 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8651
8652 // Otherwise they compare equal if and only if they would refer to the
8653 // same member of the same most derived object or the same subobject if
8654 // they were dereferenced with a hypothetical object of the associated
8655 // class type.
8656 bool Equal = LHSValue == RHSValue;
8657 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8658 }
8659
Richard Smithab44d9b2012-02-14 22:35:28 +00008660 if (LHSTy->isNullPtrType()) {
8661 assert(E->isComparisonOp() && "unexpected nullptr operation");
8662 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8663 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8664 // are compared, the result is true of the operator is <=, >= or ==, and
8665 // false otherwise.
8666 BinaryOperator::Opcode Opcode = E->getOpcode();
8667 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8668 }
8669
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008670 assert((!LHSTy->isIntegralOrEnumerationType() ||
8671 !RHSTy->isIntegralOrEnumerationType()) &&
8672 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8673 // We can't continue from here for non-integral types.
8674 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008675}
8676
Peter Collingbournee190dee2011-03-11 19:24:49 +00008677/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8678/// a result as the expression's type.
8679bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8680 const UnaryExprOrTypeTraitExpr *E) {
8681 switch(E->getKind()) {
8682 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008683 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008684 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008685 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008686 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008687 }
Eli Friedman64004332009-03-23 04:38:34 +00008688
Peter Collingbournee190dee2011-03-11 19:24:49 +00008689 case UETT_VecStep: {
8690 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008691
Peter Collingbournee190dee2011-03-11 19:24:49 +00008692 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008693 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008694
Peter Collingbournee190dee2011-03-11 19:24:49 +00008695 // The vec_step built-in functions that take a 3-component
8696 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8697 if (n == 3)
8698 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008699
Peter Collingbournee190dee2011-03-11 19:24:49 +00008700 return Success(n, E);
8701 } else
8702 return Success(1, E);
8703 }
8704
8705 case UETT_SizeOf: {
8706 QualType SrcTy = E->getTypeOfArgument();
8707 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8708 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008709 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8710 SrcTy = Ref->getPointeeType();
8711
Richard Smithd62306a2011-11-10 06:34:14 +00008712 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008713 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008714 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008715 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008716 }
Alexey Bataev00396512015-07-02 03:40:19 +00008717 case UETT_OpenMPRequiredSimdAlign:
8718 assert(E->isArgumentType());
8719 return Success(
8720 Info.Ctx.toCharUnitsFromBits(
8721 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8722 .getQuantity(),
8723 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008724 }
8725
8726 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008727}
8728
Peter Collingbournee9200682011-05-13 03:29:01 +00008729bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008730 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008731 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008732 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008733 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008734 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008735 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008736 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008737 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008738 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008739 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008740 APSInt IdxResult;
8741 if (!EvaluateInteger(Idx, IdxResult, Info))
8742 return false;
8743 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8744 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008745 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008746 CurrentType = AT->getElementType();
8747 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8748 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008749 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008750 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008751
James Y Knight7281c352015-12-29 22:31:18 +00008752 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008753 FieldDecl *MemberDecl = ON.getField();
8754 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008755 if (!RT)
8756 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008757 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008758 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008759 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008760 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008761 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008762 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008763 CurrentType = MemberDecl->getType().getNonReferenceType();
8764 break;
8765 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008766
James Y Knight7281c352015-12-29 22:31:18 +00008767 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008768 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008769
James Y Knight7281c352015-12-29 22:31:18 +00008770 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008771 CXXBaseSpecifier *BaseSpec = ON.getBase();
8772 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008773 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008774
8775 // Find the layout of the class whose base we are looking into.
8776 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008777 if (!RT)
8778 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008779 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008780 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008781 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8782
8783 // Find the base class itself.
8784 CurrentType = BaseSpec->getType();
8785 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8786 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008787 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008788
Douglas Gregord1702062010-04-29 00:18:15 +00008789 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008790 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008791 break;
8792 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008793 }
8794 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008795 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008796}
8797
Chris Lattnere13042c2008-07-11 19:10:17 +00008798bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008799 switch (E->getOpcode()) {
8800 default:
8801 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8802 // See C99 6.6p3.
8803 return Error(E);
8804 case UO_Extension:
8805 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8806 // If so, we could clear the diagnostic ID.
8807 return Visit(E->getSubExpr());
8808 case UO_Plus:
8809 // The result is just the value.
8810 return Visit(E->getSubExpr());
8811 case UO_Minus: {
8812 if (!Visit(E->getSubExpr()))
8813 return false;
8814 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008815 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008816 if (Value.isSigned() && Value.isMinSignedValue() &&
8817 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8818 E->getType()))
8819 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008820 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008821 }
8822 case UO_Not: {
8823 if (!Visit(E->getSubExpr()))
8824 return false;
8825 if (!Result.isInt()) return Error(E);
8826 return Success(~Result.getInt(), E);
8827 }
8828 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008829 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008830 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008831 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008832 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008833 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008834 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008835}
Mike Stump11289f42009-09-09 15:08:12 +00008836
Chris Lattner477c4be2008-07-12 01:15:53 +00008837/// HandleCast - This is used to evaluate implicit or explicit casts where the
8838/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008839bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8840 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008841 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008842 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008843
Eli Friedmanc757de22011-03-25 00:43:55 +00008844 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008845 case CK_BaseToDerived:
8846 case CK_DerivedToBase:
8847 case CK_UncheckedDerivedToBase:
8848 case CK_Dynamic:
8849 case CK_ToUnion:
8850 case CK_ArrayToPointerDecay:
8851 case CK_FunctionToPointerDecay:
8852 case CK_NullToPointer:
8853 case CK_NullToMemberPointer:
8854 case CK_BaseToDerivedMemberPointer:
8855 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008856 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008857 case CK_ConstructorConversion:
8858 case CK_IntegralToPointer:
8859 case CK_ToVoid:
8860 case CK_VectorSplat:
8861 case CK_IntegralToFloating:
8862 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008863 case CK_CPointerToObjCPointerCast:
8864 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008865 case CK_AnyPointerToBlockPointerCast:
8866 case CK_ObjCObjectLValueCast:
8867 case CK_FloatingRealToComplex:
8868 case CK_FloatingComplexToReal:
8869 case CK_FloatingComplexCast:
8870 case CK_FloatingComplexToIntegralComplex:
8871 case CK_IntegralRealToComplex:
8872 case CK_IntegralComplexCast:
8873 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008874 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008875 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008876 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008877 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008878 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008879 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008880 llvm_unreachable("invalid cast kind for integral value");
8881
Eli Friedman9faf2f92011-03-25 19:07:11 +00008882 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008883 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008884 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008885 case CK_ARCProduceObject:
8886 case CK_ARCConsumeObject:
8887 case CK_ARCReclaimReturnedObject:
8888 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008889 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008890 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008891
Richard Smith4ef685b2012-01-17 21:17:26 +00008892 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008893 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008894 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008895 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008896 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008897
8898 case CK_MemberPointerToBoolean:
8899 case CK_PointerToBoolean:
8900 case CK_IntegralToBoolean:
8901 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008902 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008903 case CK_FloatingComplexToBoolean:
8904 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008905 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008906 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008907 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008908 uint64_t IntResult = BoolResult;
8909 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8910 IntResult = (uint64_t)-1;
8911 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008912 }
8913
Eli Friedmanc757de22011-03-25 00:43:55 +00008914 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008915 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008916 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008917
Eli Friedman742421e2009-02-20 01:15:07 +00008918 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008919 // Allow casts of address-of-label differences if they are no-ops
8920 // or narrowing. (The narrowing case isn't actually guaranteed to
8921 // be constant-evaluatable except in some narrow cases which are hard
8922 // to detect here. We let it through on the assumption the user knows
8923 // what they are doing.)
8924 if (Result.isAddrLabelDiff())
8925 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008926 // Only allow casts of lvalues if they are lossless.
8927 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8928 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008929
Richard Smith911e1422012-01-30 22:27:01 +00008930 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8931 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008932 }
Mike Stump11289f42009-09-09 15:08:12 +00008933
Eli Friedmanc757de22011-03-25 00:43:55 +00008934 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008935 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8936
John McCall45d55e42010-05-07 21:00:08 +00008937 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008938 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008939 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008940
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008941 if (LV.getLValueBase()) {
8942 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008943 // FIXME: Allow a larger integer size than the pointer size, and allow
8944 // narrowing back down to pointer width in subsequent integral casts.
8945 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008946 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008947 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008948
Richard Smithcf74da72011-11-16 07:18:12 +00008949 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008950 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008951 return true;
8952 }
8953
Yaxun Liu402804b2016-12-15 08:09:08 +00008954 uint64_t V;
8955 if (LV.isNullPointer())
8956 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8957 else
8958 V = LV.getLValueOffset().getQuantity();
8959
8960 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008961 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008962 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008963
Eli Friedmanc757de22011-03-25 00:43:55 +00008964 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008965 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008966 if (!EvaluateComplex(SubExpr, C, Info))
8967 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008968 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008969 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008970
Eli Friedmanc757de22011-03-25 00:43:55 +00008971 case CK_FloatingToIntegral: {
8972 APFloat F(0.0);
8973 if (!EvaluateFloat(SubExpr, F, Info))
8974 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008975
Richard Smith357362d2011-12-13 06:39:58 +00008976 APSInt Value;
8977 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8978 return false;
8979 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008980 }
8981 }
Mike Stump11289f42009-09-09 15:08:12 +00008982
Eli Friedmanc757de22011-03-25 00:43:55 +00008983 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008984}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008985
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008986bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8987 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008988 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008989 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8990 return false;
8991 if (!LV.isComplexInt())
8992 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008993 return Success(LV.getComplexIntReal(), E);
8994 }
8995
8996 return Visit(E->getSubExpr());
8997}
8998
Eli Friedman4e7a2412009-02-27 04:45:43 +00008999bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009000 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009001 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009002 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9003 return false;
9004 if (!LV.isComplexInt())
9005 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009006 return Success(LV.getComplexIntImag(), E);
9007 }
9008
Richard Smith4a678122011-10-24 18:44:57 +00009009 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009010 return Success(0, E);
9011}
9012
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009013bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9014 return Success(E->getPackLength(), E);
9015}
9016
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009017bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9018 return Success(E->getValue(), E);
9019}
9020
Chris Lattner05706e882008-07-11 18:11:29 +00009021//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009022// Float Evaluation
9023//===----------------------------------------------------------------------===//
9024
9025namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009026class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009027 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009028 APFloat &Result;
9029public:
9030 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009031 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009032
Richard Smith2e312c82012-03-03 22:46:17 +00009033 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009034 Result = V.getFloat();
9035 return true;
9036 }
Eli Friedman24c01542008-08-22 00:06:13 +00009037
Richard Smithfddd3842011-12-30 21:15:51 +00009038 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009039 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9040 return true;
9041 }
9042
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009043 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009044
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009045 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009046 bool VisitBinaryOperator(const BinaryOperator *E);
9047 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009048 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009049
John McCallb1fb0d32010-05-07 22:08:54 +00009050 bool VisitUnaryReal(const UnaryOperator *E);
9051 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009052
Richard Smithfddd3842011-12-30 21:15:51 +00009053 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009054};
9055} // end anonymous namespace
9056
9057static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009058 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009059 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009060}
9061
Jay Foad39c79802011-01-12 09:06:06 +00009062static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009063 QualType ResultTy,
9064 const Expr *Arg,
9065 bool SNaN,
9066 llvm::APFloat &Result) {
9067 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9068 if (!S) return false;
9069
9070 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9071
9072 llvm::APInt fill;
9073
9074 // Treat empty strings as if they were zero.
9075 if (S->getString().empty())
9076 fill = llvm::APInt(32, 0);
9077 else if (S->getString().getAsInteger(0, fill))
9078 return false;
9079
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009080 if (Context.getTargetInfo().isNan2008()) {
9081 if (SNaN)
9082 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9083 else
9084 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9085 } else {
9086 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9087 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9088 // a different encoding to what became a standard in 2008, and for pre-
9089 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9090 // sNaN. This is now known as "legacy NaN" encoding.
9091 if (SNaN)
9092 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9093 else
9094 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9095 }
9096
John McCall16291492010-02-28 13:00:19 +00009097 return true;
9098}
9099
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009100bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009101 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009102 default:
9103 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9104
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009105 case Builtin::BI__builtin_huge_val:
9106 case Builtin::BI__builtin_huge_valf:
9107 case Builtin::BI__builtin_huge_vall:
9108 case Builtin::BI__builtin_inf:
9109 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009110 case Builtin::BI__builtin_infl: {
9111 const llvm::fltSemantics &Sem =
9112 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009113 Result = llvm::APFloat::getInf(Sem);
9114 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009115 }
Mike Stump11289f42009-09-09 15:08:12 +00009116
John McCall16291492010-02-28 13:00:19 +00009117 case Builtin::BI__builtin_nans:
9118 case Builtin::BI__builtin_nansf:
9119 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009120 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9121 true, Result))
9122 return Error(E);
9123 return true;
John McCall16291492010-02-28 13:00:19 +00009124
Chris Lattner0b7282e2008-10-06 06:31:58 +00009125 case Builtin::BI__builtin_nan:
9126 case Builtin::BI__builtin_nanf:
9127 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00009128 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009129 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009130 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9131 false, Result))
9132 return Error(E);
9133 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009134
9135 case Builtin::BI__builtin_fabs:
9136 case Builtin::BI__builtin_fabsf:
9137 case Builtin::BI__builtin_fabsl:
9138 if (!EvaluateFloat(E->getArg(0), Result, Info))
9139 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009140
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009141 if (Result.isNegative())
9142 Result.changeSign();
9143 return true;
9144
Richard Smith8889a3d2013-06-13 06:26:32 +00009145 // FIXME: Builtin::BI__builtin_powi
9146 // FIXME: Builtin::BI__builtin_powif
9147 // FIXME: Builtin::BI__builtin_powil
9148
Mike Stump11289f42009-09-09 15:08:12 +00009149 case Builtin::BI__builtin_copysign:
9150 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009151 case Builtin::BI__builtin_copysignl: {
9152 APFloat RHS(0.);
9153 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9154 !EvaluateFloat(E->getArg(1), RHS, Info))
9155 return false;
9156 Result.copySign(RHS);
9157 return true;
9158 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009159 }
9160}
9161
John McCallb1fb0d32010-05-07 22:08:54 +00009162bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009163 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9164 ComplexValue CV;
9165 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9166 return false;
9167 Result = CV.FloatReal;
9168 return true;
9169 }
9170
9171 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009172}
9173
9174bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009175 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9176 ComplexValue CV;
9177 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9178 return false;
9179 Result = CV.FloatImag;
9180 return true;
9181 }
9182
Richard Smith4a678122011-10-24 18:44:57 +00009183 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009184 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9185 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009186 return true;
9187}
9188
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009189bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009190 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009191 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009192 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009193 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009194 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009195 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9196 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009197 Result.changeSign();
9198 return true;
9199 }
9200}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009201
Eli Friedman24c01542008-08-22 00:06:13 +00009202bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009203 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9204 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009205
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009206 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009207 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009208 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009209 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009210 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9211 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009212}
9213
9214bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9215 Result = E->getValue();
9216 return true;
9217}
9218
Peter Collingbournee9200682011-05-13 03:29:01 +00009219bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9220 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009221
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009222 switch (E->getCastKind()) {
9223 default:
Richard Smith11562c52011-10-28 17:51:58 +00009224 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009225
9226 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009227 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009228 return EvaluateInteger(SubExpr, IntResult, Info) &&
9229 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9230 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009231 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009232
9233 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009234 if (!Visit(SubExpr))
9235 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009236 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9237 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009238 }
John McCalld7646252010-11-14 08:17:51 +00009239
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009240 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009241 ComplexValue V;
9242 if (!EvaluateComplex(SubExpr, V, Info))
9243 return false;
9244 Result = V.getComplexFloatReal();
9245 return true;
9246 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009247 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009248}
9249
Eli Friedman24c01542008-08-22 00:06:13 +00009250//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009251// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009252//===----------------------------------------------------------------------===//
9253
9254namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009255class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009256 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009257 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009258
Anders Carlsson537969c2008-11-16 20:27:53 +00009259public:
John McCall93d91dc2010-05-07 17:22:02 +00009260 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009261 : ExprEvaluatorBaseTy(info), Result(Result) {}
9262
Richard Smith2e312c82012-03-03 22:46:17 +00009263 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009264 Result.setFrom(V);
9265 return true;
9266 }
Mike Stump11289f42009-09-09 15:08:12 +00009267
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009268 bool ZeroInitialization(const Expr *E);
9269
Anders Carlsson537969c2008-11-16 20:27:53 +00009270 //===--------------------------------------------------------------------===//
9271 // Visitor Methods
9272 //===--------------------------------------------------------------------===//
9273
Peter Collingbournee9200682011-05-13 03:29:01 +00009274 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009275 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009276 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009277 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009278 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009279};
9280} // end anonymous namespace
9281
John McCall93d91dc2010-05-07 17:22:02 +00009282static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9283 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009284 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009285 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009286}
9287
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009288bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009289 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009290 if (ElemTy->isRealFloatingType()) {
9291 Result.makeComplexFloat();
9292 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9293 Result.FloatReal = Zero;
9294 Result.FloatImag = Zero;
9295 } else {
9296 Result.makeComplexInt();
9297 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9298 Result.IntReal = Zero;
9299 Result.IntImag = Zero;
9300 }
9301 return true;
9302}
9303
Peter Collingbournee9200682011-05-13 03:29:01 +00009304bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9305 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009306
9307 if (SubExpr->getType()->isRealFloatingType()) {
9308 Result.makeComplexFloat();
9309 APFloat &Imag = Result.FloatImag;
9310 if (!EvaluateFloat(SubExpr, Imag, Info))
9311 return false;
9312
9313 Result.FloatReal = APFloat(Imag.getSemantics());
9314 return true;
9315 } else {
9316 assert(SubExpr->getType()->isIntegerType() &&
9317 "Unexpected imaginary literal.");
9318
9319 Result.makeComplexInt();
9320 APSInt &Imag = Result.IntImag;
9321 if (!EvaluateInteger(SubExpr, Imag, Info))
9322 return false;
9323
9324 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9325 return true;
9326 }
9327}
9328
Peter Collingbournee9200682011-05-13 03:29:01 +00009329bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009330
John McCallfcef3cf2010-12-14 17:51:41 +00009331 switch (E->getCastKind()) {
9332 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009333 case CK_BaseToDerived:
9334 case CK_DerivedToBase:
9335 case CK_UncheckedDerivedToBase:
9336 case CK_Dynamic:
9337 case CK_ToUnion:
9338 case CK_ArrayToPointerDecay:
9339 case CK_FunctionToPointerDecay:
9340 case CK_NullToPointer:
9341 case CK_NullToMemberPointer:
9342 case CK_BaseToDerivedMemberPointer:
9343 case CK_DerivedToBaseMemberPointer:
9344 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009345 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009346 case CK_ConstructorConversion:
9347 case CK_IntegralToPointer:
9348 case CK_PointerToIntegral:
9349 case CK_PointerToBoolean:
9350 case CK_ToVoid:
9351 case CK_VectorSplat:
9352 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009353 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009354 case CK_IntegralToBoolean:
9355 case CK_IntegralToFloating:
9356 case CK_FloatingToIntegral:
9357 case CK_FloatingToBoolean:
9358 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009359 case CK_CPointerToObjCPointerCast:
9360 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009361 case CK_AnyPointerToBlockPointerCast:
9362 case CK_ObjCObjectLValueCast:
9363 case CK_FloatingComplexToReal:
9364 case CK_FloatingComplexToBoolean:
9365 case CK_IntegralComplexToReal:
9366 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009367 case CK_ARCProduceObject:
9368 case CK_ARCConsumeObject:
9369 case CK_ARCReclaimReturnedObject:
9370 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009371 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009372 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009373 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009374 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009375 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009376 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009377 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009378 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009379
John McCallfcef3cf2010-12-14 17:51:41 +00009380 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009381 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009382 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009383 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009384
9385 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009386 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009387 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009388 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009389
9390 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009391 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009392 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009393 return false;
9394
John McCallfcef3cf2010-12-14 17:51:41 +00009395 Result.makeComplexFloat();
9396 Result.FloatImag = APFloat(Real.getSemantics());
9397 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009398 }
9399
John McCallfcef3cf2010-12-14 17:51:41 +00009400 case CK_FloatingComplexCast: {
9401 if (!Visit(E->getSubExpr()))
9402 return false;
9403
9404 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9405 QualType From
9406 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9407
Richard Smith357362d2011-12-13 06:39:58 +00009408 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9409 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009410 }
9411
9412 case CK_FloatingComplexToIntegralComplex: {
9413 if (!Visit(E->getSubExpr()))
9414 return false;
9415
9416 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9417 QualType From
9418 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9419 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009420 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9421 To, Result.IntReal) &&
9422 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9423 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009424 }
9425
9426 case CK_IntegralRealToComplex: {
9427 APSInt &Real = Result.IntReal;
9428 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9429 return false;
9430
9431 Result.makeComplexInt();
9432 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9433 return true;
9434 }
9435
9436 case CK_IntegralComplexCast: {
9437 if (!Visit(E->getSubExpr()))
9438 return false;
9439
9440 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9441 QualType From
9442 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9443
Richard Smith911e1422012-01-30 22:27:01 +00009444 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9445 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009446 return true;
9447 }
9448
9449 case CK_IntegralComplexToFloatingComplex: {
9450 if (!Visit(E->getSubExpr()))
9451 return false;
9452
Ted Kremenek28831752012-08-23 20:46:57 +00009453 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009454 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009455 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009456 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009457 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9458 To, Result.FloatReal) &&
9459 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9460 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009461 }
9462 }
9463
9464 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009465}
9466
John McCall93d91dc2010-05-07 17:22:02 +00009467bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009468 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009469 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9470
Chandler Carrutha216cad2014-10-11 00:57:18 +00009471 // Track whether the LHS or RHS is real at the type system level. When this is
9472 // the case we can simplify our evaluation strategy.
9473 bool LHSReal = false, RHSReal = false;
9474
9475 bool LHSOK;
9476 if (E->getLHS()->getType()->isRealFloatingType()) {
9477 LHSReal = true;
9478 APFloat &Real = Result.FloatReal;
9479 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9480 if (LHSOK) {
9481 Result.makeComplexFloat();
9482 Result.FloatImag = APFloat(Real.getSemantics());
9483 }
9484 } else {
9485 LHSOK = Visit(E->getLHS());
9486 }
George Burgess IVa145e252016-05-25 22:38:36 +00009487 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009488 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009489
John McCall93d91dc2010-05-07 17:22:02 +00009490 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009491 if (E->getRHS()->getType()->isRealFloatingType()) {
9492 RHSReal = true;
9493 APFloat &Real = RHS.FloatReal;
9494 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9495 return false;
9496 RHS.makeComplexFloat();
9497 RHS.FloatImag = APFloat(Real.getSemantics());
9498 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009499 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009500
Chandler Carrutha216cad2014-10-11 00:57:18 +00009501 assert(!(LHSReal && RHSReal) &&
9502 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009503 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009504 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009505 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009506 if (Result.isComplexFloat()) {
9507 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9508 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009509 if (LHSReal)
9510 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9511 else if (!RHSReal)
9512 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9513 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009514 } else {
9515 Result.getComplexIntReal() += RHS.getComplexIntReal();
9516 Result.getComplexIntImag() += RHS.getComplexIntImag();
9517 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009518 break;
John McCalle3027922010-08-25 11:45:40 +00009519 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009520 if (Result.isComplexFloat()) {
9521 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9522 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009523 if (LHSReal) {
9524 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9525 Result.getComplexFloatImag().changeSign();
9526 } else if (!RHSReal) {
9527 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9528 APFloat::rmNearestTiesToEven);
9529 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009530 } else {
9531 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9532 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9533 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009534 break;
John McCalle3027922010-08-25 11:45:40 +00009535 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009536 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009537 // This is an implementation of complex multiplication according to the
9538 // constraints laid out in C11 Annex G. The implemantion uses the
9539 // following naming scheme:
9540 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009541 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009542 APFloat &A = LHS.getComplexFloatReal();
9543 APFloat &B = LHS.getComplexFloatImag();
9544 APFloat &C = RHS.getComplexFloatReal();
9545 APFloat &D = RHS.getComplexFloatImag();
9546 APFloat &ResR = Result.getComplexFloatReal();
9547 APFloat &ResI = Result.getComplexFloatImag();
9548 if (LHSReal) {
9549 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9550 ResR = A * C;
9551 ResI = A * D;
9552 } else if (RHSReal) {
9553 ResR = C * A;
9554 ResI = C * B;
9555 } else {
9556 // In the fully general case, we need to handle NaNs and infinities
9557 // robustly.
9558 APFloat AC = A * C;
9559 APFloat BD = B * D;
9560 APFloat AD = A * D;
9561 APFloat BC = B * C;
9562 ResR = AC - BD;
9563 ResI = AD + BC;
9564 if (ResR.isNaN() && ResI.isNaN()) {
9565 bool Recalc = false;
9566 if (A.isInfinity() || B.isInfinity()) {
9567 A = APFloat::copySign(
9568 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9569 B = APFloat::copySign(
9570 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9571 if (C.isNaN())
9572 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9573 if (D.isNaN())
9574 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9575 Recalc = true;
9576 }
9577 if (C.isInfinity() || D.isInfinity()) {
9578 C = APFloat::copySign(
9579 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9580 D = APFloat::copySign(
9581 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9582 if (A.isNaN())
9583 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9584 if (B.isNaN())
9585 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9586 Recalc = true;
9587 }
9588 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9589 AD.isInfinity() || BC.isInfinity())) {
9590 if (A.isNaN())
9591 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9592 if (B.isNaN())
9593 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9594 if (C.isNaN())
9595 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9596 if (D.isNaN())
9597 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9598 Recalc = true;
9599 }
9600 if (Recalc) {
9601 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9602 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9603 }
9604 }
9605 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009606 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009607 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009608 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009609 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9610 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009611 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009612 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9613 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9614 }
9615 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009616 case BO_Div:
9617 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009618 // This is an implementation of complex division according to the
9619 // constraints laid out in C11 Annex G. The implemantion uses the
9620 // following naming scheme:
9621 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009622 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009623 APFloat &A = LHS.getComplexFloatReal();
9624 APFloat &B = LHS.getComplexFloatImag();
9625 APFloat &C = RHS.getComplexFloatReal();
9626 APFloat &D = RHS.getComplexFloatImag();
9627 APFloat &ResR = Result.getComplexFloatReal();
9628 APFloat &ResI = Result.getComplexFloatImag();
9629 if (RHSReal) {
9630 ResR = A / C;
9631 ResI = B / C;
9632 } else {
9633 if (LHSReal) {
9634 // No real optimizations we can do here, stub out with zero.
9635 B = APFloat::getZero(A.getSemantics());
9636 }
9637 int DenomLogB = 0;
9638 APFloat MaxCD = maxnum(abs(C), abs(D));
9639 if (MaxCD.isFinite()) {
9640 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009641 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9642 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009643 }
9644 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009645 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9646 APFloat::rmNearestTiesToEven);
9647 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9648 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009649 if (ResR.isNaN() && ResI.isNaN()) {
9650 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9651 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9652 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9653 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9654 D.isFinite()) {
9655 A = APFloat::copySign(
9656 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9657 B = APFloat::copySign(
9658 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9659 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9660 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9661 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9662 C = APFloat::copySign(
9663 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9664 D = APFloat::copySign(
9665 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9666 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9667 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9668 }
9669 }
9670 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009671 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009672 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9673 return Error(E, diag::note_expr_divide_by_zero);
9674
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009675 ComplexValue LHS = Result;
9676 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9677 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9678 Result.getComplexIntReal() =
9679 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9680 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9681 Result.getComplexIntImag() =
9682 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9683 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9684 }
9685 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009686 }
9687
John McCall93d91dc2010-05-07 17:22:02 +00009688 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009689}
9690
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009691bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9692 // Get the operand value into 'Result'.
9693 if (!Visit(E->getSubExpr()))
9694 return false;
9695
9696 switch (E->getOpcode()) {
9697 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009698 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009699 case UO_Extension:
9700 return true;
9701 case UO_Plus:
9702 // The result is always just the subexpr.
9703 return true;
9704 case UO_Minus:
9705 if (Result.isComplexFloat()) {
9706 Result.getComplexFloatReal().changeSign();
9707 Result.getComplexFloatImag().changeSign();
9708 }
9709 else {
9710 Result.getComplexIntReal() = -Result.getComplexIntReal();
9711 Result.getComplexIntImag() = -Result.getComplexIntImag();
9712 }
9713 return true;
9714 case UO_Not:
9715 if (Result.isComplexFloat())
9716 Result.getComplexFloatImag().changeSign();
9717 else
9718 Result.getComplexIntImag() = -Result.getComplexIntImag();
9719 return true;
9720 }
9721}
9722
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009723bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9724 if (E->getNumInits() == 2) {
9725 if (E->getType()->isComplexType()) {
9726 Result.makeComplexFloat();
9727 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9728 return false;
9729 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9730 return false;
9731 } else {
9732 Result.makeComplexInt();
9733 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9734 return false;
9735 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9736 return false;
9737 }
9738 return true;
9739 }
9740 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9741}
9742
Anders Carlsson537969c2008-11-16 20:27:53 +00009743//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009744// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9745// implicit conversion.
9746//===----------------------------------------------------------------------===//
9747
9748namespace {
9749class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009750 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009751 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009752 APValue &Result;
9753public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009754 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9755 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009756
9757 bool Success(const APValue &V, const Expr *E) {
9758 Result = V;
9759 return true;
9760 }
9761
9762 bool ZeroInitialization(const Expr *E) {
9763 ImplicitValueInitExpr VIE(
9764 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009765 // For atomic-qualified class (and array) types in C++, initialize the
9766 // _Atomic-wrapped subobject directly, in-place.
9767 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9768 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009769 }
9770
9771 bool VisitCastExpr(const CastExpr *E) {
9772 switch (E->getCastKind()) {
9773 default:
9774 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9775 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009776 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9777 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009778 }
9779 }
9780};
9781} // end anonymous namespace
9782
Richard Smith64cb9ca2017-02-22 22:09:50 +00009783static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9784 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009785 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009786 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009787}
9788
9789//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009790// Void expression evaluation, primarily for a cast to void on the LHS of a
9791// comma operator
9792//===----------------------------------------------------------------------===//
9793
9794namespace {
9795class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009796 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009797public:
9798 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9799
Richard Smith2e312c82012-03-03 22:46:17 +00009800 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009801
9802 bool VisitCastExpr(const CastExpr *E) {
9803 switch (E->getCastKind()) {
9804 default:
9805 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9806 case CK_ToVoid:
9807 VisitIgnoredValue(E->getSubExpr());
9808 return true;
9809 }
9810 }
Hal Finkela8443c32014-07-17 14:49:58 +00009811
9812 bool VisitCallExpr(const CallExpr *E) {
9813 switch (E->getBuiltinCallee()) {
9814 default:
9815 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9816 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009817 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009818 // The argument is not evaluated!
9819 return true;
9820 }
9821 }
Richard Smith42d3af92011-12-07 00:43:50 +00009822};
9823} // end anonymous namespace
9824
9825static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9826 assert(E->isRValue() && E->getType()->isVoidType());
9827 return VoidExprEvaluator(Info).Visit(E);
9828}
9829
9830//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009831// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009832//===----------------------------------------------------------------------===//
9833
Richard Smith2e312c82012-03-03 22:46:17 +00009834static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009835 // In C, function designators are not lvalues, but we evaluate them as if they
9836 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009837 QualType T = E->getType();
9838 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009839 LValue LV;
9840 if (!EvaluateLValue(E, LV, Info))
9841 return false;
9842 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009843 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009844 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009845 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009846 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009847 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009848 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009849 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009850 LValue LV;
9851 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009852 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009853 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009854 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009855 llvm::APFloat F(0.0);
9856 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009857 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009858 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009859 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009860 ComplexValue C;
9861 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009862 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009863 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009864 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009865 MemberPtr P;
9866 if (!EvaluateMemberPointer(E, P, Info))
9867 return false;
9868 P.moveInto(Result);
9869 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009870 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009871 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009872 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009873 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9874 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009875 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009876 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009877 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009878 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009879 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009880 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9881 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009882 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009883 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009884 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009885 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009886 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009887 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009888 if (!EvaluateVoid(E, Info))
9889 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009890 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009891 QualType Unqual = T.getAtomicUnqualifiedType();
9892 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9893 LValue LV;
9894 LV.set(E, Info.CurrentCall->Index);
9895 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9896 if (!EvaluateAtomic(E, &LV, Value, Info))
9897 return false;
9898 } else {
9899 if (!EvaluateAtomic(E, nullptr, Result, Info))
9900 return false;
9901 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009902 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009903 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009904 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009905 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009906 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009907 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009908 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009909
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009910 return true;
9911}
9912
Richard Smithb228a862012-02-15 02:18:13 +00009913/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9914/// cases, the in-place evaluation is essential, since later initializers for
9915/// an object can indirectly refer to subobjects which were initialized earlier.
9916static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009917 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009918 assert(!E->isValueDependent());
9919
Richard Smith7525ff62013-05-09 07:14:00 +00009920 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009921 return false;
9922
9923 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009924 // Evaluate arrays and record types in-place, so that later initializers can
9925 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +00009926 QualType T = E->getType();
9927 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +00009928 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009929 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +00009930 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009931 else if (T->isAtomicType()) {
9932 QualType Unqual = T.getAtomicUnqualifiedType();
9933 if (Unqual->isArrayType() || Unqual->isRecordType())
9934 return EvaluateAtomic(E, &This, Result, Info);
9935 }
Richard Smithed5165f2011-11-04 05:33:44 +00009936 }
9937
9938 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009939 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009940}
9941
Richard Smithf57d8cb2011-12-09 22:58:01 +00009942/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9943/// lvalue-to-rvalue cast if it is an lvalue.
9944static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009945 if (E->getType().isNull())
9946 return false;
9947
Nick Lewyckyc190f962017-05-02 01:06:16 +00009948 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00009949 return false;
9950
Richard Smith2e312c82012-03-03 22:46:17 +00009951 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009952 return false;
9953
9954 if (E->isGLValue()) {
9955 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009956 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009957 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009958 return false;
9959 }
9960
Richard Smith2e312c82012-03-03 22:46:17 +00009961 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009962 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009963}
Richard Smith11562c52011-10-28 17:51:58 +00009964
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009965static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Nick Lewyckye7d6fbd2017-04-29 09:33:46 +00009966 const ASTContext &Ctx, bool &IsConst,
9967 bool IsCheckingForOverflow) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009968 // Fast-path evaluations of integer literals, since we sometimes see files
9969 // containing vast quantities of these.
9970 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9971 Result.Val = APValue(APSInt(L->getValue(),
9972 L->getType()->isUnsignedIntegerType()));
9973 IsConst = true;
9974 return true;
9975 }
James Dennett0492ef02014-03-14 17:44:10 +00009976
9977 // This case should be rare, but we need to check it before we check on
9978 // the type below.
9979 if (Exp->getType().isNull()) {
9980 IsConst = false;
9981 return true;
9982 }
Daniel Jasperffdee092017-05-02 19:21:42 +00009983
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009984 // FIXME: Evaluating values of large array and record types can cause
9985 // performance problems. Only do so in C++11 for now.
9986 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9987 Exp->getType()->isRecordType()) &&
Nick Lewyckye7d6fbd2017-04-29 09:33:46 +00009988 !Ctx.getLangOpts().CPlusPlus11 && !IsCheckingForOverflow) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009989 IsConst = false;
9990 return true;
9991 }
9992 return false;
9993}
9994
9995
Richard Smith7b553f12011-10-29 00:50:52 +00009996/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009997/// any crazy technique (that has nothing to do with language standards) that
9998/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009999/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10000/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010001bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010002 bool IsConst;
Nick Lewyckye7d6fbd2017-04-29 09:33:46 +000010003 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst, false))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010004 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010005
Richard Smith6d4c6582013-11-05 22:18:15 +000010006 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010007 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010008}
10009
Jay Foad39c79802011-01-12 09:06:06 +000010010bool Expr::EvaluateAsBooleanCondition(bool &Result,
10011 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010012 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010013 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010014 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010015}
10016
Richard Smithce8eca52015-12-08 03:21:47 +000010017static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10018 Expr::SideEffectsKind SEK) {
10019 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10020 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10021}
10022
Richard Smith5fab0c92011-12-28 19:48:30 +000010023bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10024 SideEffectsKind AllowSideEffects) const {
10025 if (!getType()->isIntegralOrEnumerationType())
10026 return false;
10027
Richard Smith11562c52011-10-28 17:51:58 +000010028 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010029 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010030 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010031 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010032
Richard Smith11562c52011-10-28 17:51:58 +000010033 Result = ExprResult.Val.getInt();
10034 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010035}
10036
Richard Trieube234c32016-04-21 21:04:55 +000010037bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10038 SideEffectsKind AllowSideEffects) const {
10039 if (!getType()->isRealFloatingType())
10040 return false;
10041
10042 EvalResult ExprResult;
10043 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10044 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10045 return false;
10046
10047 Result = ExprResult.Val.getFloat();
10048 return true;
10049}
10050
Jay Foad39c79802011-01-12 09:06:06 +000010051bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010052 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010053
John McCall45d55e42010-05-07 21:00:08 +000010054 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010055 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10056 !CheckLValueConstantExpression(Info, getExprLoc(),
10057 Ctx.getLValueReferenceType(getType()), LV))
10058 return false;
10059
Richard Smith2e312c82012-03-03 22:46:17 +000010060 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010061 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010062}
10063
Richard Smithd0b4dd62011-12-19 06:19:21 +000010064bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10065 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010066 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010067 // FIXME: Evaluating initializers for large array and record types can cause
10068 // performance problems. Only do so in C++11 for now.
10069 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010070 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010071 return false;
10072
Richard Smithd0b4dd62011-12-19 06:19:21 +000010073 Expr::EvalStatus EStatus;
10074 EStatus.Diag = &Notes;
10075
Richard Smith0c6124b2015-12-03 01:36:22 +000010076 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10077 ? EvalInfo::EM_ConstantExpression
10078 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010079 InitInfo.setEvaluatingDecl(VD, Value);
10080
10081 LValue LVal;
10082 LVal.set(VD);
10083
Richard Smithfddd3842011-12-30 21:15:51 +000010084 // C++11 [basic.start.init]p2:
10085 // Variables with static storage duration or thread storage duration shall be
10086 // zero-initialized before any other initialization takes place.
10087 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010088 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010089 !VD->getType()->isReferenceType()) {
10090 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010091 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010092 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010093 return false;
10094 }
10095
Richard Smith7525ff62013-05-09 07:14:00 +000010096 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10097 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010098 EStatus.HasSideEffects)
10099 return false;
10100
10101 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10102 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010103}
10104
Richard Smith7b553f12011-10-29 00:50:52 +000010105/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10106/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010107bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010108 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010109 return EvaluateAsRValue(Result, Ctx) &&
10110 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010111}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010112
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010113APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010114 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010115 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010116 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010117 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010118 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010119 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010120 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010121
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010122 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010123}
John McCall864e3962010-05-07 05:32:02 +000010124
Richard Smithe9ff7702013-11-05 22:23:30 +000010125void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010126 bool IsConst;
10127 EvalResult EvalResult;
Nick Lewyckye7d6fbd2017-04-29 09:33:46 +000010128 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst, true)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010129 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010130 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10131 }
10132}
10133
Richard Smithe6c01442013-06-05 00:46:14 +000010134bool Expr::EvalResult::isGlobalLValue() const {
10135 assert(Val.isLValue());
10136 return IsGlobalLValue(Val.getLValueBase());
10137}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010138
10139
John McCall864e3962010-05-07 05:32:02 +000010140/// isIntegerConstantExpr - this recursive routine will test if an expression is
10141/// an integer constant expression.
10142
10143/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10144/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010145
10146// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010147// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10148// and a (possibly null) SourceLocation indicating the location of the problem.
10149//
John McCall864e3962010-05-07 05:32:02 +000010150// Note that to reduce code duplication, this helper does no evaluation
10151// itself; the caller checks whether the expression is evaluatable, and
10152// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010153// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010154
Dan Gohman28ade552010-07-26 21:25:24 +000010155namespace {
10156
Richard Smith9e575da2012-12-28 13:25:52 +000010157enum ICEKind {
10158 /// This expression is an ICE.
10159 IK_ICE,
10160 /// This expression is not an ICE, but if it isn't evaluated, it's
10161 /// a legal subexpression for an ICE. This return value is used to handle
10162 /// the comma operator in C99 mode, and non-constant subexpressions.
10163 IK_ICEIfUnevaluated,
10164 /// This expression is not an ICE, and is not a legal subexpression for one.
10165 IK_NotICE
10166};
10167
John McCall864e3962010-05-07 05:32:02 +000010168struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010169 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010170 SourceLocation Loc;
10171
Richard Smith9e575da2012-12-28 13:25:52 +000010172 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010173};
10174
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010175}
Dan Gohman28ade552010-07-26 21:25:24 +000010176
Richard Smith9e575da2012-12-28 13:25:52 +000010177static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10178
10179static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010180
Craig Toppera31a8822013-08-22 07:09:37 +000010181static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010182 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010183 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010184 !EVResult.Val.isInt())
10185 return ICEDiag(IK_NotICE, E->getLocStart());
10186
John McCall864e3962010-05-07 05:32:02 +000010187 return NoDiag();
10188}
10189
Craig Toppera31a8822013-08-22 07:09:37 +000010190static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010191 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010192 if (!E->getType()->isIntegralOrEnumerationType())
10193 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010194
10195 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010196#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010197#define STMT(Node, Base) case Expr::Node##Class:
10198#define EXPR(Node, Base)
10199#include "clang/AST/StmtNodes.inc"
10200 case Expr::PredefinedExprClass:
10201 case Expr::FloatingLiteralClass:
10202 case Expr::ImaginaryLiteralClass:
10203 case Expr::StringLiteralClass:
10204 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010205 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010206 case Expr::MemberExprClass:
10207 case Expr::CompoundAssignOperatorClass:
10208 case Expr::CompoundLiteralExprClass:
10209 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010210 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010211 case Expr::ArrayInitLoopExprClass:
10212 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010213 case Expr::NoInitExprClass:
10214 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010215 case Expr::ImplicitValueInitExprClass:
10216 case Expr::ParenListExprClass:
10217 case Expr::VAArgExprClass:
10218 case Expr::AddrLabelExprClass:
10219 case Expr::StmtExprClass:
10220 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010221 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010222 case Expr::CXXDynamicCastExprClass:
10223 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010224 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010225 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010226 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010227 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010228 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010229 case Expr::CXXThisExprClass:
10230 case Expr::CXXThrowExprClass:
10231 case Expr::CXXNewExprClass:
10232 case Expr::CXXDeleteExprClass:
10233 case Expr::CXXPseudoDestructorExprClass:
10234 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010235 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010236 case Expr::DependentScopeDeclRefExprClass:
10237 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010238 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010239 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010240 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010241 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010242 case Expr::CXXTemporaryObjectExprClass:
10243 case Expr::CXXUnresolvedConstructExprClass:
10244 case Expr::CXXDependentScopeMemberExprClass:
10245 case Expr::UnresolvedMemberExprClass:
10246 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010247 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010248 case Expr::ObjCArrayLiteralClass:
10249 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010250 case Expr::ObjCEncodeExprClass:
10251 case Expr::ObjCMessageExprClass:
10252 case Expr::ObjCSelectorExprClass:
10253 case Expr::ObjCProtocolExprClass:
10254 case Expr::ObjCIvarRefExprClass:
10255 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010256 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010257 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010258 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010259 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010260 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010261 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010262 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010263 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010264 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010265 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010266 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010267 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010268 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010269 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010270 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010271 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010272 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010273 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010274 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010275 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010276 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010277 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010278
Richard Smithf137f932014-01-25 20:50:08 +000010279 case Expr::InitListExprClass: {
10280 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10281 // form "T x = { a };" is equivalent to "T x = a;".
10282 // Unless we're initializing a reference, T is a scalar as it is known to be
10283 // of integral or enumeration type.
10284 if (E->isRValue())
10285 if (cast<InitListExpr>(E)->getNumInits() == 1)
10286 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10287 return ICEDiag(IK_NotICE, E->getLocStart());
10288 }
10289
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010290 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010291 case Expr::GNUNullExprClass:
10292 // GCC considers the GNU __null value to be an integral constant expression.
10293 return NoDiag();
10294
John McCall7c454bb2011-07-15 05:09:51 +000010295 case Expr::SubstNonTypeTemplateParmExprClass:
10296 return
10297 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10298
John McCall864e3962010-05-07 05:32:02 +000010299 case Expr::ParenExprClass:
10300 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010301 case Expr::GenericSelectionExprClass:
10302 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010303 case Expr::IntegerLiteralClass:
10304 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010305 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010306 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010307 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010308 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010309 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010310 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010311 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010312 return NoDiag();
10313 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010314 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010315 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10316 // constant expressions, but they can never be ICEs because an ICE cannot
10317 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010318 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010319 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010320 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010321 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010322 }
Richard Smith6365c912012-02-24 22:12:32 +000010323 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010324 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10325 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010326 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010327 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010328 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010329 // Parameter variables are never constants. Without this check,
10330 // getAnyInitializer() can find a default argument, which leads
10331 // to chaos.
10332 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010333 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010334
10335 // C++ 7.1.5.1p2
10336 // A variable of non-volatile const-qualified integral or enumeration
10337 // type initialized by an ICE can be used in ICEs.
10338 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010339 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010340 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010341
Richard Smithd0b4dd62011-12-19 06:19:21 +000010342 const VarDecl *VD;
10343 // Look for a declaration of this variable that has an initializer, and
10344 // check whether it is an ICE.
10345 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10346 return NoDiag();
10347 else
Richard Smith9e575da2012-12-28 13:25:52 +000010348 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010349 }
10350 }
Richard Smith9e575da2012-12-28 13:25:52 +000010351 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010352 }
John McCall864e3962010-05-07 05:32:02 +000010353 case Expr::UnaryOperatorClass: {
10354 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10355 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010356 case UO_PostInc:
10357 case UO_PostDec:
10358 case UO_PreInc:
10359 case UO_PreDec:
10360 case UO_AddrOf:
10361 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010362 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010363 // C99 6.6/3 allows increment and decrement within unevaluated
10364 // subexpressions of constant expressions, but they can never be ICEs
10365 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010366 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010367 case UO_Extension:
10368 case UO_LNot:
10369 case UO_Plus:
10370 case UO_Minus:
10371 case UO_Not:
10372 case UO_Real:
10373 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010374 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010375 }
Richard Smith9e575da2012-12-28 13:25:52 +000010376
John McCall864e3962010-05-07 05:32:02 +000010377 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010378 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010379 }
10380 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010381 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10382 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10383 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10384 // compliance: we should warn earlier for offsetof expressions with
10385 // array subscripts that aren't ICEs, and if the array subscripts
10386 // are ICEs, the value of the offsetof must be an integer constant.
10387 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010388 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010389 case Expr::UnaryExprOrTypeTraitExprClass: {
10390 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10391 if ((Exp->getKind() == UETT_SizeOf) &&
10392 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010393 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010394 return NoDiag();
10395 }
10396 case Expr::BinaryOperatorClass: {
10397 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10398 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010399 case BO_PtrMemD:
10400 case BO_PtrMemI:
10401 case BO_Assign:
10402 case BO_MulAssign:
10403 case BO_DivAssign:
10404 case BO_RemAssign:
10405 case BO_AddAssign:
10406 case BO_SubAssign:
10407 case BO_ShlAssign:
10408 case BO_ShrAssign:
10409 case BO_AndAssign:
10410 case BO_XorAssign:
10411 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010412 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10413 // constant expressions, but they can never be ICEs because an ICE cannot
10414 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010415 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010416
John McCalle3027922010-08-25 11:45:40 +000010417 case BO_Mul:
10418 case BO_Div:
10419 case BO_Rem:
10420 case BO_Add:
10421 case BO_Sub:
10422 case BO_Shl:
10423 case BO_Shr:
10424 case BO_LT:
10425 case BO_GT:
10426 case BO_LE:
10427 case BO_GE:
10428 case BO_EQ:
10429 case BO_NE:
10430 case BO_And:
10431 case BO_Xor:
10432 case BO_Or:
10433 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010434 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10435 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010436 if (Exp->getOpcode() == BO_Div ||
10437 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010438 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010439 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010440 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010441 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010442 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010443 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010444 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010445 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010446 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010447 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010448 }
10449 }
10450 }
John McCalle3027922010-08-25 11:45:40 +000010451 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010452 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010453 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10454 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010455 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10456 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010457 } else {
10458 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010459 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010460 }
10461 }
Richard Smith9e575da2012-12-28 13:25:52 +000010462 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010463 }
John McCalle3027922010-08-25 11:45:40 +000010464 case BO_LAnd:
10465 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010466 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10467 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010468 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010469 // Rare case where the RHS has a comma "side-effect"; we need
10470 // to actually check the condition to see whether the side
10471 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010472 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010473 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010474 return RHSResult;
10475 return NoDiag();
10476 }
10477
Richard Smith9e575da2012-12-28 13:25:52 +000010478 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010479 }
10480 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010481 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010482 }
10483 case Expr::ImplicitCastExprClass:
10484 case Expr::CStyleCastExprClass:
10485 case Expr::CXXFunctionalCastExprClass:
10486 case Expr::CXXStaticCastExprClass:
10487 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010488 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010489 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010490 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010491 if (isa<ExplicitCastExpr>(E)) {
10492 if (const FloatingLiteral *FL
10493 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10494 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10495 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10496 APSInt IgnoredVal(DestWidth, !DestSigned);
10497 bool Ignored;
10498 // If the value does not fit in the destination type, the behavior is
10499 // undefined, so we are not required to treat it as a constant
10500 // expression.
10501 if (FL->getValue().convertToInteger(IgnoredVal,
10502 llvm::APFloat::rmTowardZero,
10503 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010504 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010505 return NoDiag();
10506 }
10507 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010508 switch (cast<CastExpr>(E)->getCastKind()) {
10509 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010510 case CK_AtomicToNonAtomic:
10511 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010512 case CK_NoOp:
10513 case CK_IntegralToBoolean:
10514 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010515 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010516 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010517 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010518 }
John McCall864e3962010-05-07 05:32:02 +000010519 }
John McCallc07a0c72011-02-17 10:25:35 +000010520 case Expr::BinaryConditionalOperatorClass: {
10521 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10522 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010523 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010524 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010525 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10526 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10527 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010528 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010529 return FalseResult;
10530 }
John McCall864e3962010-05-07 05:32:02 +000010531 case Expr::ConditionalOperatorClass: {
10532 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10533 // If the condition (ignoring parens) is a __builtin_constant_p call,
10534 // then only the true side is actually considered in an integer constant
10535 // expression, and it is fully evaluated. This is an important GNU
10536 // extension. See GCC PR38377 for discussion.
10537 if (const CallExpr *CallCE
10538 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010539 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010540 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010541 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010542 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010543 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010544
Richard Smithf57d8cb2011-12-09 22:58:01 +000010545 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10546 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010547
Richard Smith9e575da2012-12-28 13:25:52 +000010548 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010549 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010550 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010551 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010552 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010553 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010554 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010555 return NoDiag();
10556 // Rare case where the diagnostics depend on which side is evaluated
10557 // Note that if we get here, CondResult is 0, and at least one of
10558 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010559 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010560 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010561 return TrueResult;
10562 }
10563 case Expr::CXXDefaultArgExprClass:
10564 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010565 case Expr::CXXDefaultInitExprClass:
10566 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010567 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010568 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010569 }
10570 }
10571
David Blaikiee4d798f2012-01-20 21:50:17 +000010572 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010573}
10574
Richard Smithf57d8cb2011-12-09 22:58:01 +000010575/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010576static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010577 const Expr *E,
10578 llvm::APSInt *Value,
10579 SourceLocation *Loc) {
10580 if (!E->getType()->isIntegralOrEnumerationType()) {
10581 if (Loc) *Loc = E->getExprLoc();
10582 return false;
10583 }
10584
Richard Smith66e05fe2012-01-18 05:21:49 +000010585 APValue Result;
10586 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010587 return false;
10588
Richard Smith98710fc2014-11-13 23:03:19 +000010589 if (!Result.isInt()) {
10590 if (Loc) *Loc = E->getExprLoc();
10591 return false;
10592 }
10593
Richard Smith66e05fe2012-01-18 05:21:49 +000010594 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010595 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010596}
10597
Craig Toppera31a8822013-08-22 07:09:37 +000010598bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10599 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010600 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010601 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010602
Richard Smith9e575da2012-12-28 13:25:52 +000010603 ICEDiag D = CheckICE(this, Ctx);
10604 if (D.Kind != IK_ICE) {
10605 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010606 return false;
10607 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010608 return true;
10609}
10610
Craig Toppera31a8822013-08-22 07:09:37 +000010611bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010612 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010613 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010614 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10615
10616 if (!isIntegerConstantExpr(Ctx, Loc))
10617 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010618 // The only possible side-effects here are due to UB discovered in the
10619 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10620 // required to treat the expression as an ICE, so we produce the folded
10621 // value.
10622 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010623 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010624 return true;
10625}
Richard Smith66e05fe2012-01-18 05:21:49 +000010626
Craig Toppera31a8822013-08-22 07:09:37 +000010627bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010628 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010629}
10630
Craig Toppera31a8822013-08-22 07:09:37 +000010631bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010632 SourceLocation *Loc) const {
10633 // We support this checking in C++98 mode in order to diagnose compatibility
10634 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010635 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010636
Richard Smith98a0a492012-02-14 21:38:30 +000010637 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010638 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010639 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010640 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010641 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010642
10643 APValue Scratch;
10644 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10645
10646 if (!Diags.empty()) {
10647 IsConstExpr = false;
10648 if (Loc) *Loc = Diags[0].first;
10649 } else if (!IsConstExpr) {
10650 // FIXME: This shouldn't happen.
10651 if (Loc) *Loc = getExprLoc();
10652 }
10653
10654 return IsConstExpr;
10655}
Richard Smith253c2a32012-01-27 01:14:48 +000010656
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010657bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10658 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010659 ArrayRef<const Expr*> Args,
10660 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010661 Expr::EvalStatus Status;
10662 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10663
George Burgess IV177399e2017-01-09 04:12:14 +000010664 LValue ThisVal;
10665 const LValue *ThisPtr = nullptr;
10666 if (This) {
10667#ifndef NDEBUG
10668 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10669 assert(MD && "Don't provide `this` for non-methods.");
10670 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10671#endif
10672 if (EvaluateObjectArgument(Info, This, ThisVal))
10673 ThisPtr = &ThisVal;
10674 if (Info.EvalStatus.HasSideEffects)
10675 return false;
10676 }
10677
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010678 ArgVector ArgValues(Args.size());
10679 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10680 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010681 if ((*I)->isValueDependent() ||
10682 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010683 // If evaluation fails, throw away the argument entirely.
10684 ArgValues[I - Args.begin()] = APValue();
10685 if (Info.EvalStatus.HasSideEffects)
10686 return false;
10687 }
10688
10689 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010690 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010691 ArgValues.data());
10692 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10693}
10694
Richard Smith253c2a32012-01-27 01:14:48 +000010695bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010696 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010697 PartialDiagnosticAt> &Diags) {
10698 // FIXME: It would be useful to check constexpr function templates, but at the
10699 // moment the constant expression evaluator cannot cope with the non-rigorous
10700 // ASTs which we build for dependent expressions.
10701 if (FD->isDependentContext())
10702 return true;
10703
10704 Expr::EvalStatus Status;
10705 Status.Diag = &Diags;
10706
Richard Smith6d4c6582013-11-05 22:18:15 +000010707 EvalInfo Info(FD->getASTContext(), Status,
10708 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010709
10710 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010711 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010712
Richard Smith7525ff62013-05-09 07:14:00 +000010713 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010714 // is a temporary being used as the 'this' pointer.
10715 LValue This;
10716 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010717 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010718
Richard Smith253c2a32012-01-27 01:14:48 +000010719 ArrayRef<const Expr*> Args;
10720
Richard Smith2e312c82012-03-03 22:46:17 +000010721 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010722 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10723 // Evaluate the call as a constant initializer, to allow the construction
10724 // of objects of non-literal types.
10725 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010726 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10727 } else {
10728 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010729 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010730 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010731 }
Richard Smith253c2a32012-01-27 01:14:48 +000010732
10733 return Diags.empty();
10734}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010735
10736bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10737 const FunctionDecl *FD,
10738 SmallVectorImpl<
10739 PartialDiagnosticAt> &Diags) {
10740 Expr::EvalStatus Status;
10741 Status.Diag = &Diags;
10742
10743 EvalInfo Info(FD->getASTContext(), Status,
10744 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10745
10746 // Fabricate a call stack frame to give the arguments a plausible cover story.
10747 ArrayRef<const Expr*> Args;
10748 ArgVector ArgValues(0);
10749 bool Success = EvaluateArgs(Args, ArgValues, Info);
10750 (void)Success;
10751 assert(Success &&
10752 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010753 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010754
10755 APValue ResultScratch;
10756 Evaluate(ResultScratch, Info, E);
10757 return Diags.empty();
10758}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010759
10760bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10761 unsigned Type) const {
10762 if (!getType()->isPointerType())
10763 return false;
10764
10765 Expr::EvalStatus Status;
10766 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010767 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010768}