blob: be4b3af4d6625c86436f20ba4cf024061817c8ce [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,
Martin Bohme542c84b2017-08-30 10:44:46 +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()) {
Martin Bohme542c84b2017-08-30 10:44:46 +0000161 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,
Martin Bohme542c84b2017-08-30 10:44:46 +0000251 MostDerivedType, IsArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000252 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.
Martin Bohme542c84b2017-08-30 10:44:46 +0000321 MostDerivedArraySize = std::numeric_limits<uint64_t>::max() / 2;
George Burgess IVe3763372016-12-22 02:50:20 +0000322 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 Klecknerfdb3df62017-08-15 01:17:47 +0000540 struct 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 {
Chandler Carruthbacb80d2017-08-16 07:22:49 +0000980 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000981 Expr::EvalStatus OldStatus;
982 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +0000983
George Burgess IV8c892b52016-05-25 22:31:54 +0000984 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000985 Info = Other.Info;
986 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +0000987 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000988 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +0000989 }
990
991 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000992 if (!Info)
993 return;
994
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000995 Info->EvalStatus = OldStatus;
996 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +0000997 }
998
Richard Smith17100ba2012-02-16 02:46:34 +0000999 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001000 SpeculativeEvaluationRAII() = default;
1001
1002 SpeculativeEvaluationRAII(
1003 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001004 : Info(&Info), OldStatus(Info.EvalStatus),
1005 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001006 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001007 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001008 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001009
1010 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1011 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1012 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001013 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001014
1015 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1016 maybeRestoreState();
1017 moveFromAndCancel(std::move(Other));
1018 return *this;
1019 }
1020
1021 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001022 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001023
1024 /// RAII object wrapping a full-expression or block scope, and handling
1025 /// the ending of the lifetime of temporaries created within it.
1026 template<bool IsFullExpression>
1027 class ScopeRAII {
1028 EvalInfo &Info;
1029 unsigned OldStackSize;
1030 public:
1031 ScopeRAII(EvalInfo &Info)
1032 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1033 ~ScopeRAII() {
1034 // Body moved to a static method to encourage the compiler to inline away
1035 // instances of this class.
1036 cleanup(Info, OldStackSize);
1037 }
1038 private:
1039 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1040 unsigned NewEnd = OldStackSize;
1041 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1042 I != N; ++I) {
1043 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1044 // Full-expression cleanup of a lifetime-extended temporary: nothing
1045 // to do, just move this cleanup to the right place in the stack.
1046 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1047 ++NewEnd;
1048 } else {
1049 // End the lifetime of the object.
1050 Info.CleanupStack[I].endLifetime();
1051 }
1052 }
1053 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1054 Info.CleanupStack.end());
1055 }
1056 };
1057 typedef ScopeRAII<false> BlockScopeRAII;
1058 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001059}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001060
Richard Smitha8105bc2012-01-06 16:39:00 +00001061bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1062 CheckSubobjectKind CSK) {
1063 if (Invalid)
1064 return false;
1065 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001066 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001067 << CSK;
1068 setInvalid();
1069 return false;
1070 }
1071 return true;
1072}
1073
1074void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001075 const Expr *E,
1076 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001077 // If we're complaining, we must be able to statically determine the size of
1078 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001079 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001080 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001081 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001082 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001083 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001084 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001085 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001086 setInvalid();
1087}
1088
Richard Smithf6f003a2011-12-16 19:06:07 +00001089CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1090 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001091 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001092 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1093 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001094 Info.CurrentCall = this;
1095 ++Info.CallStackDepth;
1096}
1097
1098CallStackFrame::~CallStackFrame() {
1099 assert(Info.CurrentCall == this && "calls retired out of order");
1100 --Info.CallStackDepth;
1101 Info.CurrentCall = Caller;
1102}
1103
Richard Smith08d6a2c2013-07-24 07:11:57 +00001104APValue &CallStackFrame::createTemporary(const void *Key,
1105 bool IsLifetimeExtended) {
1106 APValue &Result = Temporaries[Key];
1107 assert(Result.isUninit() && "temporary created multiple times");
1108 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1109 return Result;
1110}
1111
Richard Smith84401042013-06-03 05:03:02 +00001112static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001113
1114void EvalInfo::addCallStack(unsigned Limit) {
1115 // Determine which calls to skip, if any.
1116 unsigned ActiveCalls = CallStackDepth - 1;
1117 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1118 if (Limit && Limit < ActiveCalls) {
1119 SkipStart = Limit / 2 + Limit % 2;
1120 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001121 }
1122
Richard Smithf6f003a2011-12-16 19:06:07 +00001123 // Walk the call stack and add the diagnostics.
1124 unsigned CallIdx = 0;
1125 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1126 Frame = Frame->Caller, ++CallIdx) {
1127 // Skip this call?
1128 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1129 if (CallIdx == SkipStart) {
1130 // Note that we're skipping calls.
1131 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1132 << unsigned(ActiveCalls - Limit);
1133 }
1134 continue;
1135 }
1136
Richard Smith5179eb72016-06-28 19:03:57 +00001137 // Use a different note for an inheriting constructor, because from the
1138 // user's perspective it's not really a function at all.
1139 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1140 if (CD->isInheritingConstructor()) {
1141 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1142 << CD->getParent();
1143 continue;
1144 }
1145 }
1146
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001147 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001148 llvm::raw_svector_ostream Out(Buffer);
1149 describeCall(Frame, Out);
1150 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1151 }
1152}
1153
1154namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001155 struct ComplexValue {
1156 private:
1157 bool IsInt;
1158
1159 public:
1160 APSInt IntReal, IntImag;
1161 APFloat FloatReal, FloatImag;
1162
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001163 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001164
1165 void makeComplexFloat() { IsInt = false; }
1166 bool isComplexFloat() const { return !IsInt; }
1167 APFloat &getComplexFloatReal() { return FloatReal; }
1168 APFloat &getComplexFloatImag() { return FloatImag; }
1169
1170 void makeComplexInt() { IsInt = true; }
1171 bool isComplexInt() const { return IsInt; }
1172 APSInt &getComplexIntReal() { return IntReal; }
1173 APSInt &getComplexIntImag() { return IntImag; }
1174
Richard Smith2e312c82012-03-03 22:46:17 +00001175 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001176 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001177 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001178 else
Richard Smith2e312c82012-03-03 22:46:17 +00001179 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001180 }
Richard Smith2e312c82012-03-03 22:46:17 +00001181 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001182 assert(v.isComplexFloat() || v.isComplexInt());
1183 if (v.isComplexFloat()) {
1184 makeComplexFloat();
1185 FloatReal = v.getComplexFloatReal();
1186 FloatImag = v.getComplexFloatImag();
1187 } else {
1188 makeComplexInt();
1189 IntReal = v.getComplexIntReal();
1190 IntImag = v.getComplexIntImag();
1191 }
1192 }
John McCall93d91dc2010-05-07 17:22:02 +00001193 };
John McCall45d55e42010-05-07 21:00:08 +00001194
1195 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001196 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001197 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001198 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001199 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001200 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001201 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001202
Richard Smithce40ad62011-11-12 22:28:03 +00001203 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001204 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001205 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001206 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001207 SubobjectDesignator &getLValueDesignator() { return Designator; }
1208 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001209 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001210
Richard Smith2e312c82012-03-03 22:46:17 +00001211 void moveInto(APValue &V) const {
1212 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001213 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1214 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001215 else {
1216 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Martin Bohme542c84b2017-08-30 10:44:46 +00001217 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1218 "Unsized array with a valid base?");
Richard Smith2e312c82012-03-03 22:46:17 +00001219 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001220 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001221 }
John McCall45d55e42010-05-07 21:00:08 +00001222 }
Richard Smith2e312c82012-03-03 22:46:17 +00001223 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001224 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001225 Base = V.getLValueBase();
1226 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001227 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001228 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001229 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001230 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001231 }
1232
Tim Northover01503332017-05-26 02:16:00 +00001233 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001234#ifndef NDEBUG
1235 // We only allow a few types of invalid bases. Enforce that here.
1236 if (BInvalid) {
1237 const auto *E = B.get<const Expr *>();
1238 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1239 "Unexpected type of invalid base");
1240 }
1241#endif
1242
Richard Smithce40ad62011-11-12 22:28:03 +00001243 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001244 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001245 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001246 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001247 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001248 IsNullPtr = false;
1249 }
1250
1251 void setNull(QualType PointerTy, uint64_t TargetVal) {
1252 Base = (Expr *)nullptr;
1253 Offset = CharUnits::fromQuantity(TargetVal);
1254 InvalidBase = false;
1255 CallIndex = 0;
1256 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1257 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001258 }
1259
George Burgess IV3a03fab2015-09-04 21:28:13 +00001260 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1261 set(B, I, true);
1262 }
1263
Richard Smitha8105bc2012-01-06 16:39:00 +00001264 // Check that this LValue is not based on a null pointer. If it is, produce
1265 // a diagnostic and mark the designator as invalid.
1266 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1267 CheckSubobjectKind CSK) {
1268 if (Designator.Invalid)
1269 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001270 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001271 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001272 << CSK;
1273 Designator.setInvalid();
1274 return false;
1275 }
1276 return true;
1277 }
1278
1279 // Check this LValue refers to an object. If not, set the designator to be
1280 // invalid and emit a diagnostic.
1281 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001282 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001283 Designator.checkSubobject(Info, E, CSK);
1284 }
1285
1286 void addDecl(EvalInfo &Info, const Expr *E,
1287 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001288 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1289 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001290 }
Martin Bohme542c84b2017-08-30 10:44:46 +00001291 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1292 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1293 assert(isBaseAnAllocSizeCall(Base) &&
1294 "Only alloc_size bases can have unsized arrays");
Daniel Jasperffdee092017-05-02 19:21:42 +00001295 Designator.FirstEntryIsAnUnsizedArray = true;
1296 Designator.addUnsizedArrayUnchecked(ElemTy);
George Burgess IVe3763372016-12-22 02:50:20 +00001297 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001298 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001299 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1300 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001301 }
Richard Smith66c96992012-02-18 22:04:06 +00001302 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001303 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1304 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001305 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001306 void clearIsNullPointer() {
1307 IsNullPtr = false;
1308 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001309 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1310 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001311 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1312 // but we're not required to diagnose it and it's valid in C++.)
1313 if (!Index)
1314 return;
1315
1316 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1317 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1318 // offsets.
1319 uint64_t Offset64 = Offset.getQuantity();
1320 uint64_t ElemSize64 = ElementSize.getQuantity();
1321 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1322 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1323
1324 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001325 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001326 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001327 }
1328 void adjustOffset(CharUnits N) {
1329 Offset += N;
1330 if (N.getQuantity())
1331 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001332 }
John McCall45d55e42010-05-07 21:00:08 +00001333 };
Richard Smith027bf112011-11-17 22:56:20 +00001334
1335 struct MemberPtr {
1336 MemberPtr() {}
1337 explicit MemberPtr(const ValueDecl *Decl) :
1338 DeclAndIsDerivedMember(Decl, false), Path() {}
1339
1340 /// The member or (direct or indirect) field referred to by this member
1341 /// pointer, or 0 if this is a null member pointer.
1342 const ValueDecl *getDecl() const {
1343 return DeclAndIsDerivedMember.getPointer();
1344 }
1345 /// Is this actually a member of some type derived from the relevant class?
1346 bool isDerivedMember() const {
1347 return DeclAndIsDerivedMember.getInt();
1348 }
1349 /// Get the class which the declaration actually lives in.
1350 const CXXRecordDecl *getContainingRecord() const {
1351 return cast<CXXRecordDecl>(
1352 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1353 }
1354
Richard Smith2e312c82012-03-03 22:46:17 +00001355 void moveInto(APValue &V) const {
1356 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001357 }
Richard Smith2e312c82012-03-03 22:46:17 +00001358 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001359 assert(V.isMemberPointer());
1360 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1361 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1362 Path.clear();
1363 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1364 Path.insert(Path.end(), P.begin(), P.end());
1365 }
1366
1367 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1368 /// whether the member is a member of some class derived from the class type
1369 /// of the member pointer.
1370 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1371 /// Path - The path of base/derived classes from the member declaration's
1372 /// class (exclusive) to the class type of the member pointer (inclusive).
1373 SmallVector<const CXXRecordDecl*, 4> Path;
1374
1375 /// Perform a cast towards the class of the Decl (either up or down the
1376 /// hierarchy).
1377 bool castBack(const CXXRecordDecl *Class) {
1378 assert(!Path.empty());
1379 const CXXRecordDecl *Expected;
1380 if (Path.size() >= 2)
1381 Expected = Path[Path.size() - 2];
1382 else
1383 Expected = getContainingRecord();
1384 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1385 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1386 // if B does not contain the original member and is not a base or
1387 // derived class of the class containing the original member, the result
1388 // of the cast is undefined.
1389 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1390 // (D::*). We consider that to be a language defect.
1391 return false;
1392 }
1393 Path.pop_back();
1394 return true;
1395 }
1396 /// Perform a base-to-derived member pointer cast.
1397 bool castToDerived(const CXXRecordDecl *Derived) {
1398 if (!getDecl())
1399 return true;
1400 if (!isDerivedMember()) {
1401 Path.push_back(Derived);
1402 return true;
1403 }
1404 if (!castBack(Derived))
1405 return false;
1406 if (Path.empty())
1407 DeclAndIsDerivedMember.setInt(false);
1408 return true;
1409 }
1410 /// Perform a derived-to-base member pointer cast.
1411 bool castToBase(const CXXRecordDecl *Base) {
1412 if (!getDecl())
1413 return true;
1414 if (Path.empty())
1415 DeclAndIsDerivedMember.setInt(true);
1416 if (isDerivedMember()) {
1417 Path.push_back(Base);
1418 return true;
1419 }
1420 return castBack(Base);
1421 }
1422 };
Richard Smith357362d2011-12-13 06:39:58 +00001423
Richard Smith7bb00672012-02-01 01:42:44 +00001424 /// Compare two member pointers, which are assumed to be of the same type.
1425 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1426 if (!LHS.getDecl() || !RHS.getDecl())
1427 return !LHS.getDecl() && !RHS.getDecl();
1428 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1429 return false;
1430 return LHS.Path == RHS.Path;
1431 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001432}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001433
Richard Smith2e312c82012-03-03 22:46:17 +00001434static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001435static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1436 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001437 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001438static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1439 bool InvalidBaseOK = false);
1440static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1441 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001442static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1443 EvalInfo &Info);
1444static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001445static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001446static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001447 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001448static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001449static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001450static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1451 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001452static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001453
1454//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001455// Misc utilities
1456//===----------------------------------------------------------------------===//
1457
Richard Smithd6cc1982017-01-31 02:23:02 +00001458/// Negate an APSInt in place, converting it to a signed form if necessary, and
1459/// preserving its value (by extending by up to one bit as needed).
1460static void negateAsSigned(APSInt &Int) {
1461 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1462 Int = Int.extend(Int.getBitWidth() + 1);
1463 Int.setIsSigned(true);
1464 }
1465 Int = -Int;
1466}
1467
Richard Smith84401042013-06-03 05:03:02 +00001468/// Produce a string describing the given constexpr call.
1469static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1470 unsigned ArgIndex = 0;
1471 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1472 !isa<CXXConstructorDecl>(Frame->Callee) &&
1473 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1474
1475 if (!IsMemberCall)
1476 Out << *Frame->Callee << '(';
1477
1478 if (Frame->This && IsMemberCall) {
1479 APValue Val;
1480 Frame->This->moveInto(Val);
1481 Val.printPretty(Out, Frame->Info.Ctx,
1482 Frame->This->Designator.MostDerivedType);
1483 // FIXME: Add parens around Val if needed.
1484 Out << "->" << *Frame->Callee << '(';
1485 IsMemberCall = false;
1486 }
1487
1488 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1489 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1490 if (ArgIndex > (unsigned)IsMemberCall)
1491 Out << ", ";
1492
1493 const ParmVarDecl *Param = *I;
1494 const APValue &Arg = Frame->Arguments[ArgIndex];
1495 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1496
1497 if (ArgIndex == 0 && IsMemberCall)
1498 Out << "->" << *Frame->Callee << '(';
1499 }
1500
1501 Out << ')';
1502}
1503
Richard Smithd9f663b2013-04-22 15:31:51 +00001504/// Evaluate an expression to see if it had side-effects, and discard its
1505/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001506/// \return \c true if the caller should keep evaluating.
1507static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001508 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001509 if (!Evaluate(Scratch, Info, E))
1510 // We don't need the value, but we might have skipped a side effect here.
1511 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001512 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001513}
1514
Richard Smithd62306a2011-11-10 06:34:14 +00001515/// Should this call expression be treated as a string literal?
1516static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001517 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001518 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1519 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1520}
1521
Richard Smithce40ad62011-11-12 22:28:03 +00001522static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001523 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1524 // constant expression of pointer type that evaluates to...
1525
1526 // ... a null pointer value, or a prvalue core constant expression of type
1527 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001528 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001529
Richard Smithce40ad62011-11-12 22:28:03 +00001530 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1531 // ... the address of an object with static storage duration,
1532 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1533 return VD->hasGlobalStorage();
1534 // ... the address of a function,
1535 return isa<FunctionDecl>(D);
1536 }
1537
1538 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001539 switch (E->getStmtClass()) {
1540 default:
1541 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001542 case Expr::CompoundLiteralExprClass: {
1543 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1544 return CLE->isFileScope() && CLE->isLValue();
1545 }
Richard Smithe6c01442013-06-05 00:46:14 +00001546 case Expr::MaterializeTemporaryExprClass:
1547 // A materialized temporary might have been lifetime-extended to static
1548 // storage duration.
1549 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001550 // A string literal has static storage duration.
1551 case Expr::StringLiteralClass:
1552 case Expr::PredefinedExprClass:
1553 case Expr::ObjCStringLiteralClass:
1554 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001555 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001556 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001557 return true;
1558 case Expr::CallExprClass:
1559 return IsStringLiteralCall(cast<CallExpr>(E));
1560 // For GCC compatibility, &&label has static storage duration.
1561 case Expr::AddrLabelExprClass:
1562 return true;
1563 // A Block literal expression may be used as the initialization value for
1564 // Block variables at global or local static scope.
1565 case Expr::BlockExprClass:
1566 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001567 case Expr::ImplicitValueInitExprClass:
1568 // FIXME:
1569 // We can never form an lvalue with an implicit value initialization as its
1570 // base through expression evaluation, so these only appear in one case: the
1571 // implicit variable declaration we invent when checking whether a constexpr
1572 // constructor can produce a constant expression. We must assume that such
1573 // an expression might be a global lvalue.
1574 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001575 }
John McCall95007602010-05-10 23:27:23 +00001576}
1577
Richard Smithb228a862012-02-15 02:18:13 +00001578static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1579 assert(Base && "no location for a null lvalue");
1580 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1581 if (VD)
1582 Info.Note(VD->getLocation(), diag::note_declared_at);
1583 else
Ted Kremenek28831752012-08-23 20:46:57 +00001584 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001585 diag::note_constexpr_temporary_here);
1586}
1587
Richard Smith80815602011-11-07 05:07:52 +00001588/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001589/// value for an address or reference constant expression. Return true if we
1590/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001591static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1592 QualType Type, const LValue &LVal) {
1593 bool IsReferenceType = Type->isReferenceType();
1594
Richard Smith357362d2011-12-13 06:39:58 +00001595 APValue::LValueBase Base = LVal.getLValueBase();
1596 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1597
Richard Smith0dea49e2012-02-18 04:58:18 +00001598 // Check that the object is a global. Note that the fake 'this' object we
1599 // manufacture when checking potential constant expressions is conservatively
1600 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001601 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001602 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001603 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001604 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001605 << IsReferenceType << !Designator.Entries.empty()
1606 << !!VD << VD;
1607 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001608 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001609 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001610 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001611 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001612 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001613 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001614 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001615 LVal.getLValueCallIndex() == 0) &&
1616 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001617
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001618 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1619 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001620 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001621 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001622 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001623
Hans Wennborg82dd8772014-06-25 22:19:48 +00001624 // A dllimport variable never acts like a constant.
1625 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001626 return false;
1627 }
1628 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1629 // __declspec(dllimport) must be handled very carefully:
1630 // We must never initialize an expression with the thunk in C++.
1631 // Doing otherwise would allow the same id-expression to yield
1632 // different addresses for the same function in different translation
1633 // units. However, this means that we must dynamically initialize the
1634 // expression with the contents of the import address table at runtime.
1635 //
1636 // The C language has no notion of ODR; furthermore, it has no notion of
1637 // dynamic initialization. This means that we are permitted to
1638 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001639 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001640 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001641 }
1642 }
1643
Richard Smitha8105bc2012-01-06 16:39:00 +00001644 // Allow address constant expressions to be past-the-end pointers. This is
1645 // an extension: the standard requires them to point to an object.
1646 if (!IsReferenceType)
1647 return true;
1648
1649 // A reference constant expression must refer to an object.
1650 if (!Base) {
1651 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001652 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001653 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001654 }
1655
Richard Smith357362d2011-12-13 06:39:58 +00001656 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001657 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001658 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001659 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001660 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001661 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001662 }
1663
Richard Smith80815602011-11-07 05:07:52 +00001664 return true;
1665}
1666
Reid Klecknercd016d82017-07-07 22:04:29 +00001667/// Member pointers are constant expressions unless they point to a
1668/// non-virtual dllimport member function.
1669static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1670 SourceLocation Loc,
1671 QualType Type,
1672 const APValue &Value) {
1673 const ValueDecl *Member = Value.getMemberPointerDecl();
1674 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1675 if (!FD)
1676 return true;
1677 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1678}
1679
Richard Smithfddd3842011-12-30 21:15:51 +00001680/// Check that this core constant expression is of literal type, and if not,
1681/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001682static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001683 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001684 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001685 return true;
1686
Richard Smith7525ff62013-05-09 07:14:00 +00001687 // C++1y: A constant initializer for an object o [...] may also invoke
1688 // constexpr constructors for o and its subobjects even if those objects
1689 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001690 //
1691 // C++11 missed this detail for aggregates, so classes like this:
1692 // struct foo_t { union { int i; volatile int j; } u; };
1693 // are not (obviously) initializable like so:
1694 // __attribute__((__require_constant_initialization__))
1695 // static const foo_t x = {{0}};
1696 // because "i" is a subobject with non-literal initialization (due to the
1697 // volatile member of the union). See:
1698 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1699 // Therefore, we use the C++1y behavior.
1700 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001701 return true;
1702
Richard Smithfddd3842011-12-30 21:15:51 +00001703 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001704 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001705 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001706 << E->getType();
1707 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001708 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001709 return false;
1710}
1711
Richard Smith0b0a0b62011-10-29 20:57:55 +00001712/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001713/// constant expression. If not, report an appropriate diagnostic. Does not
1714/// check that the expression is of literal type.
1715static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1716 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001717 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001718 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001719 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001720 return false;
1721 }
1722
Richard Smith77be48a2014-07-31 06:31:19 +00001723 // We allow _Atomic(T) to be initialized from anything that T can be
1724 // initialized from.
1725 if (const AtomicType *AT = Type->getAs<AtomicType>())
1726 Type = AT->getValueType();
1727
Richard Smithb228a862012-02-15 02:18:13 +00001728 // Core issue 1454: For a literal constant expression of array or class type,
1729 // each subobject of its value shall have been initialized by a constant
1730 // expression.
1731 if (Value.isArray()) {
1732 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1733 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1734 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1735 Value.getArrayInitializedElt(I)))
1736 return false;
1737 }
1738 if (!Value.hasArrayFiller())
1739 return true;
1740 return CheckConstantExpression(Info, DiagLoc, EltTy,
1741 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001742 }
Richard Smithb228a862012-02-15 02:18:13 +00001743 if (Value.isUnion() && Value.getUnionField()) {
1744 return CheckConstantExpression(Info, DiagLoc,
1745 Value.getUnionField()->getType(),
1746 Value.getUnionValue());
1747 }
1748 if (Value.isStruct()) {
1749 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1750 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1751 unsigned BaseIndex = 0;
1752 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1753 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1754 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1755 Value.getStructBase(BaseIndex)))
1756 return false;
1757 }
1758 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001759 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001760 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1761 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001762 return false;
1763 }
1764 }
1765
1766 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001767 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001768 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001769 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1770 }
1771
Reid Klecknercd016d82017-07-07 22:04:29 +00001772 if (Value.isMemberPointer())
1773 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1774
Richard Smithb228a862012-02-15 02:18:13 +00001775 // Everything else is fine.
1776 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001777}
1778
Benjamin Kramer8407df72015-03-09 16:47:52 +00001779static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001780 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001781}
1782
1783static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001784 if (Value.CallIndex)
1785 return false;
1786 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1787 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001788}
1789
Richard Smithcecf1842011-11-01 21:06:14 +00001790static bool IsWeakLValue(const LValue &Value) {
1791 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001792 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001793}
1794
David Majnemerb5116032014-12-09 23:32:34 +00001795static bool isZeroSized(const LValue &Value) {
1796 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001797 if (Decl && isa<VarDecl>(Decl)) {
1798 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001799 if (Ty->isArrayType())
1800 return Ty->isIncompleteType() ||
1801 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001802 }
1803 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001804}
1805
Richard Smith2e312c82012-03-03 22:46:17 +00001806static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001807 // A null base expression indicates a null pointer. These are always
1808 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001809 if (!Value.getLValueBase()) {
1810 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001811 return true;
1812 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001813
Richard Smith027bf112011-11-17 22:56:20 +00001814 // We have a non-null base. These are generally known to be true, but if it's
1815 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001816 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001817 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001818 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001819}
1820
Richard Smith2e312c82012-03-03 22:46:17 +00001821static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001822 switch (Val.getKind()) {
1823 case APValue::Uninitialized:
1824 return false;
1825 case APValue::Int:
1826 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001827 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001828 case APValue::Float:
1829 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001830 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001831 case APValue::ComplexInt:
1832 Result = Val.getComplexIntReal().getBoolValue() ||
1833 Val.getComplexIntImag().getBoolValue();
1834 return true;
1835 case APValue::ComplexFloat:
1836 Result = !Val.getComplexFloatReal().isZero() ||
1837 !Val.getComplexFloatImag().isZero();
1838 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001839 case APValue::LValue:
1840 return EvalPointerValueAsBool(Val, Result);
1841 case APValue::MemberPointer:
1842 Result = Val.getMemberPointerDecl();
1843 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001844 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001845 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001846 case APValue::Struct:
1847 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001848 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001849 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001850 }
1851
Richard Smith11562c52011-10-28 17:51:58 +00001852 llvm_unreachable("unknown APValue kind");
1853}
1854
1855static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1856 EvalInfo &Info) {
1857 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001858 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001859 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001860 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001861 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001862}
1863
Richard Smith357362d2011-12-13 06:39:58 +00001864template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001865static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001866 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001867 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001868 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001869 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001870}
1871
1872static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1873 QualType SrcType, const APFloat &Value,
1874 QualType DestType, APSInt &Result) {
1875 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001876 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001877 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001878
Richard Smith357362d2011-12-13 06:39:58 +00001879 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001880 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001881 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1882 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001883 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001884 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001885}
1886
Richard Smith357362d2011-12-13 06:39:58 +00001887static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1888 QualType SrcType, QualType DestType,
1889 APFloat &Result) {
1890 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001891 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001892 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1893 APFloat::rmNearestTiesToEven, &ignored)
1894 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001895 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001896 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001897}
1898
Richard Smith911e1422012-01-30 22:27:01 +00001899static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1900 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001901 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001902 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001903 APSInt Result = Value;
1904 // Figure out if this is a truncate, extend or noop cast.
1905 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001906 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001907 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001908 return Result;
1909}
1910
Richard Smith357362d2011-12-13 06:39:58 +00001911static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1912 QualType SrcType, const APSInt &Value,
1913 QualType DestType, APFloat &Result) {
1914 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1915 if (Result.convertFromAPInt(Value, Value.isSigned(),
1916 APFloat::rmNearestTiesToEven)
1917 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001918 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001919 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001920}
1921
Richard Smith49ca8aa2013-08-06 07:09:20 +00001922static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1923 APValue &Value, const FieldDecl *FD) {
1924 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1925
1926 if (!Value.isInt()) {
1927 // Trying to store a pointer-cast-to-integer into a bitfield.
1928 // FIXME: In this case, we should provide the diagnostic for casting
1929 // a pointer to an integer.
1930 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001931 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001932 return false;
1933 }
1934
1935 APSInt &Int = Value.getInt();
1936 unsigned OldBitWidth = Int.getBitWidth();
1937 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1938 if (NewBitWidth < OldBitWidth)
1939 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1940 return true;
1941}
1942
Eli Friedman803acb32011-12-22 03:51:45 +00001943static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1944 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001945 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001946 if (!Evaluate(SVal, Info, E))
1947 return false;
1948 if (SVal.isInt()) {
1949 Res = SVal.getInt();
1950 return true;
1951 }
1952 if (SVal.isFloat()) {
1953 Res = SVal.getFloat().bitcastToAPInt();
1954 return true;
1955 }
1956 if (SVal.isVector()) {
1957 QualType VecTy = E->getType();
1958 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1959 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1960 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1961 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1962 Res = llvm::APInt::getNullValue(VecSize);
1963 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1964 APValue &Elt = SVal.getVectorElt(i);
1965 llvm::APInt EltAsInt;
1966 if (Elt.isInt()) {
1967 EltAsInt = Elt.getInt();
1968 } else if (Elt.isFloat()) {
1969 EltAsInt = Elt.getFloat().bitcastToAPInt();
1970 } else {
1971 // Don't try to handle vectors of anything other than int or float
1972 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001973 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001974 return false;
1975 }
1976 unsigned BaseEltSize = EltAsInt.getBitWidth();
1977 if (BigEndian)
1978 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1979 else
1980 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1981 }
1982 return true;
1983 }
1984 // Give up if the input isn't an int, float, or vector. For example, we
1985 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001986 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001987 return false;
1988}
1989
Richard Smith43e77732013-05-07 04:50:00 +00001990/// Perform the given integer operation, which is known to need at most BitWidth
1991/// bits, and check for overflow in the original type (if that type was not an
1992/// unsigned type).
1993template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001994static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1995 const APSInt &LHS, const APSInt &RHS,
1996 unsigned BitWidth, Operation Op,
1997 APSInt &Result) {
1998 if (LHS.isUnsigned()) {
1999 Result = Op(LHS, RHS);
2000 return true;
2001 }
Richard Smith43e77732013-05-07 04:50:00 +00002002
2003 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002004 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002005 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002006 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002007 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002008 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002009 << Result.toString(10) << E->getType();
2010 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002011 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002012 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002013 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002014}
2015
2016/// Perform the given binary integer operation.
2017static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2018 BinaryOperatorKind Opcode, APSInt RHS,
2019 APSInt &Result) {
2020 switch (Opcode) {
2021 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002022 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002023 return false;
2024 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002025 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2026 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002027 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002028 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2029 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002030 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002031 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2032 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002033 case BO_And: Result = LHS & RHS; return true;
2034 case BO_Xor: Result = LHS ^ RHS; return true;
2035 case BO_Or: Result = LHS | RHS; return true;
2036 case BO_Div:
2037 case BO_Rem:
2038 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002039 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002040 return false;
2041 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002042 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2043 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2044 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002045 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2046 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002047 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2048 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002049 return true;
2050 case BO_Shl: {
2051 if (Info.getLangOpts().OpenCL)
2052 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2053 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2054 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2055 RHS.isUnsigned());
2056 else if (RHS.isSigned() && RHS.isNegative()) {
2057 // During constant-folding, a negative shift is an opposite shift. Such
2058 // a shift is not a constant expression.
2059 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2060 RHS = -RHS;
2061 goto shift_right;
2062 }
2063 shift_left:
2064 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2065 // the shifted type.
2066 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2067 if (SA != RHS) {
2068 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2069 << RHS << E->getType() << LHS.getBitWidth();
2070 } else if (LHS.isSigned()) {
2071 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2072 // operand, and must not overflow the corresponding unsigned type.
2073 if (LHS.isNegative())
2074 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2075 else if (LHS.countLeadingZeros() < SA)
2076 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2077 }
2078 Result = LHS << SA;
2079 return true;
2080 }
2081 case BO_Shr: {
2082 if (Info.getLangOpts().OpenCL)
2083 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2084 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2085 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2086 RHS.isUnsigned());
2087 else if (RHS.isSigned() && RHS.isNegative()) {
2088 // During constant-folding, a negative shift is an opposite shift. Such a
2089 // shift is not a constant expression.
2090 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2091 RHS = -RHS;
2092 goto shift_left;
2093 }
2094 shift_right:
2095 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2096 // shifted type.
2097 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2098 if (SA != RHS)
2099 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2100 << RHS << E->getType() << LHS.getBitWidth();
2101 Result = LHS >> SA;
2102 return true;
2103 }
2104
2105 case BO_LT: Result = LHS < RHS; return true;
2106 case BO_GT: Result = LHS > RHS; return true;
2107 case BO_LE: Result = LHS <= RHS; return true;
2108 case BO_GE: Result = LHS >= RHS; return true;
2109 case BO_EQ: Result = LHS == RHS; return true;
2110 case BO_NE: Result = LHS != RHS; return true;
2111 }
2112}
2113
Richard Smith861b5b52013-05-07 23:34:45 +00002114/// Perform the given binary floating-point operation, in-place, on LHS.
2115static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2116 APFloat &LHS, BinaryOperatorKind Opcode,
2117 const APFloat &RHS) {
2118 switch (Opcode) {
2119 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002120 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002121 return false;
2122 case BO_Mul:
2123 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2124 break;
2125 case BO_Add:
2126 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2127 break;
2128 case BO_Sub:
2129 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2130 break;
2131 case BO_Div:
2132 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2133 break;
2134 }
2135
Richard Smith0c6124b2015-12-03 01:36:22 +00002136 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002137 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002138 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002139 }
Richard Smith861b5b52013-05-07 23:34:45 +00002140 return true;
2141}
2142
Richard Smitha8105bc2012-01-06 16:39:00 +00002143/// Cast an lvalue referring to a base subobject to a derived class, by
2144/// truncating the lvalue's path to the given length.
2145static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2146 const RecordDecl *TruncatedType,
2147 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002148 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002149
2150 // Check we actually point to a derived class object.
2151 if (TruncatedElements == D.Entries.size())
2152 return true;
2153 assert(TruncatedElements >= D.MostDerivedPathLength &&
2154 "not casting to a derived class");
2155 if (!Result.checkSubobject(Info, E, CSK_Derived))
2156 return false;
2157
2158 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002159 const RecordDecl *RD = TruncatedType;
2160 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002161 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002162 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2163 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002164 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002165 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002166 else
Richard Smithd62306a2011-11-10 06:34:14 +00002167 Result.Offset -= Layout.getBaseClassOffset(Base);
2168 RD = Base;
2169 }
Richard Smith027bf112011-11-17 22:56:20 +00002170 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002171 return true;
2172}
2173
John McCalld7bca762012-05-01 00:38:49 +00002174static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002175 const CXXRecordDecl *Derived,
2176 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002177 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002178 if (!RL) {
2179 if (Derived->isInvalidDecl()) return false;
2180 RL = &Info.Ctx.getASTRecordLayout(Derived);
2181 }
2182
Richard Smithd62306a2011-11-10 06:34:14 +00002183 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002184 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002185 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002186}
2187
Richard Smitha8105bc2012-01-06 16:39:00 +00002188static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002189 const CXXRecordDecl *DerivedDecl,
2190 const CXXBaseSpecifier *Base) {
2191 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2192
John McCalld7bca762012-05-01 00:38:49 +00002193 if (!Base->isVirtual())
2194 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002195
Richard Smitha8105bc2012-01-06 16:39:00 +00002196 SubobjectDesignator &D = Obj.Designator;
2197 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002198 return false;
2199
Richard Smitha8105bc2012-01-06 16:39:00 +00002200 // Extract most-derived object and corresponding type.
2201 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2202 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2203 return false;
2204
2205 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002206 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002207 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2208 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002209 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002210 return true;
2211}
2212
Richard Smith84401042013-06-03 05:03:02 +00002213static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2214 QualType Type, LValue &Result) {
2215 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2216 PathE = E->path_end();
2217 PathI != PathE; ++PathI) {
2218 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2219 *PathI))
2220 return false;
2221 Type = (*PathI)->getType();
2222 }
2223 return true;
2224}
2225
Richard Smithd62306a2011-11-10 06:34:14 +00002226/// Update LVal to refer to the given field, which must be a member of the type
2227/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002228static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002229 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002230 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002231 if (!RL) {
2232 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002233 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002234 }
Richard Smithd62306a2011-11-10 06:34:14 +00002235
2236 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002237 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002238 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002239 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002240}
2241
Richard Smith1b78b3d2012-01-25 22:15:11 +00002242/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002243static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002244 LValue &LVal,
2245 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002246 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002247 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002248 return false;
2249 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002250}
2251
Richard Smithd62306a2011-11-10 06:34:14 +00002252/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002253static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2254 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002255 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2256 // extension.
2257 if (Type->isVoidType() || Type->isFunctionType()) {
2258 Size = CharUnits::One();
2259 return true;
2260 }
2261
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002262 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002263 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002264 return false;
2265 }
2266
Richard Smithd62306a2011-11-10 06:34:14 +00002267 if (!Type->isConstantSizeType()) {
2268 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002269 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002270 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002271 return false;
2272 }
2273
2274 Size = Info.Ctx.getTypeSizeInChars(Type);
2275 return true;
2276}
2277
2278/// Update a pointer value to model pointer arithmetic.
2279/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002280/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002281/// \param LVal - The pointer value to be updated.
2282/// \param EltTy - The pointee type represented by LVal.
2283/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002284static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2285 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002286 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002287 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002288 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002289 return false;
2290
Yaxun Liu402804b2016-12-15 08:09:08 +00002291 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002292 return true;
2293}
2294
Richard Smithd6cc1982017-01-31 02:23:02 +00002295static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2296 LValue &LVal, QualType EltTy,
2297 int64_t Adjustment) {
2298 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2299 APSInt::get(Adjustment));
2300}
2301
Richard Smith66c96992012-02-18 22:04:06 +00002302/// Update an lvalue to refer to a component of a complex number.
2303/// \param Info - Information about the ongoing evaluation.
2304/// \param LVal - The lvalue to be updated.
2305/// \param EltTy - The complex number's component type.
2306/// \param Imag - False for the real component, true for the imaginary.
2307static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2308 LValue &LVal, QualType EltTy,
2309 bool Imag) {
2310 if (Imag) {
2311 CharUnits SizeOfComponent;
2312 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2313 return false;
2314 LVal.Offset += SizeOfComponent;
2315 }
2316 LVal.addComplex(Info, E, EltTy, Imag);
2317 return true;
2318}
2319
Faisal Vali051e3a22017-02-16 04:12:21 +00002320static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2321 QualType Type, const LValue &LVal,
2322 APValue &RVal);
2323
Richard Smith27908702011-10-24 17:54:18 +00002324/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002325///
2326/// \param Info Information about the ongoing evaluation.
2327/// \param E An expression to be used when printing diagnostics.
2328/// \param VD The variable whose initializer should be obtained.
2329/// \param Frame The frame in which the variable was created. Must be null
2330/// if this variable is not local to the evaluation.
2331/// \param Result Filled in with a pointer to the value of the variable.
2332static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2333 const VarDecl *VD, CallStackFrame *Frame,
2334 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002335
Richard Smith254a73d2011-10-28 22:34:42 +00002336 // If this is a parameter to an active constexpr function call, perform
2337 // argument substitution.
2338 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002339 // Assume arguments of a potential constant expression are unknown
2340 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002341 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002342 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002343 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002344 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002345 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002346 }
Richard Smith3229b742013-05-05 21:17:10 +00002347 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002348 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002349 }
Richard Smith27908702011-10-24 17:54:18 +00002350
Richard Smithd9f663b2013-04-22 15:31:51 +00002351 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002352 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002353 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002354 if (!Result) {
2355 // Assume variables referenced within a lambda's call operator that were
2356 // not declared within the call operator are captures and during checking
2357 // of a potential constant expression, assume they are unknown constant
2358 // expressions.
2359 assert(isLambdaCallOperator(Frame->Callee) &&
2360 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2361 "missing value for local variable");
2362 if (Info.checkingPotentialConstantExpression())
2363 return false;
2364 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002365 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002366 diag::note_unimplemented_constexpr_lambda_feature_ast)
2367 << "captures not currently allowed";
2368 return false;
2369 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002370 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002371 }
2372
Richard Smithd0b4dd62011-12-19 06:19:21 +00002373 // Dig out the initializer, and use the declaration which it's attached to.
2374 const Expr *Init = VD->getAnyInitializer(VD);
2375 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002376 // If we're checking a potential constant expression, the variable could be
2377 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002378 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002379 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002380 return false;
2381 }
2382
Richard Smithd62306a2011-11-10 06:34:14 +00002383 // If we're currently evaluating the initializer of this declaration, use that
2384 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002385 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002386 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002387 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002388 }
2389
Richard Smithcecf1842011-11-01 21:06:14 +00002390 // Never evaluate the initializer of a weak variable. We can't be sure that
2391 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002392 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002393 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002394 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002395 }
Richard Smithcecf1842011-11-01 21:06:14 +00002396
Richard Smithd0b4dd62011-12-19 06:19:21 +00002397 // Check that we can fold the initializer. In C++, we will have already done
2398 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002399 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002400 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002401 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002402 Notes.size() + 1) << VD;
2403 Info.Note(VD->getLocation(), diag::note_declared_at);
2404 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002405 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002406 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002407 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002408 Notes.size() + 1) << VD;
2409 Info.Note(VD->getLocation(), diag::note_declared_at);
2410 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002411 }
Richard Smith27908702011-10-24 17:54:18 +00002412
Richard Smith3229b742013-05-05 21:17:10 +00002413 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002414 return true;
Richard Smith27908702011-10-24 17:54:18 +00002415}
2416
Richard Smith11562c52011-10-28 17:51:58 +00002417static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002418 Qualifiers Quals = T.getQualifiers();
2419 return Quals.hasConst() && !Quals.hasVolatile();
2420}
2421
Richard Smithe97cbd72011-11-11 04:05:33 +00002422/// Get the base index of the given base class within an APValue representing
2423/// the given derived class.
2424static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2425 const CXXRecordDecl *Base) {
2426 Base = Base->getCanonicalDecl();
2427 unsigned Index = 0;
2428 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2429 E = Derived->bases_end(); I != E; ++I, ++Index) {
2430 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2431 return Index;
2432 }
2433
2434 llvm_unreachable("base class missing from derived class's bases list");
2435}
2436
Richard Smith3da88fa2013-04-26 14:36:30 +00002437/// Extract the value of a character from a string literal.
2438static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2439 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002440 // FIXME: Support MakeStringConstant
2441 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2442 std::string Str;
2443 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2444 assert(Index <= Str.size() && "Index too large");
2445 return APSInt::getUnsigned(Str.c_str()[Index]);
2446 }
2447
Alexey Bataevec474782014-10-09 08:45:04 +00002448 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2449 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002450 const StringLiteral *S = cast<StringLiteral>(Lit);
2451 const ConstantArrayType *CAT =
2452 Info.Ctx.getAsConstantArrayType(S->getType());
2453 assert(CAT && "string literal isn't an array");
2454 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002455 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002456
2457 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002458 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002459 if (Index < S->getLength())
2460 Value = S->getCodeUnit(Index);
2461 return Value;
2462}
2463
Richard Smith3da88fa2013-04-26 14:36:30 +00002464// Expand a string literal into an array of characters.
2465static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2466 APValue &Result) {
2467 const StringLiteral *S = cast<StringLiteral>(Lit);
2468 const ConstantArrayType *CAT =
2469 Info.Ctx.getAsConstantArrayType(S->getType());
2470 assert(CAT && "string literal isn't an array");
2471 QualType CharType = CAT->getElementType();
2472 assert(CharType->isIntegerType() && "unexpected character type");
2473
2474 unsigned Elts = CAT->getSize().getZExtValue();
2475 Result = APValue(APValue::UninitArray(),
2476 std::min(S->getLength(), Elts), Elts);
2477 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2478 CharType->isUnsignedIntegerType());
2479 if (Result.hasArrayFiller())
2480 Result.getArrayFiller() = APValue(Value);
2481 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2482 Value = S->getCodeUnit(I);
2483 Result.getArrayInitializedElt(I) = APValue(Value);
2484 }
2485}
2486
2487// Expand an array so that it has more than Index filled elements.
2488static void expandArray(APValue &Array, unsigned Index) {
2489 unsigned Size = Array.getArraySize();
2490 assert(Index < Size);
2491
2492 // Always at least double the number of elements for which we store a value.
2493 unsigned OldElts = Array.getArrayInitializedElts();
2494 unsigned NewElts = std::max(Index+1, OldElts * 2);
2495 NewElts = std::min(Size, std::max(NewElts, 8u));
2496
2497 // Copy the data across.
2498 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2499 for (unsigned I = 0; I != OldElts; ++I)
2500 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2501 for (unsigned I = OldElts; I != NewElts; ++I)
2502 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2503 if (NewValue.hasArrayFiller())
2504 NewValue.getArrayFiller() = Array.getArrayFiller();
2505 Array.swap(NewValue);
2506}
2507
Richard Smithb01fe402014-09-16 01:24:02 +00002508/// Determine whether a type would actually be read by an lvalue-to-rvalue
2509/// conversion. If it's of class type, we may assume that the copy operation
2510/// is trivial. Note that this is never true for a union type with fields
2511/// (because the copy always "reads" the active member) and always true for
2512/// a non-class type.
2513static bool isReadByLvalueToRvalueConversion(QualType T) {
2514 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2515 if (!RD || (RD->isUnion() && !RD->field_empty()))
2516 return true;
2517 if (RD->isEmpty())
2518 return false;
2519
2520 for (auto *Field : RD->fields())
2521 if (isReadByLvalueToRvalueConversion(Field->getType()))
2522 return true;
2523
2524 for (auto &BaseSpec : RD->bases())
2525 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2526 return true;
2527
2528 return false;
2529}
2530
2531/// Diagnose an attempt to read from any unreadable field within the specified
2532/// type, which might be a class type.
2533static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2534 QualType T) {
2535 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2536 if (!RD)
2537 return false;
2538
2539 if (!RD->hasMutableFields())
2540 return false;
2541
2542 for (auto *Field : RD->fields()) {
2543 // If we're actually going to read this field in some way, then it can't
2544 // be mutable. If we're in a union, then assigning to a mutable field
2545 // (even an empty one) can change the active member, so that's not OK.
2546 // FIXME: Add core issue number for the union case.
2547 if (Field->isMutable() &&
2548 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002549 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002550 Info.Note(Field->getLocation(), diag::note_declared_at);
2551 return true;
2552 }
2553
2554 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2555 return true;
2556 }
2557
2558 for (auto &BaseSpec : RD->bases())
2559 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2560 return true;
2561
2562 // All mutable fields were empty, and thus not actually read.
2563 return false;
2564}
2565
Richard Smith861b5b52013-05-07 23:34:45 +00002566/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002567enum AccessKinds {
2568 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002569 AK_Assign,
2570 AK_Increment,
2571 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002572};
2573
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002574namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002575/// A handle to a complete object (an object that is not a subobject of
2576/// another object).
2577struct CompleteObject {
2578 /// The value of the complete object.
2579 APValue *Value;
2580 /// The type of the complete object.
2581 QualType Type;
2582
Craig Topper36250ad2014-05-12 05:36:57 +00002583 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002584 CompleteObject(APValue *Value, QualType Type)
2585 : Value(Value), Type(Type) {
2586 assert(Value && "missing value for complete object");
2587 }
2588
Aaron Ballman67347662015-02-15 22:00:28 +00002589 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002590};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002591} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002592
Richard Smith3da88fa2013-04-26 14:36:30 +00002593/// Find the designated sub-object of an rvalue.
2594template<typename SubobjectHandler>
2595typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002596findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002597 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002598 if (Sub.Invalid)
2599 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002600 return handler.failed();
Martin Bohme542c84b2017-08-30 10:44:46 +00002601 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002602 if (Info.getLangOpts().CPlusPlus11)
Martin Bohme542c84b2017-08-30 10:44:46 +00002603 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2604 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002605 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002606 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002607 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002608 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002609
Richard Smith3229b742013-05-05 21:17:10 +00002610 APValue *O = Obj.Value;
2611 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002612 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002613
Richard Smithd62306a2011-11-10 06:34:14 +00002614 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002615 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2616 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002617 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002618 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002619 return handler.failed();
2620 }
2621
Richard Smith49ca8aa2013-08-06 07:09:20 +00002622 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002623 // If we are reading an object of class type, there may still be more
2624 // things we need to check: if there are any mutable subobjects, we
2625 // cannot perform this read. (This only happens when performing a trivial
2626 // copy or assignment.)
2627 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2628 diagnoseUnreadableFields(Info, E, ObjType))
2629 return handler.failed();
2630
Richard Smith49ca8aa2013-08-06 07:09:20 +00002631 if (!handler.found(*O, ObjType))
2632 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002633
Richard Smith49ca8aa2013-08-06 07:09:20 +00002634 // If we modified a bit-field, truncate it to the right width.
2635 if (handler.AccessKind != AK_Read &&
2636 LastField && LastField->isBitField() &&
2637 !truncateBitfieldValue(Info, E, *O, LastField))
2638 return false;
2639
2640 return true;
2641 }
2642
Craig Topper36250ad2014-05-12 05:36:57 +00002643 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002644 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002645 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002646 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002647 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002648 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002649 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002650 // Note, it should not be possible to form a pointer with a valid
2651 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002652 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002653 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002654 << handler.AccessKind;
2655 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002656 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002657 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002658 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002659
2660 ObjType = CAT->getElementType();
2661
Richard Smith14a94132012-02-17 03:35:37 +00002662 // An array object is represented as either an Array APValue or as an
2663 // LValue which refers to a string literal.
2664 if (O->isLValue()) {
2665 assert(I == N - 1 && "extracting subobject of character?");
2666 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002667 if (handler.AccessKind != AK_Read)
2668 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2669 *O);
2670 else
2671 return handler.foundString(*O, ObjType, Index);
2672 }
2673
2674 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002675 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002676 else if (handler.AccessKind != AK_Read) {
2677 expandArray(*O, Index);
2678 O = &O->getArrayInitializedElt(Index);
2679 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002680 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002681 } else if (ObjType->isAnyComplexType()) {
2682 // Next subobject is a complex number.
2683 uint64_t Index = Sub.Entries[I].ArrayIndex;
2684 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002685 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002686 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002687 << handler.AccessKind;
2688 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002689 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002690 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002691 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002692
2693 bool WasConstQualified = ObjType.isConstQualified();
2694 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2695 if (WasConstQualified)
2696 ObjType.addConst();
2697
Richard Smith66c96992012-02-18 22:04:06 +00002698 assert(I == N - 1 && "extracting subobject of scalar?");
2699 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002700 return handler.found(Index ? O->getComplexIntImag()
2701 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002702 } else {
2703 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002704 return handler.found(Index ? O->getComplexFloatImag()
2705 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002706 }
Richard Smithd62306a2011-11-10 06:34:14 +00002707 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002708 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002709 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002710 << Field;
2711 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002712 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002713 }
2714
Richard Smithd62306a2011-11-10 06:34:14 +00002715 // Next subobject is a class, struct or union field.
2716 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2717 if (RD->isUnion()) {
2718 const FieldDecl *UnionField = O->getUnionField();
2719 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002720 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002721 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002722 << handler.AccessKind << Field << !UnionField << UnionField;
2723 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002724 }
Richard Smithd62306a2011-11-10 06:34:14 +00002725 O = &O->getUnionValue();
2726 } else
2727 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002728
2729 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002730 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002731 if (WasConstQualified && !Field->isMutable())
2732 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002733
2734 if (ObjType.isVolatileQualified()) {
2735 if (Info.getLangOpts().CPlusPlus) {
2736 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002737 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002738 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002739 Info.Note(Field->getLocation(), diag::note_declared_at);
2740 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002741 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002742 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002743 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002744 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002745
2746 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002747 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002748 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002749 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2750 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2751 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002752
2753 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002754 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002755 if (WasConstQualified)
2756 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002757 }
2758 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002759}
2760
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002761namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002762struct ExtractSubobjectHandler {
2763 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002764 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002765
2766 static const AccessKinds AccessKind = AK_Read;
2767
2768 typedef bool result_type;
2769 bool failed() { return false; }
2770 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002771 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002772 return true;
2773 }
2774 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002775 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002776 return true;
2777 }
2778 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002779 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002780 return true;
2781 }
2782 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002783 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002784 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2785 return true;
2786 }
2787};
Richard Smith3229b742013-05-05 21:17:10 +00002788} // end anonymous namespace
2789
Richard Smith3da88fa2013-04-26 14:36:30 +00002790const AccessKinds ExtractSubobjectHandler::AccessKind;
2791
2792/// Extract the designated sub-object of an rvalue.
2793static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002794 const CompleteObject &Obj,
2795 const SubobjectDesignator &Sub,
2796 APValue &Result) {
2797 ExtractSubobjectHandler Handler = { Info, Result };
2798 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002799}
2800
Richard Smith3229b742013-05-05 21:17:10 +00002801namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002802struct ModifySubobjectHandler {
2803 EvalInfo &Info;
2804 APValue &NewVal;
2805 const Expr *E;
2806
2807 typedef bool result_type;
2808 static const AccessKinds AccessKind = AK_Assign;
2809
2810 bool checkConst(QualType QT) {
2811 // Assigning to a const object has undefined behavior.
2812 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002813 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002814 return false;
2815 }
2816 return true;
2817 }
2818
2819 bool failed() { return false; }
2820 bool found(APValue &Subobj, QualType SubobjType) {
2821 if (!checkConst(SubobjType))
2822 return false;
2823 // We've been given ownership of NewVal, so just swap it in.
2824 Subobj.swap(NewVal);
2825 return true;
2826 }
2827 bool found(APSInt &Value, QualType SubobjType) {
2828 if (!checkConst(SubobjType))
2829 return false;
2830 if (!NewVal.isInt()) {
2831 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002832 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002833 return false;
2834 }
2835 Value = NewVal.getInt();
2836 return true;
2837 }
2838 bool found(APFloat &Value, QualType SubobjType) {
2839 if (!checkConst(SubobjType))
2840 return false;
2841 Value = NewVal.getFloat();
2842 return true;
2843 }
2844 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2845 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2846 }
2847};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002848} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002849
Richard Smith3229b742013-05-05 21:17:10 +00002850const AccessKinds ModifySubobjectHandler::AccessKind;
2851
Richard Smith3da88fa2013-04-26 14:36:30 +00002852/// Update the designated sub-object of an rvalue to the given value.
2853static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002854 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002855 const SubobjectDesignator &Sub,
2856 APValue &NewVal) {
2857 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002858 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002859}
2860
Richard Smith84f6dcf2012-02-02 01:16:57 +00002861/// Find the position where two subobject designators diverge, or equivalently
2862/// the length of the common initial subsequence.
2863static unsigned FindDesignatorMismatch(QualType ObjType,
2864 const SubobjectDesignator &A,
2865 const SubobjectDesignator &B,
2866 bool &WasArrayIndex) {
2867 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2868 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002869 if (!ObjType.isNull() &&
2870 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002871 // Next subobject is an array element.
2872 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2873 WasArrayIndex = true;
2874 return I;
2875 }
Richard Smith66c96992012-02-18 22:04:06 +00002876 if (ObjType->isAnyComplexType())
2877 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2878 else
2879 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002880 } else {
2881 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2882 WasArrayIndex = false;
2883 return I;
2884 }
2885 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2886 // Next subobject is a field.
2887 ObjType = FD->getType();
2888 else
2889 // Next subobject is a base class.
2890 ObjType = QualType();
2891 }
2892 }
2893 WasArrayIndex = false;
2894 return I;
2895}
2896
2897/// Determine whether the given subobject designators refer to elements of the
2898/// same array object.
2899static bool AreElementsOfSameArray(QualType ObjType,
2900 const SubobjectDesignator &A,
2901 const SubobjectDesignator &B) {
2902 if (A.Entries.size() != B.Entries.size())
2903 return false;
2904
George Burgess IVa51c4072015-10-16 01:49:01 +00002905 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002906 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2907 // A is a subobject of the array element.
2908 return false;
2909
2910 // If A (and B) designates an array element, the last entry will be the array
2911 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2912 // of length 1' case, and the entire path must match.
2913 bool WasArrayIndex;
2914 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2915 return CommonLength >= A.Entries.size() - IsArray;
2916}
2917
Richard Smith3229b742013-05-05 21:17:10 +00002918/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002919static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2920 AccessKinds AK, const LValue &LVal,
2921 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002922 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002923 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002924 return CompleteObject();
2925 }
2926
Craig Topper36250ad2014-05-12 05:36:57 +00002927 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002928 if (LVal.CallIndex) {
2929 Frame = Info.getCallFrame(LVal.CallIndex);
2930 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002931 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002932 << AK << LVal.Base.is<const ValueDecl*>();
2933 NoteLValueLocation(Info, LVal.Base);
2934 return CompleteObject();
2935 }
Richard Smith3229b742013-05-05 21:17:10 +00002936 }
2937
2938 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2939 // is not a constant expression (even if the object is non-volatile). We also
2940 // apply this rule to C++98, in order to conform to the expected 'volatile'
2941 // semantics.
2942 if (LValType.isVolatileQualified()) {
2943 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002944 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002945 << AK << LValType;
2946 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002947 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002948 return CompleteObject();
2949 }
2950
2951 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002952 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002953 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002954
2955 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2956 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2957 // In C++11, constexpr, non-volatile variables initialized with constant
2958 // expressions are constant expressions too. Inside constexpr functions,
2959 // parameters are constant expressions even if they're non-const.
2960 // In C++1y, objects local to a constant expression (those with a Frame) are
2961 // both readable and writable inside constant expressions.
2962 // In C, such things can also be folded, although they are not ICEs.
2963 const VarDecl *VD = dyn_cast<VarDecl>(D);
2964 if (VD) {
2965 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2966 VD = VDef;
2967 }
2968 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002969 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002970 return CompleteObject();
2971 }
2972
2973 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002974 if (BaseType.isVolatileQualified()) {
2975 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002976 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002977 << AK << 1 << VD;
2978 Info.Note(VD->getLocation(), diag::note_declared_at);
2979 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002980 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002981 }
2982 return CompleteObject();
2983 }
2984
2985 // Unless we're looking at a local variable or argument in a constexpr call,
2986 // the variable we're reading must be const.
2987 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002988 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002989 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2990 // OK, we can read and modify an object if we're in the process of
2991 // evaluating its initializer, because its lifetime began in this
2992 // evaluation.
2993 } else if (AK != AK_Read) {
2994 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002995 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002996 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00002997 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002998 // OK, we can read this variable.
2999 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003000 // In OpenCL if a variable is in constant address space it is a const value.
3001 if (!(BaseType.isConstQualified() ||
3002 (Info.getLangOpts().OpenCL &&
3003 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003004 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003005 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003006 Info.Note(VD->getLocation(), diag::note_declared_at);
3007 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003008 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003009 }
3010 return CompleteObject();
3011 }
3012 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3013 // We support folding of const floating-point types, in order to make
3014 // static const data members of such types (supported as an extension)
3015 // more useful.
3016 if (Info.getLangOpts().CPlusPlus11) {
3017 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3018 Info.Note(VD->getLocation(), diag::note_declared_at);
3019 } else {
3020 Info.CCEDiag(E);
3021 }
George Burgess IVb5316982016-12-27 05:33:20 +00003022 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3023 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3024 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003025 } else {
3026 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003027 if (Info.checkingPotentialConstantExpression() &&
3028 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3029 // The definition of this variable could be constexpr. We can't
3030 // access it right now, but may be able to in future.
3031 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003032 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003033 Info.Note(VD->getLocation(), diag::note_declared_at);
3034 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003035 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003036 }
3037 return CompleteObject();
3038 }
3039 }
3040
3041 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3042 return CompleteObject();
3043 } else {
3044 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3045
3046 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003047 if (const MaterializeTemporaryExpr *MTE =
3048 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3049 assert(MTE->getStorageDuration() == SD_Static &&
3050 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003051
Richard Smithe6c01442013-06-05 00:46:14 +00003052 // Per C++1y [expr.const]p2:
3053 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3054 // - a [...] glvalue of integral or enumeration type that refers to
3055 // a non-volatile const object [...]
3056 // [...]
3057 // - a [...] glvalue of literal type that refers to a non-volatile
3058 // object whose lifetime began within the evaluation of e.
3059 //
3060 // C++11 misses the 'began within the evaluation of e' check and
3061 // instead allows all temporaries, including things like:
3062 // int &&r = 1;
3063 // int x = ++r;
3064 // constexpr int k = r;
3065 // Therefore we use the C++1y rules in C++11 too.
3066 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3067 const ValueDecl *ED = MTE->getExtendingDecl();
3068 if (!(BaseType.isConstQualified() &&
3069 BaseType->isIntegralOrEnumerationType()) &&
3070 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003071 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003072 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3073 return CompleteObject();
3074 }
3075
3076 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3077 assert(BaseVal && "got reference to unevaluated temporary");
3078 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003079 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003080 return CompleteObject();
3081 }
3082 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003083 BaseVal = Frame->getTemporary(Base);
3084 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003085 }
Richard Smith3229b742013-05-05 21:17:10 +00003086
3087 // Volatile temporary objects cannot be accessed in constant expressions.
3088 if (BaseType.isVolatileQualified()) {
3089 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003090 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003091 << AK << 0;
3092 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3093 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003094 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003095 }
3096 return CompleteObject();
3097 }
3098 }
3099
Richard Smith7525ff62013-05-09 07:14:00 +00003100 // During the construction of an object, it is not yet 'const'.
3101 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3102 // and this doesn't do quite the right thing for const subobjects of the
3103 // object under construction.
3104 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3105 BaseType = Info.Ctx.getCanonicalType(BaseType);
3106 BaseType.removeLocalConst();
3107 }
3108
Richard Smith6d4c6582013-11-05 22:18:15 +00003109 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003110 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003111 //
3112 // FIXME: Not all local state is mutable. Allow local constant subobjects
3113 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003114 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3115 Info.EvalStatus.HasSideEffects) ||
3116 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003117 return CompleteObject();
3118
3119 return CompleteObject(BaseVal, BaseType);
3120}
3121
Richard Smith243ef902013-05-05 23:31:59 +00003122/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3123/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3124/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003125///
3126/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003127/// \param Conv - The expression for which we are performing the conversion.
3128/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003129/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3130/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003131/// \param LVal - The glvalue on which we are attempting to perform this action.
3132/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003133static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003134 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003135 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003136 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003137 return false;
3138
Richard Smith3229b742013-05-05 21:17:10 +00003139 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003140 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003141 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003142 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3143 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3144 // initializer until now for such expressions. Such an expression can't be
3145 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003146 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003147 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003148 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003149 }
Richard Smith3229b742013-05-05 21:17:10 +00003150 APValue Lit;
3151 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3152 return false;
3153 CompleteObject LitObj(&Lit, Base->getType());
3154 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003155 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003156 // We represent a string literal array as an lvalue pointing at the
3157 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003158 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003159 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3160 CompleteObject StrObj(&Str, Base->getType());
3161 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003162 }
Richard Smith11562c52011-10-28 17:51:58 +00003163 }
3164
Richard Smith3229b742013-05-05 21:17:10 +00003165 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3166 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003167}
3168
3169/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003170static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003171 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003172 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003173 return false;
3174
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003175 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003176 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003177 return false;
3178 }
3179
Richard Smith3229b742013-05-05 21:17:10 +00003180 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3181 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003182}
3183
Richard Smith243ef902013-05-05 23:31:59 +00003184static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3185 return T->isSignedIntegerType() &&
3186 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3187}
3188
3189namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003190struct CompoundAssignSubobjectHandler {
3191 EvalInfo &Info;
3192 const Expr *E;
3193 QualType PromotedLHSType;
3194 BinaryOperatorKind Opcode;
3195 const APValue &RHS;
3196
3197 static const AccessKinds AccessKind = AK_Assign;
3198
3199 typedef bool result_type;
3200
3201 bool checkConst(QualType QT) {
3202 // Assigning to a const object has undefined behavior.
3203 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003204 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003205 return false;
3206 }
3207 return true;
3208 }
3209
3210 bool failed() { return false; }
3211 bool found(APValue &Subobj, QualType SubobjType) {
3212 switch (Subobj.getKind()) {
3213 case APValue::Int:
3214 return found(Subobj.getInt(), SubobjType);
3215 case APValue::Float:
3216 return found(Subobj.getFloat(), SubobjType);
3217 case APValue::ComplexInt:
3218 case APValue::ComplexFloat:
3219 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003220 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003221 return false;
3222 case APValue::LValue:
3223 return foundPointer(Subobj, SubobjType);
3224 default:
3225 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003226 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003227 return false;
3228 }
3229 }
3230 bool found(APSInt &Value, QualType SubobjType) {
3231 if (!checkConst(SubobjType))
3232 return false;
3233
3234 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3235 // We don't support compound assignment on integer-cast-to-pointer
3236 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003237 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003238 return false;
3239 }
3240
3241 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3242 SubobjType, Value);
3243 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3244 return false;
3245 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3246 return true;
3247 }
3248 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003249 return checkConst(SubobjType) &&
3250 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3251 Value) &&
3252 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3253 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003254 }
3255 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3256 if (!checkConst(SubobjType))
3257 return false;
3258
3259 QualType PointeeType;
3260 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3261 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003262
3263 if (PointeeType.isNull() || !RHS.isInt() ||
3264 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003265 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003266 return false;
3267 }
3268
Richard Smithd6cc1982017-01-31 02:23:02 +00003269 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003270 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003271 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003272
3273 LValue LVal;
3274 LVal.setFrom(Info.Ctx, Subobj);
3275 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3276 return false;
3277 LVal.moveInto(Subobj);
3278 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003279 }
3280 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3281 llvm_unreachable("shouldn't encounter string elements here");
3282 }
3283};
3284} // end anonymous namespace
3285
3286const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3287
3288/// Perform a compound assignment of LVal <op>= RVal.
3289static bool handleCompoundAssignment(
3290 EvalInfo &Info, const Expr *E,
3291 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3292 BinaryOperatorKind Opcode, const APValue &RVal) {
3293 if (LVal.Designator.Invalid)
3294 return false;
3295
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003296 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003297 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003298 return false;
3299 }
3300
3301 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3302 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3303 RVal };
3304 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3305}
3306
3307namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003308struct IncDecSubobjectHandler {
3309 EvalInfo &Info;
3310 const Expr *E;
3311 AccessKinds AccessKind;
3312 APValue *Old;
3313
3314 typedef bool result_type;
3315
3316 bool checkConst(QualType QT) {
3317 // Assigning to a const object has undefined behavior.
3318 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003319 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003320 return false;
3321 }
3322 return true;
3323 }
3324
3325 bool failed() { return false; }
3326 bool found(APValue &Subobj, QualType SubobjType) {
3327 // Stash the old value. Also clear Old, so we don't clobber it later
3328 // if we're post-incrementing a complex.
3329 if (Old) {
3330 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003331 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003332 }
3333
3334 switch (Subobj.getKind()) {
3335 case APValue::Int:
3336 return found(Subobj.getInt(), SubobjType);
3337 case APValue::Float:
3338 return found(Subobj.getFloat(), SubobjType);
3339 case APValue::ComplexInt:
3340 return found(Subobj.getComplexIntReal(),
3341 SubobjType->castAs<ComplexType>()->getElementType()
3342 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3343 case APValue::ComplexFloat:
3344 return found(Subobj.getComplexFloatReal(),
3345 SubobjType->castAs<ComplexType>()->getElementType()
3346 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3347 case APValue::LValue:
3348 return foundPointer(Subobj, SubobjType);
3349 default:
3350 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003351 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003352 return false;
3353 }
3354 }
3355 bool found(APSInt &Value, QualType SubobjType) {
3356 if (!checkConst(SubobjType))
3357 return false;
3358
3359 if (!SubobjType->isIntegerType()) {
3360 // We don't support increment / decrement on integer-cast-to-pointer
3361 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003362 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003363 return false;
3364 }
3365
3366 if (Old) *Old = APValue(Value);
3367
3368 // bool arithmetic promotes to int, and the conversion back to bool
3369 // doesn't reduce mod 2^n, so special-case it.
3370 if (SubobjType->isBooleanType()) {
3371 if (AccessKind == AK_Increment)
3372 Value = 1;
3373 else
3374 Value = !Value;
3375 return true;
3376 }
3377
3378 bool WasNegative = Value.isNegative();
3379 if (AccessKind == AK_Increment) {
3380 ++Value;
3381
3382 if (!WasNegative && Value.isNegative() &&
3383 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3384 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003385 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003386 }
3387 } else {
3388 --Value;
3389
3390 if (WasNegative && !Value.isNegative() &&
3391 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3392 unsigned BitWidth = Value.getBitWidth();
3393 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3394 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003395 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003396 }
3397 }
3398 return true;
3399 }
3400 bool found(APFloat &Value, QualType SubobjType) {
3401 if (!checkConst(SubobjType))
3402 return false;
3403
3404 if (Old) *Old = APValue(Value);
3405
3406 APFloat One(Value.getSemantics(), 1);
3407 if (AccessKind == AK_Increment)
3408 Value.add(One, APFloat::rmNearestTiesToEven);
3409 else
3410 Value.subtract(One, APFloat::rmNearestTiesToEven);
3411 return true;
3412 }
3413 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3414 if (!checkConst(SubobjType))
3415 return false;
3416
3417 QualType PointeeType;
3418 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3419 PointeeType = PT->getPointeeType();
3420 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003421 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003422 return false;
3423 }
3424
3425 LValue LVal;
3426 LVal.setFrom(Info.Ctx, Subobj);
3427 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3428 AccessKind == AK_Increment ? 1 : -1))
3429 return false;
3430 LVal.moveInto(Subobj);
3431 return true;
3432 }
3433 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3434 llvm_unreachable("shouldn't encounter string elements here");
3435 }
3436};
3437} // end anonymous namespace
3438
3439/// Perform an increment or decrement on LVal.
3440static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3441 QualType LValType, bool IsIncrement, APValue *Old) {
3442 if (LVal.Designator.Invalid)
3443 return false;
3444
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003445 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003446 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003447 return false;
3448 }
3449
3450 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3451 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3452 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3453 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3454}
3455
Richard Smithe97cbd72011-11-11 04:05:33 +00003456/// Build an lvalue for the object argument of a member function call.
3457static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3458 LValue &This) {
3459 if (Object->getType()->isPointerType())
3460 return EvaluatePointer(Object, This, Info);
3461
3462 if (Object->isGLValue())
3463 return EvaluateLValue(Object, This, Info);
3464
Richard Smithd9f663b2013-04-22 15:31:51 +00003465 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003466 return EvaluateTemporary(Object, This, Info);
3467
Faisal Valie690b7a2016-07-02 22:34:24 +00003468 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003469 return false;
3470}
3471
3472/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3473/// lvalue referring to the result.
3474///
3475/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003476/// \param LV - An lvalue referring to the base of the member pointer.
3477/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003478/// \param IncludeMember - Specifies whether the member itself is included in
3479/// the resulting LValue subobject designator. This is not possible when
3480/// creating a bound member function.
3481/// \return The field or method declaration to which the member pointer refers,
3482/// or 0 if evaluation fails.
3483static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003484 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003485 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003486 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003487 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003488 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003489 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003490 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003491
3492 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3493 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003494 if (!MemPtr.getDecl()) {
3495 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003496 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003497 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003498 }
Richard Smith253c2a32012-01-27 01:14:48 +00003499
Richard Smith027bf112011-11-17 22:56:20 +00003500 if (MemPtr.isDerivedMember()) {
3501 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003502 // The end of the derived-to-base path for the base object must match the
3503 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003504 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003505 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003506 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003507 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003508 }
Richard Smith027bf112011-11-17 22:56:20 +00003509 unsigned PathLengthToMember =
3510 LV.Designator.Entries.size() - MemPtr.Path.size();
3511 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3512 const CXXRecordDecl *LVDecl = getAsBaseClass(
3513 LV.Designator.Entries[PathLengthToMember + I]);
3514 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003515 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003516 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003517 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003518 }
Richard Smith027bf112011-11-17 22:56:20 +00003519 }
3520
3521 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003522 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003523 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003524 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003525 } else if (!MemPtr.Path.empty()) {
3526 // Extend the LValue path with the member pointer's path.
3527 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3528 MemPtr.Path.size() + IncludeMember);
3529
3530 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003531 if (const PointerType *PT = LVType->getAs<PointerType>())
3532 LVType = PT->getPointeeType();
3533 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3534 assert(RD && "member pointer access on non-class-type expression");
3535 // The first class in the path is that of the lvalue.
3536 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3537 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003538 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003539 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003540 RD = Base;
3541 }
3542 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003543 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3544 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003545 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003546 }
3547
3548 // Add the member. Note that we cannot build bound member functions here.
3549 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003550 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003551 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003552 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003553 } else if (const IndirectFieldDecl *IFD =
3554 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003555 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003556 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003557 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003558 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003559 }
Richard Smith027bf112011-11-17 22:56:20 +00003560 }
3561
3562 return MemPtr.getDecl();
3563}
3564
Richard Smith84401042013-06-03 05:03:02 +00003565static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3566 const BinaryOperator *BO,
3567 LValue &LV,
3568 bool IncludeMember = true) {
3569 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3570
3571 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003572 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003573 MemberPtr MemPtr;
3574 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3575 }
Craig Topper36250ad2014-05-12 05:36:57 +00003576 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003577 }
3578
3579 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3580 BO->getRHS(), IncludeMember);
3581}
3582
Richard Smith027bf112011-11-17 22:56:20 +00003583/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3584/// the provided lvalue, which currently refers to the base object.
3585static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3586 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003587 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003588 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003589 return false;
3590
Richard Smitha8105bc2012-01-06 16:39:00 +00003591 QualType TargetQT = E->getType();
3592 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3593 TargetQT = PT->getPointeeType();
3594
3595 // Check this cast lands within the final derived-to-base subobject path.
3596 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
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;
3599 return false;
3600 }
3601
Richard Smith027bf112011-11-17 22:56:20 +00003602 // Check the type of the final cast. We don't need to check the path,
3603 // since a cast can only be formed if the path is unique.
3604 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003605 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3606 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003607 if (NewEntriesSize == D.MostDerivedPathLength)
3608 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3609 else
Richard Smith027bf112011-11-17 22:56:20 +00003610 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003611 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003612 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003613 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003614 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003615 }
Richard Smith027bf112011-11-17 22:56:20 +00003616
3617 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003618 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003619}
3620
Mike Stump876387b2009-10-27 22:09:17 +00003621namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003622enum EvalStmtResult {
3623 /// Evaluation failed.
3624 ESR_Failed,
3625 /// Hit a 'return' statement.
3626 ESR_Returned,
3627 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003628 ESR_Succeeded,
3629 /// Hit a 'continue' statement.
3630 ESR_Continue,
3631 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003632 ESR_Break,
3633 /// Still scanning for 'case' or 'default' statement.
3634 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003635};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003636}
Richard Smith254a73d2011-10-28 22:34:42 +00003637
Richard Smith97fcf4b2016-08-14 23:15:52 +00003638static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3639 // We don't need to evaluate the initializer for a static local.
3640 if (!VD->hasLocalStorage())
3641 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003642
Richard Smith97fcf4b2016-08-14 23:15:52 +00003643 LValue Result;
3644 Result.set(VD, Info.CurrentCall->Index);
3645 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003646
Richard Smith97fcf4b2016-08-14 23:15:52 +00003647 const Expr *InitE = VD->getInit();
3648 if (!InitE) {
3649 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3650 << false << VD->getType();
3651 Val = APValue();
3652 return false;
3653 }
Richard Smith51f03172013-06-20 03:00:05 +00003654
Richard Smith97fcf4b2016-08-14 23:15:52 +00003655 if (InitE->isValueDependent())
3656 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003657
Richard Smith97fcf4b2016-08-14 23:15:52 +00003658 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3659 // Wipe out any partially-computed value, to allow tracking that this
3660 // evaluation failed.
3661 Val = APValue();
3662 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003663 }
3664
3665 return true;
3666}
3667
Richard Smith97fcf4b2016-08-14 23:15:52 +00003668static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3669 bool OK = true;
3670
3671 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3672 OK &= EvaluateVarDecl(Info, VD);
3673
3674 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3675 for (auto *BD : DD->bindings())
3676 if (auto *VD = BD->getHoldingVar())
3677 OK &= EvaluateDecl(Info, VD);
3678
3679 return OK;
3680}
3681
3682
Richard Smith4e18ca52013-05-06 05:56:11 +00003683/// Evaluate a condition (either a variable declaration or an expression).
3684static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3685 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003686 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003687 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3688 return false;
3689 return EvaluateAsBooleanCondition(Cond, Result, Info);
3690}
3691
Richard Smith89210072016-04-04 23:29:43 +00003692namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003693/// \brief A location where the result (returned value) of evaluating a
3694/// statement should be stored.
3695struct StmtResult {
3696 /// The APValue that should be filled in with the returned value.
3697 APValue &Value;
3698 /// The location containing the result, if any (used to support RVO).
3699 const LValue *Slot;
3700};
Richard Smith89210072016-04-04 23:29:43 +00003701}
Richard Smith52a980a2015-08-28 02:43:42 +00003702
3703static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003704 const Stmt *S,
3705 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003706
3707/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003708static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003709 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003710 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003711 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003712 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003713 case ESR_Break:
3714 return ESR_Succeeded;
3715 case ESR_Succeeded:
3716 case ESR_Continue:
3717 return ESR_Continue;
3718 case ESR_Failed:
3719 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003720 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003721 return ESR;
3722 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003723 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003724}
3725
Richard Smith496ddcf2013-05-12 17:32:42 +00003726/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003727static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003728 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003729 BlockScopeRAII Scope(Info);
3730
Richard Smith496ddcf2013-05-12 17:32:42 +00003731 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003732 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003733 {
3734 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003735 if (const Stmt *Init = SS->getInit()) {
3736 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3737 if (ESR != ESR_Succeeded)
3738 return ESR;
3739 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003740 if (SS->getConditionVariable() &&
3741 !EvaluateDecl(Info, SS->getConditionVariable()))
3742 return ESR_Failed;
3743 if (!EvaluateInteger(SS->getCond(), Value, Info))
3744 return ESR_Failed;
3745 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003746
3747 // Find the switch case corresponding to the value of the condition.
3748 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003749 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003750 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3751 SC = SC->getNextSwitchCase()) {
3752 if (isa<DefaultStmt>(SC)) {
3753 Found = SC;
3754 continue;
3755 }
3756
3757 const CaseStmt *CS = cast<CaseStmt>(SC);
3758 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3759 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3760 : LHS;
3761 if (LHS <= Value && Value <= RHS) {
3762 Found = SC;
3763 break;
3764 }
3765 }
3766
3767 if (!Found)
3768 return ESR_Succeeded;
3769
3770 // Search the switch body for the switch case and evaluate it from there.
3771 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3772 case ESR_Break:
3773 return ESR_Succeeded;
3774 case ESR_Succeeded:
3775 case ESR_Continue:
3776 case ESR_Failed:
3777 case ESR_Returned:
3778 return ESR;
3779 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003780 // This can only happen if the switch case is nested within a statement
3781 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003782 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003783 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003784 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003785 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003786}
3787
Richard Smith254a73d2011-10-28 22:34:42 +00003788// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003789static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003790 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003791 if (!Info.nextStep(S))
3792 return ESR_Failed;
3793
Richard Smith496ddcf2013-05-12 17:32:42 +00003794 // If we're hunting down a 'case' or 'default' label, recurse through
3795 // substatements until we hit the label.
3796 if (Case) {
3797 // FIXME: We don't start the lifetime of objects whose initialization we
3798 // jump over. However, such objects must be of class type with a trivial
3799 // default constructor that initialize all subobjects, so must be empty,
3800 // so this almost never matters.
3801 switch (S->getStmtClass()) {
3802 case Stmt::CompoundStmtClass:
3803 // FIXME: Precompute which substatement of a compound statement we
3804 // would jump to, and go straight there rather than performing a
3805 // linear scan each time.
3806 case Stmt::LabelStmtClass:
3807 case Stmt::AttributedStmtClass:
3808 case Stmt::DoStmtClass:
3809 break;
3810
3811 case Stmt::CaseStmtClass:
3812 case Stmt::DefaultStmtClass:
3813 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003814 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003815 break;
3816
3817 case Stmt::IfStmtClass: {
3818 // FIXME: Precompute which side of an 'if' we would jump to, and go
3819 // straight there rather than scanning both sides.
3820 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003821
3822 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3823 // preceded by our switch label.
3824 BlockScopeRAII Scope(Info);
3825
Richard Smith496ddcf2013-05-12 17:32:42 +00003826 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3827 if (ESR != ESR_CaseNotFound || !IS->getElse())
3828 return ESR;
3829 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3830 }
3831
3832 case Stmt::WhileStmtClass: {
3833 EvalStmtResult ESR =
3834 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3835 if (ESR != ESR_Continue)
3836 return ESR;
3837 break;
3838 }
3839
3840 case Stmt::ForStmtClass: {
3841 const ForStmt *FS = cast<ForStmt>(S);
3842 EvalStmtResult ESR =
3843 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3844 if (ESR != ESR_Continue)
3845 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003846 if (FS->getInc()) {
3847 FullExpressionRAII IncScope(Info);
3848 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3849 return ESR_Failed;
3850 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003851 break;
3852 }
3853
3854 case Stmt::DeclStmtClass:
3855 // FIXME: If the variable has initialization that can't be jumped over,
3856 // bail out of any immediately-surrounding compound-statement too.
3857 default:
3858 return ESR_CaseNotFound;
3859 }
3860 }
3861
Richard Smith254a73d2011-10-28 22:34:42 +00003862 switch (S->getStmtClass()) {
3863 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003864 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003865 // Don't bother evaluating beyond an expression-statement which couldn't
3866 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003867 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003868 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003869 return ESR_Failed;
3870 return ESR_Succeeded;
3871 }
3872
Faisal Valie690b7a2016-07-02 22:34:24 +00003873 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003874 return ESR_Failed;
3875
3876 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003877 return ESR_Succeeded;
3878
Richard Smithd9f663b2013-04-22 15:31:51 +00003879 case Stmt::DeclStmtClass: {
3880 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003881 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003882 // Each declaration initialization is its own full-expression.
3883 // FIXME: This isn't quite right; if we're performing aggregate
3884 // initialization, each braced subexpression is its own full-expression.
3885 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003886 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003887 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003888 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003889 return ESR_Succeeded;
3890 }
3891
Richard Smith357362d2011-12-13 06:39:58 +00003892 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003893 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003894 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003895 if (RetExpr &&
3896 !(Result.Slot
3897 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3898 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003899 return ESR_Failed;
3900 return ESR_Returned;
3901 }
Richard Smith254a73d2011-10-28 22:34:42 +00003902
3903 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003904 BlockScopeRAII Scope(Info);
3905
Richard Smith254a73d2011-10-28 22:34:42 +00003906 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003907 for (const auto *BI : CS->body()) {
3908 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003909 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003910 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003911 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003912 return ESR;
3913 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003914 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003915 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003916
3917 case Stmt::IfStmtClass: {
3918 const IfStmt *IS = cast<IfStmt>(S);
3919
3920 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003921 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003922 if (const Stmt *Init = IS->getInit()) {
3923 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3924 if (ESR != ESR_Succeeded)
3925 return ESR;
3926 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003927 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003928 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003929 return ESR_Failed;
3930
3931 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3932 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3933 if (ESR != ESR_Succeeded)
3934 return ESR;
3935 }
3936 return ESR_Succeeded;
3937 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003938
3939 case Stmt::WhileStmtClass: {
3940 const WhileStmt *WS = cast<WhileStmt>(S);
3941 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003942 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003943 bool Continue;
3944 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3945 Continue))
3946 return ESR_Failed;
3947 if (!Continue)
3948 break;
3949
3950 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3951 if (ESR != ESR_Continue)
3952 return ESR;
3953 }
3954 return ESR_Succeeded;
3955 }
3956
3957 case Stmt::DoStmtClass: {
3958 const DoStmt *DS = cast<DoStmt>(S);
3959 bool Continue;
3960 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003961 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003962 if (ESR != ESR_Continue)
3963 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003964 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003965
Richard Smith08d6a2c2013-07-24 07:11:57 +00003966 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003967 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3968 return ESR_Failed;
3969 } while (Continue);
3970 return ESR_Succeeded;
3971 }
3972
3973 case Stmt::ForStmtClass: {
3974 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003975 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003976 if (FS->getInit()) {
3977 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3978 if (ESR != ESR_Succeeded)
3979 return ESR;
3980 }
3981 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003982 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003983 bool Continue = true;
3984 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3985 FS->getCond(), Continue))
3986 return ESR_Failed;
3987 if (!Continue)
3988 break;
3989
3990 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3991 if (ESR != ESR_Continue)
3992 return ESR;
3993
Richard Smith08d6a2c2013-07-24 07:11:57 +00003994 if (FS->getInc()) {
3995 FullExpressionRAII IncScope(Info);
3996 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3997 return ESR_Failed;
3998 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003999 }
4000 return ESR_Succeeded;
4001 }
4002
Richard Smith896e0d72013-05-06 06:51:17 +00004003 case Stmt::CXXForRangeStmtClass: {
4004 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004005 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004006
4007 // Initialize the __range variable.
4008 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4009 if (ESR != ESR_Succeeded)
4010 return ESR;
4011
4012 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004013 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4014 if (ESR != ESR_Succeeded)
4015 return ESR;
4016 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004017 if (ESR != ESR_Succeeded)
4018 return ESR;
4019
4020 while (true) {
4021 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004022 {
4023 bool Continue = true;
4024 FullExpressionRAII CondExpr(Info);
4025 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4026 return ESR_Failed;
4027 if (!Continue)
4028 break;
4029 }
Richard Smith896e0d72013-05-06 06:51:17 +00004030
4031 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004032 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004033 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4034 if (ESR != ESR_Succeeded)
4035 return ESR;
4036
4037 // Loop body.
4038 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4039 if (ESR != ESR_Continue)
4040 return ESR;
4041
4042 // Increment: ++__begin
4043 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4044 return ESR_Failed;
4045 }
4046
4047 return ESR_Succeeded;
4048 }
4049
Richard Smith496ddcf2013-05-12 17:32:42 +00004050 case Stmt::SwitchStmtClass:
4051 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4052
Richard Smith4e18ca52013-05-06 05:56:11 +00004053 case Stmt::ContinueStmtClass:
4054 return ESR_Continue;
4055
4056 case Stmt::BreakStmtClass:
4057 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004058
4059 case Stmt::LabelStmtClass:
4060 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4061
4062 case Stmt::AttributedStmtClass:
4063 // As a general principle, C++11 attributes can be ignored without
4064 // any semantic impact.
4065 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4066 Case);
4067
4068 case Stmt::CaseStmtClass:
4069 case Stmt::DefaultStmtClass:
4070 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004071 }
4072}
4073
Richard Smithcc36f692011-12-22 02:22:31 +00004074/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4075/// default constructor. If so, we'll fold it whether or not it's marked as
4076/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4077/// so we need special handling.
4078static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004079 const CXXConstructorDecl *CD,
4080 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004081 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4082 return false;
4083
Richard Smith66e05fe2012-01-18 05:21:49 +00004084 // Value-initialization does not call a trivial default constructor, so such a
4085 // call is a core constant expression whether or not the constructor is
4086 // constexpr.
4087 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004088 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004089 // FIXME: If DiagDecl is an implicitly-declared special member function,
4090 // we should be much more explicit about why it's not constexpr.
4091 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4092 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4093 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004094 } else {
4095 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4096 }
4097 }
4098 return true;
4099}
4100
Richard Smith357362d2011-12-13 06:39:58 +00004101/// CheckConstexprFunction - Check that a function can be called in a constant
4102/// expression.
4103static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4104 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004105 const FunctionDecl *Definition,
4106 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004107 // Potential constant expressions can contain calls to declared, but not yet
4108 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004109 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004110 Declaration->isConstexpr())
4111 return false;
4112
Richard Smith0838f3a2013-05-14 05:18:44 +00004113 // Bail out with no diagnostic if the function declaration itself is invalid.
4114 // We will have produced a relevant diagnostic while parsing it.
4115 if (Declaration->isInvalidDecl())
4116 return false;
4117
Richard Smith357362d2011-12-13 06:39:58 +00004118 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004119 if (Definition && Definition->isConstexpr() &&
4120 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004121 return true;
4122
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004123 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004124 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004125
Richard Smith5179eb72016-06-28 19:03:57 +00004126 // If this function is not constexpr because it is an inherited
4127 // non-constexpr constructor, diagnose that directly.
4128 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4129 if (CD && CD->isInheritingConstructor()) {
4130 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004131 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004132 DiagDecl = CD = Inherited;
4133 }
4134
4135 // FIXME: If DiagDecl is an implicitly-declared special member function
4136 // or an inheriting constructor, we should be much more explicit about why
4137 // it's not constexpr.
4138 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004139 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004140 << CD->getInheritedConstructor().getConstructor()->getParent();
4141 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004142 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004143 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004144 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4145 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004146 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004147 }
4148 return false;
4149}
4150
Richard Smithbe6dd812014-11-19 21:27:17 +00004151/// Determine if a class has any fields that might need to be copied by a
4152/// trivial copy or move operation.
4153static bool hasFields(const CXXRecordDecl *RD) {
4154 if (!RD || RD->isEmpty())
4155 return false;
4156 for (auto *FD : RD->fields()) {
4157 if (FD->isUnnamedBitfield())
4158 continue;
4159 return true;
4160 }
4161 for (auto &Base : RD->bases())
4162 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4163 return true;
4164 return false;
4165}
4166
Richard Smithd62306a2011-11-10 06:34:14 +00004167namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004168typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004169}
4170
4171/// EvaluateArgs - Evaluate the arguments to a function call.
4172static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4173 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004174 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004175 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004176 I != E; ++I) {
4177 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4178 // If we're checking for a potential constant expression, evaluate all
4179 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004180 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004181 return false;
4182 Success = false;
4183 }
4184 }
4185 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004186}
4187
Richard Smith254a73d2011-10-28 22:34:42 +00004188/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004189static bool HandleFunctionCall(SourceLocation CallLoc,
4190 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004191 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004192 EvalInfo &Info, APValue &Result,
4193 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004194 ArgVector ArgValues(Args.size());
4195 if (!EvaluateArgs(Args, ArgValues, Info))
4196 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004197
Richard Smith253c2a32012-01-27 01:14:48 +00004198 if (!Info.CheckCallLimit(CallLoc))
4199 return false;
4200
4201 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004202
4203 // For a trivial copy or move assignment, perform an APValue copy. This is
4204 // essential for unions, where the operations performed by the assignment
4205 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004206 //
4207 // Skip this for non-union classes with no fields; in that case, the defaulted
4208 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004209 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004210 if (MD && MD->isDefaulted() &&
4211 (MD->getParent()->isUnion() ||
4212 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004213 assert(This &&
4214 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4215 LValue RHS;
4216 RHS.setFrom(Info.Ctx, ArgValues[0]);
4217 APValue RHSValue;
4218 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4219 RHS, RHSValue))
4220 return false;
4221 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4222 RHSValue))
4223 return false;
4224 This->moveInto(Result);
4225 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004226 } else if (MD && isLambdaCallOperator(MD)) {
4227 // We're in a lambda; determine the lambda capture field maps.
4228 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4229 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004230 }
4231
Richard Smith52a980a2015-08-28 02:43:42 +00004232 StmtResult Ret = {Result, ResultSlot};
4233 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004234 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004235 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004236 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004237 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004238 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004239 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004240}
4241
Richard Smithd62306a2011-11-10 06:34:14 +00004242/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004243static bool HandleConstructorCall(const Expr *E, const LValue &This,
4244 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004245 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004246 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004247 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004248 if (!Info.CheckCallLimit(CallLoc))
4249 return false;
4250
Richard Smith3607ffe2012-02-13 03:54:03 +00004251 const CXXRecordDecl *RD = Definition->getParent();
4252 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004253 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004254 return false;
4255 }
4256
Richard Smith5179eb72016-06-28 19:03:57 +00004257 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004258
Richard Smith52a980a2015-08-28 02:43:42 +00004259 // FIXME: Creating an APValue just to hold a nonexistent return value is
4260 // wasteful.
4261 APValue RetVal;
4262 StmtResult Ret = {RetVal, nullptr};
4263
Richard Smith5179eb72016-06-28 19:03:57 +00004264 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004265 if (Definition->isDelegatingConstructor()) {
4266 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004267 {
4268 FullExpressionRAII InitScope(Info);
4269 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4270 return false;
4271 }
Richard Smith52a980a2015-08-28 02:43:42 +00004272 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004273 }
4274
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004275 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004276 // essential for unions (or classes with anonymous union members), where the
4277 // operations performed by the constructor cannot be represented by
4278 // ctor-initializers.
4279 //
4280 // Skip this for empty non-union classes; we should not perform an
4281 // lvalue-to-rvalue conversion on them because their copy constructor does not
4282 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004283 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004284 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004285 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004286 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004287 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004288 return handleLValueToRValueConversion(
4289 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4290 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004291 }
4292
4293 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004294 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004295 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004296 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004297
John McCalld7bca762012-05-01 00:38:49 +00004298 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004299 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4300
Richard Smith08d6a2c2013-07-24 07:11:57 +00004301 // A scope for temporaries lifetime-extended by reference members.
4302 BlockScopeRAII LifetimeExtendedScope(Info);
4303
Richard Smith253c2a32012-01-27 01:14:48 +00004304 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004305 unsigned BasesSeen = 0;
4306#ifndef NDEBUG
4307 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4308#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004309 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004310 LValue Subobject = This;
4311 APValue *Value = &Result;
4312
4313 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004314 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004315 if (I->isBaseInitializer()) {
4316 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004317#ifndef NDEBUG
4318 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004319 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004320 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4321 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4322 "base class initializers not in expected order");
4323 ++BaseIt;
4324#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004325 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004326 BaseType->getAsCXXRecordDecl(), &Layout))
4327 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004328 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004329 } else if ((FD = I->getMember())) {
4330 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004331 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004332 if (RD->isUnion()) {
4333 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004334 Value = &Result.getUnionValue();
4335 } else {
4336 Value = &Result.getStructField(FD->getFieldIndex());
4337 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004338 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004339 // Walk the indirect field decl's chain to find the object to initialize,
4340 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004341 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004342 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004343 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4344 // Switch the union field if it differs. This happens if we had
4345 // preceding zero-initialization, and we're now initializing a union
4346 // subobject other than the first.
4347 // FIXME: In this case, the values of the other subobjects are
4348 // specified, since zero-initialization sets all padding bits to zero.
4349 if (Value->isUninit() ||
4350 (Value->isUnion() && Value->getUnionField() != FD)) {
4351 if (CD->isUnion())
4352 *Value = APValue(FD);
4353 else
4354 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004355 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004356 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004357 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004358 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004359 if (CD->isUnion())
4360 Value = &Value->getUnionValue();
4361 else
4362 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004363 }
Richard Smithd62306a2011-11-10 06:34:14 +00004364 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004365 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004366 }
Richard Smith253c2a32012-01-27 01:14:48 +00004367
Richard Smith08d6a2c2013-07-24 07:11:57 +00004368 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004369 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4370 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004371 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004372 // If we're checking for a potential constant expression, evaluate all
4373 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004374 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004375 return false;
4376 Success = false;
4377 }
Richard Smithd62306a2011-11-10 06:34:14 +00004378 }
4379
Richard Smithd9f663b2013-04-22 15:31:51 +00004380 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004381 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004382}
4383
Richard Smith5179eb72016-06-28 19:03:57 +00004384static bool HandleConstructorCall(const Expr *E, const LValue &This,
4385 ArrayRef<const Expr*> Args,
4386 const CXXConstructorDecl *Definition,
4387 EvalInfo &Info, APValue &Result) {
4388 ArgVector ArgValues(Args.size());
4389 if (!EvaluateArgs(Args, ArgValues, Info))
4390 return false;
4391
4392 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4393 Info, Result);
4394}
4395
Eli Friedman9a156e52008-11-12 09:44:48 +00004396//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004397// Generic Evaluation
4398//===----------------------------------------------------------------------===//
4399namespace {
4400
Aaron Ballman68af21c2014-01-03 19:26:43 +00004401template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004402class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004403 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004404private:
Richard Smith52a980a2015-08-28 02:43:42 +00004405 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004406 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004407 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004408 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004409 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004410 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004411 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004412
Richard Smith17100ba2012-02-16 02:46:34 +00004413 // Check whether a conditional operator with a non-constant condition is a
4414 // potential constant expression. If neither arm is a potential constant
4415 // expression, then the conditional operator is not either.
4416 template<typename ConditionalOperator>
4417 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004418 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004419
4420 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004421 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004422 {
Richard Smith17100ba2012-02-16 02:46:34 +00004423 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004424 StmtVisitorTy::Visit(E->getFalseExpr());
4425 if (Diag.empty())
4426 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004427 }
Richard Smith17100ba2012-02-16 02:46:34 +00004428
George Burgess IV8c892b52016-05-25 22:31:54 +00004429 {
4430 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004431 Diag.clear();
4432 StmtVisitorTy::Visit(E->getTrueExpr());
4433 if (Diag.empty())
4434 return;
4435 }
4436
4437 Error(E, diag::note_constexpr_conditional_never_const);
4438 }
4439
4440
4441 template<typename ConditionalOperator>
4442 bool HandleConditionalOperator(const ConditionalOperator *E) {
4443 bool BoolResult;
4444 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004445 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004446 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004447 return false;
4448 }
4449 if (Info.noteFailure()) {
4450 StmtVisitorTy::Visit(E->getTrueExpr());
4451 StmtVisitorTy::Visit(E->getFalseExpr());
4452 }
Richard Smith17100ba2012-02-16 02:46:34 +00004453 return false;
4454 }
4455
4456 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4457 return StmtVisitorTy::Visit(EvalExpr);
4458 }
4459
Peter Collingbournee9200682011-05-13 03:29:01 +00004460protected:
4461 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004462 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004463 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4464
Richard Smith92b1ce02011-12-12 09:28:41 +00004465 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004466 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004467 }
4468
Aaron Ballman68af21c2014-01-03 19:26:43 +00004469 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004470
4471public:
4472 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4473
4474 EvalInfo &getEvalInfo() { return Info; }
4475
Richard Smithf57d8cb2011-12-09 22:58:01 +00004476 /// Report an evaluation error. This should only be called when an error is
4477 /// first discovered. When propagating an error, just return false.
4478 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004479 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004480 return false;
4481 }
4482 bool Error(const Expr *E) {
4483 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4484 }
4485
Aaron Ballman68af21c2014-01-03 19:26:43 +00004486 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004487 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004488 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004489 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004490 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004491 }
4492
Aaron Ballman68af21c2014-01-03 19:26:43 +00004493 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004494 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004495 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004496 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004497 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004498 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004499 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004500 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004501 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004502 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004503 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004504 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004505 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004506 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004507 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004508 // The initializer may not have been parsed yet, or might be erroneous.
4509 if (!E->getExpr())
4510 return Error(E);
4511 return StmtVisitorTy::Visit(E->getExpr());
4512 }
Richard Smith5894a912011-12-19 22:12:41 +00004513 // We cannot create any objects for which cleanups are required, so there is
4514 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004515 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004516 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004517
Aaron Ballman68af21c2014-01-03 19:26:43 +00004518 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004519 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4520 return static_cast<Derived*>(this)->VisitCastExpr(E);
4521 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004522 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004523 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4524 return static_cast<Derived*>(this)->VisitCastExpr(E);
4525 }
4526
Aaron Ballman68af21c2014-01-03 19:26:43 +00004527 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004528 switch (E->getOpcode()) {
4529 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004530 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004531
4532 case BO_Comma:
4533 VisitIgnoredValue(E->getLHS());
4534 return StmtVisitorTy::Visit(E->getRHS());
4535
4536 case BO_PtrMemD:
4537 case BO_PtrMemI: {
4538 LValue Obj;
4539 if (!HandleMemberPointerAccess(Info, E, Obj))
4540 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004541 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004542 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004543 return false;
4544 return DerivedSuccess(Result, E);
4545 }
4546 }
4547 }
4548
Aaron Ballman68af21c2014-01-03 19:26:43 +00004549 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004550 // Evaluate and cache the common expression. We treat it as a temporary,
4551 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004552 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004553 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004554 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004555
Richard Smith17100ba2012-02-16 02:46:34 +00004556 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004557 }
4558
Aaron Ballman68af21c2014-01-03 19:26:43 +00004559 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004560 bool IsBcpCall = false;
4561 // If the condition (ignoring parens) is a __builtin_constant_p call,
4562 // the result is a constant expression if it can be folded without
4563 // side-effects. This is an important GNU extension. See GCC PR38377
4564 // for discussion.
4565 if (const CallExpr *CallCE =
4566 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004567 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004568 IsBcpCall = true;
4569
4570 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4571 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004572 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004573 return false;
4574
Richard Smith6d4c6582013-11-05 22:18:15 +00004575 FoldConstant Fold(Info, IsBcpCall);
4576 if (!HandleConditionalOperator(E)) {
4577 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004578 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004579 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004580
4581 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004582 }
4583
Aaron Ballman68af21c2014-01-03 19:26:43 +00004584 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004585 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4586 return DerivedSuccess(*Value, E);
4587
4588 const Expr *Source = E->getSourceExpr();
4589 if (!Source)
4590 return Error(E);
4591 if (Source == E) { // sanity checking.
4592 assert(0 && "OpaqueValueExpr recursively refers to itself");
4593 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004594 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004595 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004596 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004597
Aaron Ballman68af21c2014-01-03 19:26:43 +00004598 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004599 APValue Result;
4600 if (!handleCallExpr(E, Result, nullptr))
4601 return false;
4602 return DerivedSuccess(Result, E);
4603 }
4604
4605 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004606 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004607 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004608 QualType CalleeType = Callee->getType();
4609
Craig Topper36250ad2014-05-12 05:36:57 +00004610 const FunctionDecl *FD = nullptr;
4611 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004612 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004613 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004614
Richard Smithe97cbd72011-11-11 04:05:33 +00004615 // Extract function decl and 'this' pointer from the callee.
4616 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004617 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004618 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4619 // Explicit bound member calls, such as x.f() or p->g();
4620 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004621 return false;
4622 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004623 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004624 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004625 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4626 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004627 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4628 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004629 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004630 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004631 return Error(Callee);
4632
4633 FD = dyn_cast<FunctionDecl>(Member);
4634 if (!FD)
4635 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004636 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004637 LValue Call;
4638 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004639 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004640
Richard Smitha8105bc2012-01-06 16:39:00 +00004641 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004642 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004643 FD = dyn_cast_or_null<FunctionDecl>(
4644 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004645 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004646 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004647 // Don't call function pointers which have been cast to some other type.
4648 // Per DR (no number yet), the caller and callee can differ in noexcept.
4649 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4650 CalleeType->getPointeeType(), FD->getType())) {
4651 return Error(E);
4652 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004653
4654 // Overloaded operator calls to member functions are represented as normal
4655 // calls with '*this' as the first argument.
4656 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4657 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004658 // FIXME: When selecting an implicit conversion for an overloaded
4659 // operator delete, we sometimes try to evaluate calls to conversion
4660 // operators without a 'this' parameter!
4661 if (Args.empty())
4662 return Error(E);
4663
Nick Lewycky13073a62017-06-12 21:15:44 +00004664 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004665 return false;
4666 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004667 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004668 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004669 // Map the static invoker for the lambda back to the call operator.
4670 // Conveniently, we don't have to slice out the 'this' argument (as is
4671 // being done for the non-static case), since a static member function
4672 // doesn't have an implicit argument passed in.
4673 const CXXRecordDecl *ClosureClass = MD->getParent();
4674 assert(
4675 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4676 "Number of captures must be zero for conversion to function-ptr");
4677
4678 const CXXMethodDecl *LambdaCallOp =
4679 ClosureClass->getLambdaCallOperator();
4680
4681 // Set 'FD', the function that will be called below, to the call
4682 // operator. If the closure object represents a generic lambda, find
4683 // the corresponding specialization of the call operator.
4684
4685 if (ClosureClass->isGenericLambda()) {
4686 assert(MD->isFunctionTemplateSpecialization() &&
4687 "A generic lambda's static-invoker function must be a "
4688 "template specialization");
4689 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4690 FunctionTemplateDecl *CallOpTemplate =
4691 LambdaCallOp->getDescribedFunctionTemplate();
4692 void *InsertPos = nullptr;
4693 FunctionDecl *CorrespondingCallOpSpecialization =
4694 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4695 assert(CorrespondingCallOpSpecialization &&
4696 "We must always have a function call operator specialization "
4697 "that corresponds to our static invoker specialization");
4698 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4699 } else
4700 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004701 }
4702
Daniel Jasperffdee092017-05-02 19:21:42 +00004703
Richard Smithe97cbd72011-11-11 04:05:33 +00004704 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004705 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004706
Richard Smith47b34932012-02-01 02:39:43 +00004707 if (This && !This->checkSubobject(Info, E, CSK_This))
4708 return false;
4709
Richard Smith3607ffe2012-02-13 03:54:03 +00004710 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4711 // calls to such functions in constant expressions.
4712 if (This && !HasQualifier &&
4713 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4714 return Error(E, diag::note_constexpr_virtual_call);
4715
Craig Topper36250ad2014-05-12 05:36:57 +00004716 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004717 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004718
Nick Lewycky13073a62017-06-12 21:15:44 +00004719 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4720 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004721 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004722 return false;
4723
Richard Smith52a980a2015-08-28 02:43:42 +00004724 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004725 }
4726
Aaron Ballman68af21c2014-01-03 19:26:43 +00004727 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004728 return StmtVisitorTy::Visit(E->getInitializer());
4729 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004730 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004731 if (E->getNumInits() == 0)
4732 return DerivedZeroInitialization(E);
4733 if (E->getNumInits() == 1)
4734 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004735 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004736 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004737 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004738 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004739 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004740 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004741 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004742 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004743 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004744 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004745 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004746
Richard Smithd62306a2011-11-10 06:34:14 +00004747 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004748 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004749 assert(!E->isArrow() && "missing call to bound member function?");
4750
Richard Smith2e312c82012-03-03 22:46:17 +00004751 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004752 if (!Evaluate(Val, Info, E->getBase()))
4753 return false;
4754
4755 QualType BaseTy = E->getBase()->getType();
4756
4757 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004758 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004759 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004760 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004761 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4762
Richard Smith3229b742013-05-05 21:17:10 +00004763 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004764 SubobjectDesignator Designator(BaseTy);
4765 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004766
Richard Smith3229b742013-05-05 21:17:10 +00004767 APValue Result;
4768 return extractSubobject(Info, E, Obj, Designator, Result) &&
4769 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004770 }
4771
Aaron Ballman68af21c2014-01-03 19:26:43 +00004772 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004773 switch (E->getCastKind()) {
4774 default:
4775 break;
4776
Richard Smitha23ab512013-05-23 00:30:41 +00004777 case CK_AtomicToNonAtomic: {
4778 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004779 // This does not need to be done in place even for class/array types:
4780 // atomic-to-non-atomic conversion implies copying the object
4781 // representation.
4782 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004783 return false;
4784 return DerivedSuccess(AtomicVal, E);
4785 }
4786
Richard Smith11562c52011-10-28 17:51:58 +00004787 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004788 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004789 return StmtVisitorTy::Visit(E->getSubExpr());
4790
4791 case CK_LValueToRValue: {
4792 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004793 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4794 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004795 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004796 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004797 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004798 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004799 return false;
4800 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004801 }
4802 }
4803
Richard Smithf57d8cb2011-12-09 22:58:01 +00004804 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004805 }
4806
Aaron Ballman68af21c2014-01-03 19:26:43 +00004807 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004808 return VisitUnaryPostIncDec(UO);
4809 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004810 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004811 return VisitUnaryPostIncDec(UO);
4812 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004813 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004814 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004815 return Error(UO);
4816
4817 LValue LVal;
4818 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4819 return false;
4820 APValue RVal;
4821 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4822 UO->isIncrementOp(), &RVal))
4823 return false;
4824 return DerivedSuccess(RVal, UO);
4825 }
4826
Aaron Ballman68af21c2014-01-03 19:26:43 +00004827 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004828 // We will have checked the full-expressions inside the statement expression
4829 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004830 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004831 return Error(E);
4832
Richard Smith08d6a2c2013-07-24 07:11:57 +00004833 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004834 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004835 if (CS->body_empty())
4836 return true;
4837
Richard Smith51f03172013-06-20 03:00:05 +00004838 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4839 BE = CS->body_end();
4840 /**/; ++BI) {
4841 if (BI + 1 == BE) {
4842 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4843 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004844 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004845 diag::note_constexpr_stmt_expr_unsupported);
4846 return false;
4847 }
4848 return this->Visit(FinalExpr);
4849 }
4850
4851 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004852 StmtResult Result = { ReturnValue, nullptr };
4853 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004854 if (ESR != ESR_Succeeded) {
4855 // FIXME: If the statement-expression terminated due to 'return',
4856 // 'break', or 'continue', it would be nice to propagate that to
4857 // the outer statement evaluation rather than bailing out.
4858 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004859 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004860 diag::note_constexpr_stmt_expr_unsupported);
4861 return false;
4862 }
4863 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004864
4865 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004866 }
4867
Richard Smith4a678122011-10-24 18:44:57 +00004868 /// Visit a value which is evaluated, but whose value is ignored.
4869 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004870 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004871 }
David Majnemere9807b22016-02-26 04:23:19 +00004872
4873 /// Potentially visit a MemberExpr's base expression.
4874 void VisitIgnoredBaseExpression(const Expr *E) {
4875 // While MSVC doesn't evaluate the base expression, it does diagnose the
4876 // presence of side-effecting behavior.
4877 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4878 return;
4879 VisitIgnoredValue(E);
4880 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004881};
4882
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004883}
Peter Collingbournee9200682011-05-13 03:29:01 +00004884
4885//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004886// Common base class for lvalue and temporary evaluation.
4887//===----------------------------------------------------------------------===//
4888namespace {
4889template<class Derived>
4890class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004891 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004892protected:
4893 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004894 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004895 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004896 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004897
4898 bool Success(APValue::LValueBase B) {
4899 Result.set(B);
4900 return true;
4901 }
4902
George Burgess IVf9013bf2017-02-10 22:52:29 +00004903 bool evaluatePointer(const Expr *E, LValue &Result) {
4904 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4905 }
4906
Richard Smith027bf112011-11-17 22:56:20 +00004907public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004908 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4909 : ExprEvaluatorBaseTy(Info), Result(Result),
4910 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00004911
Richard Smith2e312c82012-03-03 22:46:17 +00004912 bool Success(const APValue &V, const Expr *E) {
4913 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004914 return true;
4915 }
Richard Smith027bf112011-11-17 22:56:20 +00004916
Richard Smith027bf112011-11-17 22:56:20 +00004917 bool VisitMemberExpr(const MemberExpr *E) {
4918 // Handle non-static data members.
4919 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004920 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004921 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004922 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00004923 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004924 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004925 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004926 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004927 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004928 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004929 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004930 BaseTy = E->getBase()->getType();
4931 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004932 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004933 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004934 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004935 Result.setInvalid(E);
4936 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004937 }
Richard Smith027bf112011-11-17 22:56:20 +00004938
Richard Smith1b78b3d2012-01-25 22:15:11 +00004939 const ValueDecl *MD = E->getMemberDecl();
4940 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4941 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4942 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4943 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004944 if (!HandleLValueMember(this->Info, E, Result, FD))
4945 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004946 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004947 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4948 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004949 } else
4950 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004951
Richard Smith1b78b3d2012-01-25 22:15:11 +00004952 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004953 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004954 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004955 RefValue))
4956 return false;
4957 return Success(RefValue, E);
4958 }
4959 return true;
4960 }
4961
4962 bool VisitBinaryOperator(const BinaryOperator *E) {
4963 switch (E->getOpcode()) {
4964 default:
4965 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4966
4967 case BO_PtrMemD:
4968 case BO_PtrMemI:
4969 return HandleMemberPointerAccess(this->Info, E, Result);
4970 }
4971 }
4972
4973 bool VisitCastExpr(const CastExpr *E) {
4974 switch (E->getCastKind()) {
4975 default:
4976 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4977
4978 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004979 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004980 if (!this->Visit(E->getSubExpr()))
4981 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004982
4983 // Now figure out the necessary offset to add to the base LV to get from
4984 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004985 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4986 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004987 }
4988 }
4989};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004990}
Richard Smith027bf112011-11-17 22:56:20 +00004991
4992//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004993// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004994//
4995// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4996// function designators (in C), decl references to void objects (in C), and
4997// temporaries (if building with -Wno-address-of-temporary).
4998//
4999// LValue evaluation produces values comprising a base expression of one of the
5000// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005001// - Declarations
5002// * VarDecl
5003// * FunctionDecl
5004// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005005// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005006// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005007// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005008// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005009// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005010// * ObjCEncodeExpr
5011// * AddrLabelExpr
5012// * BlockExpr
5013// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005014// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005015// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005016// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005017// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5018// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005019// * A MaterializeTemporaryExpr that has static storage duration, with no
5020// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005021// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005022//===----------------------------------------------------------------------===//
5023namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005024class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005025 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005026public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005027 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5028 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005029
Richard Smith11562c52011-10-28 17:51:58 +00005030 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005031 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005032
Peter Collingbournee9200682011-05-13 03:29:01 +00005033 bool VisitDeclRefExpr(const DeclRefExpr *E);
5034 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005035 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005036 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5037 bool VisitMemberExpr(const MemberExpr *E);
5038 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5039 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005040 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005041 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005042 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5043 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005044 bool VisitUnaryReal(const UnaryOperator *E);
5045 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005046 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5047 return VisitUnaryPreIncDec(UO);
5048 }
5049 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5050 return VisitUnaryPreIncDec(UO);
5051 }
Richard Smith3229b742013-05-05 21:17:10 +00005052 bool VisitBinAssign(const BinaryOperator *BO);
5053 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005054
Peter Collingbournee9200682011-05-13 03:29:01 +00005055 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005056 switch (E->getCastKind()) {
5057 default:
Richard Smith027bf112011-11-17 22:56:20 +00005058 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005059
Eli Friedmance3e02a2011-10-11 00:13:24 +00005060 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005061 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005062 if (!Visit(E->getSubExpr()))
5063 return false;
5064 Result.Designator.setInvalid();
5065 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005066
Richard Smith027bf112011-11-17 22:56:20 +00005067 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005068 if (!Visit(E->getSubExpr()))
5069 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005070 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005071 }
5072 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005073};
5074} // end anonymous namespace
5075
Richard Smith11562c52011-10-28 17:51:58 +00005076/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005077/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005078/// * function designators in C, and
5079/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005080/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005081static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5082 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005083 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005084 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005085 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005086}
5087
Peter Collingbournee9200682011-05-13 03:29:01 +00005088bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005089 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005090 return Success(FD);
5091 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005092 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005093 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005094 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005095 return Error(E);
5096}
Richard Smith733237d2011-10-24 23:14:33 +00005097
Faisal Vali0528a312016-11-13 06:09:16 +00005098
Richard Smith11562c52011-10-28 17:51:58 +00005099bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005100
5101 // If we are within a lambda's call operator, check whether the 'VD' referred
5102 // to within 'E' actually represents a lambda-capture that maps to a
5103 // data-member/field within the closure object, and if so, evaluate to the
5104 // field or what the field refers to.
5105 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5106 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5107 if (Info.checkingPotentialConstantExpression())
5108 return false;
5109 // Start with 'Result' referring to the complete closure object...
5110 Result = *Info.CurrentCall->This;
5111 // ... then update it to refer to the field of the closure object
5112 // that represents the capture.
5113 if (!HandleLValueMember(Info, E, Result, FD))
5114 return false;
5115 // And if the field is of reference type, update 'Result' to refer to what
5116 // the field refers to.
5117 if (FD->getType()->isReferenceType()) {
5118 APValue RVal;
5119 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5120 RVal))
5121 return false;
5122 Result.setFrom(Info.Ctx, RVal);
5123 }
5124 return true;
5125 }
5126 }
Craig Topper36250ad2014-05-12 05:36:57 +00005127 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005128 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5129 // Only if a local variable was declared in the function currently being
5130 // evaluated, do we expect to be able to find its value in the current
5131 // frame. (Otherwise it was likely declared in an enclosing context and
5132 // could either have a valid evaluatable value (for e.g. a constexpr
5133 // variable) or be ill-formed (and trigger an appropriate evaluation
5134 // diagnostic)).
5135 if (Info.CurrentCall->Callee &&
5136 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5137 Frame = Info.CurrentCall;
5138 }
5139 }
Richard Smith3229b742013-05-05 21:17:10 +00005140
Richard Smithfec09922011-11-01 16:57:24 +00005141 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005142 if (Frame) {
5143 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005144 return true;
5145 }
Richard Smithce40ad62011-11-12 22:28:03 +00005146 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005147 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005148
Richard Smith3229b742013-05-05 21:17:10 +00005149 APValue *V;
5150 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005151 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005152 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005153 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005154 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005155 return false;
5156 }
Richard Smith3229b742013-05-05 21:17:10 +00005157 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005158}
5159
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005160bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5161 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005162 // Walk through the expression to find the materialized temporary itself.
5163 SmallVector<const Expr *, 2> CommaLHSs;
5164 SmallVector<SubobjectAdjustment, 2> Adjustments;
5165 const Expr *Inner = E->GetTemporaryExpr()->
5166 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005167
Richard Smith84401042013-06-03 05:03:02 +00005168 // If we passed any comma operators, evaluate their LHSs.
5169 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5170 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5171 return false;
5172
Richard Smithe6c01442013-06-05 00:46:14 +00005173 // A materialized temporary with static storage duration can appear within the
5174 // result of a constant expression evaluation, so we need to preserve its
5175 // value for use outside this evaluation.
5176 APValue *Value;
5177 if (E->getStorageDuration() == SD_Static) {
5178 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005179 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005180 Result.set(E);
5181 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005182 Value = &Info.CurrentCall->
5183 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005184 Result.set(E, Info.CurrentCall->Index);
5185 }
5186
Richard Smithea4ad5d2013-06-06 08:19:16 +00005187 QualType Type = Inner->getType();
5188
Richard Smith84401042013-06-03 05:03:02 +00005189 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005190 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5191 (E->getStorageDuration() == SD_Static &&
5192 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5193 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005194 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005195 }
Richard Smith84401042013-06-03 05:03:02 +00005196
5197 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005198 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5199 --I;
5200 switch (Adjustments[I].Kind) {
5201 case SubobjectAdjustment::DerivedToBaseAdjustment:
5202 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5203 Type, Result))
5204 return false;
5205 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5206 break;
5207
5208 case SubobjectAdjustment::FieldAdjustment:
5209 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5210 return false;
5211 Type = Adjustments[I].Field->getType();
5212 break;
5213
5214 case SubobjectAdjustment::MemberPointerAdjustment:
5215 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5216 Adjustments[I].Ptr.RHS))
5217 return false;
5218 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5219 break;
5220 }
5221 }
5222
5223 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005224}
5225
Peter Collingbournee9200682011-05-13 03:29:01 +00005226bool
5227LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005228 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5229 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005230 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5231 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005232 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005233}
5234
Richard Smith6e525142011-12-27 12:18:28 +00005235bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005236 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005237 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005238
Faisal Valie690b7a2016-07-02 22:34:24 +00005239 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005240 << E->getExprOperand()->getType()
5241 << E->getExprOperand()->getSourceRange();
5242 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005243}
5244
Francois Pichet0066db92012-04-16 04:08:35 +00005245bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5246 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005247}
Francois Pichet0066db92012-04-16 04:08:35 +00005248
Peter Collingbournee9200682011-05-13 03:29:01 +00005249bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005250 // Handle static data members.
5251 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005252 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005253 return VisitVarDecl(E, VD);
5254 }
5255
Richard Smith254a73d2011-10-28 22:34:42 +00005256 // Handle static member functions.
5257 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5258 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005259 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005260 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005261 }
5262 }
5263
Richard Smithd62306a2011-11-10 06:34:14 +00005264 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005265 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005266}
5267
Peter Collingbournee9200682011-05-13 03:29:01 +00005268bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005269 // FIXME: Deal with vectors as array subscript bases.
5270 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005271 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005272
Nick Lewyckyad888682017-04-27 07:27:36 +00005273 bool Success = true;
5274 if (!evaluatePointer(E->getBase(), Result)) {
5275 if (!Info.noteFailure())
5276 return false;
5277 Success = false;
5278 }
Mike Stump11289f42009-09-09 15:08:12 +00005279
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005280 APSInt Index;
5281 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005282 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005283
Nick Lewyckyad888682017-04-27 07:27:36 +00005284 return Success &&
5285 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005286}
Eli Friedman9a156e52008-11-12 09:44:48 +00005287
Peter Collingbournee9200682011-05-13 03:29:01 +00005288bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005289 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005290}
5291
Richard Smith66c96992012-02-18 22:04:06 +00005292bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5293 if (!Visit(E->getSubExpr()))
5294 return false;
5295 // __real is a no-op on scalar lvalues.
5296 if (E->getSubExpr()->getType()->isAnyComplexType())
5297 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5298 return true;
5299}
5300
5301bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5302 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5303 "lvalue __imag__ on scalar?");
5304 if (!Visit(E->getSubExpr()))
5305 return false;
5306 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5307 return true;
5308}
5309
Richard Smith243ef902013-05-05 23:31:59 +00005310bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005311 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005312 return Error(UO);
5313
5314 if (!this->Visit(UO->getSubExpr()))
5315 return false;
5316
Richard Smith243ef902013-05-05 23:31:59 +00005317 return handleIncDec(
5318 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005319 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005320}
5321
5322bool LValueExprEvaluator::VisitCompoundAssignOperator(
5323 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005324 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005325 return Error(CAO);
5326
Richard Smith3229b742013-05-05 21:17:10 +00005327 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005328
5329 // The overall lvalue result is the result of evaluating the LHS.
5330 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005331 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005332 Evaluate(RHS, this->Info, CAO->getRHS());
5333 return false;
5334 }
5335
Richard Smith3229b742013-05-05 21:17:10 +00005336 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5337 return false;
5338
Richard Smith43e77732013-05-07 04:50:00 +00005339 return handleCompoundAssignment(
5340 this->Info, CAO,
5341 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5342 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005343}
5344
5345bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005346 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005347 return Error(E);
5348
Richard Smith3229b742013-05-05 21:17:10 +00005349 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005350
5351 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005352 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005353 Evaluate(NewVal, this->Info, E->getRHS());
5354 return false;
5355 }
5356
Richard Smith3229b742013-05-05 21:17:10 +00005357 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5358 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005359
5360 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005361 NewVal);
5362}
5363
Eli Friedman9a156e52008-11-12 09:44:48 +00005364//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005365// Pointer Evaluation
5366//===----------------------------------------------------------------------===//
5367
George Burgess IVe3763372016-12-22 02:50:20 +00005368/// \brief Attempts to compute the number of bytes available at the pointer
5369/// returned by a function with the alloc_size attribute. Returns true if we
5370/// were successful. Places an unsigned number into `Result`.
5371///
5372/// This expects the given CallExpr to be a call to a function with an
5373/// alloc_size attribute.
5374static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5375 const CallExpr *Call,
5376 llvm::APInt &Result) {
5377 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5378
5379 // alloc_size args are 1-indexed, 0 means not present.
5380 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5381 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5382 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5383 if (Call->getNumArgs() <= SizeArgNo)
5384 return false;
5385
5386 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5387 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5388 return false;
5389 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5390 return false;
5391 Into = Into.zextOrSelf(BitsInSizeT);
5392 return true;
5393 };
5394
5395 APSInt SizeOfElem;
5396 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5397 return false;
5398
5399 if (!AllocSize->getNumElemsParam()) {
5400 Result = std::move(SizeOfElem);
5401 return true;
5402 }
5403
5404 APSInt NumberOfElems;
5405 // Argument numbers start at 1
5406 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5407 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5408 return false;
5409
5410 bool Overflow;
5411 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5412 if (Overflow)
5413 return false;
5414
5415 Result = std::move(BytesAvailable);
5416 return true;
5417}
5418
5419/// \brief Convenience function. LVal's base must be a call to an alloc_size
5420/// function.
5421static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5422 const LValue &LVal,
5423 llvm::APInt &Result) {
5424 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5425 "Can't get the size of a non alloc_size function");
5426 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5427 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5428 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5429}
5430
5431/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5432/// a function with the alloc_size attribute. If it was possible to do so, this
5433/// function will return true, make Result's Base point to said function call,
5434/// and mark Result's Base as invalid.
5435static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5436 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005437 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005438 return false;
5439
5440 // Because we do no form of static analysis, we only support const variables.
5441 //
5442 // Additionally, we can't support parameters, nor can we support static
5443 // variables (in the latter case, use-before-assign isn't UB; in the former,
5444 // we have no clue what they'll be assigned to).
5445 const auto *VD =
5446 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5447 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5448 return false;
5449
5450 const Expr *Init = VD->getAnyInitializer();
5451 if (!Init)
5452 return false;
5453
5454 const Expr *E = Init->IgnoreParens();
5455 if (!tryUnwrapAllocSizeCall(E))
5456 return false;
5457
5458 // Store E instead of E unwrapped so that the type of the LValue's base is
5459 // what the user wanted.
5460 Result.setInvalid(E);
5461
5462 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Martin Bohme542c84b2017-08-30 10:44:46 +00005463 Result.addUnsizedArray(Info, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005464 return true;
5465}
5466
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005467namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005468class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005469 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005470 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005471 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005472
Peter Collingbournee9200682011-05-13 03:29:01 +00005473 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005474 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005475 return true;
5476 }
George Burgess IVe3763372016-12-22 02:50:20 +00005477
George Burgess IVf9013bf2017-02-10 22:52:29 +00005478 bool evaluateLValue(const Expr *E, LValue &Result) {
5479 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5480 }
5481
5482 bool evaluatePointer(const Expr *E, LValue &Result) {
5483 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5484 }
5485
George Burgess IVe3763372016-12-22 02:50:20 +00005486 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005487public:
Mike Stump11289f42009-09-09 15:08:12 +00005488
George Burgess IVf9013bf2017-02-10 22:52:29 +00005489 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5490 : ExprEvaluatorBaseTy(info), Result(Result),
5491 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005492
Richard Smith2e312c82012-03-03 22:46:17 +00005493 bool Success(const APValue &V, const Expr *E) {
5494 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005495 return true;
5496 }
Richard Smithfddd3842011-12-30 21:15:51 +00005497 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005498 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5499 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005500 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005501 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005502
John McCall45d55e42010-05-07 21:00:08 +00005503 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005504 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005505 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005506 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005507 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005508 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5509 if (Info.noteFailure())
5510 EvaluateIgnoredValue(Info, E->getSubExpr());
5511 return Error(E);
5512 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005513 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005514 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005515 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005516 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005517 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005518 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005519 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005520 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005521 }
Richard Smithd62306a2011-11-10 06:34:14 +00005522 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005523 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005524 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005525 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005526 if (!Info.CurrentCall->This) {
5527 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005528 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005529 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005530 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005531 return false;
5532 }
Richard Smithd62306a2011-11-10 06:34:14 +00005533 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005534 // If we are inside a lambda's call operator, the 'this' expression refers
5535 // to the enclosing '*this' object (either by value or reference) which is
5536 // either copied into the closure object's field that represents the '*this'
5537 // or refers to '*this'.
5538 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5539 // Update 'Result' to refer to the data member/field of the closure object
5540 // that represents the '*this' capture.
5541 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005542 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005543 return false;
5544 // If we captured '*this' by reference, replace the field with its referent.
5545 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5546 ->isPointerType()) {
5547 APValue RVal;
5548 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5549 RVal))
5550 return false;
5551
5552 Result.setFrom(Info.Ctx, RVal);
5553 }
5554 }
Richard Smithd62306a2011-11-10 06:34:14 +00005555 return true;
5556 }
John McCallc07a0c72011-02-17 10:25:35 +00005557
Eli Friedman449fe542009-03-23 04:56:01 +00005558 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005559};
Chris Lattner05706e882008-07-11 18:11:29 +00005560} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005561
George Burgess IVf9013bf2017-02-10 22:52:29 +00005562static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5563 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005564 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005565 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005566}
5567
John McCall45d55e42010-05-07 21:00:08 +00005568bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005569 if (E->getOpcode() != BO_Add &&
5570 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005571 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005572
Chris Lattner05706e882008-07-11 18:11:29 +00005573 const Expr *PExp = E->getLHS();
5574 const Expr *IExp = E->getRHS();
5575 if (IExp->getType()->isPointerType())
5576 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005577
George Burgess IVf9013bf2017-02-10 22:52:29 +00005578 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005579 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005580 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005581
John McCall45d55e42010-05-07 21:00:08 +00005582 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005583 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005584 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005585
Richard Smith96e0c102011-11-04 02:25:55 +00005586 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005587 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005588
Ted Kremenek28831752012-08-23 20:46:57 +00005589 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005590 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005591}
Eli Friedman9a156e52008-11-12 09:44:48 +00005592
John McCall45d55e42010-05-07 21:00:08 +00005593bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005594 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005595}
Mike Stump11289f42009-09-09 15:08:12 +00005596
Peter Collingbournee9200682011-05-13 03:29:01 +00005597bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5598 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005599
Eli Friedman847a2bc2009-12-27 05:43:15 +00005600 switch (E->getCastKind()) {
5601 default:
5602 break;
5603
John McCalle3027922010-08-25 11:45:40 +00005604 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005605 case CK_CPointerToObjCPointerCast:
5606 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005607 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005608 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005609 if (!Visit(SubExpr))
5610 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005611 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5612 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5613 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005614 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005615 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005616 if (SubExpr->getType()->isVoidPointerType())
5617 CCEDiag(E, diag::note_constexpr_invalid_cast)
5618 << 3 << SubExpr->getType();
5619 else
5620 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5621 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005622 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5623 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005624 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005625
Anders Carlsson18275092010-10-31 20:41:46 +00005626 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005627 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005628 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005629 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005630 if (!Result.Base && Result.Offset.isZero())
5631 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005632
Richard Smithd62306a2011-11-10 06:34:14 +00005633 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005634 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005635 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5636 castAs<PointerType>()->getPointeeType(),
5637 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005638
Richard Smith027bf112011-11-17 22:56:20 +00005639 case CK_BaseToDerived:
5640 if (!Visit(E->getSubExpr()))
5641 return false;
5642 if (!Result.Base && Result.Offset.isZero())
5643 return true;
5644 return HandleBaseToDerivedCast(Info, E, Result);
5645
Richard Smith0b0a0b62011-10-29 20:57:55 +00005646 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005647 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005648 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005649
John McCalle3027922010-08-25 11:45:40 +00005650 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005651 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5652
Richard Smith2e312c82012-03-03 22:46:17 +00005653 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005654 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005655 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005656
John McCall45d55e42010-05-07 21:00:08 +00005657 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005658 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5659 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005660 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005661 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005662 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005663 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005664 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005665 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005666 return true;
5667 } else {
5668 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005669 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005670 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005671 }
5672 }
Martin Bohme542c84b2017-08-30 10:44:46 +00005673 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005674 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005675 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005676 return false;
5677 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005678 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005679 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005680 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005681 return false;
5682 }
Richard Smith96e0c102011-11-04 02:25:55 +00005683 // The result is a pointer to the first element of the array.
Martin Bohme542c84b2017-08-30 10:44:46 +00005684 if (const ConstantArrayType *CAT
5685 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
Richard Smitha8105bc2012-01-06 16:39:00 +00005686 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005687 else
Martin Bohme542c84b2017-08-30 10:44:46 +00005688 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005689 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005690
John McCalle3027922010-08-25 11:45:40 +00005691 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005692 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005693
5694 case CK_LValueToRValue: {
5695 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005696 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005697 return false;
5698
5699 APValue RVal;
5700 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5701 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5702 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005703 return InvalidBaseOK &&
5704 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005705 return Success(RVal, E);
5706 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005707 }
5708
Richard Smith11562c52011-10-28 17:51:58 +00005709 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005710}
Chris Lattner05706e882008-07-11 18:11:29 +00005711
Hal Finkel0dd05d42014-10-03 17:18:37 +00005712static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5713 // C++ [expr.alignof]p3:
5714 // When alignof is applied to a reference type, the result is the
5715 // alignment of the referenced type.
5716 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5717 T = Ref->getPointeeType();
5718
5719 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005720 if (T.getQualifiers().hasUnaligned())
5721 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005722 return Info.Ctx.toCharUnitsFromBits(
5723 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5724}
5725
5726static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5727 E = E->IgnoreParens();
5728
5729 // The kinds of expressions that we have special-case logic here for
5730 // should be kept up to date with the special checks for those
5731 // expressions in Sema.
5732
5733 // alignof decl is always accepted, even if it doesn't make sense: we default
5734 // to 1 in those cases.
5735 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5736 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5737 /*RefAsPointee*/true);
5738
5739 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5740 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5741 /*RefAsPointee*/true);
5742
5743 return GetAlignOfType(Info, E->getType());
5744}
5745
George Burgess IVe3763372016-12-22 02:50:20 +00005746// To be clear: this happily visits unsupported builtins. Better name welcomed.
5747bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5748 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5749 return true;
5750
George Burgess IVf9013bf2017-02-10 22:52:29 +00005751 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005752 return false;
5753
5754 Result.setInvalid(E);
5755 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Martin Bohme542c84b2017-08-30 10:44:46 +00005756 Result.addUnsizedArray(Info, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005757 return true;
5758}
5759
Peter Collingbournee9200682011-05-13 03:29:01 +00005760bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005761 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005762 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005763
Richard Smith6328cbd2016-11-16 00:57:23 +00005764 if (unsigned BuiltinOp = E->getBuiltinCallee())
5765 return VisitBuiltinCallExpr(E, BuiltinOp);
5766
George Burgess IVe3763372016-12-22 02:50:20 +00005767 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005768}
5769
5770bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5771 unsigned BuiltinOp) {
5772 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005773 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005774 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005775 case Builtin::BI__builtin_assume_aligned: {
5776 // We need to be very careful here because: if the pointer does not have the
5777 // asserted alignment, then the behavior is undefined, and undefined
5778 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005779 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005780 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005781
Hal Finkel0dd05d42014-10-03 17:18:37 +00005782 LValue OffsetResult(Result);
5783 APSInt Alignment;
5784 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5785 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005786 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005787
5788 if (E->getNumArgs() > 2) {
5789 APSInt Offset;
5790 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5791 return false;
5792
Richard Smith642a2362017-01-30 23:30:26 +00005793 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005794 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5795 }
5796
5797 // If there is a base object, then it must have the correct alignment.
5798 if (OffsetResult.Base) {
5799 CharUnits BaseAlignment;
5800 if (const ValueDecl *VD =
5801 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5802 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5803 } else {
5804 BaseAlignment =
5805 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5806 }
5807
5808 if (BaseAlignment < Align) {
5809 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005810 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005811 CCEDiag(E->getArg(0),
5812 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005813 << (unsigned)BaseAlignment.getQuantity()
5814 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005815 return false;
5816 }
5817 }
5818
5819 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005820 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005821 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005822
Richard Smith642a2362017-01-30 23:30:26 +00005823 (OffsetResult.Base
5824 ? CCEDiag(E->getArg(0),
5825 diag::note_constexpr_baa_insufficient_alignment) << 1
5826 : CCEDiag(E->getArg(0),
5827 diag::note_constexpr_baa_value_insufficient_alignment))
5828 << (int)OffsetResult.Offset.getQuantity()
5829 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005830 return false;
5831 }
5832
5833 return true;
5834 }
Richard Smithe9507952016-11-12 01:39:56 +00005835
5836 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005837 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005838 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005839 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005840 if (Info.getLangOpts().CPlusPlus11)
5841 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5842 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005843 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005844 else
5845 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5846 // Fall through.
5847 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005848 case Builtin::BI__builtin_wcschr:
5849 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005850 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005851 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005852 if (!Visit(E->getArg(0)))
5853 return false;
5854 APSInt Desired;
5855 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5856 return false;
5857 uint64_t MaxLength = uint64_t(-1);
5858 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005859 BuiltinOp != Builtin::BIwcschr &&
5860 BuiltinOp != Builtin::BI__builtin_strchr &&
5861 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005862 APSInt N;
5863 if (!EvaluateInteger(E->getArg(2), N, Info))
5864 return false;
5865 MaxLength = N.getExtValue();
5866 }
5867
Richard Smith8110c9d2016-11-29 19:45:17 +00005868 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005869
Richard Smith8110c9d2016-11-29 19:45:17 +00005870 // Figure out what value we're actually looking for (after converting to
5871 // the corresponding unsigned type if necessary).
5872 uint64_t DesiredVal;
5873 bool StopAtNull = false;
5874 switch (BuiltinOp) {
5875 case Builtin::BIstrchr:
5876 case Builtin::BI__builtin_strchr:
5877 // strchr compares directly to the passed integer, and therefore
5878 // always fails if given an int that is not a char.
5879 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5880 E->getArg(1)->getType(),
5881 Desired),
5882 Desired))
5883 return ZeroInitialization(E);
5884 StopAtNull = true;
5885 // Fall through.
5886 case Builtin::BImemchr:
5887 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005888 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005889 // memchr compares by converting both sides to unsigned char. That's also
5890 // correct for strchr if we get this far (to cope with plain char being
5891 // unsigned in the strchr case).
5892 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5893 break;
Richard Smithe9507952016-11-12 01:39:56 +00005894
Richard Smith8110c9d2016-11-29 19:45:17 +00005895 case Builtin::BIwcschr:
5896 case Builtin::BI__builtin_wcschr:
5897 StopAtNull = true;
5898 // Fall through.
5899 case Builtin::BIwmemchr:
5900 case Builtin::BI__builtin_wmemchr:
5901 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5902 DesiredVal = Desired.getZExtValue();
5903 break;
5904 }
Richard Smithe9507952016-11-12 01:39:56 +00005905
5906 for (; MaxLength; --MaxLength) {
5907 APValue Char;
5908 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5909 !Char.isInt())
5910 return false;
5911 if (Char.getInt().getZExtValue() == DesiredVal)
5912 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005913 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005914 break;
5915 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5916 return false;
5917 }
5918 // Not found: return nullptr.
5919 return ZeroInitialization(E);
5920 }
5921
Richard Smith6cbd65d2013-07-11 02:27:57 +00005922 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005923 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005924 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005925}
Chris Lattner05706e882008-07-11 18:11:29 +00005926
5927//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005928// Member Pointer Evaluation
5929//===----------------------------------------------------------------------===//
5930
5931namespace {
5932class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005933 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005934 MemberPtr &Result;
5935
5936 bool Success(const ValueDecl *D) {
5937 Result = MemberPtr(D);
5938 return true;
5939 }
5940public:
5941
5942 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5943 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5944
Richard Smith2e312c82012-03-03 22:46:17 +00005945 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005946 Result.setFrom(V);
5947 return true;
5948 }
Richard Smithfddd3842011-12-30 21:15:51 +00005949 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005950 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005951 }
5952
5953 bool VisitCastExpr(const CastExpr *E);
5954 bool VisitUnaryAddrOf(const UnaryOperator *E);
5955};
5956} // end anonymous namespace
5957
5958static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5959 EvalInfo &Info) {
5960 assert(E->isRValue() && E->getType()->isMemberPointerType());
5961 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5962}
5963
5964bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5965 switch (E->getCastKind()) {
5966 default:
5967 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5968
5969 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005970 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005971 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005972
5973 case CK_BaseToDerivedMemberPointer: {
5974 if (!Visit(E->getSubExpr()))
5975 return false;
5976 if (E->path_empty())
5977 return true;
5978 // Base-to-derived member pointer casts store the path in derived-to-base
5979 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5980 // the wrong end of the derived->base arc, so stagger the path by one class.
5981 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5982 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5983 PathI != PathE; ++PathI) {
5984 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5985 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5986 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005987 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005988 }
5989 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5990 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005991 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005992 return true;
5993 }
5994
5995 case CK_DerivedToBaseMemberPointer:
5996 if (!Visit(E->getSubExpr()))
5997 return false;
5998 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5999 PathE = E->path_end(); PathI != PathE; ++PathI) {
6000 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6001 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6002 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006003 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006004 }
6005 return true;
6006 }
6007}
6008
6009bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6010 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6011 // member can be formed.
6012 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6013}
6014
6015//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006016// Record Evaluation
6017//===----------------------------------------------------------------------===//
6018
6019namespace {
6020 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006021 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006022 const LValue &This;
6023 APValue &Result;
6024 public:
6025
6026 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6027 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6028
Richard Smith2e312c82012-03-03 22:46:17 +00006029 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006030 Result = V;
6031 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006032 }
Richard Smithb8348f52016-05-12 22:16:28 +00006033 bool ZeroInitialization(const Expr *E) {
6034 return ZeroInitialization(E, E->getType());
6035 }
6036 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006037
Richard Smith52a980a2015-08-28 02:43:42 +00006038 bool VisitCallExpr(const CallExpr *E) {
6039 return handleCallExpr(E, Result, &This);
6040 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006041 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006042 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006043 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6044 return VisitCXXConstructExpr(E, E->getType());
6045 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006046 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006047 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006048 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006049 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006050 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006051}
Richard Smithd62306a2011-11-10 06:34:14 +00006052
Richard Smithfddd3842011-12-30 21:15:51 +00006053/// Perform zero-initialization on an object of non-union class type.
6054/// C++11 [dcl.init]p5:
6055/// To zero-initialize an object or reference of type T means:
6056/// [...]
6057/// -- if T is a (possibly cv-qualified) non-union class type,
6058/// each non-static data member and each base-class subobject is
6059/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006060static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6061 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006062 const LValue &This, APValue &Result) {
6063 assert(!RD->isUnion() && "Expected non-union class type");
6064 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6065 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006066 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006067
John McCalld7bca762012-05-01 00:38:49 +00006068 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006069 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6070
6071 if (CD) {
6072 unsigned Index = 0;
6073 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006074 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006075 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6076 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006077 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6078 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006079 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006080 Result.getStructBase(Index)))
6081 return false;
6082 }
6083 }
6084
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006085 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006086 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006087 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006088 continue;
6089
6090 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006091 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006092 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006093
David Blaikie2d7c57e2012-04-30 02:36:29 +00006094 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006095 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006096 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006097 return false;
6098 }
6099
6100 return true;
6101}
6102
Richard Smithb8348f52016-05-12 22:16:28 +00006103bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6104 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006105 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006106 if (RD->isUnion()) {
6107 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6108 // object's first non-static named data member is zero-initialized
6109 RecordDecl::field_iterator I = RD->field_begin();
6110 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006111 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006112 return true;
6113 }
6114
6115 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006116 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006117 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006118 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006119 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006120 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006121 }
6122
Richard Smith5d108602012-02-17 00:44:16 +00006123 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006124 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006125 return false;
6126 }
6127
Richard Smitha8105bc2012-01-06 16:39:00 +00006128 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006129}
6130
Richard Smithe97cbd72011-11-11 04:05:33 +00006131bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6132 switch (E->getCastKind()) {
6133 default:
6134 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6135
6136 case CK_ConstructorConversion:
6137 return Visit(E->getSubExpr());
6138
6139 case CK_DerivedToBase:
6140 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006141 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006142 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006143 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006144 if (!DerivedObject.isStruct())
6145 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006146
6147 // Derived-to-base rvalue conversion: just slice off the derived part.
6148 APValue *Value = &DerivedObject;
6149 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6150 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6151 PathE = E->path_end(); PathI != PathE; ++PathI) {
6152 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6153 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6154 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6155 RD = Base;
6156 }
6157 Result = *Value;
6158 return true;
6159 }
6160 }
6161}
6162
Richard Smithd62306a2011-11-10 06:34:14 +00006163bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006164 if (E->isTransparent())
6165 return Visit(E->getInit(0));
6166
Richard Smithd62306a2011-11-10 06:34:14 +00006167 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006168 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006169 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6170
6171 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006172 const FieldDecl *Field = E->getInitializedFieldInUnion();
6173 Result = APValue(Field);
6174 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006175 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006176
6177 // If the initializer list for a union does not contain any elements, the
6178 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006179 // FIXME: The element should be initialized from an initializer list.
6180 // Is this difference ever observable for initializer lists which
6181 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006182 ImplicitValueInitExpr VIE(Field->getType());
6183 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6184
Richard Smithd62306a2011-11-10 06:34:14 +00006185 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006186 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6187 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006188
6189 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6190 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6191 isa<CXXDefaultInitExpr>(InitExpr));
6192
Richard Smithb228a862012-02-15 02:18:13 +00006193 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006194 }
6195
Richard Smith872307e2016-03-08 22:17:41 +00006196 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006197 if (Result.isUninit())
6198 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6199 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006200 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006201 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006202
6203 // Initialize base classes.
6204 if (CXXRD) {
6205 for (const auto &Base : CXXRD->bases()) {
6206 assert(ElementNo < E->getNumInits() && "missing init for base class");
6207 const Expr *Init = E->getInit(ElementNo);
6208
6209 LValue Subobject = This;
6210 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6211 return false;
6212
6213 APValue &FieldVal = Result.getStructBase(ElementNo);
6214 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006215 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006216 return false;
6217 Success = false;
6218 }
6219 ++ElementNo;
6220 }
6221 }
6222
6223 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006224 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006225 // Anonymous bit-fields are not considered members of the class for
6226 // purposes of aggregate initialization.
6227 if (Field->isUnnamedBitfield())
6228 continue;
6229
6230 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006231
Richard Smith253c2a32012-01-27 01:14:48 +00006232 bool HaveInit = ElementNo < E->getNumInits();
6233
6234 // FIXME: Diagnostics here should point to the end of the initializer
6235 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006236 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006237 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006238 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006239
6240 // Perform an implicit value-initialization for members beyond the end of
6241 // the initializer list.
6242 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006243 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006244
Richard Smith852c9db2013-04-20 22:23:05 +00006245 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6246 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6247 isa<CXXDefaultInitExpr>(Init));
6248
Richard Smith49ca8aa2013-08-06 07:09:20 +00006249 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6250 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6251 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006252 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006253 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006254 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006255 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006256 }
6257 }
6258
Richard Smith253c2a32012-01-27 01:14:48 +00006259 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006260}
6261
Richard Smithb8348f52016-05-12 22:16:28 +00006262bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6263 QualType T) {
6264 // Note that E's type is not necessarily the type of our class here; we might
6265 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006266 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006267 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6268
Richard Smithfddd3842011-12-30 21:15:51 +00006269 bool ZeroInit = E->requiresZeroInitialization();
6270 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006271 // If we've already performed zero-initialization, we're already done.
6272 if (!Result.isUninit())
6273 return true;
6274
Richard Smithda3f4fd2014-03-05 23:32:50 +00006275 // We can get here in two different ways:
6276 // 1) We're performing value-initialization, and should zero-initialize
6277 // the object, or
6278 // 2) We're performing default-initialization of an object with a trivial
6279 // constexpr default constructor, in which case we should start the
6280 // lifetimes of all the base subobjects (there can be no data member
6281 // subobjects in this case) per [basic.life]p1.
6282 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006283 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006284 }
6285
Craig Topper36250ad2014-05-12 05:36:57 +00006286 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006287 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006288
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006289 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006290 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006291
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006292 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006293 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006294 if (const MaterializeTemporaryExpr *ME
6295 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6296 return Visit(ME->GetTemporaryExpr());
6297
Richard Smithb8348f52016-05-12 22:16:28 +00006298 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006299 return false;
6300
Craig Topper5fc8fc22014-08-27 06:28:36 +00006301 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006302 return HandleConstructorCall(E, This, Args,
6303 cast<CXXConstructorDecl>(Definition), Info,
6304 Result);
6305}
6306
6307bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6308 const CXXInheritedCtorInitExpr *E) {
6309 if (!Info.CurrentCall) {
6310 assert(Info.checkingPotentialConstantExpression());
6311 return false;
6312 }
6313
6314 const CXXConstructorDecl *FD = E->getConstructor();
6315 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6316 return false;
6317
6318 const FunctionDecl *Definition = nullptr;
6319 auto Body = FD->getBody(Definition);
6320
6321 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6322 return false;
6323
6324 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006325 cast<CXXConstructorDecl>(Definition), Info,
6326 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006327}
6328
Richard Smithcc1b96d2013-06-12 22:31:48 +00006329bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6330 const CXXStdInitializerListExpr *E) {
6331 const ConstantArrayType *ArrayType =
6332 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6333
6334 LValue Array;
6335 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6336 return false;
6337
6338 // Get a pointer to the first element of the array.
6339 Array.addArray(Info, E, ArrayType);
6340
6341 // FIXME: Perform the checks on the field types in SemaInit.
6342 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6343 RecordDecl::field_iterator Field = Record->field_begin();
6344 if (Field == Record->field_end())
6345 return Error(E);
6346
6347 // Start pointer.
6348 if (!Field->getType()->isPointerType() ||
6349 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6350 ArrayType->getElementType()))
6351 return Error(E);
6352
6353 // FIXME: What if the initializer_list type has base classes, etc?
6354 Result = APValue(APValue::UninitStruct(), 0, 2);
6355 Array.moveInto(Result.getStructField(0));
6356
6357 if (++Field == Record->field_end())
6358 return Error(E);
6359
6360 if (Field->getType()->isPointerType() &&
6361 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6362 ArrayType->getElementType())) {
6363 // End pointer.
6364 if (!HandleLValueArrayAdjustment(Info, E, Array,
6365 ArrayType->getElementType(),
6366 ArrayType->getSize().getZExtValue()))
6367 return false;
6368 Array.moveInto(Result.getStructField(1));
6369 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6370 // Length.
6371 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6372 else
6373 return Error(E);
6374
6375 if (++Field != Record->field_end())
6376 return Error(E);
6377
6378 return true;
6379}
6380
Faisal Valic72a08c2017-01-09 03:02:53 +00006381bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6382 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6383 if (ClosureClass->isInvalidDecl()) return false;
6384
6385 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006386
Faisal Vali051e3a22017-02-16 04:12:21 +00006387 const size_t NumFields =
6388 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006389
6390 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6391 E->capture_init_end()) &&
6392 "The number of lambda capture initializers should equal the number of "
6393 "fields within the closure type");
6394
Faisal Vali051e3a22017-02-16 04:12:21 +00006395 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6396 // Iterate through all the lambda's closure object's fields and initialize
6397 // them.
6398 auto *CaptureInitIt = E->capture_init_begin();
6399 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6400 bool Success = true;
6401 for (const auto *Field : ClosureClass->fields()) {
6402 assert(CaptureInitIt != E->capture_init_end());
6403 // Get the initializer for this field
6404 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006405
Faisal Vali051e3a22017-02-16 04:12:21 +00006406 // If there is no initializer, either this is a VLA or an error has
6407 // occurred.
6408 if (!CurFieldInit)
6409 return Error(E);
6410
6411 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6412 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6413 if (!Info.keepEvaluatingAfterFailure())
6414 return false;
6415 Success = false;
6416 }
6417 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006418 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006419 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006420}
6421
Richard Smithd62306a2011-11-10 06:34:14 +00006422static bool EvaluateRecord(const Expr *E, const LValue &This,
6423 APValue &Result, EvalInfo &Info) {
6424 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006425 "can't evaluate expression as a record rvalue");
6426 return RecordExprEvaluator(Info, This, Result).Visit(E);
6427}
6428
6429//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006430// Temporary Evaluation
6431//
6432// Temporaries are represented in the AST as rvalues, but generally behave like
6433// lvalues. The full-object of which the temporary is a subobject is implicitly
6434// materialized so that a reference can bind to it.
6435//===----------------------------------------------------------------------===//
6436namespace {
6437class TemporaryExprEvaluator
6438 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6439public:
6440 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006441 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006442
6443 /// Visit an expression which constructs the value of this temporary.
6444 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006445 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006446 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6447 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006448 }
6449
6450 bool VisitCastExpr(const CastExpr *E) {
6451 switch (E->getCastKind()) {
6452 default:
6453 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6454
6455 case CK_ConstructorConversion:
6456 return VisitConstructExpr(E->getSubExpr());
6457 }
6458 }
6459 bool VisitInitListExpr(const InitListExpr *E) {
6460 return VisitConstructExpr(E);
6461 }
6462 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6463 return VisitConstructExpr(E);
6464 }
6465 bool VisitCallExpr(const CallExpr *E) {
6466 return VisitConstructExpr(E);
6467 }
Richard Smith513955c2014-12-17 19:24:30 +00006468 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6469 return VisitConstructExpr(E);
6470 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006471 bool VisitLambdaExpr(const LambdaExpr *E) {
6472 return VisitConstructExpr(E);
6473 }
Richard Smith027bf112011-11-17 22:56:20 +00006474};
6475} // end anonymous namespace
6476
6477/// Evaluate an expression of record type as a temporary.
6478static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006479 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006480 return TemporaryExprEvaluator(Info, Result).Visit(E);
6481}
6482
6483//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006484// Vector Evaluation
6485//===----------------------------------------------------------------------===//
6486
6487namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006488 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006489 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006490 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006491 public:
Mike Stump11289f42009-09-09 15:08:12 +00006492
Richard Smith2d406342011-10-22 21:10:00 +00006493 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6494 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006495
Craig Topper9798b932015-09-29 04:30:05 +00006496 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006497 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6498 // FIXME: remove this APValue copy.
6499 Result = APValue(V.data(), V.size());
6500 return true;
6501 }
Richard Smith2e312c82012-03-03 22:46:17 +00006502 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006503 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006504 Result = V;
6505 return true;
6506 }
Richard Smithfddd3842011-12-30 21:15:51 +00006507 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006508
Richard Smith2d406342011-10-22 21:10:00 +00006509 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006510 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006511 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006512 bool VisitInitListExpr(const InitListExpr *E);
6513 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006514 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006515 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006516 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006517 };
6518} // end anonymous namespace
6519
6520static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006521 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006522 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006523}
6524
George Burgess IV533ff002015-12-11 00:23:35 +00006525bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006526 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006527 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006528
Richard Smith161f09a2011-12-06 22:44:34 +00006529 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006530 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006531
Eli Friedmanc757de22011-03-25 00:43:55 +00006532 switch (E->getCastKind()) {
6533 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006534 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006535 if (SETy->isIntegerType()) {
6536 APSInt IntResult;
6537 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006538 return false;
6539 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006540 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006541 APFloat FloatResult(0.0);
6542 if (!EvaluateFloat(SE, FloatResult, Info))
6543 return false;
6544 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006545 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006546 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006547 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006548
6549 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006550 SmallVector<APValue, 4> Elts(NElts, Val);
6551 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006552 }
Eli Friedman803acb32011-12-22 03:51:45 +00006553 case CK_BitCast: {
6554 // Evaluate the operand into an APInt we can extract from.
6555 llvm::APInt SValInt;
6556 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6557 return false;
6558 // Extract the elements
6559 QualType EltTy = VTy->getElementType();
6560 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6561 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6562 SmallVector<APValue, 4> Elts;
6563 if (EltTy->isRealFloatingType()) {
6564 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006565 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006566 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006567 FloatEltSize = 80;
6568 for (unsigned i = 0; i < NElts; i++) {
6569 llvm::APInt Elt;
6570 if (BigEndian)
6571 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6572 else
6573 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006574 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006575 }
6576 } else if (EltTy->isIntegerType()) {
6577 for (unsigned i = 0; i < NElts; i++) {
6578 llvm::APInt Elt;
6579 if (BigEndian)
6580 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6581 else
6582 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6583 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6584 }
6585 } else {
6586 return Error(E);
6587 }
6588 return Success(Elts, E);
6589 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006590 default:
Richard Smith11562c52011-10-28 17:51:58 +00006591 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006592 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006593}
6594
Richard Smith2d406342011-10-22 21:10:00 +00006595bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006596VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006597 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006598 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006599 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006600
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006601 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006602 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006603
Eli Friedmanb9c71292012-01-03 23:24:20 +00006604 // The number of initializers can be less than the number of
6605 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006606 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006607 // should be initialized with zeroes.
6608 unsigned CountInits = 0, CountElts = 0;
6609 while (CountElts < NumElements) {
6610 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006611 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006612 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006613 APValue v;
6614 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6615 return Error(E);
6616 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006617 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006618 Elements.push_back(v.getVectorElt(j));
6619 CountElts += vlen;
6620 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006621 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006622 if (CountInits < NumInits) {
6623 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006624 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006625 } else // trailing integer zero.
6626 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6627 Elements.push_back(APValue(sInt));
6628 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006629 } else {
6630 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006631 if (CountInits < NumInits) {
6632 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006633 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006634 } else // trailing float zero.
6635 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6636 Elements.push_back(APValue(f));
6637 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006638 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006639 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006640 }
Richard Smith2d406342011-10-22 21:10:00 +00006641 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006642}
6643
Richard Smith2d406342011-10-22 21:10:00 +00006644bool
Richard Smithfddd3842011-12-30 21:15:51 +00006645VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006646 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006647 QualType EltTy = VT->getElementType();
6648 APValue ZeroElement;
6649 if (EltTy->isIntegerType())
6650 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6651 else
6652 ZeroElement =
6653 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6654
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006655 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006656 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006657}
6658
Richard Smith2d406342011-10-22 21:10:00 +00006659bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006660 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006661 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006662}
6663
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006664//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006665// Array Evaluation
6666//===----------------------------------------------------------------------===//
6667
6668namespace {
6669 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006670 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006671 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006672 APValue &Result;
6673 public:
6674
Richard Smithd62306a2011-11-10 06:34:14 +00006675 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6676 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006677
6678 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006679 assert((V.isArray() || V.isLValue()) &&
6680 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006681 Result = V;
6682 return true;
6683 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006684
Richard Smithfddd3842011-12-30 21:15:51 +00006685 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006686 const ConstantArrayType *CAT =
6687 Info.Ctx.getAsConstantArrayType(E->getType());
6688 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006689 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006690
6691 Result = APValue(APValue::UninitArray(), 0,
6692 CAT->getSize().getZExtValue());
6693 if (!Result.hasArrayFiller()) return true;
6694
Richard Smithfddd3842011-12-30 21:15:51 +00006695 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006696 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006697 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006698 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006699 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006700 }
6701
Richard Smith52a980a2015-08-28 02:43:42 +00006702 bool VisitCallExpr(const CallExpr *E) {
6703 return handleCallExpr(E, Result, &This);
6704 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006705 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006706 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006707 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006708 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6709 const LValue &Subobject,
6710 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006711 };
6712} // end anonymous namespace
6713
Richard Smithd62306a2011-11-10 06:34:14 +00006714static bool EvaluateArray(const Expr *E, const LValue &This,
6715 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006716 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006717 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006718}
6719
6720bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6721 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6722 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006723 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006724
Richard Smithca2cfbf2011-12-22 01:07:19 +00006725 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6726 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006727 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006728 LValue LV;
6729 if (!EvaluateLValue(E->getInit(0), LV, Info))
6730 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006731 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006732 LV.moveInto(Val);
6733 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006734 }
6735
Richard Smith253c2a32012-01-27 01:14:48 +00006736 bool Success = true;
6737
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006738 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6739 "zero-initialized array shouldn't have any initialized elts");
6740 APValue Filler;
6741 if (Result.isArray() && Result.hasArrayFiller())
6742 Filler = Result.getArrayFiller();
6743
Richard Smith9543c5e2013-04-22 14:44:29 +00006744 unsigned NumEltsToInit = E->getNumInits();
6745 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006746 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006747
6748 // If the initializer might depend on the array index, run it for each
6749 // array element. For now, just whitelist non-class value-initialization.
6750 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6751 NumEltsToInit = NumElts;
6752
6753 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006754
6755 // If the array was previously zero-initialized, preserve the
6756 // zero-initialized values.
6757 if (!Filler.isUninit()) {
6758 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6759 Result.getArrayInitializedElt(I) = Filler;
6760 if (Result.hasArrayFiller())
6761 Result.getArrayFiller() = Filler;
6762 }
6763
Richard Smithd62306a2011-11-10 06:34:14 +00006764 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006765 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006766 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6767 const Expr *Init =
6768 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006769 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006770 Info, Subobject, Init) ||
6771 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006772 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006773 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006774 return false;
6775 Success = false;
6776 }
Richard Smithd62306a2011-11-10 06:34:14 +00006777 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006778
Richard Smith9543c5e2013-04-22 14:44:29 +00006779 if (!Result.hasArrayFiller())
6780 return Success;
6781
6782 // If we get here, we have a trivial filler, which we can just evaluate
6783 // once and splat over the rest of the array elements.
6784 assert(FillerExpr && "no array filler for incomplete init list");
6785 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6786 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006787}
6788
Richard Smith410306b2016-12-12 02:53:20 +00006789bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6790 if (E->getCommonExpr() &&
6791 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6792 Info, E->getCommonExpr()->getSourceExpr()))
6793 return false;
6794
6795 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6796
6797 uint64_t Elements = CAT->getSize().getZExtValue();
6798 Result = APValue(APValue::UninitArray(), Elements, Elements);
6799
6800 LValue Subobject = This;
6801 Subobject.addArray(Info, E, CAT);
6802
6803 bool Success = true;
6804 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6805 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6806 Info, Subobject, E->getSubExpr()) ||
6807 !HandleLValueArrayAdjustment(Info, E, Subobject,
6808 CAT->getElementType(), 1)) {
6809 if (!Info.noteFailure())
6810 return false;
6811 Success = false;
6812 }
6813 }
6814
6815 return Success;
6816}
6817
Richard Smith027bf112011-11-17 22:56:20 +00006818bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006819 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6820}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006821
Richard Smith9543c5e2013-04-22 14:44:29 +00006822bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6823 const LValue &Subobject,
6824 APValue *Value,
6825 QualType Type) {
6826 bool HadZeroInit = !Value->isUninit();
6827
6828 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6829 unsigned N = CAT->getSize().getZExtValue();
6830
6831 // Preserve the array filler if we had prior zero-initialization.
6832 APValue Filler =
6833 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6834 : APValue();
6835
6836 *Value = APValue(APValue::UninitArray(), N, N);
6837
6838 if (HadZeroInit)
6839 for (unsigned I = 0; I != N; ++I)
6840 Value->getArrayInitializedElt(I) = Filler;
6841
6842 // Initialize the elements.
6843 LValue ArrayElt = Subobject;
6844 ArrayElt.addArray(Info, E, CAT);
6845 for (unsigned I = 0; I != N; ++I)
6846 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6847 CAT->getElementType()) ||
6848 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6849 CAT->getElementType(), 1))
6850 return false;
6851
6852 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006853 }
Richard Smith027bf112011-11-17 22:56:20 +00006854
Richard Smith9543c5e2013-04-22 14:44:29 +00006855 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006856 return Error(E);
6857
Richard Smithb8348f52016-05-12 22:16:28 +00006858 return RecordExprEvaluator(Info, Subobject, *Value)
6859 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006860}
6861
Richard Smithf3e9e432011-11-07 09:22:26 +00006862//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006863// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006864//
6865// As a GNU extension, we support casting pointers to sufficiently-wide integer
6866// types and back in constant folding. Integer values are thus represented
6867// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006868//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006869
6870namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006871class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006872 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006873 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006874public:
Richard Smith2e312c82012-03-03 22:46:17 +00006875 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006876 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006877
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006878 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006879 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006880 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006881 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006882 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006883 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006884 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006885 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006886 return true;
6887 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006888 bool Success(const llvm::APSInt &SI, const Expr *E) {
6889 return Success(SI, E, Result);
6890 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006891
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006892 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006893 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006894 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006895 assert(I.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(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006898 Result.getInt().setIsUnsigned(
6899 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006900 return true;
6901 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006902 bool Success(const llvm::APInt &I, const Expr *E) {
6903 return Success(I, E, Result);
6904 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006905
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006906 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006907 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006908 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006909 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006910 return true;
6911 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006912 bool Success(uint64_t Value, const Expr *E) {
6913 return Success(Value, E, Result);
6914 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006915
Ken Dyckdbc01912011-03-11 02:13:43 +00006916 bool Success(CharUnits Size, const Expr *E) {
6917 return Success(Size.getQuantity(), E);
6918 }
6919
Richard Smith2e312c82012-03-03 22:46:17 +00006920 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006921 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006922 Result = V;
6923 return true;
6924 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006925 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006926 }
Mike Stump11289f42009-09-09 15:08:12 +00006927
Richard Smithfddd3842011-12-30 21:15:51 +00006928 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006929
Peter Collingbournee9200682011-05-13 03:29:01 +00006930 //===--------------------------------------------------------------------===//
6931 // Visitor Methods
6932 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006933
Chris Lattner7174bf32008-07-12 00:38:25 +00006934 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006935 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006936 }
6937 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006938 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006939 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006940
6941 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6942 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006943 if (CheckReferencedDecl(E, E->getDecl()))
6944 return true;
6945
6946 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006947 }
6948 bool VisitMemberExpr(const MemberExpr *E) {
6949 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006950 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006951 return true;
6952 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006953
6954 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006955 }
6956
Peter Collingbournee9200682011-05-13 03:29:01 +00006957 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006958 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006959 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006960 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006961 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006962
Peter Collingbournee9200682011-05-13 03:29:01 +00006963 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006964 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006965
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006966 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006967 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006968 }
Mike Stump11289f42009-09-09 15:08:12 +00006969
Ted Kremeneke65b0862012-03-06 20:05:56 +00006970 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6971 return Success(E->getValue(), E);
6972 }
Richard Smith410306b2016-12-12 02:53:20 +00006973
6974 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6975 if (Info.ArrayInitIndex == uint64_t(-1)) {
6976 // We were asked to evaluate this subexpression independent of the
6977 // enclosing ArrayInitLoopExpr. We can't do that.
6978 Info.FFDiag(E);
6979 return false;
6980 }
6981 return Success(Info.ArrayInitIndex, E);
6982 }
Daniel Jasperffdee092017-05-02 19:21:42 +00006983
Richard Smith4ce706a2011-10-11 21:43:33 +00006984 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006985 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006986 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006987 }
6988
Douglas Gregor29c42f22012-02-24 07:38:34 +00006989 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6990 return Success(E->getValue(), E);
6991 }
6992
John Wiegley6242b6a2011-04-28 00:16:57 +00006993 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6994 return Success(E->getValue(), E);
6995 }
6996
John Wiegleyf9f65842011-04-25 06:54:41 +00006997 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6998 return Success(E->getValue(), E);
6999 }
7000
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007001 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007002 bool VisitUnaryImag(const UnaryOperator *E);
7003
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007004 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007005 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007006
Eli Friedman4e7a2412009-02-27 04:45:43 +00007007 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007008};
Chris Lattner05706e882008-07-11 18:11:29 +00007009} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007010
Richard Smith11562c52011-10-28 17:51:58 +00007011/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7012/// produce either the integer value or a pointer.
7013///
7014/// GCC has a heinous extension which folds casts between pointer types and
7015/// pointer-sized integral types. We support this by allowing the evaluation of
7016/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7017/// Some simple arithmetic on such values is supported (they are treated much
7018/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007019static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007020 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007021 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007022 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007023}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007024
Richard Smithf57d8cb2011-12-09 22:58:01 +00007025static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007026 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007027 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007028 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007029 if (!Val.isInt()) {
7030 // FIXME: It would be better to produce the diagnostic for casting
7031 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007032 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007033 return false;
7034 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007035 Result = Val.getInt();
7036 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007037}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007038
Richard Smithf57d8cb2011-12-09 22:58:01 +00007039/// Check whether the given declaration can be directly converted to an integral
7040/// rvalue. If not, no diagnostic is produced; there are other things we can
7041/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007042bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007043 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007044 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007045 // Check for signedness/width mismatches between E type and ECD value.
7046 bool SameSign = (ECD->getInitVal().isSigned()
7047 == E->getType()->isSignedIntegerOrEnumerationType());
7048 bool SameWidth = (ECD->getInitVal().getBitWidth()
7049 == Info.Ctx.getIntWidth(E->getType()));
7050 if (SameSign && SameWidth)
7051 return Success(ECD->getInitVal(), E);
7052 else {
7053 // Get rid of mismatch (otherwise Success assertions will fail)
7054 // by computing a new value matching the type of E.
7055 llvm::APSInt Val = ECD->getInitVal();
7056 if (!SameSign)
7057 Val.setIsSigned(!ECD->getInitVal().isSigned());
7058 if (!SameWidth)
7059 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7060 return Success(Val, E);
7061 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007062 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007063 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007064}
7065
Chris Lattner86ee2862008-10-06 06:40:35 +00007066/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7067/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007068static int EvaluateBuiltinClassifyType(const CallExpr *E,
7069 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007070 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007071 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007072 enum gcc_type_class {
7073 no_type_class = -1,
7074 void_type_class, integer_type_class, char_type_class,
7075 enumeral_type_class, boolean_type_class,
7076 pointer_type_class, reference_type_class, offset_type_class,
7077 real_type_class, complex_type_class,
7078 function_type_class, method_type_class,
7079 record_type_class, union_type_class,
7080 array_type_class, string_type_class,
7081 lang_type_class
7082 };
Mike Stump11289f42009-09-09 15:08:12 +00007083
7084 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007085 // ideal, however it is what gcc does.
7086 if (E->getNumArgs() == 0)
7087 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007088
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007089 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7090 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7091
7092 switch (CanTy->getTypeClass()) {
7093#define TYPE(ID, BASE)
7094#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7095#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7096#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7097#include "clang/AST/TypeNodes.def"
7098 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7099
7100 case Type::Builtin:
7101 switch (BT->getKind()) {
7102#define BUILTIN_TYPE(ID, SINGLETON_ID)
7103#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7104#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7105#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7106#include "clang/AST/BuiltinTypes.def"
7107 case BuiltinType::Void:
7108 return void_type_class;
7109
7110 case BuiltinType::Bool:
7111 return boolean_type_class;
7112
7113 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7114 case BuiltinType::UChar:
7115 case BuiltinType::UShort:
7116 case BuiltinType::UInt:
7117 case BuiltinType::ULong:
7118 case BuiltinType::ULongLong:
7119 case BuiltinType::UInt128:
7120 return integer_type_class;
7121
7122 case BuiltinType::NullPtr:
7123 return pointer_type_class;
7124
7125 case BuiltinType::WChar_U:
7126 case BuiltinType::Char16:
7127 case BuiltinType::Char32:
7128 case BuiltinType::ObjCId:
7129 case BuiltinType::ObjCClass:
7130 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007131#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7132 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007133#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007134 case BuiltinType::OCLSampler:
7135 case BuiltinType::OCLEvent:
7136 case BuiltinType::OCLClkEvent:
7137 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007138 case BuiltinType::OCLReserveID:
7139 case BuiltinType::Dependent:
7140 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7141 };
7142
7143 case Type::Enum:
7144 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7145 break;
7146
7147 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007148 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007149 break;
7150
7151 case Type::MemberPointer:
7152 if (CanTy->isMemberDataPointerType())
7153 return offset_type_class;
7154 else {
7155 // We expect member pointers to be either data or function pointers,
7156 // nothing else.
7157 assert(CanTy->isMemberFunctionPointerType());
7158 return method_type_class;
7159 }
7160
7161 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007162 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007163
7164 case Type::FunctionNoProto:
7165 case Type::FunctionProto:
7166 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7167
7168 case Type::Record:
7169 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7170 switch (RT->getDecl()->getTagKind()) {
7171 case TagTypeKind::TTK_Struct:
7172 case TagTypeKind::TTK_Class:
7173 case TagTypeKind::TTK_Interface:
7174 return record_type_class;
7175
7176 case TagTypeKind::TTK_Enum:
7177 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7178
7179 case TagTypeKind::TTK_Union:
7180 return union_type_class;
7181 }
7182 }
David Blaikie83d382b2011-09-23 05:06:16 +00007183 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007184
7185 case Type::ConstantArray:
7186 case Type::VariableArray:
7187 case Type::IncompleteArray:
7188 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7189
7190 case Type::BlockPointer:
7191 case Type::LValueReference:
7192 case Type::RValueReference:
7193 case Type::Vector:
7194 case Type::ExtVector:
7195 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007196 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007197 case Type::ObjCObject:
7198 case Type::ObjCInterface:
7199 case Type::ObjCObjectPointer:
7200 case Type::Pipe:
7201 case Type::Atomic:
7202 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7203 }
7204
7205 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007206}
7207
Richard Smith5fab0c92011-12-28 19:48:30 +00007208/// EvaluateBuiltinConstantPForLValue - Determine the result of
7209/// __builtin_constant_p when applied to the given lvalue.
7210///
7211/// An lvalue is only "constant" if it is a pointer or reference to the first
7212/// character of a string literal.
7213template<typename LValue>
7214static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007215 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007216 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7217}
7218
7219/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7220/// GCC as we can manage.
7221static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7222 QualType ArgType = Arg->getType();
7223
7224 // __builtin_constant_p always has one operand. The rules which gcc follows
7225 // are not precisely documented, but are as follows:
7226 //
7227 // - If the operand is of integral, floating, complex or enumeration type,
7228 // and can be folded to a known value of that type, it returns 1.
7229 // - If the operand and can be folded to a pointer to the first character
7230 // of a string literal (or such a pointer cast to an integral type), it
7231 // returns 1.
7232 //
7233 // Otherwise, it returns 0.
7234 //
7235 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7236 // its support for this does not currently work.
7237 if (ArgType->isIntegralOrEnumerationType()) {
7238 Expr::EvalResult Result;
7239 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7240 return false;
7241
7242 APValue &V = Result.Val;
7243 if (V.getKind() == APValue::Int)
7244 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007245 if (V.getKind() == APValue::LValue)
7246 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007247 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7248 return Arg->isEvaluatable(Ctx);
7249 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7250 LValue LV;
7251 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007252 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007253 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7254 : EvaluatePointer(Arg, LV, Info)) &&
7255 !Status.HasSideEffects)
7256 return EvaluateBuiltinConstantPForLValue(LV);
7257 }
7258
7259 // Anything else isn't considered to be sufficiently constant.
7260 return false;
7261}
7262
John McCall95007602010-05-10 23:27:23 +00007263/// Retrieves the "underlying object type" of the given expression,
7264/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007265static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007266 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7267 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007268 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007269 } else if (const Expr *E = B.get<const Expr*>()) {
7270 if (isa<CompoundLiteralExpr>(E))
7271 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007272 }
7273
7274 return QualType();
7275}
7276
George Burgess IV3a03fab2015-09-04 21:28:13 +00007277/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007278/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007279/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007280/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7281///
7282/// Always returns an RValue with a pointer representation.
7283static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7284 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7285
7286 auto *NoParens = E->IgnoreParens();
7287 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007288 if (Cast == nullptr)
7289 return NoParens;
7290
7291 // We only conservatively allow a few kinds of casts, because this code is
7292 // inherently a simple solution that seeks to support the common case.
7293 auto CastKind = Cast->getCastKind();
7294 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7295 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007296 return NoParens;
7297
7298 auto *SubExpr = Cast->getSubExpr();
7299 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7300 return NoParens;
7301 return ignorePointerCastsAndParens(SubExpr);
7302}
7303
George Burgess IVa51c4072015-10-16 01:49:01 +00007304/// Checks to see if the given LValue's Designator is at the end of the LValue's
7305/// record layout. e.g.
7306/// struct { struct { int a, b; } fst, snd; } obj;
7307/// obj.fst // no
7308/// obj.snd // yes
7309/// obj.fst.a // no
7310/// obj.fst.b // no
7311/// obj.snd.a // no
7312/// obj.snd.b // yes
7313///
7314/// Please note: this function is specialized for how __builtin_object_size
7315/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007316///
Martin Bohme542c84b2017-08-30 10:44:46 +00007317/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007318static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7319 assert(!LVal.Designator.Invalid);
7320
George Burgess IV4168d752016-06-27 19:40:41 +00007321 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7322 const RecordDecl *Parent = FD->getParent();
7323 Invalid = Parent->isInvalidDecl();
7324 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007325 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007326 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007327 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7328 };
7329
7330 auto &Base = LVal.getLValueBase();
7331 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7332 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007333 bool Invalid;
7334 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7335 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007336 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007337 for (auto *FD : IFD->chain()) {
7338 bool Invalid;
7339 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7340 return Invalid;
7341 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007342 }
7343 }
7344
George Burgess IVe3763372016-12-22 02:50:20 +00007345 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007346 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007347 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Martin Bohme542c84b2017-08-30 10:44:46 +00007348 assert(isBaseAnAllocSizeCall(Base) &&
7349 "Unsized array in non-alloc_size call?");
7350 // If this is an alloc_size base, we should ignore the initial array index
George Burgess IVe3763372016-12-22 02:50:20 +00007351 ++I;
7352 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7353 }
7354
7355 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7356 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007357 if (BaseType->isArrayType()) {
7358 // Because __builtin_object_size treats arrays as objects, we can ignore
7359 // the index iff this is the last array in the Designator.
7360 if (I + 1 == E)
7361 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007362 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7363 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007364 if (Index + 1 != CAT->getSize())
7365 return false;
7366 BaseType = CAT->getElementType();
7367 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007368 const auto *CT = BaseType->castAs<ComplexType>();
7369 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007370 if (Index != 1)
7371 return false;
7372 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007373 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007374 bool Invalid;
7375 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7376 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007377 BaseType = FD->getType();
7378 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007379 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007380 return false;
7381 }
7382 }
7383 return true;
7384}
7385
George Burgess IVe3763372016-12-22 02:50:20 +00007386/// Tests to see if the LValue has a user-specified designator (that isn't
7387/// necessarily valid). Note that this always returns 'true' if the LValue has
7388/// an unsized array as its first designator entry, because there's currently no
7389/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007390static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007391 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007392 return false;
7393
George Burgess IVe3763372016-12-22 02:50:20 +00007394 if (!LVal.Designator.Entries.empty())
7395 return LVal.Designator.isMostDerivedAnUnsizedArray();
7396
George Burgess IVa51c4072015-10-16 01:49:01 +00007397 if (!LVal.InvalidBase)
7398 return true;
7399
George Burgess IVe3763372016-12-22 02:50:20 +00007400 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7401 // the LValueBase.
7402 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7403 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007404}
7405
George Burgess IVe3763372016-12-22 02:50:20 +00007406/// Attempts to detect a user writing into a piece of memory that's impossible
7407/// to figure out the size of by just using types.
7408static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7409 const SubobjectDesignator &Designator = LVal.Designator;
7410 // Notes:
7411 // - Users can only write off of the end when we have an invalid base. Invalid
7412 // bases imply we don't know where the memory came from.
7413 // - We used to be a bit more aggressive here; we'd only be conservative if
7414 // the array at the end was flexible, or if it had 0 or 1 elements. This
7415 // broke some common standard library extensions (PR30346), but was
7416 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7417 // with some sort of whitelist. OTOH, it seems that GCC is always
7418 // conservative with the last element in structs (if it's an array), so our
7419 // current behavior is more compatible than a whitelisting approach would
7420 // be.
7421 return LVal.InvalidBase &&
7422 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7423 Designator.MostDerivedIsArrayElement &&
7424 isDesignatorAtObjectEnd(Ctx, LVal);
7425}
7426
7427/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7428/// Fails if the conversion would cause loss of precision.
7429static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7430 CharUnits &Result) {
7431 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7432 if (Int.ugt(CharUnitsMax))
7433 return false;
7434 Result = CharUnits::fromQuantity(Int.getZExtValue());
7435 return true;
7436}
7437
7438/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7439/// determine how many bytes exist from the beginning of the object to either
7440/// the end of the current subobject, or the end of the object itself, depending
7441/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007442///
George Burgess IVe3763372016-12-22 02:50:20 +00007443/// If this returns false, the value of Result is undefined.
7444static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7445 unsigned Type, const LValue &LVal,
7446 CharUnits &EndOffset) {
7447 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007448
George Burgess IV7fb7e362017-01-03 23:35:19 +00007449 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7450 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7451 return false;
7452 return HandleSizeof(Info, ExprLoc, Ty, Result);
7453 };
7454
George Burgess IVe3763372016-12-22 02:50:20 +00007455 // We want to evaluate the size of the entire object. This is a valid fallback
7456 // for when Type=1 and the designator is invalid, because we're asked for an
7457 // upper-bound.
7458 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7459 // Type=3 wants a lower bound, so we can't fall back to this.
7460 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007461 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007462
7463 llvm::APInt APEndOffset;
7464 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7465 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7466 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7467
7468 if (LVal.InvalidBase)
7469 return false;
7470
7471 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007472 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007473 }
7474
George Burgess IVe3763372016-12-22 02:50:20 +00007475 // We want to evaluate the size of a subobject.
7476 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007477
7478 // The following is a moderately common idiom in C:
7479 //
7480 // struct Foo { int a; char c[1]; };
7481 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7482 // strcpy(&F->c[0], Bar);
7483 //
George Burgess IVe3763372016-12-22 02:50:20 +00007484 // In order to not break too much legacy code, we need to support it.
7485 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7486 // If we can resolve this to an alloc_size call, we can hand that back,
7487 // because we know for certain how many bytes there are to write to.
7488 llvm::APInt APEndOffset;
7489 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7490 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7491 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7492
7493 // If we cannot determine the size of the initial allocation, then we can't
7494 // given an accurate upper-bound. However, we are still able to give
7495 // conservative lower-bounds for Type=3.
7496 if (Type == 1)
7497 return false;
7498 }
7499
7500 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007501 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007502 return false;
7503
George Burgess IVe3763372016-12-22 02:50:20 +00007504 // According to the GCC documentation, we want the size of the subobject
7505 // denoted by the pointer. But that's not quite right -- what we actually
7506 // want is the size of the immediately-enclosing array, if there is one.
7507 int64_t ElemsRemaining;
7508 if (Designator.MostDerivedIsArrayElement &&
7509 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7510 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7511 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7512 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7513 } else {
7514 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7515 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007516
George Burgess IVe3763372016-12-22 02:50:20 +00007517 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7518 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007519}
7520
George Burgess IVe3763372016-12-22 02:50:20 +00007521/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7522/// returns true and stores the result in @p Size.
7523///
7524/// If @p WasError is non-null, this will report whether the failure to evaluate
7525/// is to be treated as an Error in IntExprEvaluator.
7526static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7527 EvalInfo &Info, uint64_t &Size) {
7528 // Determine the denoted object.
7529 LValue LVal;
7530 {
7531 // The operand of __builtin_object_size is never evaluated for side-effects.
7532 // If there are any, but we can determine the pointed-to object anyway, then
7533 // ignore the side-effects.
7534 SpeculativeEvaluationRAII SpeculativeEval(Info);
7535 FoldOffsetRAII Fold(Info);
7536
7537 if (E->isGLValue()) {
7538 // It's possible for us to be given GLValues if we're called via
7539 // Expr::tryEvaluateObjectSize.
7540 APValue RVal;
7541 if (!EvaluateAsRValue(Info, E, RVal))
7542 return false;
7543 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007544 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7545 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007546 return false;
7547 }
7548
7549 // If we point to before the start of the object, there are no accessible
7550 // bytes.
7551 if (LVal.getLValueOffset().isNegative()) {
7552 Size = 0;
7553 return true;
7554 }
7555
7556 CharUnits EndOffset;
7557 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7558 return false;
7559
7560 // If we've fallen outside of the end offset, just pretend there's nothing to
7561 // write to/read from.
7562 if (EndOffset <= LVal.getLValueOffset())
7563 Size = 0;
7564 else
7565 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7566 return true;
John McCall95007602010-05-10 23:27:23 +00007567}
7568
Peter Collingbournee9200682011-05-13 03:29:01 +00007569bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007570 if (unsigned BuiltinOp = E->getBuiltinCallee())
7571 return VisitBuiltinCallExpr(E, BuiltinOp);
7572
7573 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7574}
7575
7576bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7577 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007578 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007579 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007580 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007581
7582 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007583 // The type was checked when we built the expression.
7584 unsigned Type =
7585 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7586 assert(Type <= 3 && "unexpected type");
7587
George Burgess IVe3763372016-12-22 02:50:20 +00007588 uint64_t Size;
7589 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7590 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007591
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007592 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007593 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007594
Richard Smith01ade172012-05-23 04:13:20 +00007595 // Expression had no side effects, but we couldn't statically determine the
7596 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007597 switch (Info.EvalMode) {
7598 case EvalInfo::EM_ConstantExpression:
7599 case EvalInfo::EM_PotentialConstantExpression:
7600 case EvalInfo::EM_ConstantFold:
7601 case EvalInfo::EM_EvaluateForOverflow:
7602 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007603 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007604 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007605 return Error(E);
7606 case EvalInfo::EM_ConstantExpressionUnevaluated:
7607 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007608 // Reduce it to a constant now.
7609 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007610 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007611
7612 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007613 }
7614
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007615 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007616 case Builtin::BI__builtin_bswap32:
7617 case Builtin::BI__builtin_bswap64: {
7618 APSInt Val;
7619 if (!EvaluateInteger(E->getArg(0), Val, Info))
7620 return false;
7621
7622 return Success(Val.byteSwap(), E);
7623 }
7624
Richard Smith8889a3d2013-06-13 06:26:32 +00007625 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007626 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007627
7628 // FIXME: BI__builtin_clrsb
7629 // FIXME: BI__builtin_clrsbl
7630 // FIXME: BI__builtin_clrsbll
7631
Richard Smith80b3c8e2013-06-13 05:04:16 +00007632 case Builtin::BI__builtin_clz:
7633 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007634 case Builtin::BI__builtin_clzll:
7635 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007636 APSInt Val;
7637 if (!EvaluateInteger(E->getArg(0), Val, Info))
7638 return false;
7639 if (!Val)
7640 return Error(E);
7641
7642 return Success(Val.countLeadingZeros(), E);
7643 }
7644
Richard Smith8889a3d2013-06-13 06:26:32 +00007645 case Builtin::BI__builtin_constant_p:
7646 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7647
Richard Smith80b3c8e2013-06-13 05:04:16 +00007648 case Builtin::BI__builtin_ctz:
7649 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007650 case Builtin::BI__builtin_ctzll:
7651 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007652 APSInt Val;
7653 if (!EvaluateInteger(E->getArg(0), Val, Info))
7654 return false;
7655 if (!Val)
7656 return Error(E);
7657
7658 return Success(Val.countTrailingZeros(), E);
7659 }
7660
Richard Smith8889a3d2013-06-13 06:26:32 +00007661 case Builtin::BI__builtin_eh_return_data_regno: {
7662 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7663 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7664 return Success(Operand, E);
7665 }
7666
7667 case Builtin::BI__builtin_expect:
7668 return Visit(E->getArg(0));
7669
7670 case Builtin::BI__builtin_ffs:
7671 case Builtin::BI__builtin_ffsl:
7672 case Builtin::BI__builtin_ffsll: {
7673 APSInt Val;
7674 if (!EvaluateInteger(E->getArg(0), Val, Info))
7675 return false;
7676
7677 unsigned N = Val.countTrailingZeros();
7678 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7679 }
7680
7681 case Builtin::BI__builtin_fpclassify: {
7682 APFloat Val(0.0);
7683 if (!EvaluateFloat(E->getArg(5), Val, Info))
7684 return false;
7685 unsigned Arg;
7686 switch (Val.getCategory()) {
7687 case APFloat::fcNaN: Arg = 0; break;
7688 case APFloat::fcInfinity: Arg = 1; break;
7689 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7690 case APFloat::fcZero: Arg = 4; break;
7691 }
7692 return Visit(E->getArg(Arg));
7693 }
7694
7695 case Builtin::BI__builtin_isinf_sign: {
7696 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007697 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007698 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7699 }
7700
Richard Smithea3019d2013-10-15 19:07:14 +00007701 case Builtin::BI__builtin_isinf: {
7702 APFloat Val(0.0);
7703 return EvaluateFloat(E->getArg(0), Val, Info) &&
7704 Success(Val.isInfinity() ? 1 : 0, E);
7705 }
7706
7707 case Builtin::BI__builtin_isfinite: {
7708 APFloat Val(0.0);
7709 return EvaluateFloat(E->getArg(0), Val, Info) &&
7710 Success(Val.isFinite() ? 1 : 0, E);
7711 }
7712
7713 case Builtin::BI__builtin_isnan: {
7714 APFloat Val(0.0);
7715 return EvaluateFloat(E->getArg(0), Val, Info) &&
7716 Success(Val.isNaN() ? 1 : 0, E);
7717 }
7718
7719 case Builtin::BI__builtin_isnormal: {
7720 APFloat Val(0.0);
7721 return EvaluateFloat(E->getArg(0), Val, Info) &&
7722 Success(Val.isNormal() ? 1 : 0, E);
7723 }
7724
Richard Smith8889a3d2013-06-13 06:26:32 +00007725 case Builtin::BI__builtin_parity:
7726 case Builtin::BI__builtin_parityl:
7727 case Builtin::BI__builtin_parityll: {
7728 APSInt Val;
7729 if (!EvaluateInteger(E->getArg(0), Val, Info))
7730 return false;
7731
7732 return Success(Val.countPopulation() % 2, E);
7733 }
7734
Richard Smith80b3c8e2013-06-13 05:04:16 +00007735 case Builtin::BI__builtin_popcount:
7736 case Builtin::BI__builtin_popcountl:
7737 case Builtin::BI__builtin_popcountll: {
7738 APSInt Val;
7739 if (!EvaluateInteger(E->getArg(0), Val, Info))
7740 return false;
7741
7742 return Success(Val.countPopulation(), E);
7743 }
7744
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007745 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007746 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007747 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007748 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007749 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007750 << /*isConstexpr*/0 << /*isConstructor*/0
7751 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007752 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007753 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007754 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007755 case Builtin::BI__builtin_strlen:
7756 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007757 // As an extension, we support __builtin_strlen() as a constant expression,
7758 // and support folding strlen() to a constant.
7759 LValue String;
7760 if (!EvaluatePointer(E->getArg(0), String, Info))
7761 return false;
7762
Richard Smith8110c9d2016-11-29 19:45:17 +00007763 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7764
Richard Smithe6c19f22013-11-15 02:10:04 +00007765 // Fast path: if it's a string literal, search the string value.
7766 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7767 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007768 // The string literal may have embedded null characters. Find the first
7769 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007770 StringRef Str = S->getBytes();
7771 int64_t Off = String.Offset.getQuantity();
7772 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007773 S->getCharByteWidth() == 1 &&
7774 // FIXME: Add fast-path for wchar_t too.
7775 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007776 Str = Str.substr(Off);
7777
7778 StringRef::size_type Pos = Str.find(0);
7779 if (Pos != StringRef::npos)
7780 Str = Str.substr(0, Pos);
7781
7782 return Success(Str.size(), E);
7783 }
7784
7785 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007786 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007787
7788 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007789 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7790 APValue Char;
7791 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7792 !Char.isInt())
7793 return false;
7794 if (!Char.getInt())
7795 return Success(Strlen, E);
7796 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7797 return false;
7798 }
7799 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007800
Richard Smithe151bab2016-11-11 23:43:35 +00007801 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007802 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007803 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007804 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007805 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007806 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007807 // A call to strlen is not a constant expression.
7808 if (Info.getLangOpts().CPlusPlus11)
7809 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7810 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007811 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007812 else
7813 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7814 // Fall through.
7815 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007816 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007817 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007818 case Builtin::BI__builtin_wcsncmp:
7819 case Builtin::BI__builtin_memcmp:
7820 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007821 LValue String1, String2;
7822 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7823 !EvaluatePointer(E->getArg(1), String2, Info))
7824 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007825
7826 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7827
Richard Smithe151bab2016-11-11 23:43:35 +00007828 uint64_t MaxLength = uint64_t(-1);
7829 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007830 BuiltinOp != Builtin::BIwcscmp &&
7831 BuiltinOp != Builtin::BI__builtin_strcmp &&
7832 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007833 APSInt N;
7834 if (!EvaluateInteger(E->getArg(2), N, Info))
7835 return false;
7836 MaxLength = N.getExtValue();
7837 }
7838 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007839 BuiltinOp != Builtin::BIwmemcmp &&
7840 BuiltinOp != Builtin::BI__builtin_memcmp &&
7841 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007842 for (; MaxLength; --MaxLength) {
7843 APValue Char1, Char2;
7844 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7845 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7846 !Char1.isInt() || !Char2.isInt())
7847 return false;
7848 if (Char1.getInt() != Char2.getInt())
7849 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7850 if (StopAtNull && !Char1.getInt())
7851 return Success(0, E);
7852 assert(!(StopAtNull && !Char2.getInt()));
7853 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7854 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7855 return false;
7856 }
7857 // We hit the strncmp / memcmp limit.
7858 return Success(0, E);
7859 }
7860
Richard Smith01ba47d2012-04-13 00:45:38 +00007861 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007862 case Builtin::BI__atomic_is_lock_free:
7863 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007864 APSInt SizeVal;
7865 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7866 return false;
7867
7868 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7869 // of two less than the maximum inline atomic width, we know it is
7870 // lock-free. If the size isn't a power of two, or greater than the
7871 // maximum alignment where we promote atomics, we know it is not lock-free
7872 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7873 // the answer can only be determined at runtime; for example, 16-byte
7874 // atomics have lock-free implementations on some, but not all,
7875 // x86-64 processors.
7876
7877 // Check power-of-two.
7878 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007879 if (Size.isPowerOfTwo()) {
7880 // Check against inlining width.
7881 unsigned InlineWidthBits =
7882 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7883 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7884 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7885 Size == CharUnits::One() ||
7886 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7887 Expr::NPC_NeverValueDependent))
7888 // OK, we will inline appropriately-aligned operations of this size,
7889 // and _Atomic(T) is appropriately-aligned.
7890 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007891
Richard Smith01ba47d2012-04-13 00:45:38 +00007892 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7893 castAs<PointerType>()->getPointeeType();
7894 if (!PointeeType->isIncompleteType() &&
7895 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7896 // OK, we will inline operations on this object.
7897 return Success(1, E);
7898 }
7899 }
7900 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007901
Richard Smith01ba47d2012-04-13 00:45:38 +00007902 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7903 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007904 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007905 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007906}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007907
Richard Smith8b3497e2011-10-31 01:37:14 +00007908static bool HasSameBase(const LValue &A, const LValue &B) {
7909 if (!A.getLValueBase())
7910 return !B.getLValueBase();
7911 if (!B.getLValueBase())
7912 return false;
7913
Richard Smithce40ad62011-11-12 22:28:03 +00007914 if (A.getLValueBase().getOpaqueValue() !=
7915 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007916 const Decl *ADecl = GetLValueBaseDecl(A);
7917 if (!ADecl)
7918 return false;
7919 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007920 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007921 return false;
7922 }
7923
7924 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007925 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007926}
7927
Richard Smithd20f1e62014-10-21 23:01:04 +00007928/// \brief Determine whether this is a pointer past the end of the complete
7929/// object referred to by the lvalue.
7930static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7931 const LValue &LV) {
7932 // A null pointer can be viewed as being "past the end" but we don't
7933 // choose to look at it that way here.
7934 if (!LV.getLValueBase())
7935 return false;
7936
7937 // If the designator is valid and refers to a subobject, we're not pointing
7938 // past the end.
7939 if (!LV.getLValueDesignator().Invalid &&
7940 !LV.getLValueDesignator().isOnePastTheEnd())
7941 return false;
7942
David Majnemerc378ca52015-08-29 08:32:55 +00007943 // A pointer to an incomplete type might be past-the-end if the type's size is
7944 // zero. We cannot tell because the type is incomplete.
7945 QualType Ty = getType(LV.getLValueBase());
7946 if (Ty->isIncompleteType())
7947 return true;
7948
Richard Smithd20f1e62014-10-21 23:01:04 +00007949 // We're a past-the-end pointer if we point to the byte after the object,
7950 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007951 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007952 return LV.getLValueOffset() == Size;
7953}
7954
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007955namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007956
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007957/// \brief Data recursive integer evaluator of certain binary operators.
7958///
7959/// We use a data recursive algorithm for binary operators so that we are able
7960/// to handle extreme cases of chained binary operators without causing stack
7961/// overflow.
7962class DataRecursiveIntBinOpEvaluator {
7963 struct EvalResult {
7964 APValue Val;
7965 bool Failed;
7966
7967 EvalResult() : Failed(false) { }
7968
7969 void swap(EvalResult &RHS) {
7970 Val.swap(RHS.Val);
7971 Failed = RHS.Failed;
7972 RHS.Failed = false;
7973 }
7974 };
7975
7976 struct Job {
7977 const Expr *E;
7978 EvalResult LHSResult; // meaningful only for binary operator expression.
7979 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007980
David Blaikie73726062015-08-12 23:09:24 +00007981 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007982 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007983
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007984 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007985 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007986 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007987
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007988 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007989 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007990 };
7991
7992 SmallVector<Job, 16> Queue;
7993
7994 IntExprEvaluator &IntEval;
7995 EvalInfo &Info;
7996 APValue &FinalResult;
7997
7998public:
7999 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8000 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8001
8002 /// \brief True if \param E is a binary operator that we are going to handle
8003 /// data recursively.
8004 /// We handle binary operators that are comma, logical, or that have operands
8005 /// with integral or enumeration type.
8006 static bool shouldEnqueue(const BinaryOperator *E) {
8007 return E->getOpcode() == BO_Comma ||
8008 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008009 (E->isRValue() &&
8010 E->getType()->isIntegralOrEnumerationType() &&
8011 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008012 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008013 }
8014
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008015 bool Traverse(const BinaryOperator *E) {
8016 enqueue(E);
8017 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008018 while (!Queue.empty())
8019 process(PrevResult);
8020
8021 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008022
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008023 FinalResult.swap(PrevResult.Val);
8024 return true;
8025 }
8026
8027private:
8028 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8029 return IntEval.Success(Value, E, Result);
8030 }
8031 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8032 return IntEval.Success(Value, E, Result);
8033 }
8034 bool Error(const Expr *E) {
8035 return IntEval.Error(E);
8036 }
8037 bool Error(const Expr *E, diag::kind D) {
8038 return IntEval.Error(E, D);
8039 }
8040
8041 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8042 return Info.CCEDiag(E, D);
8043 }
8044
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008045 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8046 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008047 bool &SuppressRHSDiags);
8048
8049 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8050 const BinaryOperator *E, APValue &Result);
8051
8052 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8053 Result.Failed = !Evaluate(Result.Val, Info, E);
8054 if (Result.Failed)
8055 Result.Val = APValue();
8056 }
8057
Richard Trieuba4d0872012-03-21 23:30:30 +00008058 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008059
8060 void enqueue(const Expr *E) {
8061 E = E->IgnoreParens();
8062 Queue.resize(Queue.size()+1);
8063 Queue.back().E = E;
8064 Queue.back().Kind = Job::AnyExprKind;
8065 }
8066};
8067
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008068}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008069
8070bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008071 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008072 bool &SuppressRHSDiags) {
8073 if (E->getOpcode() == BO_Comma) {
8074 // Ignore LHS but note if we could not evaluate it.
8075 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008076 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008077 return true;
8078 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008079
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008080 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008081 bool LHSAsBool;
8082 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008083 // We were able to evaluate the LHS, see if we can get away with not
8084 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008085 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8086 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008087 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008088 }
8089 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008090 LHSResult.Failed = true;
8091
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008092 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008093 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008094 if (!Info.noteSideEffect())
8095 return false;
8096
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008097 // We can't evaluate the LHS; however, sometimes the result
8098 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8099 // Don't ignore RHS and suppress diagnostics from this arm.
8100 SuppressRHSDiags = true;
8101 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008102
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008103 return true;
8104 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008105
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008106 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8107 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008108
George Burgess IVa145e252016-05-25 22:38:36 +00008109 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008110 return false; // Ignore RHS;
8111
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008112 return true;
8113}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008114
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008115static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8116 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008117 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8118 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8119 // offsets.
8120 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8121 CharUnits &Offset = LVal.getLValueOffset();
8122 uint64_t Offset64 = Offset.getQuantity();
8123 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8124 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8125 : Offset64 + Index64);
8126}
8127
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008128bool DataRecursiveIntBinOpEvaluator::
8129 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8130 const BinaryOperator *E, APValue &Result) {
8131 if (E->getOpcode() == BO_Comma) {
8132 if (RHSResult.Failed)
8133 return false;
8134 Result = RHSResult.Val;
8135 return true;
8136 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008137
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008138 if (E->isLogicalOp()) {
8139 bool lhsResult, rhsResult;
8140 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8141 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008142
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008143 if (LHSIsOK) {
8144 if (RHSIsOK) {
8145 if (E->getOpcode() == BO_LOr)
8146 return Success(lhsResult || rhsResult, E, Result);
8147 else
8148 return Success(lhsResult && rhsResult, E, Result);
8149 }
8150 } else {
8151 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008152 // We can't evaluate the LHS; however, sometimes the result
8153 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8154 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008155 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008156 }
8157 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008158
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008159 return false;
8160 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008161
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008162 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8163 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008164
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008165 if (LHSResult.Failed || RHSResult.Failed)
8166 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008167
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008168 const APValue &LHSVal = LHSResult.Val;
8169 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008170
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008171 // Handle cases like (unsigned long)&a + 4.
8172 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8173 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008174 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008175 return true;
8176 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008177
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008178 // Handle cases like 4 + (unsigned long)&a
8179 if (E->getOpcode() == BO_Add &&
8180 RHSVal.isLValue() && LHSVal.isInt()) {
8181 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008182 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008183 return true;
8184 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008185
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008186 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8187 // Handle (intptr_t)&&A - (intptr_t)&&B.
8188 if (!LHSVal.getLValueOffset().isZero() ||
8189 !RHSVal.getLValueOffset().isZero())
8190 return false;
8191 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8192 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8193 if (!LHSExpr || !RHSExpr)
8194 return false;
8195 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8196 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8197 if (!LHSAddrExpr || !RHSAddrExpr)
8198 return false;
8199 // Make sure both labels come from the same function.
8200 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8201 RHSAddrExpr->getLabel()->getDeclContext())
8202 return false;
8203 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8204 return true;
8205 }
Richard Smith43e77732013-05-07 04:50:00 +00008206
8207 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008208 if (!LHSVal.isInt() || !RHSVal.isInt())
8209 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008210
8211 // Set up the width and signedness manually, in case it can't be deduced
8212 // from the operation we're performing.
8213 // FIXME: Don't do this in the cases where we can deduce it.
8214 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8215 E->getType()->isUnsignedIntegerOrEnumerationType());
8216 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8217 RHSVal.getInt(), Value))
8218 return false;
8219 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008220}
8221
Richard Trieuba4d0872012-03-21 23:30:30 +00008222void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008223 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008224
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008225 switch (job.Kind) {
8226 case Job::AnyExprKind: {
8227 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8228 if (shouldEnqueue(Bop)) {
8229 job.Kind = Job::BinOpKind;
8230 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008231 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008232 }
8233 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008234
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008235 EvaluateExpr(job.E, Result);
8236 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008237 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008238 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008239
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008240 case Job::BinOpKind: {
8241 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008242 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008243 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008244 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008245 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008246 }
8247 if (SuppressRHSDiags)
8248 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008249 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008250 job.Kind = Job::BinOpVisitedLHSKind;
8251 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008252 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008253 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008254
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008255 case Job::BinOpVisitedLHSKind: {
8256 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8257 EvalResult RHS;
8258 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008259 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008260 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008261 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008262 }
8263 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008264
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008265 llvm_unreachable("Invalid Job::Kind!");
8266}
8267
George Burgess IV8c892b52016-05-25 22:31:54 +00008268namespace {
8269/// Used when we determine that we should fail, but can keep evaluating prior to
8270/// noting that we had a failure.
8271class DelayedNoteFailureRAII {
8272 EvalInfo &Info;
8273 bool NoteFailure;
8274
8275public:
8276 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8277 : Info(Info), NoteFailure(NoteFailure) {}
8278 ~DelayedNoteFailureRAII() {
8279 if (NoteFailure) {
8280 bool ContinueAfterFailure = Info.noteFailure();
8281 (void)ContinueAfterFailure;
8282 assert(ContinueAfterFailure &&
8283 "Shouldn't have kept evaluating on failure.");
8284 }
8285 }
8286};
8287}
8288
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008289bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008290 // We don't call noteFailure immediately because the assignment happens after
8291 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008292 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008293 return Error(E);
8294
George Burgess IV8c892b52016-05-25 22:31:54 +00008295 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008296 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8297 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008298
Anders Carlssonacc79812008-11-16 07:17:21 +00008299 QualType LHSTy = E->getLHS()->getType();
8300 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008301
Chandler Carruthb29a7432014-10-11 11:03:30 +00008302 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008303 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008304 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008305 if (E->isAssignmentOp()) {
8306 LValue LV;
8307 EvaluateLValue(E->getLHS(), LV, Info);
8308 LHSOK = false;
8309 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008310 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8311 if (LHSOK) {
8312 LHS.makeComplexFloat();
8313 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8314 }
8315 } else {
8316 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8317 }
George Burgess IVa145e252016-05-25 22:38:36 +00008318 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008319 return false;
8320
Chandler Carruthb29a7432014-10-11 11:03:30 +00008321 if (E->getRHS()->getType()->isRealFloatingType()) {
8322 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8323 return false;
8324 RHS.makeComplexFloat();
8325 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8326 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008327 return false;
8328
8329 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008330 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008331 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008332 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008333 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8334
John McCalle3027922010-08-25 11:45:40 +00008335 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008336 return Success((CR_r == APFloat::cmpEqual &&
8337 CR_i == APFloat::cmpEqual), E);
8338 else {
John McCalle3027922010-08-25 11:45:40 +00008339 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008340 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008341 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008342 CR_r == APFloat::cmpLessThan ||
8343 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008344 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008345 CR_i == APFloat::cmpLessThan ||
8346 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008347 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008348 } else {
John McCalle3027922010-08-25 11:45:40 +00008349 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008350 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8351 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8352 else {
John McCalle3027922010-08-25 11:45:40 +00008353 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008354 "Invalid compex comparison.");
8355 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8356 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8357 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008358 }
8359 }
Mike Stump11289f42009-09-09 15:08:12 +00008360
Anders Carlssonacc79812008-11-16 07:17:21 +00008361 if (LHSTy->isRealFloatingType() &&
8362 RHSTy->isRealFloatingType()) {
8363 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008364
Richard Smith253c2a32012-01-27 01:14:48 +00008365 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008366 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008367 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008368
Richard Smith253c2a32012-01-27 01:14:48 +00008369 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008370 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008371
Anders Carlssonacc79812008-11-16 07:17:21 +00008372 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008373
Anders Carlssonacc79812008-11-16 07:17:21 +00008374 switch (E->getOpcode()) {
8375 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008376 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008377 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008378 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008379 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008380 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008381 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008382 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008383 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008384 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008385 E);
John McCalle3027922010-08-25 11:45:40 +00008386 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008387 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008388 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008389 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008390 || CR == APFloat::cmpLessThan
8391 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008392 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008393 }
Mike Stump11289f42009-09-09 15:08:12 +00008394
Eli Friedmana38da572009-04-28 19:17:36 +00008395 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008396 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008397 LValue LHSValue, RHSValue;
8398
8399 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008400 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008401 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008402
Richard Smith253c2a32012-01-27 01:14:48 +00008403 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008404 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008405
Richard Smith8b3497e2011-10-31 01:37:14 +00008406 // Reject differing bases from the normal codepath; we special-case
8407 // comparisons to null.
8408 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008409 if (E->getOpcode() == BO_Sub) {
8410 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008411 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008412 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008413 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008414 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008415 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008416 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008417 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8418 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8419 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008420 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008421 // Make sure both labels come from the same function.
8422 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8423 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008424 return Error(E);
8425 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008426 }
Richard Smith83c68212011-10-31 05:11:32 +00008427 // Inequalities and subtractions between unrelated pointers have
8428 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008429 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008430 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008431 // A constant address may compare equal to the address of a symbol.
8432 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008433 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008434 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8435 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008436 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008437 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008438 // distinct addresses. In clang, the result of such a comparison is
8439 // unspecified, so it is not a constant expression. However, we do know
8440 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008441 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8442 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008443 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008444 // We can't tell whether weak symbols will end up pointing to the same
8445 // object.
8446 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008447 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008448 // We can't compare the address of the start of one object with the
8449 // past-the-end address of another object, per C++ DR1652.
8450 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8451 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8452 (RHSValue.Base && RHSValue.Offset.isZero() &&
8453 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8454 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008455 // We can't tell whether an object is at the same address as another
8456 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008457 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8458 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008459 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008460 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008461 // (Note that clang defaults to -fmerge-all-constants, which can
8462 // lead to inconsistent results for comparisons involving the address
8463 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008464 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008465 }
Eli Friedman64004332009-03-23 04:38:34 +00008466
Richard Smith1b470412012-02-01 08:10:20 +00008467 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8468 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8469
Richard Smith84f6dcf2012-02-02 01:16:57 +00008470 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8471 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8472
John McCalle3027922010-08-25 11:45:40 +00008473 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008474 // C++11 [expr.add]p6:
8475 // Unless both pointers point to elements of the same array object, or
8476 // one past the last element of the array object, the behavior is
8477 // undefined.
8478 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8479 !AreElementsOfSameArray(getType(LHSValue.Base),
8480 LHSDesignator, RHSDesignator))
8481 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8482
Chris Lattner882bdf22010-04-20 17:13:14 +00008483 QualType Type = E->getLHS()->getType();
8484 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008485
Richard Smithd62306a2011-11-10 06:34:14 +00008486 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008487 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008488 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008489
Richard Smith84c6b3d2013-09-10 21:34:14 +00008490 // As an extension, a type may have zero size (empty struct or union in
8491 // C, array of zero length). Pointer subtraction in such cases has
8492 // undefined behavior, so is not constant.
8493 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008494 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008495 << ElementType;
8496 return false;
8497 }
8498
Richard Smith1b470412012-02-01 08:10:20 +00008499 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8500 // and produce incorrect results when it overflows. Such behavior
8501 // appears to be non-conforming, but is common, so perhaps we should
8502 // assume the standard intended for such cases to be undefined behavior
8503 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008504
Richard Smith1b470412012-02-01 08:10:20 +00008505 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8506 // overflow in the final conversion to ptrdiff_t.
8507 APSInt LHS(
8508 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8509 APSInt RHS(
8510 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8511 APSInt ElemSize(
8512 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8513 APSInt TrueResult = (LHS - RHS) / ElemSize;
8514 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8515
Richard Smith0c6124b2015-12-03 01:36:22 +00008516 if (Result.extend(65) != TrueResult &&
8517 !HandleOverflow(Info, E, TrueResult, E->getType()))
8518 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008519 return Success(Result, E);
8520 }
Richard Smithde21b242012-01-31 06:41:30 +00008521
8522 // C++11 [expr.rel]p3:
8523 // Pointers to void (after pointer conversions) can be compared, with a
8524 // result defined as follows: If both pointers represent the same
8525 // address or are both the null pointer value, the result is true if the
8526 // operator is <= or >= and false otherwise; otherwise the result is
8527 // unspecified.
8528 // We interpret this as applying to pointers to *cv* void.
8529 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008530 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008531 CCEDiag(E, diag::note_constexpr_void_comparison);
8532
Richard Smith84f6dcf2012-02-02 01:16:57 +00008533 // C++11 [expr.rel]p2:
8534 // - If two pointers point to non-static data members of the same object,
8535 // or to subobjects or array elements fo such members, recursively, the
8536 // pointer to the later declared member compares greater provided the
8537 // two members have the same access control and provided their class is
8538 // not a union.
8539 // [...]
8540 // - Otherwise pointer comparisons are unspecified.
8541 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8542 E->isRelationalOp()) {
8543 bool WasArrayIndex;
8544 unsigned Mismatch =
8545 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8546 RHSDesignator, WasArrayIndex);
8547 // At the point where the designators diverge, the comparison has a
8548 // specified value if:
8549 // - we are comparing array indices
8550 // - we are comparing fields of a union, or fields with the same access
8551 // Otherwise, the result is unspecified and thus the comparison is not a
8552 // constant expression.
8553 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8554 Mismatch < RHSDesignator.Entries.size()) {
8555 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8556 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8557 if (!LF && !RF)
8558 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8559 else if (!LF)
8560 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8561 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8562 << RF->getParent() << RF;
8563 else if (!RF)
8564 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8565 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8566 << LF->getParent() << LF;
8567 else if (!LF->getParent()->isUnion() &&
8568 LF->getAccess() != RF->getAccess())
8569 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8570 << LF << LF->getAccess() << RF << RF->getAccess()
8571 << LF->getParent();
8572 }
8573 }
8574
Eli Friedman6c31cb42012-04-16 04:30:08 +00008575 // The comparison here must be unsigned, and performed with the same
8576 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008577 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8578 uint64_t CompareLHS = LHSOffset.getQuantity();
8579 uint64_t CompareRHS = RHSOffset.getQuantity();
8580 assert(PtrSize <= 64 && "Unexpected pointer width");
8581 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8582 CompareLHS &= Mask;
8583 CompareRHS &= Mask;
8584
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008585 // If there is a base and this is a relational operator, we can only
8586 // compare pointers within the object in question; otherwise, the result
8587 // depends on where the object is located in memory.
8588 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8589 QualType BaseTy = getType(LHSValue.Base);
8590 if (BaseTy->isIncompleteType())
8591 return Error(E);
8592 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8593 uint64_t OffsetLimit = Size.getQuantity();
8594 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8595 return Error(E);
8596 }
8597
Richard Smith8b3497e2011-10-31 01:37:14 +00008598 switch (E->getOpcode()) {
8599 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008600 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8601 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8602 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8603 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8604 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8605 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008606 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008607 }
8608 }
Richard Smith7bb00672012-02-01 01:42:44 +00008609
8610 if (LHSTy->isMemberPointerType()) {
8611 assert(E->isEqualityOp() && "unexpected member pointer operation");
8612 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8613
8614 MemberPtr LHSValue, RHSValue;
8615
8616 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008617 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008618 return false;
8619
8620 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8621 return false;
8622
8623 // C++11 [expr.eq]p2:
8624 // If both operands are null, they compare equal. Otherwise if only one is
8625 // null, they compare unequal.
8626 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8627 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8628 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8629 }
8630
8631 // Otherwise if either is a pointer to a virtual member function, the
8632 // result is unspecified.
8633 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8634 if (MD->isVirtual())
8635 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8636 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8637 if (MD->isVirtual())
8638 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8639
8640 // Otherwise they compare equal if and only if they would refer to the
8641 // same member of the same most derived object or the same subobject if
8642 // they were dereferenced with a hypothetical object of the associated
8643 // class type.
8644 bool Equal = LHSValue == RHSValue;
8645 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8646 }
8647
Richard Smithab44d9b2012-02-14 22:35:28 +00008648 if (LHSTy->isNullPtrType()) {
8649 assert(E->isComparisonOp() && "unexpected nullptr operation");
8650 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8651 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8652 // are compared, the result is true of the operator is <=, >= or ==, and
8653 // false otherwise.
8654 BinaryOperator::Opcode Opcode = E->getOpcode();
8655 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8656 }
8657
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008658 assert((!LHSTy->isIntegralOrEnumerationType() ||
8659 !RHSTy->isIntegralOrEnumerationType()) &&
8660 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8661 // We can't continue from here for non-integral types.
8662 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008663}
8664
Peter Collingbournee190dee2011-03-11 19:24:49 +00008665/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8666/// a result as the expression's type.
8667bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8668 const UnaryExprOrTypeTraitExpr *E) {
8669 switch(E->getKind()) {
8670 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008671 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008672 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008673 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008674 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008675 }
Eli Friedman64004332009-03-23 04:38:34 +00008676
Peter Collingbournee190dee2011-03-11 19:24:49 +00008677 case UETT_VecStep: {
8678 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008679
Peter Collingbournee190dee2011-03-11 19:24:49 +00008680 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008681 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008682
Peter Collingbournee190dee2011-03-11 19:24:49 +00008683 // The vec_step built-in functions that take a 3-component
8684 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8685 if (n == 3)
8686 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008687
Peter Collingbournee190dee2011-03-11 19:24:49 +00008688 return Success(n, E);
8689 } else
8690 return Success(1, E);
8691 }
8692
8693 case UETT_SizeOf: {
8694 QualType SrcTy = E->getTypeOfArgument();
8695 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8696 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008697 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8698 SrcTy = Ref->getPointeeType();
8699
Richard Smithd62306a2011-11-10 06:34:14 +00008700 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008701 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008702 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008703 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008704 }
Alexey Bataev00396512015-07-02 03:40:19 +00008705 case UETT_OpenMPRequiredSimdAlign:
8706 assert(E->isArgumentType());
8707 return Success(
8708 Info.Ctx.toCharUnitsFromBits(
8709 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8710 .getQuantity(),
8711 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008712 }
8713
8714 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008715}
8716
Peter Collingbournee9200682011-05-13 03:29:01 +00008717bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008718 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008719 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008720 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008721 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008722 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008723 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008724 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008725 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008726 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008727 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008728 APSInt IdxResult;
8729 if (!EvaluateInteger(Idx, IdxResult, Info))
8730 return false;
8731 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8732 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008733 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008734 CurrentType = AT->getElementType();
8735 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8736 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008737 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008738 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008739
James Y Knight7281c352015-12-29 22:31:18 +00008740 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008741 FieldDecl *MemberDecl = ON.getField();
8742 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008743 if (!RT)
8744 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008745 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008746 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008747 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008748 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008749 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008750 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008751 CurrentType = MemberDecl->getType().getNonReferenceType();
8752 break;
8753 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008754
James Y Knight7281c352015-12-29 22:31:18 +00008755 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008756 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008757
James Y Knight7281c352015-12-29 22:31:18 +00008758 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008759 CXXBaseSpecifier *BaseSpec = ON.getBase();
8760 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008761 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008762
8763 // Find the layout of the class whose base we are looking into.
8764 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008765 if (!RT)
8766 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008767 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008768 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008769 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8770
8771 // Find the base class itself.
8772 CurrentType = BaseSpec->getType();
8773 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8774 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008775 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008776
Douglas Gregord1702062010-04-29 00:18:15 +00008777 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008778 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008779 break;
8780 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008781 }
8782 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008783 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008784}
8785
Chris Lattnere13042c2008-07-11 19:10:17 +00008786bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008787 switch (E->getOpcode()) {
8788 default:
8789 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8790 // See C99 6.6p3.
8791 return Error(E);
8792 case UO_Extension:
8793 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8794 // If so, we could clear the diagnostic ID.
8795 return Visit(E->getSubExpr());
8796 case UO_Plus:
8797 // The result is just the value.
8798 return Visit(E->getSubExpr());
8799 case UO_Minus: {
8800 if (!Visit(E->getSubExpr()))
8801 return false;
8802 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008803 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008804 if (Value.isSigned() && Value.isMinSignedValue() &&
8805 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8806 E->getType()))
8807 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008808 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008809 }
8810 case UO_Not: {
8811 if (!Visit(E->getSubExpr()))
8812 return false;
8813 if (!Result.isInt()) return Error(E);
8814 return Success(~Result.getInt(), E);
8815 }
8816 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008817 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008818 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008819 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008820 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008821 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008822 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008823}
Mike Stump11289f42009-09-09 15:08:12 +00008824
Chris Lattner477c4be2008-07-12 01:15:53 +00008825/// HandleCast - This is used to evaluate implicit or explicit casts where the
8826/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008827bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8828 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008829 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008830 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008831
Eli Friedmanc757de22011-03-25 00:43:55 +00008832 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008833 case CK_BaseToDerived:
8834 case CK_DerivedToBase:
8835 case CK_UncheckedDerivedToBase:
8836 case CK_Dynamic:
8837 case CK_ToUnion:
8838 case CK_ArrayToPointerDecay:
8839 case CK_FunctionToPointerDecay:
8840 case CK_NullToPointer:
8841 case CK_NullToMemberPointer:
8842 case CK_BaseToDerivedMemberPointer:
8843 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008844 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008845 case CK_ConstructorConversion:
8846 case CK_IntegralToPointer:
8847 case CK_ToVoid:
8848 case CK_VectorSplat:
8849 case CK_IntegralToFloating:
8850 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008851 case CK_CPointerToObjCPointerCast:
8852 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008853 case CK_AnyPointerToBlockPointerCast:
8854 case CK_ObjCObjectLValueCast:
8855 case CK_FloatingRealToComplex:
8856 case CK_FloatingComplexToReal:
8857 case CK_FloatingComplexCast:
8858 case CK_FloatingComplexToIntegralComplex:
8859 case CK_IntegralRealToComplex:
8860 case CK_IntegralComplexCast:
8861 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008862 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008863 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008864 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008865 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008866 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008867 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008868 llvm_unreachable("invalid cast kind for integral value");
8869
Eli Friedman9faf2f92011-03-25 19:07:11 +00008870 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008871 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008872 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008873 case CK_ARCProduceObject:
8874 case CK_ARCConsumeObject:
8875 case CK_ARCReclaimReturnedObject:
8876 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008877 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008878 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008879
Richard Smith4ef685b2012-01-17 21:17:26 +00008880 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008881 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008882 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008883 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008884 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008885
8886 case CK_MemberPointerToBoolean:
8887 case CK_PointerToBoolean:
8888 case CK_IntegralToBoolean:
8889 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008890 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008891 case CK_FloatingComplexToBoolean:
8892 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008893 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008894 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008895 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008896 uint64_t IntResult = BoolResult;
8897 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8898 IntResult = (uint64_t)-1;
8899 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008900 }
8901
Eli Friedmanc757de22011-03-25 00:43:55 +00008902 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008903 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008904 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008905
Eli Friedman742421e2009-02-20 01:15:07 +00008906 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008907 // Allow casts of address-of-label differences if they are no-ops
8908 // or narrowing. (The narrowing case isn't actually guaranteed to
8909 // be constant-evaluatable except in some narrow cases which are hard
8910 // to detect here. We let it through on the assumption the user knows
8911 // what they are doing.)
8912 if (Result.isAddrLabelDiff())
8913 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008914 // Only allow casts of lvalues if they are lossless.
8915 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8916 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008917
Richard Smith911e1422012-01-30 22:27:01 +00008918 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8919 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008920 }
Mike Stump11289f42009-09-09 15:08:12 +00008921
Eli Friedmanc757de22011-03-25 00:43:55 +00008922 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008923 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8924
John McCall45d55e42010-05-07 21:00:08 +00008925 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008926 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008927 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008928
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008929 if (LV.getLValueBase()) {
8930 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008931 // FIXME: Allow a larger integer size than the pointer size, and allow
8932 // narrowing back down to pointer width in subsequent integral casts.
8933 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008934 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008935 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008936
Richard Smithcf74da72011-11-16 07:18:12 +00008937 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008938 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008939 return true;
8940 }
8941
Yaxun Liu402804b2016-12-15 08:09:08 +00008942 uint64_t V;
8943 if (LV.isNullPointer())
8944 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8945 else
8946 V = LV.getLValueOffset().getQuantity();
8947
8948 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008949 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008950 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008951
Eli Friedmanc757de22011-03-25 00:43:55 +00008952 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008953 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008954 if (!EvaluateComplex(SubExpr, C, Info))
8955 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008956 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008957 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008958
Eli Friedmanc757de22011-03-25 00:43:55 +00008959 case CK_FloatingToIntegral: {
8960 APFloat F(0.0);
8961 if (!EvaluateFloat(SubExpr, F, Info))
8962 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008963
Richard Smith357362d2011-12-13 06:39:58 +00008964 APSInt Value;
8965 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8966 return false;
8967 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008968 }
8969 }
Mike Stump11289f42009-09-09 15:08:12 +00008970
Eli Friedmanc757de22011-03-25 00:43:55 +00008971 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008972}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008973
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008974bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8975 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008976 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008977 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8978 return false;
8979 if (!LV.isComplexInt())
8980 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008981 return Success(LV.getComplexIntReal(), E);
8982 }
8983
8984 return Visit(E->getSubExpr());
8985}
8986
Eli Friedman4e7a2412009-02-27 04:45:43 +00008987bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008988 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008989 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008990 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8991 return false;
8992 if (!LV.isComplexInt())
8993 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008994 return Success(LV.getComplexIntImag(), E);
8995 }
8996
Richard Smith4a678122011-10-24 18:44:57 +00008997 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008998 return Success(0, E);
8999}
9000
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009001bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9002 return Success(E->getPackLength(), E);
9003}
9004
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009005bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9006 return Success(E->getValue(), E);
9007}
9008
Chris Lattner05706e882008-07-11 18:11:29 +00009009//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009010// Float Evaluation
9011//===----------------------------------------------------------------------===//
9012
9013namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009014class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009015 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009016 APFloat &Result;
9017public:
9018 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009019 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009020
Richard Smith2e312c82012-03-03 22:46:17 +00009021 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009022 Result = V.getFloat();
9023 return true;
9024 }
Eli Friedman24c01542008-08-22 00:06:13 +00009025
Richard Smithfddd3842011-12-30 21:15:51 +00009026 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009027 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9028 return true;
9029 }
9030
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009031 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009032
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009033 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009034 bool VisitBinaryOperator(const BinaryOperator *E);
9035 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009036 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009037
John McCallb1fb0d32010-05-07 22:08:54 +00009038 bool VisitUnaryReal(const UnaryOperator *E);
9039 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009040
Richard Smithfddd3842011-12-30 21:15:51 +00009041 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009042};
9043} // end anonymous namespace
9044
9045static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009046 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009047 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009048}
9049
Jay Foad39c79802011-01-12 09:06:06 +00009050static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009051 QualType ResultTy,
9052 const Expr *Arg,
9053 bool SNaN,
9054 llvm::APFloat &Result) {
9055 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9056 if (!S) return false;
9057
9058 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9059
9060 llvm::APInt fill;
9061
9062 // Treat empty strings as if they were zero.
9063 if (S->getString().empty())
9064 fill = llvm::APInt(32, 0);
9065 else if (S->getString().getAsInteger(0, fill))
9066 return false;
9067
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009068 if (Context.getTargetInfo().isNan2008()) {
9069 if (SNaN)
9070 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9071 else
9072 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9073 } else {
9074 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9075 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9076 // a different encoding to what became a standard in 2008, and for pre-
9077 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9078 // sNaN. This is now known as "legacy NaN" encoding.
9079 if (SNaN)
9080 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9081 else
9082 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9083 }
9084
John McCall16291492010-02-28 13:00:19 +00009085 return true;
9086}
9087
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009088bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009089 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009090 default:
9091 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9092
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009093 case Builtin::BI__builtin_huge_val:
9094 case Builtin::BI__builtin_huge_valf:
9095 case Builtin::BI__builtin_huge_vall:
9096 case Builtin::BI__builtin_inf:
9097 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009098 case Builtin::BI__builtin_infl: {
9099 const llvm::fltSemantics &Sem =
9100 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009101 Result = llvm::APFloat::getInf(Sem);
9102 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009103 }
Mike Stump11289f42009-09-09 15:08:12 +00009104
John McCall16291492010-02-28 13:00:19 +00009105 case Builtin::BI__builtin_nans:
9106 case Builtin::BI__builtin_nansf:
9107 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009108 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9109 true, Result))
9110 return Error(E);
9111 return true;
John McCall16291492010-02-28 13:00:19 +00009112
Chris Lattner0b7282e2008-10-06 06:31:58 +00009113 case Builtin::BI__builtin_nan:
9114 case Builtin::BI__builtin_nanf:
9115 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00009116 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009117 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009118 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9119 false, Result))
9120 return Error(E);
9121 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009122
9123 case Builtin::BI__builtin_fabs:
9124 case Builtin::BI__builtin_fabsf:
9125 case Builtin::BI__builtin_fabsl:
9126 if (!EvaluateFloat(E->getArg(0), Result, Info))
9127 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009128
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009129 if (Result.isNegative())
9130 Result.changeSign();
9131 return true;
9132
Richard Smith8889a3d2013-06-13 06:26:32 +00009133 // FIXME: Builtin::BI__builtin_powi
9134 // FIXME: Builtin::BI__builtin_powif
9135 // FIXME: Builtin::BI__builtin_powil
9136
Mike Stump11289f42009-09-09 15:08:12 +00009137 case Builtin::BI__builtin_copysign:
9138 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009139 case Builtin::BI__builtin_copysignl: {
9140 APFloat RHS(0.);
9141 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9142 !EvaluateFloat(E->getArg(1), RHS, Info))
9143 return false;
9144 Result.copySign(RHS);
9145 return true;
9146 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009147 }
9148}
9149
John McCallb1fb0d32010-05-07 22:08:54 +00009150bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009151 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9152 ComplexValue CV;
9153 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9154 return false;
9155 Result = CV.FloatReal;
9156 return true;
9157 }
9158
9159 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009160}
9161
9162bool FloatExprEvaluator::VisitUnaryImag(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.FloatImag;
9168 return true;
9169 }
9170
Richard Smith4a678122011-10-24 18:44:57 +00009171 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009172 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9173 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009174 return true;
9175}
9176
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009177bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009178 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009179 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009180 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009181 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009182 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009183 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9184 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009185 Result.changeSign();
9186 return true;
9187 }
9188}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009189
Eli Friedman24c01542008-08-22 00:06:13 +00009190bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009191 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9192 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009193
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009194 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009195 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009196 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009197 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009198 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9199 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009200}
9201
9202bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9203 Result = E->getValue();
9204 return true;
9205}
9206
Peter Collingbournee9200682011-05-13 03:29:01 +00009207bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9208 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009209
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009210 switch (E->getCastKind()) {
9211 default:
Richard Smith11562c52011-10-28 17:51:58 +00009212 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009213
9214 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009215 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009216 return EvaluateInteger(SubExpr, IntResult, Info) &&
9217 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9218 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009219 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009220
9221 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009222 if (!Visit(SubExpr))
9223 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009224 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9225 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009226 }
John McCalld7646252010-11-14 08:17:51 +00009227
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009228 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009229 ComplexValue V;
9230 if (!EvaluateComplex(SubExpr, V, Info))
9231 return false;
9232 Result = V.getComplexFloatReal();
9233 return true;
9234 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009235 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009236}
9237
Eli Friedman24c01542008-08-22 00:06:13 +00009238//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009239// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009240//===----------------------------------------------------------------------===//
9241
9242namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009243class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009244 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009245 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009246
Anders Carlsson537969c2008-11-16 20:27:53 +00009247public:
John McCall93d91dc2010-05-07 17:22:02 +00009248 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009249 : ExprEvaluatorBaseTy(info), Result(Result) {}
9250
Richard Smith2e312c82012-03-03 22:46:17 +00009251 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009252 Result.setFrom(V);
9253 return true;
9254 }
Mike Stump11289f42009-09-09 15:08:12 +00009255
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009256 bool ZeroInitialization(const Expr *E);
9257
Anders Carlsson537969c2008-11-16 20:27:53 +00009258 //===--------------------------------------------------------------------===//
9259 // Visitor Methods
9260 //===--------------------------------------------------------------------===//
9261
Peter Collingbournee9200682011-05-13 03:29:01 +00009262 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009263 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009264 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009265 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009266 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009267};
9268} // end anonymous namespace
9269
John McCall93d91dc2010-05-07 17:22:02 +00009270static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9271 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009272 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009273 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009274}
9275
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009276bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009277 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009278 if (ElemTy->isRealFloatingType()) {
9279 Result.makeComplexFloat();
9280 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9281 Result.FloatReal = Zero;
9282 Result.FloatImag = Zero;
9283 } else {
9284 Result.makeComplexInt();
9285 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9286 Result.IntReal = Zero;
9287 Result.IntImag = Zero;
9288 }
9289 return true;
9290}
9291
Peter Collingbournee9200682011-05-13 03:29:01 +00009292bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9293 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009294
9295 if (SubExpr->getType()->isRealFloatingType()) {
9296 Result.makeComplexFloat();
9297 APFloat &Imag = Result.FloatImag;
9298 if (!EvaluateFloat(SubExpr, Imag, Info))
9299 return false;
9300
9301 Result.FloatReal = APFloat(Imag.getSemantics());
9302 return true;
9303 } else {
9304 assert(SubExpr->getType()->isIntegerType() &&
9305 "Unexpected imaginary literal.");
9306
9307 Result.makeComplexInt();
9308 APSInt &Imag = Result.IntImag;
9309 if (!EvaluateInteger(SubExpr, Imag, Info))
9310 return false;
9311
9312 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9313 return true;
9314 }
9315}
9316
Peter Collingbournee9200682011-05-13 03:29:01 +00009317bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009318
John McCallfcef3cf2010-12-14 17:51:41 +00009319 switch (E->getCastKind()) {
9320 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009321 case CK_BaseToDerived:
9322 case CK_DerivedToBase:
9323 case CK_UncheckedDerivedToBase:
9324 case CK_Dynamic:
9325 case CK_ToUnion:
9326 case CK_ArrayToPointerDecay:
9327 case CK_FunctionToPointerDecay:
9328 case CK_NullToPointer:
9329 case CK_NullToMemberPointer:
9330 case CK_BaseToDerivedMemberPointer:
9331 case CK_DerivedToBaseMemberPointer:
9332 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009333 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009334 case CK_ConstructorConversion:
9335 case CK_IntegralToPointer:
9336 case CK_PointerToIntegral:
9337 case CK_PointerToBoolean:
9338 case CK_ToVoid:
9339 case CK_VectorSplat:
9340 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009341 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009342 case CK_IntegralToBoolean:
9343 case CK_IntegralToFloating:
9344 case CK_FloatingToIntegral:
9345 case CK_FloatingToBoolean:
9346 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009347 case CK_CPointerToObjCPointerCast:
9348 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009349 case CK_AnyPointerToBlockPointerCast:
9350 case CK_ObjCObjectLValueCast:
9351 case CK_FloatingComplexToReal:
9352 case CK_FloatingComplexToBoolean:
9353 case CK_IntegralComplexToReal:
9354 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009355 case CK_ARCProduceObject:
9356 case CK_ARCConsumeObject:
9357 case CK_ARCReclaimReturnedObject:
9358 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009359 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009360 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009361 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009362 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009363 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009364 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009365 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009366 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009367
John McCallfcef3cf2010-12-14 17:51:41 +00009368 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009369 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009370 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009371 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009372
9373 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009374 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009375 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009376 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009377
9378 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009379 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009380 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009381 return false;
9382
John McCallfcef3cf2010-12-14 17:51:41 +00009383 Result.makeComplexFloat();
9384 Result.FloatImag = APFloat(Real.getSemantics());
9385 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009386 }
9387
John McCallfcef3cf2010-12-14 17:51:41 +00009388 case CK_FloatingComplexCast: {
9389 if (!Visit(E->getSubExpr()))
9390 return false;
9391
9392 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9393 QualType From
9394 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9395
Richard Smith357362d2011-12-13 06:39:58 +00009396 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9397 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009398 }
9399
9400 case CK_FloatingComplexToIntegralComplex: {
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 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009408 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9409 To, Result.IntReal) &&
9410 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9411 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009412 }
9413
9414 case CK_IntegralRealToComplex: {
9415 APSInt &Real = Result.IntReal;
9416 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9417 return false;
9418
9419 Result.makeComplexInt();
9420 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9421 return true;
9422 }
9423
9424 case CK_IntegralComplexCast: {
9425 if (!Visit(E->getSubExpr()))
9426 return false;
9427
9428 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9429 QualType From
9430 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9431
Richard Smith911e1422012-01-30 22:27:01 +00009432 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9433 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009434 return true;
9435 }
9436
9437 case CK_IntegralComplexToFloatingComplex: {
9438 if (!Visit(E->getSubExpr()))
9439 return false;
9440
Ted Kremenek28831752012-08-23 20:46:57 +00009441 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009442 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009443 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009444 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009445 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9446 To, Result.FloatReal) &&
9447 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9448 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009449 }
9450 }
9451
9452 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009453}
9454
John McCall93d91dc2010-05-07 17:22:02 +00009455bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009456 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009457 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9458
Chandler Carrutha216cad2014-10-11 00:57:18 +00009459 // Track whether the LHS or RHS is real at the type system level. When this is
9460 // the case we can simplify our evaluation strategy.
9461 bool LHSReal = false, RHSReal = false;
9462
9463 bool LHSOK;
9464 if (E->getLHS()->getType()->isRealFloatingType()) {
9465 LHSReal = true;
9466 APFloat &Real = Result.FloatReal;
9467 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9468 if (LHSOK) {
9469 Result.makeComplexFloat();
9470 Result.FloatImag = APFloat(Real.getSemantics());
9471 }
9472 } else {
9473 LHSOK = Visit(E->getLHS());
9474 }
George Burgess IVa145e252016-05-25 22:38:36 +00009475 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009476 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009477
John McCall93d91dc2010-05-07 17:22:02 +00009478 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009479 if (E->getRHS()->getType()->isRealFloatingType()) {
9480 RHSReal = true;
9481 APFloat &Real = RHS.FloatReal;
9482 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9483 return false;
9484 RHS.makeComplexFloat();
9485 RHS.FloatImag = APFloat(Real.getSemantics());
9486 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009487 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009488
Chandler Carrutha216cad2014-10-11 00:57:18 +00009489 assert(!(LHSReal && RHSReal) &&
9490 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009491 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009492 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009493 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009494 if (Result.isComplexFloat()) {
9495 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9496 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009497 if (LHSReal)
9498 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9499 else if (!RHSReal)
9500 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9501 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009502 } else {
9503 Result.getComplexIntReal() += RHS.getComplexIntReal();
9504 Result.getComplexIntImag() += RHS.getComplexIntImag();
9505 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009506 break;
John McCalle3027922010-08-25 11:45:40 +00009507 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009508 if (Result.isComplexFloat()) {
9509 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9510 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009511 if (LHSReal) {
9512 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9513 Result.getComplexFloatImag().changeSign();
9514 } else if (!RHSReal) {
9515 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9516 APFloat::rmNearestTiesToEven);
9517 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009518 } else {
9519 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9520 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9521 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009522 break;
John McCalle3027922010-08-25 11:45:40 +00009523 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009524 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009525 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009526 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009527 // following naming scheme:
9528 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009529 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009530 APFloat &A = LHS.getComplexFloatReal();
9531 APFloat &B = LHS.getComplexFloatImag();
9532 APFloat &C = RHS.getComplexFloatReal();
9533 APFloat &D = RHS.getComplexFloatImag();
9534 APFloat &ResR = Result.getComplexFloatReal();
9535 APFloat &ResI = Result.getComplexFloatImag();
9536 if (LHSReal) {
9537 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9538 ResR = A * C;
9539 ResI = A * D;
9540 } else if (RHSReal) {
9541 ResR = C * A;
9542 ResI = C * B;
9543 } else {
9544 // In the fully general case, we need to handle NaNs and infinities
9545 // robustly.
9546 APFloat AC = A * C;
9547 APFloat BD = B * D;
9548 APFloat AD = A * D;
9549 APFloat BC = B * C;
9550 ResR = AC - BD;
9551 ResI = AD + BC;
9552 if (ResR.isNaN() && ResI.isNaN()) {
9553 bool Recalc = false;
9554 if (A.isInfinity() || B.isInfinity()) {
9555 A = APFloat::copySign(
9556 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9557 B = APFloat::copySign(
9558 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9559 if (C.isNaN())
9560 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9561 if (D.isNaN())
9562 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9563 Recalc = true;
9564 }
9565 if (C.isInfinity() || D.isInfinity()) {
9566 C = APFloat::copySign(
9567 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9568 D = APFloat::copySign(
9569 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9570 if (A.isNaN())
9571 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9572 if (B.isNaN())
9573 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9574 Recalc = true;
9575 }
9576 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9577 AD.isInfinity() || BC.isInfinity())) {
9578 if (A.isNaN())
9579 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9580 if (B.isNaN())
9581 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9582 if (C.isNaN())
9583 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9584 if (D.isNaN())
9585 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9586 Recalc = true;
9587 }
9588 if (Recalc) {
9589 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9590 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9591 }
9592 }
9593 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009594 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009595 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009596 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009597 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9598 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009599 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009600 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9601 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9602 }
9603 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009604 case BO_Div:
9605 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009606 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009607 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009608 // following naming scheme:
9609 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009610 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009611 APFloat &A = LHS.getComplexFloatReal();
9612 APFloat &B = LHS.getComplexFloatImag();
9613 APFloat &C = RHS.getComplexFloatReal();
9614 APFloat &D = RHS.getComplexFloatImag();
9615 APFloat &ResR = Result.getComplexFloatReal();
9616 APFloat &ResI = Result.getComplexFloatImag();
9617 if (RHSReal) {
9618 ResR = A / C;
9619 ResI = B / C;
9620 } else {
9621 if (LHSReal) {
9622 // No real optimizations we can do here, stub out with zero.
9623 B = APFloat::getZero(A.getSemantics());
9624 }
9625 int DenomLogB = 0;
9626 APFloat MaxCD = maxnum(abs(C), abs(D));
9627 if (MaxCD.isFinite()) {
9628 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009629 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9630 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009631 }
9632 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009633 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9634 APFloat::rmNearestTiesToEven);
9635 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9636 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009637 if (ResR.isNaN() && ResI.isNaN()) {
9638 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9639 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9640 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9641 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9642 D.isFinite()) {
9643 A = APFloat::copySign(
9644 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9645 B = APFloat::copySign(
9646 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9647 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9648 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9649 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9650 C = APFloat::copySign(
9651 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9652 D = APFloat::copySign(
9653 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9654 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9655 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9656 }
9657 }
9658 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009659 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009660 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9661 return Error(E, diag::note_expr_divide_by_zero);
9662
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009663 ComplexValue LHS = Result;
9664 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9665 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9666 Result.getComplexIntReal() =
9667 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9668 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9669 Result.getComplexIntImag() =
9670 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9671 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9672 }
9673 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009674 }
9675
John McCall93d91dc2010-05-07 17:22:02 +00009676 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009677}
9678
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009679bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9680 // Get the operand value into 'Result'.
9681 if (!Visit(E->getSubExpr()))
9682 return false;
9683
9684 switch (E->getOpcode()) {
9685 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009686 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009687 case UO_Extension:
9688 return true;
9689 case UO_Plus:
9690 // The result is always just the subexpr.
9691 return true;
9692 case UO_Minus:
9693 if (Result.isComplexFloat()) {
9694 Result.getComplexFloatReal().changeSign();
9695 Result.getComplexFloatImag().changeSign();
9696 }
9697 else {
9698 Result.getComplexIntReal() = -Result.getComplexIntReal();
9699 Result.getComplexIntImag() = -Result.getComplexIntImag();
9700 }
9701 return true;
9702 case UO_Not:
9703 if (Result.isComplexFloat())
9704 Result.getComplexFloatImag().changeSign();
9705 else
9706 Result.getComplexIntImag() = -Result.getComplexIntImag();
9707 return true;
9708 }
9709}
9710
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009711bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9712 if (E->getNumInits() == 2) {
9713 if (E->getType()->isComplexType()) {
9714 Result.makeComplexFloat();
9715 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9716 return false;
9717 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9718 return false;
9719 } else {
9720 Result.makeComplexInt();
9721 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9722 return false;
9723 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9724 return false;
9725 }
9726 return true;
9727 }
9728 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9729}
9730
Anders Carlsson537969c2008-11-16 20:27:53 +00009731//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009732// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9733// implicit conversion.
9734//===----------------------------------------------------------------------===//
9735
9736namespace {
9737class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009738 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009739 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009740 APValue &Result;
9741public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009742 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9743 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009744
9745 bool Success(const APValue &V, const Expr *E) {
9746 Result = V;
9747 return true;
9748 }
9749
9750 bool ZeroInitialization(const Expr *E) {
9751 ImplicitValueInitExpr VIE(
9752 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009753 // For atomic-qualified class (and array) types in C++, initialize the
9754 // _Atomic-wrapped subobject directly, in-place.
9755 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9756 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009757 }
9758
9759 bool VisitCastExpr(const CastExpr *E) {
9760 switch (E->getCastKind()) {
9761 default:
9762 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9763 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009764 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9765 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009766 }
9767 }
9768};
9769} // end anonymous namespace
9770
Richard Smith64cb9ca2017-02-22 22:09:50 +00009771static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9772 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009773 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009774 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009775}
9776
9777//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009778// Void expression evaluation, primarily for a cast to void on the LHS of a
9779// comma operator
9780//===----------------------------------------------------------------------===//
9781
9782namespace {
9783class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009784 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009785public:
9786 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9787
Richard Smith2e312c82012-03-03 22:46:17 +00009788 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009789
Richard Smith7cd577b2017-08-17 19:35:50 +00009790 bool ZeroInitialization(const Expr *E) { return true; }
9791
Richard Smith42d3af92011-12-07 00:43:50 +00009792 bool VisitCastExpr(const CastExpr *E) {
9793 switch (E->getCastKind()) {
9794 default:
9795 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9796 case CK_ToVoid:
9797 VisitIgnoredValue(E->getSubExpr());
9798 return true;
9799 }
9800 }
Hal Finkela8443c32014-07-17 14:49:58 +00009801
9802 bool VisitCallExpr(const CallExpr *E) {
9803 switch (E->getBuiltinCallee()) {
9804 default:
9805 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9806 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009807 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009808 // The argument is not evaluated!
9809 return true;
9810 }
9811 }
Richard Smith42d3af92011-12-07 00:43:50 +00009812};
9813} // end anonymous namespace
9814
9815static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9816 assert(E->isRValue() && E->getType()->isVoidType());
9817 return VoidExprEvaluator(Info).Visit(E);
9818}
9819
9820//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009821// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009822//===----------------------------------------------------------------------===//
9823
Richard Smith2e312c82012-03-03 22:46:17 +00009824static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009825 // In C, function designators are not lvalues, but we evaluate them as if they
9826 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009827 QualType T = E->getType();
9828 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009829 LValue LV;
9830 if (!EvaluateLValue(E, LV, Info))
9831 return false;
9832 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009833 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009834 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009835 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009836 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009837 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009838 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009839 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009840 LValue LV;
9841 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009842 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009843 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009844 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009845 llvm::APFloat F(0.0);
9846 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009847 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009848 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009849 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009850 ComplexValue C;
9851 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009852 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009853 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009854 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009855 MemberPtr P;
9856 if (!EvaluateMemberPointer(E, P, Info))
9857 return false;
9858 P.moveInto(Result);
9859 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009860 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009861 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009862 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009863 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9864 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009865 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009866 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009867 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009868 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009869 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009870 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9871 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009872 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009873 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009874 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009875 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009876 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009877 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009878 if (!EvaluateVoid(E, Info))
9879 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009880 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009881 QualType Unqual = T.getAtomicUnqualifiedType();
9882 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9883 LValue LV;
9884 LV.set(E, Info.CurrentCall->Index);
9885 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9886 if (!EvaluateAtomic(E, &LV, Value, Info))
9887 return false;
9888 } else {
9889 if (!EvaluateAtomic(E, nullptr, Result, Info))
9890 return false;
9891 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009892 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009893 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009894 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009895 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009896 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009897 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009898 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009899
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009900 return true;
9901}
9902
Richard Smithb228a862012-02-15 02:18:13 +00009903/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9904/// cases, the in-place evaluation is essential, since later initializers for
9905/// an object can indirectly refer to subobjects which were initialized earlier.
9906static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009907 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009908 assert(!E->isValueDependent());
9909
Richard Smith7525ff62013-05-09 07:14:00 +00009910 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009911 return false;
9912
9913 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009914 // Evaluate arrays and record types in-place, so that later initializers can
9915 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +00009916 QualType T = E->getType();
9917 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +00009918 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009919 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +00009920 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009921 else if (T->isAtomicType()) {
9922 QualType Unqual = T.getAtomicUnqualifiedType();
9923 if (Unqual->isArrayType() || Unqual->isRecordType())
9924 return EvaluateAtomic(E, &This, Result, Info);
9925 }
Richard Smithed5165f2011-11-04 05:33:44 +00009926 }
9927
9928 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009929 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009930}
9931
Richard Smithf57d8cb2011-12-09 22:58:01 +00009932/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9933/// lvalue-to-rvalue cast if it is an lvalue.
9934static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009935 if (E->getType().isNull())
9936 return false;
9937
Nick Lewyckyc190f962017-05-02 01:06:16 +00009938 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00009939 return false;
9940
Richard Smith2e312c82012-03-03 22:46:17 +00009941 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009942 return false;
9943
9944 if (E->isGLValue()) {
9945 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009946 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009947 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009948 return false;
9949 }
9950
Richard Smith2e312c82012-03-03 22:46:17 +00009951 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009952 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009953}
Richard Smith11562c52011-10-28 17:51:58 +00009954
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009955static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +00009956 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009957 // Fast-path evaluations of integer literals, since we sometimes see files
9958 // containing vast quantities of these.
9959 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9960 Result.Val = APValue(APSInt(L->getValue(),
9961 L->getType()->isUnsignedIntegerType()));
9962 IsConst = true;
9963 return true;
9964 }
James Dennett0492ef02014-03-14 17:44:10 +00009965
9966 // This case should be rare, but we need to check it before we check on
9967 // the type below.
9968 if (Exp->getType().isNull()) {
9969 IsConst = false;
9970 return true;
9971 }
Daniel Jasperffdee092017-05-02 19:21:42 +00009972
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009973 // FIXME: Evaluating values of large array and record types can cause
9974 // performance problems. Only do so in C++11 for now.
9975 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9976 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +00009977 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009978 IsConst = false;
9979 return true;
9980 }
9981 return false;
9982}
9983
9984
Richard Smith7b553f12011-10-29 00:50:52 +00009985/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009986/// any crazy technique (that has nothing to do with language standards) that
9987/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009988/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9989/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009990bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009991 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +00009992 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009993 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +00009994
Richard Smith6d4c6582013-11-05 22:18:15 +00009995 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009996 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009997}
9998
Jay Foad39c79802011-01-12 09:06:06 +00009999bool Expr::EvaluateAsBooleanCondition(bool &Result,
10000 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010001 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010002 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010003 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010004}
10005
Richard Smithce8eca52015-12-08 03:21:47 +000010006static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10007 Expr::SideEffectsKind SEK) {
10008 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10009 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10010}
10011
Richard Smith5fab0c92011-12-28 19:48:30 +000010012bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10013 SideEffectsKind AllowSideEffects) const {
10014 if (!getType()->isIntegralOrEnumerationType())
10015 return false;
10016
Richard Smith11562c52011-10-28 17:51:58 +000010017 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010018 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010019 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010020 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010021
Richard Smith11562c52011-10-28 17:51:58 +000010022 Result = ExprResult.Val.getInt();
10023 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010024}
10025
Richard Trieube234c32016-04-21 21:04:55 +000010026bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10027 SideEffectsKind AllowSideEffects) const {
10028 if (!getType()->isRealFloatingType())
10029 return false;
10030
10031 EvalResult ExprResult;
10032 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10033 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10034 return false;
10035
10036 Result = ExprResult.Val.getFloat();
10037 return true;
10038}
10039
Jay Foad39c79802011-01-12 09:06:06 +000010040bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010041 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010042
John McCall45d55e42010-05-07 21:00:08 +000010043 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010044 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10045 !CheckLValueConstantExpression(Info, getExprLoc(),
10046 Ctx.getLValueReferenceType(getType()), LV))
10047 return false;
10048
Richard Smith2e312c82012-03-03 22:46:17 +000010049 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010050 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010051}
10052
Richard Smithd0b4dd62011-12-19 06:19:21 +000010053bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10054 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010055 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010056 // FIXME: Evaluating initializers for large array and record types can cause
10057 // performance problems. Only do so in C++11 for now.
10058 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010059 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010060 return false;
10061
Richard Smithd0b4dd62011-12-19 06:19:21 +000010062 Expr::EvalStatus EStatus;
10063 EStatus.Diag = &Notes;
10064
Richard Smith0c6124b2015-12-03 01:36:22 +000010065 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10066 ? EvalInfo::EM_ConstantExpression
10067 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010068 InitInfo.setEvaluatingDecl(VD, Value);
10069
10070 LValue LVal;
10071 LVal.set(VD);
10072
Richard Smithfddd3842011-12-30 21:15:51 +000010073 // C++11 [basic.start.init]p2:
10074 // Variables with static storage duration or thread storage duration shall be
10075 // zero-initialized before any other initialization takes place.
10076 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010077 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010078 !VD->getType()->isReferenceType()) {
10079 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010080 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010081 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010082 return false;
10083 }
10084
Richard Smith7525ff62013-05-09 07:14:00 +000010085 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10086 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010087 EStatus.HasSideEffects)
10088 return false;
10089
10090 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10091 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010092}
10093
Richard Smith7b553f12011-10-29 00:50:52 +000010094/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10095/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010096bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010097 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010098 return EvaluateAsRValue(Result, Ctx) &&
10099 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010100}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010101
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010102APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010103 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010104 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010105 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010106 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010107 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010108 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010109 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010110
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010111 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010112}
John McCall864e3962010-05-07 05:32:02 +000010113
Richard Smithe9ff7702013-11-05 22:23:30 +000010114void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010115 bool IsConst;
10116 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010117 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010118 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010119 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10120 }
10121}
10122
Richard Smithe6c01442013-06-05 00:46:14 +000010123bool Expr::EvalResult::isGlobalLValue() const {
10124 assert(Val.isLValue());
10125 return IsGlobalLValue(Val.getLValueBase());
10126}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010127
10128
John McCall864e3962010-05-07 05:32:02 +000010129/// isIntegerConstantExpr - this recursive routine will test if an expression is
10130/// an integer constant expression.
10131
10132/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10133/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010134
10135// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010136// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10137// and a (possibly null) SourceLocation indicating the location of the problem.
10138//
John McCall864e3962010-05-07 05:32:02 +000010139// Note that to reduce code duplication, this helper does no evaluation
10140// itself; the caller checks whether the expression is evaluatable, and
10141// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010142// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010143
Dan Gohman28ade552010-07-26 21:25:24 +000010144namespace {
10145
Richard Smith9e575da2012-12-28 13:25:52 +000010146enum ICEKind {
10147 /// This expression is an ICE.
10148 IK_ICE,
10149 /// This expression is not an ICE, but if it isn't evaluated, it's
10150 /// a legal subexpression for an ICE. This return value is used to handle
10151 /// the comma operator in C99 mode, and non-constant subexpressions.
10152 IK_ICEIfUnevaluated,
10153 /// This expression is not an ICE, and is not a legal subexpression for one.
10154 IK_NotICE
10155};
10156
John McCall864e3962010-05-07 05:32:02 +000010157struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010158 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010159 SourceLocation Loc;
10160
Richard Smith9e575da2012-12-28 13:25:52 +000010161 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010162};
10163
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010164}
Dan Gohman28ade552010-07-26 21:25:24 +000010165
Richard Smith9e575da2012-12-28 13:25:52 +000010166static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10167
10168static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010169
Craig Toppera31a8822013-08-22 07:09:37 +000010170static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010171 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010172 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010173 !EVResult.Val.isInt())
10174 return ICEDiag(IK_NotICE, E->getLocStart());
10175
John McCall864e3962010-05-07 05:32:02 +000010176 return NoDiag();
10177}
10178
Craig Toppera31a8822013-08-22 07:09:37 +000010179static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010180 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010181 if (!E->getType()->isIntegralOrEnumerationType())
10182 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010183
10184 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010185#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010186#define STMT(Node, Base) case Expr::Node##Class:
10187#define EXPR(Node, Base)
10188#include "clang/AST/StmtNodes.inc"
10189 case Expr::PredefinedExprClass:
10190 case Expr::FloatingLiteralClass:
10191 case Expr::ImaginaryLiteralClass:
10192 case Expr::StringLiteralClass:
10193 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010194 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010195 case Expr::MemberExprClass:
10196 case Expr::CompoundAssignOperatorClass:
10197 case Expr::CompoundLiteralExprClass:
10198 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010199 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010200 case Expr::ArrayInitLoopExprClass:
10201 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010202 case Expr::NoInitExprClass:
10203 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010204 case Expr::ImplicitValueInitExprClass:
10205 case Expr::ParenListExprClass:
10206 case Expr::VAArgExprClass:
10207 case Expr::AddrLabelExprClass:
10208 case Expr::StmtExprClass:
10209 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010210 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010211 case Expr::CXXDynamicCastExprClass:
10212 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010213 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010214 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010215 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010216 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010217 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010218 case Expr::CXXThisExprClass:
10219 case Expr::CXXThrowExprClass:
10220 case Expr::CXXNewExprClass:
10221 case Expr::CXXDeleteExprClass:
10222 case Expr::CXXPseudoDestructorExprClass:
10223 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010224 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010225 case Expr::DependentScopeDeclRefExprClass:
10226 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010227 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010228 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010229 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010230 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010231 case Expr::CXXTemporaryObjectExprClass:
10232 case Expr::CXXUnresolvedConstructExprClass:
10233 case Expr::CXXDependentScopeMemberExprClass:
10234 case Expr::UnresolvedMemberExprClass:
10235 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010236 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010237 case Expr::ObjCArrayLiteralClass:
10238 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010239 case Expr::ObjCEncodeExprClass:
10240 case Expr::ObjCMessageExprClass:
10241 case Expr::ObjCSelectorExprClass:
10242 case Expr::ObjCProtocolExprClass:
10243 case Expr::ObjCIvarRefExprClass:
10244 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010245 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010246 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010247 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010248 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010249 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010250 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010251 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010252 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010253 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010254 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010255 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010256 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010257 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010258 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010259 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010260 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010261 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010262 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010263 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010264 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010265 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010266 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010267
Richard Smithf137f932014-01-25 20:50:08 +000010268 case Expr::InitListExprClass: {
10269 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10270 // form "T x = { a };" is equivalent to "T x = a;".
10271 // Unless we're initializing a reference, T is a scalar as it is known to be
10272 // of integral or enumeration type.
10273 if (E->isRValue())
10274 if (cast<InitListExpr>(E)->getNumInits() == 1)
10275 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10276 return ICEDiag(IK_NotICE, E->getLocStart());
10277 }
10278
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010279 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010280 case Expr::GNUNullExprClass:
10281 // GCC considers the GNU __null value to be an integral constant expression.
10282 return NoDiag();
10283
John McCall7c454bb2011-07-15 05:09:51 +000010284 case Expr::SubstNonTypeTemplateParmExprClass:
10285 return
10286 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10287
John McCall864e3962010-05-07 05:32:02 +000010288 case Expr::ParenExprClass:
10289 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010290 case Expr::GenericSelectionExprClass:
10291 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010292 case Expr::IntegerLiteralClass:
10293 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010294 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010295 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010296 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010297 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010298 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010299 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010300 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010301 return NoDiag();
10302 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010303 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010304 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10305 // constant expressions, but they can never be ICEs because an ICE cannot
10306 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010307 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010308 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010309 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010310 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010311 }
Richard Smith6365c912012-02-24 22:12:32 +000010312 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010313 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10314 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010315 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010316 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010317 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010318 // Parameter variables are never constants. Without this check,
10319 // getAnyInitializer() can find a default argument, which leads
10320 // to chaos.
10321 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010322 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010323
10324 // C++ 7.1.5.1p2
10325 // A variable of non-volatile const-qualified integral or enumeration
10326 // type initialized by an ICE can be used in ICEs.
10327 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010328 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010329 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010330
Richard Smithd0b4dd62011-12-19 06:19:21 +000010331 const VarDecl *VD;
10332 // Look for a declaration of this variable that has an initializer, and
10333 // check whether it is an ICE.
10334 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10335 return NoDiag();
10336 else
Richard Smith9e575da2012-12-28 13:25:52 +000010337 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010338 }
10339 }
Richard Smith9e575da2012-12-28 13:25:52 +000010340 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010341 }
John McCall864e3962010-05-07 05:32:02 +000010342 case Expr::UnaryOperatorClass: {
10343 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10344 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010345 case UO_PostInc:
10346 case UO_PostDec:
10347 case UO_PreInc:
10348 case UO_PreDec:
10349 case UO_AddrOf:
10350 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010351 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010352 // C99 6.6/3 allows increment and decrement within unevaluated
10353 // subexpressions of constant expressions, but they can never be ICEs
10354 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010355 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010356 case UO_Extension:
10357 case UO_LNot:
10358 case UO_Plus:
10359 case UO_Minus:
10360 case UO_Not:
10361 case UO_Real:
10362 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010363 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010364 }
Richard Smith9e575da2012-12-28 13:25:52 +000010365
John McCall864e3962010-05-07 05:32:02 +000010366 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010367 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010368 }
10369 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010370 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10371 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10372 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10373 // compliance: we should warn earlier for offsetof expressions with
10374 // array subscripts that aren't ICEs, and if the array subscripts
10375 // are ICEs, the value of the offsetof must be an integer constant.
10376 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010377 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010378 case Expr::UnaryExprOrTypeTraitExprClass: {
10379 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10380 if ((Exp->getKind() == UETT_SizeOf) &&
10381 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010382 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010383 return NoDiag();
10384 }
10385 case Expr::BinaryOperatorClass: {
10386 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10387 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010388 case BO_PtrMemD:
10389 case BO_PtrMemI:
10390 case BO_Assign:
10391 case BO_MulAssign:
10392 case BO_DivAssign:
10393 case BO_RemAssign:
10394 case BO_AddAssign:
10395 case BO_SubAssign:
10396 case BO_ShlAssign:
10397 case BO_ShrAssign:
10398 case BO_AndAssign:
10399 case BO_XorAssign:
10400 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010401 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10402 // constant expressions, but they can never be ICEs because an ICE cannot
10403 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010404 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010405
John McCalle3027922010-08-25 11:45:40 +000010406 case BO_Mul:
10407 case BO_Div:
10408 case BO_Rem:
10409 case BO_Add:
10410 case BO_Sub:
10411 case BO_Shl:
10412 case BO_Shr:
10413 case BO_LT:
10414 case BO_GT:
10415 case BO_LE:
10416 case BO_GE:
10417 case BO_EQ:
10418 case BO_NE:
10419 case BO_And:
10420 case BO_Xor:
10421 case BO_Or:
10422 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010423 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10424 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010425 if (Exp->getOpcode() == BO_Div ||
10426 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010427 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010428 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010429 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010430 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010431 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010432 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010433 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010434 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010435 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010436 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010437 }
10438 }
10439 }
John McCalle3027922010-08-25 11:45:40 +000010440 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010441 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010442 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10443 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010444 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10445 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010446 } else {
10447 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010448 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010449 }
10450 }
Richard Smith9e575da2012-12-28 13:25:52 +000010451 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010452 }
John McCalle3027922010-08-25 11:45:40 +000010453 case BO_LAnd:
10454 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010455 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10456 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010457 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010458 // Rare case where the RHS has a comma "side-effect"; we need
10459 // to actually check the condition to see whether the side
10460 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010461 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010462 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010463 return RHSResult;
10464 return NoDiag();
10465 }
10466
Richard Smith9e575da2012-12-28 13:25:52 +000010467 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010468 }
10469 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010470 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010471 }
10472 case Expr::ImplicitCastExprClass:
10473 case Expr::CStyleCastExprClass:
10474 case Expr::CXXFunctionalCastExprClass:
10475 case Expr::CXXStaticCastExprClass:
10476 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010477 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010478 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010479 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010480 if (isa<ExplicitCastExpr>(E)) {
10481 if (const FloatingLiteral *FL
10482 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10483 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10484 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10485 APSInt IgnoredVal(DestWidth, !DestSigned);
10486 bool Ignored;
10487 // If the value does not fit in the destination type, the behavior is
10488 // undefined, so we are not required to treat it as a constant
10489 // expression.
10490 if (FL->getValue().convertToInteger(IgnoredVal,
10491 llvm::APFloat::rmTowardZero,
10492 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010493 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010494 return NoDiag();
10495 }
10496 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010497 switch (cast<CastExpr>(E)->getCastKind()) {
10498 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010499 case CK_AtomicToNonAtomic:
10500 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010501 case CK_NoOp:
10502 case CK_IntegralToBoolean:
10503 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010504 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010505 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010506 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010507 }
John McCall864e3962010-05-07 05:32:02 +000010508 }
John McCallc07a0c72011-02-17 10:25:35 +000010509 case Expr::BinaryConditionalOperatorClass: {
10510 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10511 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010512 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010513 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010514 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10515 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10516 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010517 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010518 return FalseResult;
10519 }
John McCall864e3962010-05-07 05:32:02 +000010520 case Expr::ConditionalOperatorClass: {
10521 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10522 // If the condition (ignoring parens) is a __builtin_constant_p call,
10523 // then only the true side is actually considered in an integer constant
10524 // expression, and it is fully evaluated. This is an important GNU
10525 // extension. See GCC PR38377 for discussion.
10526 if (const CallExpr *CallCE
10527 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010528 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010529 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010530 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010531 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010532 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010533
Richard Smithf57d8cb2011-12-09 22:58:01 +000010534 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10535 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010536
Richard Smith9e575da2012-12-28 13:25:52 +000010537 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010538 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010539 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010540 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010541 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010542 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010543 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010544 return NoDiag();
10545 // Rare case where the diagnostics depend on which side is evaluated
10546 // Note that if we get here, CondResult is 0, and at least one of
10547 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010548 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010549 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010550 return TrueResult;
10551 }
10552 case Expr::CXXDefaultArgExprClass:
10553 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010554 case Expr::CXXDefaultInitExprClass:
10555 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010556 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010557 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010558 }
10559 }
10560
David Blaikiee4d798f2012-01-20 21:50:17 +000010561 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010562}
10563
Richard Smithf57d8cb2011-12-09 22:58:01 +000010564/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010565static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010566 const Expr *E,
10567 llvm::APSInt *Value,
10568 SourceLocation *Loc) {
10569 if (!E->getType()->isIntegralOrEnumerationType()) {
10570 if (Loc) *Loc = E->getExprLoc();
10571 return false;
10572 }
10573
Richard Smith66e05fe2012-01-18 05:21:49 +000010574 APValue Result;
10575 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010576 return false;
10577
Richard Smith98710fc2014-11-13 23:03:19 +000010578 if (!Result.isInt()) {
10579 if (Loc) *Loc = E->getExprLoc();
10580 return false;
10581 }
10582
Richard Smith66e05fe2012-01-18 05:21:49 +000010583 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010584 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010585}
10586
Craig Toppera31a8822013-08-22 07:09:37 +000010587bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10588 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010589 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010590 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010591
Richard Smith9e575da2012-12-28 13:25:52 +000010592 ICEDiag D = CheckICE(this, Ctx);
10593 if (D.Kind != IK_ICE) {
10594 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010595 return false;
10596 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010597 return true;
10598}
10599
Craig Toppera31a8822013-08-22 07:09:37 +000010600bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010601 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010602 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010603 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10604
10605 if (!isIntegerConstantExpr(Ctx, Loc))
10606 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010607 // The only possible side-effects here are due to UB discovered in the
10608 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10609 // required to treat the expression as an ICE, so we produce the folded
10610 // value.
10611 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010612 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010613 return true;
10614}
Richard Smith66e05fe2012-01-18 05:21:49 +000010615
Craig Toppera31a8822013-08-22 07:09:37 +000010616bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010617 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010618}
10619
Craig Toppera31a8822013-08-22 07:09:37 +000010620bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010621 SourceLocation *Loc) const {
10622 // We support this checking in C++98 mode in order to diagnose compatibility
10623 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010624 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010625
Richard Smith98a0a492012-02-14 21:38:30 +000010626 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010627 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010628 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010629 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010630 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010631
10632 APValue Scratch;
10633 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10634
10635 if (!Diags.empty()) {
10636 IsConstExpr = false;
10637 if (Loc) *Loc = Diags[0].first;
10638 } else if (!IsConstExpr) {
10639 // FIXME: This shouldn't happen.
10640 if (Loc) *Loc = getExprLoc();
10641 }
10642
10643 return IsConstExpr;
10644}
Richard Smith253c2a32012-01-27 01:14:48 +000010645
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010646bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10647 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010648 ArrayRef<const Expr*> Args,
10649 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010650 Expr::EvalStatus Status;
10651 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10652
George Burgess IV177399e2017-01-09 04:12:14 +000010653 LValue ThisVal;
10654 const LValue *ThisPtr = nullptr;
10655 if (This) {
10656#ifndef NDEBUG
10657 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10658 assert(MD && "Don't provide `this` for non-methods.");
10659 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10660#endif
10661 if (EvaluateObjectArgument(Info, This, ThisVal))
10662 ThisPtr = &ThisVal;
10663 if (Info.EvalStatus.HasSideEffects)
10664 return false;
10665 }
10666
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010667 ArgVector ArgValues(Args.size());
10668 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10669 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010670 if ((*I)->isValueDependent() ||
10671 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010672 // If evaluation fails, throw away the argument entirely.
10673 ArgValues[I - Args.begin()] = APValue();
10674 if (Info.EvalStatus.HasSideEffects)
10675 return false;
10676 }
10677
10678 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010679 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010680 ArgValues.data());
10681 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10682}
10683
Richard Smith253c2a32012-01-27 01:14:48 +000010684bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010685 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010686 PartialDiagnosticAt> &Diags) {
10687 // FIXME: It would be useful to check constexpr function templates, but at the
10688 // moment the constant expression evaluator cannot cope with the non-rigorous
10689 // ASTs which we build for dependent expressions.
10690 if (FD->isDependentContext())
10691 return true;
10692
10693 Expr::EvalStatus Status;
10694 Status.Diag = &Diags;
10695
Richard Smith6d4c6582013-11-05 22:18:15 +000010696 EvalInfo Info(FD->getASTContext(), Status,
10697 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010698
10699 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010700 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010701
Richard Smith7525ff62013-05-09 07:14:00 +000010702 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010703 // is a temporary being used as the 'this' pointer.
10704 LValue This;
10705 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010706 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010707
Richard Smith253c2a32012-01-27 01:14:48 +000010708 ArrayRef<const Expr*> Args;
10709
Richard Smith2e312c82012-03-03 22:46:17 +000010710 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010711 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10712 // Evaluate the call as a constant initializer, to allow the construction
10713 // of objects of non-literal types.
10714 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010715 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10716 } else {
10717 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010718 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010719 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010720 }
Richard Smith253c2a32012-01-27 01:14:48 +000010721
10722 return Diags.empty();
10723}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010724
10725bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10726 const FunctionDecl *FD,
10727 SmallVectorImpl<
10728 PartialDiagnosticAt> &Diags) {
10729 Expr::EvalStatus Status;
10730 Status.Diag = &Diags;
10731
10732 EvalInfo Info(FD->getASTContext(), Status,
10733 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10734
10735 // Fabricate a call stack frame to give the arguments a plausible cover story.
10736 ArrayRef<const Expr*> Args;
10737 ArgVector ArgValues(0);
10738 bool Success = EvaluateArgs(Args, ArgValues, Info);
10739 (void)Success;
10740 assert(Success &&
10741 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010742 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010743
10744 APValue ResultScratch;
10745 Evaluate(ResultScratch, Info, E);
10746 return Diags.empty();
10747}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010748
10749bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10750 unsigned Type) const {
10751 if (!getType()->isPointerType())
10752 return false;
10753
10754 Expr::EvalStatus Status;
10755 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010756 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010757}