blob: 438990f406d169bf7d00c164d919dac6751bf060 [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
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000051#define DEBUG_TYPE "exprconstant"
52
Anders Carlsson7a241ba2008-07-03 04:20:39 +000053using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000054using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000055using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000056
Richard Smithb228a862012-02-15 02:18:13 +000057static bool IsGlobalLValue(APValue::LValueBase B);
58
John McCall93d91dc2010-05-07 17:22:02 +000059namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000060 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000061 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000062 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000063
Richard Smithb228a862012-02-15 02:18:13 +000064 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000065 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000066 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000067 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000068 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000069 //
70 // extern int arr[]; void f() { extern int arr[3]; };
71 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000072 //
73 // For now, we take the array bound from the most recent declaration.
74 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
75 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
76 QualType T = Redecl->getType();
77 if (!T->isIncompleteArrayType())
78 return T;
79 }
80 return D->getType();
81 }
Richard Smith84401042013-06-03 05:03:02 +000082
83 const Expr *Base = B.get<const Expr*>();
84
85 // For a materialized temporary, the type of the temporary we materialized
86 // may not be the type of the expression.
87 if (const MaterializeTemporaryExpr *MTE =
88 dyn_cast<MaterializeTemporaryExpr>(Base)) {
89 SmallVector<const Expr *, 2> CommaLHSs;
90 SmallVector<SubobjectAdjustment, 2> Adjustments;
91 const Expr *Temp = MTE->GetTemporaryExpr();
92 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
93 Adjustments);
94 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000095 // for it directly. Otherwise use the type after adjustment.
96 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000097 return Inner->getType();
98 }
99
100 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000101 }
102
Richard Smithd62306a2011-11-10 06:34:14 +0000103 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +0000105 static
Richard Smith84f6dcf2012-02-02 01:16:57 +0000106 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +0000107 APValue::BaseOrMemberType Value;
108 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return Value;
110 }
111
112 /// Get an LValue path entry, which is known to not be an array index, as a
113 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000114 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000115 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000116 }
117 /// Get an LValue path entry, which is known to not be an array index, as a
118 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000119 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000120 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000121 }
122 /// Determine whether this LValue path entry for a base class names a virtual
123 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000124 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000125 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000126 }
127
George Burgess IVe3763372016-12-22 02:50:20 +0000128 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
129 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
130 const FunctionDecl *Callee = CE->getDirectCallee();
131 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
132 }
133
134 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
135 /// This will look through a single cast.
136 ///
137 /// Returns null if we couldn't unwrap a function with alloc_size.
138 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
139 if (!E->getType()->isPointerType())
140 return nullptr;
141
142 E = E->IgnoreParens();
143 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000144 // probably be a cast of some kind. In exotic cases, we might also see a
145 // top-level ExprWithCleanups. Ignore them either way.
146 if (const auto *EC = dyn_cast<ExprWithCleanups>(E))
147 E = EC->getSubExpr()->IgnoreParens();
148
George Burgess IVe3763372016-12-22 02:50:20 +0000149 if (const auto *Cast = dyn_cast<CastExpr>(E))
150 E = Cast->getSubExpr()->IgnoreParens();
151
152 if (const auto *CE = dyn_cast<CallExpr>(E))
153 return getAllocSizeAttr(CE) ? CE : nullptr;
154 return nullptr;
155 }
156
157 /// Determines whether or not the given Base contains a call to a function
158 /// with the alloc_size attribute.
159 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
160 const auto *E = Base.dyn_cast<const Expr *>();
161 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
162 }
163
Richard Smith6f4f0f12017-10-20 22:56:25 +0000164 /// The bound to claim that an array of unknown bound has.
165 /// The value in MostDerivedArraySize is undefined in this case. So, set it
166 /// to an arbitrary value that's likely to loudly break things if it's used.
167 static const uint64_t AssumedSizeForUnsizedArray =
168 std::numeric_limits<uint64_t>::max() / 2;
169
George Burgess IVe3763372016-12-22 02:50:20 +0000170 /// Determines if an LValue with the given LValueBase will have an unsized
171 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000172 /// Find the path length and type of the most-derived subobject in the given
173 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000174 static unsigned
175 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
176 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000177 uint64_t &ArraySize, QualType &Type, bool &IsArray,
178 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000179 // This only accepts LValueBases from APValues, and APValues don't support
180 // arrays that lack size info.
181 assert(!isBaseAnAllocSizeCall(Base) &&
182 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000183 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000184 Type = getType(Base);
185
Richard Smith80815602011-11-07 05:07:52 +0000186 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000187 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000188 const ArrayType *AT = Ctx.getAsArrayType(Type);
189 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000190 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000191 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000192
193 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
194 ArraySize = CAT->getSize().getZExtValue();
195 } else {
196 assert(I == 0 && "unexpected unsized array designator");
197 FirstEntryIsUnsizedArray = true;
198 ArraySize = AssumedSizeForUnsizedArray;
199 }
Richard Smith66c96992012-02-18 22:04:06 +0000200 } else if (Type->isAnyComplexType()) {
201 const ComplexType *CT = Type->castAs<ComplexType>();
202 Type = CT->getElementType();
203 ArraySize = 2;
204 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000205 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000206 } else if (const FieldDecl *FD = getAsField(Path[I])) {
207 Type = FD->getType();
208 ArraySize = 0;
209 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000210 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000211 } else {
Richard Smith80815602011-11-07 05:07:52 +0000212 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000213 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000214 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000215 }
Richard Smith80815602011-11-07 05:07:52 +0000216 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000218 }
219
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 // The order of this enum is important for diagnostics.
221 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000222 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000223 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000224 };
225
Richard Smith96e0c102011-11-04 02:25:55 +0000226 /// A path from a glvalue to a subobject of that glvalue.
227 struct SubobjectDesignator {
228 /// True if the subobject was named in a manner not supported by C++11. Such
229 /// lvalues can still be folded, but they are not core constant expressions
230 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000231 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000232
Richard Smitha8105bc2012-01-06 16:39:00 +0000233 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000234 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000235
Daniel Jasperffdee092017-05-02 19:21:42 +0000236 /// Indicator of whether the first entry is an unsized array.
237 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000238
George Burgess IVa51c4072015-10-16 01:49:01 +0000239 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000240 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000241
Richard Smitha8105bc2012-01-06 16:39:00 +0000242 /// The length of the path to the most-derived object of which this is a
243 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000244 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000245
George Burgess IVa51c4072015-10-16 01:49:01 +0000246 /// The size of the array of which the most-derived object is an element.
247 /// This will always be 0 if the most-derived object is not an array
248 /// element. 0 is not an indicator of whether or not the most-derived object
249 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000250 ///
251 /// If the current array is an unsized array, the value of this is
252 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000253 uint64_t MostDerivedArraySize;
254
255 /// The type of the most derived object referred to by this address.
256 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000257
Richard Smith80815602011-11-07 05:07:52 +0000258 typedef APValue::LValuePathEntry PathEntry;
259
Richard Smith96e0c102011-11-04 02:25:55 +0000260 /// The entries on the path from the glvalue to the designated subobject.
261 SmallVector<PathEntry, 8> Entries;
262
Richard Smitha8105bc2012-01-06 16:39:00 +0000263 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000264
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000266 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000267 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000268 MostDerivedPathLength(0), MostDerivedArraySize(0),
269 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000270
271 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000272 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000273 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000274 MostDerivedPathLength(0), MostDerivedArraySize(0) {
275 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000276 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000277 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000278 ArrayRef<PathEntry> VEntries = V.getLValuePath();
279 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000280 if (V.getLValueBase()) {
281 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000282 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000283 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000284 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000285 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000286 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000287 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000288 }
Richard Smith80815602011-11-07 05:07:52 +0000289 }
290 }
291
Richard Smith96e0c102011-11-04 02:25:55 +0000292 void setInvalid() {
293 Invalid = true;
294 Entries.clear();
295 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000296
George Burgess IVe3763372016-12-22 02:50:20 +0000297 /// Determine whether the most derived subobject is an array without a
298 /// known bound.
299 bool isMostDerivedAnUnsizedArray() const {
300 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000301 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000302 }
303
304 /// Determine what the most derived array's size is. Results in an assertion
305 /// failure if the most derived array lacks a size.
306 uint64_t getMostDerivedArraySize() const {
307 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
308 return MostDerivedArraySize;
309 }
310
Richard Smitha8105bc2012-01-06 16:39:00 +0000311 /// Determine whether this is a one-past-the-end pointer.
312 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000313 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000314 if (IsOnePastTheEnd)
315 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000316 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000317 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
318 return true;
319 return false;
320 }
321
322 /// Check that this refers to a valid subobject.
323 bool isValidSubobject() const {
324 if (Invalid)
325 return false;
326 return !isOnePastTheEnd();
327 }
328 /// Check that this refers to a valid subobject, and if not, produce a
329 /// relevant diagnostic and set the designator as invalid.
330 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
331
332 /// Update this designator to refer to the first element within this array.
333 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000334 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000335 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000336 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000337
338 // This is a most-derived object.
339 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000340 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000341 MostDerivedArraySize = CAT->getSize().getZExtValue();
342 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000343 }
George Burgess IVe3763372016-12-22 02:50:20 +0000344 /// Update this designator to refer to the first element within the array of
345 /// elements of type T. This is an array of unknown size.
346 void addUnsizedArrayUnchecked(QualType ElemTy) {
347 PathEntry Entry;
348 Entry.ArrayIndex = 0;
349 Entries.push_back(Entry);
350
351 MostDerivedType = ElemTy;
352 MostDerivedIsArrayElement = true;
353 // The value in MostDerivedArraySize is undefined in this case. So, set it
354 // to an arbitrary value that's likely to loudly break things if it's
355 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000356 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000357 MostDerivedPathLength = Entries.size();
358 }
Richard Smith96e0c102011-11-04 02:25:55 +0000359 /// Update this designator to refer to the given base or member of this
360 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000361 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000362 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000363 APValue::BaseOrMemberType Value(D, Virtual);
364 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000365 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000366
367 // If this isn't a base class, it's a new most-derived object.
368 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
369 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000370 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000371 MostDerivedArraySize = 0;
372 MostDerivedPathLength = Entries.size();
373 }
Richard Smith96e0c102011-11-04 02:25:55 +0000374 }
Richard Smith66c96992012-02-18 22:04:06 +0000375 /// Update this designator to refer to the given complex component.
376 void addComplexUnchecked(QualType EltTy, bool Imag) {
377 PathEntry Entry;
378 Entry.ArrayIndex = Imag;
379 Entries.push_back(Entry);
380
381 // This is technically a most-derived object, though in practice this
382 // is unlikely to matter.
383 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000384 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000385 MostDerivedArraySize = 2;
386 MostDerivedPathLength = Entries.size();
387 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000388 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000389 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
390 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000391 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000392 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
393 if (Invalid || !N) return;
394 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
395 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000396 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000397 // Can't verify -- trust that the user is doing the right thing (or if
398 // not, trust that the caller will catch the bad behavior).
399 // FIXME: Should we reject if this overflows, at least?
400 Entries.back().ArrayIndex += TruncatedN;
401 return;
402 }
403
404 // [expr.add]p4: For the purposes of these operators, a pointer to a
405 // nonarray object behaves the same as a pointer to the first element of
406 // an array of length one with the type of the object as its element type.
407 bool IsArray = MostDerivedPathLength == Entries.size() &&
408 MostDerivedIsArrayElement;
409 uint64_t ArrayIndex =
410 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
411 uint64_t ArraySize =
412 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
413
414 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
415 // Calculate the actual index in a wide enough type, so we can include
416 // it in the note.
417 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
418 (llvm::APInt&)N += ArrayIndex;
419 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
420 diagnosePointerArithmetic(Info, E, N);
421 setInvalid();
422 return;
423 }
424
425 ArrayIndex += TruncatedN;
426 assert(ArrayIndex <= ArraySize &&
427 "bounds check succeeded for out-of-bounds index");
428
429 if (IsArray)
430 Entries.back().ArrayIndex = ArrayIndex;
431 else
432 IsOnePastTheEnd = (ArrayIndex != 0);
433 }
Richard Smith96e0c102011-11-04 02:25:55 +0000434 };
435
Richard Smith254a73d2011-10-28 22:34:42 +0000436 /// A stack frame in the constexpr call stack.
437 struct CallStackFrame {
438 EvalInfo &Info;
439
440 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000441 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000442
Richard Smithf6f003a2011-12-16 19:06:07 +0000443 /// Callee - The function which was called.
444 const FunctionDecl *Callee;
445
Richard Smithd62306a2011-11-10 06:34:14 +0000446 /// This - The binding for the this pointer in this call, if any.
447 const LValue *This;
448
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000449 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000450 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000451 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000452
Eli Friedman4830ec82012-06-25 21:21:08 +0000453 // Note that we intentionally use std::map here so that references to
454 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000455 typedef std::pair<const void *, unsigned> MapKeyTy;
456 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000457 /// Temporaries - Temporary lvalues materialized within this stack frame.
458 MapTy Temporaries;
459
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000460 /// CallLoc - The location of the call expression for this call.
461 SourceLocation CallLoc;
462
463 /// Index - The call index of this call.
464 unsigned Index;
465
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000466 /// The stack of integers for tracking version numbers for temporaries.
467 SmallVector<unsigned, 2> TempVersionStack = {1};
468 unsigned CurTempVersion = TempVersionStack.back();
469
470 unsigned getTempVersion() const { return TempVersionStack.back(); }
471
472 void pushTempVersion() {
473 TempVersionStack.push_back(++CurTempVersion);
474 }
475
476 void popTempVersion() {
477 TempVersionStack.pop_back();
478 }
479
Faisal Vali051e3a22017-02-16 04:12:21 +0000480 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
481 // on the overall stack usage of deeply-recursing constexpr evaluataions.
482 // (We should cache this map rather than recomputing it repeatedly.)
483 // But let's try this and see how it goes; we can look into caching the map
484 // as a later change.
485
486 /// LambdaCaptureFields - Mapping from captured variables/this to
487 /// corresponding data members in the closure class.
488 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
489 FieldDecl *LambdaThisCaptureField;
490
Richard Smithf6f003a2011-12-16 19:06:07 +0000491 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
492 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000493 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000494 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000495
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000496 // Return the temporary for Key whose version number is Version.
497 APValue *getTemporary(const void *Key, unsigned Version) {
498 MapKeyTy KV(Key, Version);
499 auto LB = Temporaries.lower_bound(KV);
500 if (LB != Temporaries.end() && LB->first == KV)
501 return &LB->second;
502 // Pair (Key,Version) wasn't found in the map. Check that no elements
503 // in the map have 'Key' as their key.
504 assert((LB == Temporaries.end() || LB->first.first != Key) &&
505 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
506 "Element with key 'Key' found in map");
507 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000508 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000509
510 // Return the current temporary for Key in the map.
511 APValue *getCurrentTemporary(const void *Key) {
512 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
513 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
514 return &std::prev(UB)->second;
515 return nullptr;
516 }
517
518 // Return the version number of the current temporary for Key.
519 unsigned getCurrentTemporaryVersion(const void *Key) const {
520 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
521 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
522 return std::prev(UB)->first.second;
523 return 0;
524 }
525
Richard Smith08d6a2c2013-07-24 07:11:57 +0000526 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000527 };
528
Richard Smith852c9db2013-04-20 22:23:05 +0000529 /// Temporarily override 'this'.
530 class ThisOverrideRAII {
531 public:
532 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
533 : Frame(Frame), OldThis(Frame.This) {
534 if (Enable)
535 Frame.This = NewThis;
536 }
537 ~ThisOverrideRAII() {
538 Frame.This = OldThis;
539 }
540 private:
541 CallStackFrame &Frame;
542 const LValue *OldThis;
543 };
544
Richard Smith92b1ce02011-12-12 09:28:41 +0000545 /// A partial diagnostic which we might know in advance that we are not going
546 /// to emit.
547 class OptionalDiagnostic {
548 PartialDiagnostic *Diag;
549
550 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000551 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
552 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000553
554 template<typename T>
555 OptionalDiagnostic &operator<<(const T &v) {
556 if (Diag)
557 *Diag << v;
558 return *this;
559 }
Richard Smithfe800032012-01-31 04:08:20 +0000560
561 OptionalDiagnostic &operator<<(const APSInt &I) {
562 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000563 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000564 I.toString(Buffer);
565 *Diag << StringRef(Buffer.data(), Buffer.size());
566 }
567 return *this;
568 }
569
570 OptionalDiagnostic &operator<<(const APFloat &F) {
571 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000572 // FIXME: Force the precision of the source value down so we don't
573 // print digits which are usually useless (we don't really care here if
574 // we truncate a digit by accident in edge cases). Ideally,
Daniel Jasperffdee092017-05-02 19:21:42 +0000575 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000576 // representation which rounds to the correct value, but it's a bit
577 // tricky to implement.
578 unsigned precision =
579 llvm::APFloat::semanticsPrecision(F.getSemantics());
580 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000581 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000582 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000583 *Diag << StringRef(Buffer.data(), Buffer.size());
584 }
585 return *this;
586 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000587 };
588
Richard Smith08d6a2c2013-07-24 07:11:57 +0000589 /// A cleanup, and a flag indicating whether it is lifetime-extended.
590 class Cleanup {
591 llvm::PointerIntPair<APValue*, 1, bool> Value;
592
593 public:
594 Cleanup(APValue *Val, bool IsLifetimeExtended)
595 : Value(Val, IsLifetimeExtended) {}
596
597 bool isLifetimeExtended() const { return Value.getInt(); }
598 void endLifetime() {
599 *Value.getPointer() = APValue();
600 }
601 };
602
Richard Smithb228a862012-02-15 02:18:13 +0000603 /// EvalInfo - This is a private struct used by the evaluator to capture
604 /// information about a subexpression as it is folded. It retains information
605 /// about the AST context, but also maintains information about the folded
606 /// expression.
607 ///
608 /// If an expression could be evaluated, it is still possible it is not a C
609 /// "integer constant expression" or constant expression. If not, this struct
610 /// captures information about how and why not.
611 ///
612 /// One bit of information passed *into* the request for constant folding
613 /// indicates whether the subexpression is "evaluated" or not according to C
614 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
615 /// evaluate the expression regardless of what the RHS is, but C only allows
616 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000617 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000618 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000619
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000620 /// EvalStatus - Contains information about the evaluation.
621 Expr::EvalStatus &EvalStatus;
622
623 /// CurrentCall - The top of the constexpr call stack.
624 CallStackFrame *CurrentCall;
625
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000626 /// CallStackDepth - The number of calls in the call stack right now.
627 unsigned CallStackDepth;
628
Richard Smithb228a862012-02-15 02:18:13 +0000629 /// NextCallIndex - The next call index to assign.
630 unsigned NextCallIndex;
631
Richard Smitha3d3bd22013-05-08 02:12:03 +0000632 /// StepsLeft - The remaining number of evaluation steps we're permitted
633 /// to perform. This is essentially a limit for the number of statements
634 /// we will evaluate.
635 unsigned StepsLeft;
636
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000637 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000638 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000639 CallStackFrame BottomFrame;
640
Richard Smith08d6a2c2013-07-24 07:11:57 +0000641 /// A stack of values whose lifetimes end at the end of some surrounding
642 /// evaluation frame.
643 llvm::SmallVector<Cleanup, 16> CleanupStack;
644
Richard Smithd62306a2011-11-10 06:34:14 +0000645 /// EvaluatingDecl - This is the declaration whose initializer is being
646 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000647 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000648
649 /// EvaluatingDeclValue - This is the value being constructed for the
650 /// declaration whose initializer is being evaluated, if any.
651 APValue *EvaluatingDeclValue;
652
Erik Pilkington42925492017-10-04 00:18:55 +0000653 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
654 /// the call index that that lvalue was allocated in.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000655 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
656 EvaluatingObject;
Erik Pilkington42925492017-10-04 00:18:55 +0000657
658 /// EvaluatingConstructors - Set of objects that are currently being
659 /// constructed.
660 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
661
662 struct EvaluatingConstructorRAII {
663 EvalInfo &EI;
664 EvaluatingObject Object;
665 bool DidInsert;
666 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
667 : EI(EI), Object(Object) {
668 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
669 }
670 ~EvaluatingConstructorRAII() {
671 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
672 }
673 };
674
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000675 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
676 unsigned Version) {
677 return EvaluatingConstructors.count(
678 EvaluatingObject(Decl, {CallIndex, Version}));
Erik Pilkington42925492017-10-04 00:18:55 +0000679 }
680
Richard Smith410306b2016-12-12 02:53:20 +0000681 /// The current array initialization index, if we're performing array
682 /// initialization.
683 uint64_t ArrayInitIndex = -1;
684
Richard Smith357362d2011-12-13 06:39:58 +0000685 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
686 /// notes attached to it will also be stored, otherwise they will not be.
687 bool HasActiveDiagnostic;
688
Richard Smith0c6124b2015-12-03 01:36:22 +0000689 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
690 /// fold (not just why it's not strictly a constant expression)?
691 bool HasFoldFailureDiagnostic;
692
George Burgess IV8c892b52016-05-25 22:31:54 +0000693 /// \brief Whether or not we're currently speculatively evaluating.
694 bool IsSpeculativelyEvaluating;
695
Richard Smith6d4c6582013-11-05 22:18:15 +0000696 enum EvaluationMode {
697 /// Evaluate as a constant expression. Stop if we find that the expression
698 /// is not a constant expression.
699 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000700
Richard Smith6d4c6582013-11-05 22:18:15 +0000701 /// Evaluate as a potential constant expression. Keep going if we hit a
702 /// construct that we can't evaluate yet (because we don't yet know the
703 /// value of something) but stop if we hit something that could never be
704 /// a constant expression.
705 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000706
Richard Smith6d4c6582013-11-05 22:18:15 +0000707 /// Fold the expression to a constant. Stop if we hit a side-effect that
708 /// we can't model.
709 EM_ConstantFold,
710
711 /// Evaluate the expression looking for integer overflow and similar
712 /// issues. Don't worry about side-effects, and try to visit all
713 /// subexpressions.
714 EM_EvaluateForOverflow,
715
716 /// Evaluate in any way we know how. Don't worry about side-effects that
717 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000718 EM_IgnoreSideEffects,
719
720 /// Evaluate as a constant expression. Stop if we find that the expression
721 /// is not a constant expression. Some expressions can be retried in the
722 /// optimizer if we don't constant fold them here, but in an unevaluated
723 /// context we try to fold them immediately since the optimizer never
724 /// gets a chance to look at it.
725 EM_ConstantExpressionUnevaluated,
726
727 /// Evaluate as a potential constant expression. Keep going if we hit a
728 /// construct that we can't evaluate yet (because we don't yet know the
729 /// value of something) but stop if we hit something that could never be
730 /// a constant expression. Some expressions can be retried in the
731 /// optimizer if we don't constant fold them here, but in an unevaluated
732 /// context we try to fold them immediately since the optimizer never
733 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000734 EM_PotentialConstantExpressionUnevaluated,
735
George Burgess IVf9013bf2017-02-10 22:52:29 +0000736 /// Evaluate as a constant expression. In certain scenarios, if:
737 /// - we find a MemberExpr with a base that can't be evaluated, or
738 /// - we find a variable initialized with a call to a function that has
739 /// the alloc_size attribute on it
740 /// then we may consider evaluation to have succeeded.
741 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000742 /// In either case, the LValue returned shall have an invalid base; in the
743 /// former, the base will be the invalid MemberExpr, in the latter, the
744 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
745 /// said CallExpr.
746 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000747 } EvalMode;
748
749 /// Are we checking whether the expression is a potential constant
750 /// expression?
751 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000752 return EvalMode == EM_PotentialConstantExpression ||
753 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000754 }
755
756 /// Are we checking an expression for overflow?
757 // FIXME: We should check for any kind of undefined or suspicious behavior
758 // in such constructs, not just overflow.
759 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
760
761 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000762 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000763 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000764 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000765 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
766 EvaluatingDecl((const ValueDecl *)nullptr),
767 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000768 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
769 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000770
Richard Smith7525ff62013-05-09 07:14:00 +0000771 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
772 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000773 EvaluatingDeclValue = &Value;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000774 EvaluatingConstructors.insert({Base, {0, 0}});
Richard Smithd62306a2011-11-10 06:34:14 +0000775 }
776
David Blaikiebbafb8a2012-03-11 07:00:24 +0000777 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000778
Richard Smith357362d2011-12-13 06:39:58 +0000779 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000780 // Don't perform any constexpr calls (other than the call we're checking)
781 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000782 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000783 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000784 if (NextCallIndex == 0) {
785 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000786 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000787 return false;
788 }
Richard Smith357362d2011-12-13 06:39:58 +0000789 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
790 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000791 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000792 << getLangOpts().ConstexprCallDepth;
793 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000794 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000795
Richard Smithb228a862012-02-15 02:18:13 +0000796 CallStackFrame *getCallFrame(unsigned CallIndex) {
797 assert(CallIndex && "no call index in getCallFrame");
798 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
799 // be null in this loop.
800 CallStackFrame *Frame = CurrentCall;
801 while (Frame->Index > CallIndex)
802 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000803 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000804 }
805
Richard Smitha3d3bd22013-05-08 02:12:03 +0000806 bool nextStep(const Stmt *S) {
807 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000808 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000809 return false;
810 }
811 --StepsLeft;
812 return true;
813 }
814
Richard Smith357362d2011-12-13 06:39:58 +0000815 private:
816 /// Add a diagnostic to the diagnostics list.
817 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
818 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
819 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
820 return EvalStatus.Diag->back().second;
821 }
822
Richard Smithf6f003a2011-12-16 19:06:07 +0000823 /// Add notes containing a call stack to the current point of evaluation.
824 void addCallStack(unsigned Limit);
825
Faisal Valie690b7a2016-07-02 22:34:24 +0000826 private:
827 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
828 unsigned ExtraNotes, bool IsCCEDiag) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000829
Richard Smith92b1ce02011-12-12 09:28:41 +0000830 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000831 // If we have a prior diagnostic, it will be noting that the expression
832 // isn't a constant expression. This diagnostic is more important,
833 // unless we require this evaluation to produce a constant expression.
834 //
835 // FIXME: We might want to show both diagnostics to the user in
836 // EM_ConstantFold mode.
837 if (!EvalStatus.Diag->empty()) {
838 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000839 case EM_ConstantFold:
840 case EM_IgnoreSideEffects:
841 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000842 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000843 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000844 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000845 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000846 case EM_ConstantExpression:
847 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000848 case EM_ConstantExpressionUnevaluated:
849 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000850 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000851 HasActiveDiagnostic = false;
852 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000853 }
854 }
855
Richard Smithf6f003a2011-12-16 19:06:07 +0000856 unsigned CallStackNotes = CallStackDepth - 1;
857 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
858 if (Limit)
859 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000860 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000861 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000862
Richard Smith357362d2011-12-13 06:39:58 +0000863 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000864 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000865 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000866 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
867 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000868 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000869 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000870 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000871 }
Richard Smith357362d2011-12-13 06:39:58 +0000872 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000873 return OptionalDiagnostic();
874 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000875 public:
876 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
877 OptionalDiagnostic
878 FFDiag(SourceLocation Loc,
879 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
880 unsigned ExtraNotes = 0) {
881 return Diag(Loc, DiagId, ExtraNotes, false);
882 }
Daniel Jasperffdee092017-05-02 19:21:42 +0000883
Faisal Valie690b7a2016-07-02 22:34:24 +0000884 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000885 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000886 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000887 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000888 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000889 HasActiveDiagnostic = false;
890 return OptionalDiagnostic();
891 }
892
Richard Smith92b1ce02011-12-12 09:28:41 +0000893 /// Diagnose that the evaluation does not produce a C++11 core constant
894 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000895 ///
896 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
897 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000898 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000899 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000900 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000901 // Don't override a previous diagnostic. Don't bother collecting
902 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000903 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000904 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000905 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000906 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000907 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000908 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000909 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
910 = diag::note_invalid_subexpr_in_const_expr,
911 unsigned ExtraNotes = 0) {
912 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
913 }
Richard Smith357362d2011-12-13 06:39:58 +0000914 /// Add a note to a prior diagnostic.
915 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
916 if (!HasActiveDiagnostic)
917 return OptionalDiagnostic();
918 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000919 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000920
921 /// Add a stack of notes to a prior diagnostic.
922 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
923 if (HasActiveDiagnostic) {
924 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
925 Diags.begin(), Diags.end());
926 }
927 }
Richard Smith253c2a32012-01-27 01:14:48 +0000928
Richard Smith6d4c6582013-11-05 22:18:15 +0000929 /// Should we continue evaluation after encountering a side-effect that we
930 /// couldn't model?
931 bool keepEvaluatingAfterSideEffect() {
932 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000933 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000934 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000935 case EM_EvaluateForOverflow:
936 case EM_IgnoreSideEffects:
937 return true;
938
Richard Smith6d4c6582013-11-05 22:18:15 +0000939 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000940 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000941 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000942 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000943 return false;
944 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000945 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000946 }
947
948 /// Note that we have had a side-effect, and determine whether we should
949 /// keep evaluating.
950 bool noteSideEffect() {
951 EvalStatus.HasSideEffects = true;
952 return keepEvaluatingAfterSideEffect();
953 }
954
Richard Smithce8eca52015-12-08 03:21:47 +0000955 /// Should we continue evaluation after encountering undefined behavior?
956 bool keepEvaluatingAfterUndefinedBehavior() {
957 switch (EvalMode) {
958 case EM_EvaluateForOverflow:
959 case EM_IgnoreSideEffects:
960 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000961 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000962 return true;
963
964 case EM_PotentialConstantExpression:
965 case EM_PotentialConstantExpressionUnevaluated:
966 case EM_ConstantExpression:
967 case EM_ConstantExpressionUnevaluated:
968 return false;
969 }
970 llvm_unreachable("Missed EvalMode case");
971 }
972
973 /// Note that we hit something that was technically undefined behavior, but
974 /// that we can evaluate past it (such as signed overflow or floating-point
975 /// division by zero.)
976 bool noteUndefinedBehavior() {
977 EvalStatus.HasUndefinedBehavior = true;
978 return keepEvaluatingAfterUndefinedBehavior();
979 }
980
Richard Smith253c2a32012-01-27 01:14:48 +0000981 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000982 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000983 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000984 if (!StepsLeft)
985 return false;
986
987 switch (EvalMode) {
988 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000989 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000990 case EM_EvaluateForOverflow:
991 return true;
992
993 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000994 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000995 case EM_ConstantFold:
996 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000997 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000998 return false;
999 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001000 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001001 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001002
George Burgess IV8c892b52016-05-25 22:31:54 +00001003 /// Notes that we failed to evaluate an expression that other expressions
1004 /// directly depend on, and determine if we should keep evaluating. This
1005 /// should only be called if we actually intend to keep evaluating.
1006 ///
1007 /// Call noteSideEffect() instead if we may be able to ignore the value that
1008 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1009 ///
1010 /// (Foo(), 1) // use noteSideEffect
1011 /// (Foo() || true) // use noteSideEffect
1012 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001013 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001014 // Failure when evaluating some expression often means there is some
1015 // subexpression whose evaluation was skipped. Therefore, (because we
1016 // don't track whether we skipped an expression when unwinding after an
1017 // evaluation failure) every evaluation failure that bubbles up from a
1018 // subexpression implies that a side-effect has potentially happened. We
1019 // skip setting the HasSideEffects flag to true until we decide to
1020 // continue evaluating after that point, which happens here.
1021 bool KeepGoing = keepEvaluatingAfterFailure();
1022 EvalStatus.HasSideEffects |= KeepGoing;
1023 return KeepGoing;
1024 }
1025
Richard Smith410306b2016-12-12 02:53:20 +00001026 class ArrayInitLoopIndex {
1027 EvalInfo &Info;
1028 uint64_t OuterIndex;
1029
1030 public:
1031 ArrayInitLoopIndex(EvalInfo &Info)
1032 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1033 Info.ArrayInitIndex = 0;
1034 }
1035 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1036
1037 operator uint64_t&() { return Info.ArrayInitIndex; }
1038 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001039 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001040
1041 /// Object used to treat all foldable expressions as constant expressions.
1042 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001043 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001044 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001045 bool HadNoPriorDiags;
1046 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001047
Richard Smith6d4c6582013-11-05 22:18:15 +00001048 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1049 : Info(Info),
1050 Enabled(Enabled),
1051 HadNoPriorDiags(Info.EvalStatus.Diag &&
1052 Info.EvalStatus.Diag->empty() &&
1053 !Info.EvalStatus.HasSideEffects),
1054 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001055 if (Enabled &&
1056 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1057 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001058 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001059 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001060 void keepDiagnostics() { Enabled = false; }
1061 ~FoldConstant() {
1062 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001063 !Info.EvalStatus.HasSideEffects)
1064 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001065 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001066 }
1067 };
Richard Smith17100ba2012-02-16 02:46:34 +00001068
George Burgess IV3a03fab2015-09-04 21:28:13 +00001069 /// RAII object used to treat the current evaluation as the correct pointer
1070 /// offset fold for the current EvalMode
1071 struct FoldOffsetRAII {
1072 EvalInfo &Info;
1073 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +00001074 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001075 : Info(Info), OldMode(Info.EvalMode) {
1076 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +00001077 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001078 }
1079
1080 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1081 };
1082
George Burgess IV8c892b52016-05-25 22:31:54 +00001083 /// RAII object used to optionally suppress diagnostics and side-effects from
1084 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001085 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001086 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001087 Expr::EvalStatus OldStatus;
1088 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001089
George Burgess IV8c892b52016-05-25 22:31:54 +00001090 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001091 Info = Other.Info;
1092 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001093 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001094 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001095 }
1096
1097 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001098 if (!Info)
1099 return;
1100
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001101 Info->EvalStatus = OldStatus;
1102 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001103 }
1104
Richard Smith17100ba2012-02-16 02:46:34 +00001105 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001106 SpeculativeEvaluationRAII() = default;
1107
1108 SpeculativeEvaluationRAII(
1109 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001110 : Info(&Info), OldStatus(Info.EvalStatus),
1111 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001112 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001113 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001114 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001115
1116 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1117 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1118 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001119 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001120
1121 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1122 maybeRestoreState();
1123 moveFromAndCancel(std::move(Other));
1124 return *this;
1125 }
1126
1127 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001128 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001129
1130 /// RAII object wrapping a full-expression or block scope, and handling
1131 /// the ending of the lifetime of temporaries created within it.
1132 template<bool IsFullExpression>
1133 class ScopeRAII {
1134 EvalInfo &Info;
1135 unsigned OldStackSize;
1136 public:
1137 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001138 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1139 // Push a new temporary version. This is needed to distinguish between
1140 // temporaries created in different iterations of a loop.
1141 Info.CurrentCall->pushTempVersion();
1142 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001143 ~ScopeRAII() {
1144 // Body moved to a static method to encourage the compiler to inline away
1145 // instances of this class.
1146 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001147 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001148 }
1149 private:
1150 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1151 unsigned NewEnd = OldStackSize;
1152 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1153 I != N; ++I) {
1154 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1155 // Full-expression cleanup of a lifetime-extended temporary: nothing
1156 // to do, just move this cleanup to the right place in the stack.
1157 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1158 ++NewEnd;
1159 } else {
1160 // End the lifetime of the object.
1161 Info.CleanupStack[I].endLifetime();
1162 }
1163 }
1164 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1165 Info.CleanupStack.end());
1166 }
1167 };
1168 typedef ScopeRAII<false> BlockScopeRAII;
1169 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001170}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001171
Richard Smitha8105bc2012-01-06 16:39:00 +00001172bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1173 CheckSubobjectKind CSK) {
1174 if (Invalid)
1175 return false;
1176 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001177 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001178 << CSK;
1179 setInvalid();
1180 return false;
1181 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001182 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1183 // must actually be at least one array element; even a VLA cannot have a
1184 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001185 return true;
1186}
1187
Richard Smith6f4f0f12017-10-20 22:56:25 +00001188void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1189 const Expr *E) {
1190 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1191 // Do not set the designator as invalid: we can represent this situation,
1192 // and correct handling of __builtin_object_size requires us to do so.
1193}
1194
Richard Smitha8105bc2012-01-06 16:39:00 +00001195void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001196 const Expr *E,
1197 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001198 // If we're complaining, we must be able to statically determine the size of
1199 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001200 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001201 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001202 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001203 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001204 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001205 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001206 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001207 setInvalid();
1208}
1209
Richard Smithf6f003a2011-12-16 19:06:07 +00001210CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1211 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001212 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001213 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1214 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001215 Info.CurrentCall = this;
1216 ++Info.CallStackDepth;
1217}
1218
1219CallStackFrame::~CallStackFrame() {
1220 assert(Info.CurrentCall == this && "calls retired out of order");
1221 --Info.CallStackDepth;
1222 Info.CurrentCall = Caller;
1223}
1224
Richard Smith08d6a2c2013-07-24 07:11:57 +00001225APValue &CallStackFrame::createTemporary(const void *Key,
1226 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001227 unsigned Version = Info.CurrentCall->getTempVersion();
1228 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smith08d6a2c2013-07-24 07:11:57 +00001229 assert(Result.isUninit() && "temporary created multiple times");
1230 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1231 return Result;
1232}
1233
Richard Smith84401042013-06-03 05:03:02 +00001234static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001235
1236void EvalInfo::addCallStack(unsigned Limit) {
1237 // Determine which calls to skip, if any.
1238 unsigned ActiveCalls = CallStackDepth - 1;
1239 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1240 if (Limit && Limit < ActiveCalls) {
1241 SkipStart = Limit / 2 + Limit % 2;
1242 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001243 }
1244
Richard Smithf6f003a2011-12-16 19:06:07 +00001245 // Walk the call stack and add the diagnostics.
1246 unsigned CallIdx = 0;
1247 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1248 Frame = Frame->Caller, ++CallIdx) {
1249 // Skip this call?
1250 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1251 if (CallIdx == SkipStart) {
1252 // Note that we're skipping calls.
1253 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1254 << unsigned(ActiveCalls - Limit);
1255 }
1256 continue;
1257 }
1258
Richard Smith5179eb72016-06-28 19:03:57 +00001259 // Use a different note for an inheriting constructor, because from the
1260 // user's perspective it's not really a function at all.
1261 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1262 if (CD->isInheritingConstructor()) {
1263 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1264 << CD->getParent();
1265 continue;
1266 }
1267 }
1268
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001269 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001270 llvm::raw_svector_ostream Out(Buffer);
1271 describeCall(Frame, Out);
1272 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1273 }
1274}
1275
1276namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001277 struct ComplexValue {
1278 private:
1279 bool IsInt;
1280
1281 public:
1282 APSInt IntReal, IntImag;
1283 APFloat FloatReal, FloatImag;
1284
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001285 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001286
1287 void makeComplexFloat() { IsInt = false; }
1288 bool isComplexFloat() const { return !IsInt; }
1289 APFloat &getComplexFloatReal() { return FloatReal; }
1290 APFloat &getComplexFloatImag() { return FloatImag; }
1291
1292 void makeComplexInt() { IsInt = true; }
1293 bool isComplexInt() const { return IsInt; }
1294 APSInt &getComplexIntReal() { return IntReal; }
1295 APSInt &getComplexIntImag() { return IntImag; }
1296
Richard Smith2e312c82012-03-03 22:46:17 +00001297 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001298 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001299 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001300 else
Richard Smith2e312c82012-03-03 22:46:17 +00001301 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001302 }
Richard Smith2e312c82012-03-03 22:46:17 +00001303 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001304 assert(v.isComplexFloat() || v.isComplexInt());
1305 if (v.isComplexFloat()) {
1306 makeComplexFloat();
1307 FloatReal = v.getComplexFloatReal();
1308 FloatImag = v.getComplexFloatImag();
1309 } else {
1310 makeComplexInt();
1311 IntReal = v.getComplexIntReal();
1312 IntImag = v.getComplexIntImag();
1313 }
1314 }
John McCall93d91dc2010-05-07 17:22:02 +00001315 };
John McCall45d55e42010-05-07 21:00:08 +00001316
1317 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001318 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001319 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001320 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001321 bool IsNullPtr : 1;
1322 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001323
Richard Smithce40ad62011-11-12 22:28:03 +00001324 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001325 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001326 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001327 SubobjectDesignator &getLValueDesignator() { return Designator; }
1328 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001329 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001330
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001331 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1332 unsigned getLValueVersion() const { return Base.getVersion(); }
1333
Richard Smith2e312c82012-03-03 22:46:17 +00001334 void moveInto(APValue &V) const {
1335 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001336 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001337 else {
1338 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001339 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001340 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001341 }
John McCall45d55e42010-05-07 21:00:08 +00001342 }
Richard Smith2e312c82012-03-03 22:46:17 +00001343 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001344 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001345 Base = V.getLValueBase();
1346 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001347 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001348 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001349 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001350 }
1351
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001352 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001353#ifndef NDEBUG
1354 // We only allow a few types of invalid bases. Enforce that here.
1355 if (BInvalid) {
1356 const auto *E = B.get<const Expr *>();
1357 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1358 "Unexpected type of invalid base");
1359 }
1360#endif
1361
Richard Smithce40ad62011-11-12 22:28:03 +00001362 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001363 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001364 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001365 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001366 IsNullPtr = false;
1367 }
1368
1369 void setNull(QualType PointerTy, uint64_t TargetVal) {
1370 Base = (Expr *)nullptr;
1371 Offset = CharUnits::fromQuantity(TargetVal);
1372 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001373 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1374 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001375 }
1376
George Burgess IV3a03fab2015-09-04 21:28:13 +00001377 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001378 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001379 }
1380
Richard Smitha8105bc2012-01-06 16:39:00 +00001381 // Check that this LValue is not based on a null pointer. If it is, produce
1382 // a diagnostic and mark the designator as invalid.
1383 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1384 CheckSubobjectKind CSK) {
1385 if (Designator.Invalid)
1386 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001387 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001388 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001389 << CSK;
1390 Designator.setInvalid();
1391 return false;
1392 }
1393 return true;
1394 }
1395
1396 // Check this LValue refers to an object. If not, set the designator to be
1397 // invalid and emit a diagnostic.
1398 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001399 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001400 Designator.checkSubobject(Info, E, CSK);
1401 }
1402
1403 void addDecl(EvalInfo &Info, const Expr *E,
1404 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001405 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1406 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001407 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001408 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1409 if (!Designator.Entries.empty()) {
1410 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1411 Designator.setInvalid();
1412 return;
1413 }
Richard Smithefdb5032017-11-15 03:03:56 +00001414 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1415 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1416 Designator.FirstEntryIsAnUnsizedArray = true;
1417 Designator.addUnsizedArrayUnchecked(ElemTy);
1418 }
George Burgess IVe3763372016-12-22 02:50:20 +00001419 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001420 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001421 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1422 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001423 }
Richard Smith66c96992012-02-18 22:04:06 +00001424 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001425 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1426 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001427 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001428 void clearIsNullPointer() {
1429 IsNullPtr = false;
1430 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001431 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1432 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001433 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1434 // but we're not required to diagnose it and it's valid in C++.)
1435 if (!Index)
1436 return;
1437
1438 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1439 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1440 // offsets.
1441 uint64_t Offset64 = Offset.getQuantity();
1442 uint64_t ElemSize64 = ElementSize.getQuantity();
1443 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1444 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1445
1446 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001447 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001448 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001449 }
1450 void adjustOffset(CharUnits N) {
1451 Offset += N;
1452 if (N.getQuantity())
1453 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001454 }
John McCall45d55e42010-05-07 21:00:08 +00001455 };
Richard Smith027bf112011-11-17 22:56:20 +00001456
1457 struct MemberPtr {
1458 MemberPtr() {}
1459 explicit MemberPtr(const ValueDecl *Decl) :
1460 DeclAndIsDerivedMember(Decl, false), Path() {}
1461
1462 /// The member or (direct or indirect) field referred to by this member
1463 /// pointer, or 0 if this is a null member pointer.
1464 const ValueDecl *getDecl() const {
1465 return DeclAndIsDerivedMember.getPointer();
1466 }
1467 /// Is this actually a member of some type derived from the relevant class?
1468 bool isDerivedMember() const {
1469 return DeclAndIsDerivedMember.getInt();
1470 }
1471 /// Get the class which the declaration actually lives in.
1472 const CXXRecordDecl *getContainingRecord() const {
1473 return cast<CXXRecordDecl>(
1474 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1475 }
1476
Richard Smith2e312c82012-03-03 22:46:17 +00001477 void moveInto(APValue &V) const {
1478 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001479 }
Richard Smith2e312c82012-03-03 22:46:17 +00001480 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001481 assert(V.isMemberPointer());
1482 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1483 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1484 Path.clear();
1485 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1486 Path.insert(Path.end(), P.begin(), P.end());
1487 }
1488
1489 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1490 /// whether the member is a member of some class derived from the class type
1491 /// of the member pointer.
1492 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1493 /// Path - The path of base/derived classes from the member declaration's
1494 /// class (exclusive) to the class type of the member pointer (inclusive).
1495 SmallVector<const CXXRecordDecl*, 4> Path;
1496
1497 /// Perform a cast towards the class of the Decl (either up or down the
1498 /// hierarchy).
1499 bool castBack(const CXXRecordDecl *Class) {
1500 assert(!Path.empty());
1501 const CXXRecordDecl *Expected;
1502 if (Path.size() >= 2)
1503 Expected = Path[Path.size() - 2];
1504 else
1505 Expected = getContainingRecord();
1506 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1507 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1508 // if B does not contain the original member and is not a base or
1509 // derived class of the class containing the original member, the result
1510 // of the cast is undefined.
1511 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1512 // (D::*). We consider that to be a language defect.
1513 return false;
1514 }
1515 Path.pop_back();
1516 return true;
1517 }
1518 /// Perform a base-to-derived member pointer cast.
1519 bool castToDerived(const CXXRecordDecl *Derived) {
1520 if (!getDecl())
1521 return true;
1522 if (!isDerivedMember()) {
1523 Path.push_back(Derived);
1524 return true;
1525 }
1526 if (!castBack(Derived))
1527 return false;
1528 if (Path.empty())
1529 DeclAndIsDerivedMember.setInt(false);
1530 return true;
1531 }
1532 /// Perform a derived-to-base member pointer cast.
1533 bool castToBase(const CXXRecordDecl *Base) {
1534 if (!getDecl())
1535 return true;
1536 if (Path.empty())
1537 DeclAndIsDerivedMember.setInt(true);
1538 if (isDerivedMember()) {
1539 Path.push_back(Base);
1540 return true;
1541 }
1542 return castBack(Base);
1543 }
1544 };
Richard Smith357362d2011-12-13 06:39:58 +00001545
Richard Smith7bb00672012-02-01 01:42:44 +00001546 /// Compare two member pointers, which are assumed to be of the same type.
1547 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1548 if (!LHS.getDecl() || !RHS.getDecl())
1549 return !LHS.getDecl() && !RHS.getDecl();
1550 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1551 return false;
1552 return LHS.Path == RHS.Path;
1553 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001554}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001555
Richard Smith2e312c82012-03-03 22:46:17 +00001556static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001557static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1558 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001559 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001560static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1561 bool InvalidBaseOK = false);
1562static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1563 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001564static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1565 EvalInfo &Info);
1566static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001567static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001568static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001569 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001570static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001571static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001572static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1573 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001574static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001575
1576//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001577// Misc utilities
1578//===----------------------------------------------------------------------===//
1579
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001580/// A helper function to create a temporary and set an LValue.
1581template <class KeyTy>
1582static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1583 LValue &LV, CallStackFrame &Frame) {
1584 LV.set({Key, Frame.Info.CurrentCall->Index,
1585 Frame.Info.CurrentCall->getTempVersion()});
1586 return Frame.createTemporary(Key, IsLifetimeExtended);
1587}
1588
Richard Smithd6cc1982017-01-31 02:23:02 +00001589/// Negate an APSInt in place, converting it to a signed form if necessary, and
1590/// preserving its value (by extending by up to one bit as needed).
1591static void negateAsSigned(APSInt &Int) {
1592 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1593 Int = Int.extend(Int.getBitWidth() + 1);
1594 Int.setIsSigned(true);
1595 }
1596 Int = -Int;
1597}
1598
Richard Smith84401042013-06-03 05:03:02 +00001599/// Produce a string describing the given constexpr call.
1600static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1601 unsigned ArgIndex = 0;
1602 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1603 !isa<CXXConstructorDecl>(Frame->Callee) &&
1604 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1605
1606 if (!IsMemberCall)
1607 Out << *Frame->Callee << '(';
1608
1609 if (Frame->This && IsMemberCall) {
1610 APValue Val;
1611 Frame->This->moveInto(Val);
1612 Val.printPretty(Out, Frame->Info.Ctx,
1613 Frame->This->Designator.MostDerivedType);
1614 // FIXME: Add parens around Val if needed.
1615 Out << "->" << *Frame->Callee << '(';
1616 IsMemberCall = false;
1617 }
1618
1619 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1620 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1621 if (ArgIndex > (unsigned)IsMemberCall)
1622 Out << ", ";
1623
1624 const ParmVarDecl *Param = *I;
1625 const APValue &Arg = Frame->Arguments[ArgIndex];
1626 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1627
1628 if (ArgIndex == 0 && IsMemberCall)
1629 Out << "->" << *Frame->Callee << '(';
1630 }
1631
1632 Out << ')';
1633}
1634
Richard Smithd9f663b2013-04-22 15:31:51 +00001635/// Evaluate an expression to see if it had side-effects, and discard its
1636/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001637/// \return \c true if the caller should keep evaluating.
1638static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001639 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001640 if (!Evaluate(Scratch, Info, E))
1641 // We don't need the value, but we might have skipped a side effect here.
1642 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001643 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001644}
1645
Richard Smithd62306a2011-11-10 06:34:14 +00001646/// Should this call expression be treated as a string literal?
1647static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001648 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001649 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1650 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1651}
1652
Richard Smithce40ad62011-11-12 22:28:03 +00001653static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001654 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1655 // constant expression of pointer type that evaluates to...
1656
1657 // ... a null pointer value, or a prvalue core constant expression of type
1658 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001659 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001660
Richard Smithce40ad62011-11-12 22:28:03 +00001661 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1662 // ... the address of an object with static storage duration,
1663 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1664 return VD->hasGlobalStorage();
1665 // ... the address of a function,
1666 return isa<FunctionDecl>(D);
1667 }
1668
1669 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001670 switch (E->getStmtClass()) {
1671 default:
1672 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001673 case Expr::CompoundLiteralExprClass: {
1674 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1675 return CLE->isFileScope() && CLE->isLValue();
1676 }
Richard Smithe6c01442013-06-05 00:46:14 +00001677 case Expr::MaterializeTemporaryExprClass:
1678 // A materialized temporary might have been lifetime-extended to static
1679 // storage duration.
1680 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001681 // A string literal has static storage duration.
1682 case Expr::StringLiteralClass:
1683 case Expr::PredefinedExprClass:
1684 case Expr::ObjCStringLiteralClass:
1685 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001686 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001687 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001688 return true;
1689 case Expr::CallExprClass:
1690 return IsStringLiteralCall(cast<CallExpr>(E));
1691 // For GCC compatibility, &&label has static storage duration.
1692 case Expr::AddrLabelExprClass:
1693 return true;
1694 // A Block literal expression may be used as the initialization value for
1695 // Block variables at global or local static scope.
1696 case Expr::BlockExprClass:
1697 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001698 case Expr::ImplicitValueInitExprClass:
1699 // FIXME:
1700 // We can never form an lvalue with an implicit value initialization as its
1701 // base through expression evaluation, so these only appear in one case: the
1702 // implicit variable declaration we invent when checking whether a constexpr
1703 // constructor can produce a constant expression. We must assume that such
1704 // an expression might be a global lvalue.
1705 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001706 }
John McCall95007602010-05-10 23:27:23 +00001707}
1708
Richard Smithb228a862012-02-15 02:18:13 +00001709static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1710 assert(Base && "no location for a null lvalue");
1711 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1712 if (VD)
1713 Info.Note(VD->getLocation(), diag::note_declared_at);
1714 else
Ted Kremenek28831752012-08-23 20:46:57 +00001715 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001716 diag::note_constexpr_temporary_here);
1717}
1718
Richard Smith80815602011-11-07 05:07:52 +00001719/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001720/// value for an address or reference constant expression. Return true if we
1721/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001722static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1723 QualType Type, const LValue &LVal) {
1724 bool IsReferenceType = Type->isReferenceType();
1725
Richard Smith357362d2011-12-13 06:39:58 +00001726 APValue::LValueBase Base = LVal.getLValueBase();
1727 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1728
Richard Smith0dea49e2012-02-18 04:58:18 +00001729 // Check that the object is a global. Note that the fake 'this' object we
1730 // manufacture when checking potential constant expressions is conservatively
1731 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001732 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001733 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001734 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001735 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001736 << IsReferenceType << !Designator.Entries.empty()
1737 << !!VD << VD;
1738 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001739 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001740 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001741 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001742 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001743 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001744 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001745 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001746 LVal.getLValueCallIndex() == 0) &&
1747 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001748
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001749 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1750 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001751 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001752 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001753 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001754
Hans Wennborg82dd8772014-06-25 22:19:48 +00001755 // A dllimport variable never acts like a constant.
1756 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001757 return false;
1758 }
1759 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1760 // __declspec(dllimport) must be handled very carefully:
1761 // We must never initialize an expression with the thunk in C++.
1762 // Doing otherwise would allow the same id-expression to yield
1763 // different addresses for the same function in different translation
1764 // units. However, this means that we must dynamically initialize the
1765 // expression with the contents of the import address table at runtime.
1766 //
1767 // The C language has no notion of ODR; furthermore, it has no notion of
1768 // dynamic initialization. This means that we are permitted to
1769 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001770 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001771 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001772 }
1773 }
1774
Richard Smitha8105bc2012-01-06 16:39:00 +00001775 // Allow address constant expressions to be past-the-end pointers. This is
1776 // an extension: the standard requires them to point to an object.
1777 if (!IsReferenceType)
1778 return true;
1779
1780 // A reference constant expression must refer to an object.
1781 if (!Base) {
1782 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001783 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001784 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001785 }
1786
Richard Smith357362d2011-12-13 06:39:58 +00001787 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001788 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001789 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001790 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001791 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001792 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001793 }
1794
Richard Smith80815602011-11-07 05:07:52 +00001795 return true;
1796}
1797
Reid Klecknercd016d82017-07-07 22:04:29 +00001798/// Member pointers are constant expressions unless they point to a
1799/// non-virtual dllimport member function.
1800static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1801 SourceLocation Loc,
1802 QualType Type,
1803 const APValue &Value) {
1804 const ValueDecl *Member = Value.getMemberPointerDecl();
1805 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1806 if (!FD)
1807 return true;
1808 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1809}
1810
Richard Smithfddd3842011-12-30 21:15:51 +00001811/// Check that this core constant expression is of literal type, and if not,
1812/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001813static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001814 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001815 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001816 return true;
1817
Richard Smith7525ff62013-05-09 07:14:00 +00001818 // C++1y: A constant initializer for an object o [...] may also invoke
1819 // constexpr constructors for o and its subobjects even if those objects
1820 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001821 //
1822 // C++11 missed this detail for aggregates, so classes like this:
1823 // struct foo_t { union { int i; volatile int j; } u; };
1824 // are not (obviously) initializable like so:
1825 // __attribute__((__require_constant_initialization__))
1826 // static const foo_t x = {{0}};
1827 // because "i" is a subobject with non-literal initialization (due to the
1828 // volatile member of the union). See:
1829 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1830 // Therefore, we use the C++1y behavior.
1831 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001832 return true;
1833
Richard Smithfddd3842011-12-30 21:15:51 +00001834 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001835 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001836 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001837 << E->getType();
1838 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001839 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001840 return false;
1841}
1842
Richard Smith0b0a0b62011-10-29 20:57:55 +00001843/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001844/// constant expression. If not, report an appropriate diagnostic. Does not
1845/// check that the expression is of literal type.
1846static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1847 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001848 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001849 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001850 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001851 return false;
1852 }
1853
Richard Smith77be48a2014-07-31 06:31:19 +00001854 // We allow _Atomic(T) to be initialized from anything that T can be
1855 // initialized from.
1856 if (const AtomicType *AT = Type->getAs<AtomicType>())
1857 Type = AT->getValueType();
1858
Richard Smithb228a862012-02-15 02:18:13 +00001859 // Core issue 1454: For a literal constant expression of array or class type,
1860 // each subobject of its value shall have been initialized by a constant
1861 // expression.
1862 if (Value.isArray()) {
1863 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1864 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1865 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1866 Value.getArrayInitializedElt(I)))
1867 return false;
1868 }
1869 if (!Value.hasArrayFiller())
1870 return true;
1871 return CheckConstantExpression(Info, DiagLoc, EltTy,
1872 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001873 }
Richard Smithb228a862012-02-15 02:18:13 +00001874 if (Value.isUnion() && Value.getUnionField()) {
1875 return CheckConstantExpression(Info, DiagLoc,
1876 Value.getUnionField()->getType(),
1877 Value.getUnionValue());
1878 }
1879 if (Value.isStruct()) {
1880 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1881 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1882 unsigned BaseIndex = 0;
1883 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1884 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1885 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1886 Value.getStructBase(BaseIndex)))
1887 return false;
1888 }
1889 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001890 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001891 if (I->isUnnamedBitfield())
1892 continue;
1893
David Blaikie2d7c57e2012-04-30 02:36:29 +00001894 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1895 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001896 return false;
1897 }
1898 }
1899
1900 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001901 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001902 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001903 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1904 }
1905
Reid Klecknercd016d82017-07-07 22:04:29 +00001906 if (Value.isMemberPointer())
1907 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1908
Richard Smithb228a862012-02-15 02:18:13 +00001909 // Everything else is fine.
1910 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001911}
1912
Benjamin Kramer8407df72015-03-09 16:47:52 +00001913static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001914 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001915}
1916
1917static bool IsLiteralLValue(const LValue &Value) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001918 if (Value.getLValueCallIndex())
Richard Smithe6c01442013-06-05 00:46:14 +00001919 return false;
1920 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1921 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001922}
1923
Richard Smithcecf1842011-11-01 21:06:14 +00001924static bool IsWeakLValue(const LValue &Value) {
1925 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001926 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001927}
1928
David Majnemerb5116032014-12-09 23:32:34 +00001929static bool isZeroSized(const LValue &Value) {
1930 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001931 if (Decl && isa<VarDecl>(Decl)) {
1932 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001933 if (Ty->isArrayType())
1934 return Ty->isIncompleteType() ||
1935 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001936 }
1937 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001938}
1939
Richard Smith2e312c82012-03-03 22:46:17 +00001940static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001941 // A null base expression indicates a null pointer. These are always
1942 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001943 if (!Value.getLValueBase()) {
1944 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001945 return true;
1946 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001947
Richard Smith027bf112011-11-17 22:56:20 +00001948 // We have a non-null base. These are generally known to be true, but if it's
1949 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001950 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001951 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001952 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001953}
1954
Richard Smith2e312c82012-03-03 22:46:17 +00001955static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001956 switch (Val.getKind()) {
1957 case APValue::Uninitialized:
1958 return false;
1959 case APValue::Int:
1960 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001961 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001962 case APValue::Float:
1963 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001964 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001965 case APValue::ComplexInt:
1966 Result = Val.getComplexIntReal().getBoolValue() ||
1967 Val.getComplexIntImag().getBoolValue();
1968 return true;
1969 case APValue::ComplexFloat:
1970 Result = !Val.getComplexFloatReal().isZero() ||
1971 !Val.getComplexFloatImag().isZero();
1972 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001973 case APValue::LValue:
1974 return EvalPointerValueAsBool(Val, Result);
1975 case APValue::MemberPointer:
1976 Result = Val.getMemberPointerDecl();
1977 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001978 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001979 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001980 case APValue::Struct:
1981 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001982 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001983 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001984 }
1985
Richard Smith11562c52011-10-28 17:51:58 +00001986 llvm_unreachable("unknown APValue kind");
1987}
1988
1989static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1990 EvalInfo &Info) {
1991 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001992 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001993 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001994 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001995 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001996}
1997
Richard Smith357362d2011-12-13 06:39:58 +00001998template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001999static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002000 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002001 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002002 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002003 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002004}
2005
2006static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2007 QualType SrcType, const APFloat &Value,
2008 QualType DestType, APSInt &Result) {
2009 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002010 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002011 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002012
Richard Smith357362d2011-12-13 06:39:58 +00002013 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002014 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002015 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2016 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002017 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002018 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002019}
2020
Richard Smith357362d2011-12-13 06:39:58 +00002021static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2022 QualType SrcType, QualType DestType,
2023 APFloat &Result) {
2024 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002025 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002026 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2027 APFloat::rmNearestTiesToEven, &ignored)
2028 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002029 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002030 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002031}
2032
Richard Smith911e1422012-01-30 22:27:01 +00002033static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2034 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002035 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002036 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002037 APSInt Result = Value;
2038 // Figure out if this is a truncate, extend or noop cast.
2039 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00002040 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002041 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002042 return Result;
2043}
2044
Richard Smith357362d2011-12-13 06:39:58 +00002045static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2046 QualType SrcType, const APSInt &Value,
2047 QualType DestType, APFloat &Result) {
2048 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2049 if (Result.convertFromAPInt(Value, Value.isSigned(),
2050 APFloat::rmNearestTiesToEven)
2051 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002052 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002053 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002054}
2055
Richard Smith49ca8aa2013-08-06 07:09:20 +00002056static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2057 APValue &Value, const FieldDecl *FD) {
2058 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2059
2060 if (!Value.isInt()) {
2061 // Trying to store a pointer-cast-to-integer into a bitfield.
2062 // FIXME: In this case, we should provide the diagnostic for casting
2063 // a pointer to an integer.
2064 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002065 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002066 return false;
2067 }
2068
2069 APSInt &Int = Value.getInt();
2070 unsigned OldBitWidth = Int.getBitWidth();
2071 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2072 if (NewBitWidth < OldBitWidth)
2073 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2074 return true;
2075}
2076
Eli Friedman803acb32011-12-22 03:51:45 +00002077static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2078 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002079 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002080 if (!Evaluate(SVal, Info, E))
2081 return false;
2082 if (SVal.isInt()) {
2083 Res = SVal.getInt();
2084 return true;
2085 }
2086 if (SVal.isFloat()) {
2087 Res = SVal.getFloat().bitcastToAPInt();
2088 return true;
2089 }
2090 if (SVal.isVector()) {
2091 QualType VecTy = E->getType();
2092 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2093 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2094 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2095 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2096 Res = llvm::APInt::getNullValue(VecSize);
2097 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2098 APValue &Elt = SVal.getVectorElt(i);
2099 llvm::APInt EltAsInt;
2100 if (Elt.isInt()) {
2101 EltAsInt = Elt.getInt();
2102 } else if (Elt.isFloat()) {
2103 EltAsInt = Elt.getFloat().bitcastToAPInt();
2104 } else {
2105 // Don't try to handle vectors of anything other than int or float
2106 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002107 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002108 return false;
2109 }
2110 unsigned BaseEltSize = EltAsInt.getBitWidth();
2111 if (BigEndian)
2112 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2113 else
2114 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2115 }
2116 return true;
2117 }
2118 // Give up if the input isn't an int, float, or vector. For example, we
2119 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002120 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002121 return false;
2122}
2123
Richard Smith43e77732013-05-07 04:50:00 +00002124/// Perform the given integer operation, which is known to need at most BitWidth
2125/// bits, and check for overflow in the original type (if that type was not an
2126/// unsigned type).
2127template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002128static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2129 const APSInt &LHS, const APSInt &RHS,
2130 unsigned BitWidth, Operation Op,
2131 APSInt &Result) {
2132 if (LHS.isUnsigned()) {
2133 Result = Op(LHS, RHS);
2134 return true;
2135 }
Richard Smith43e77732013-05-07 04:50:00 +00002136
2137 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002138 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002139 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002140 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002141 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002142 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002143 << Result.toString(10) << E->getType();
2144 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002145 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002146 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002147 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002148}
2149
2150/// Perform the given binary integer operation.
2151static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2152 BinaryOperatorKind Opcode, APSInt RHS,
2153 APSInt &Result) {
2154 switch (Opcode) {
2155 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002156 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002157 return false;
2158 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002159 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2160 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002161 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002162 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2163 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002164 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002165 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2166 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002167 case BO_And: Result = LHS & RHS; return true;
2168 case BO_Xor: Result = LHS ^ RHS; return true;
2169 case BO_Or: Result = LHS | RHS; return true;
2170 case BO_Div:
2171 case BO_Rem:
2172 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002173 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002174 return false;
2175 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002176 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2177 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2178 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002179 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2180 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002181 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2182 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002183 return true;
2184 case BO_Shl: {
2185 if (Info.getLangOpts().OpenCL)
2186 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2187 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2188 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2189 RHS.isUnsigned());
2190 else if (RHS.isSigned() && RHS.isNegative()) {
2191 // During constant-folding, a negative shift is an opposite shift. Such
2192 // a shift is not a constant expression.
2193 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2194 RHS = -RHS;
2195 goto shift_right;
2196 }
2197 shift_left:
2198 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2199 // the shifted type.
2200 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2201 if (SA != RHS) {
2202 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2203 << RHS << E->getType() << LHS.getBitWidth();
2204 } else if (LHS.isSigned()) {
2205 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2206 // operand, and must not overflow the corresponding unsigned type.
2207 if (LHS.isNegative())
2208 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2209 else if (LHS.countLeadingZeros() < SA)
2210 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2211 }
2212 Result = LHS << SA;
2213 return true;
2214 }
2215 case BO_Shr: {
2216 if (Info.getLangOpts().OpenCL)
2217 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2218 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2219 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2220 RHS.isUnsigned());
2221 else if (RHS.isSigned() && RHS.isNegative()) {
2222 // During constant-folding, a negative shift is an opposite shift. Such a
2223 // shift is not a constant expression.
2224 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2225 RHS = -RHS;
2226 goto shift_left;
2227 }
2228 shift_right:
2229 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2230 // shifted type.
2231 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2232 if (SA != RHS)
2233 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2234 << RHS << E->getType() << LHS.getBitWidth();
2235 Result = LHS >> SA;
2236 return true;
2237 }
2238
2239 case BO_LT: Result = LHS < RHS; return true;
2240 case BO_GT: Result = LHS > RHS; return true;
2241 case BO_LE: Result = LHS <= RHS; return true;
2242 case BO_GE: Result = LHS >= RHS; return true;
2243 case BO_EQ: Result = LHS == RHS; return true;
2244 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002245 case BO_Cmp:
2246 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002247 }
2248}
2249
Richard Smith861b5b52013-05-07 23:34:45 +00002250/// Perform the given binary floating-point operation, in-place, on LHS.
2251static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2252 APFloat &LHS, BinaryOperatorKind Opcode,
2253 const APFloat &RHS) {
2254 switch (Opcode) {
2255 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002256 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002257 return false;
2258 case BO_Mul:
2259 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2260 break;
2261 case BO_Add:
2262 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2263 break;
2264 case BO_Sub:
2265 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2266 break;
2267 case BO_Div:
2268 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2269 break;
2270 }
2271
Richard Smith0c6124b2015-12-03 01:36:22 +00002272 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002273 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002274 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002275 }
Richard Smith861b5b52013-05-07 23:34:45 +00002276 return true;
2277}
2278
Richard Smitha8105bc2012-01-06 16:39:00 +00002279/// Cast an lvalue referring to a base subobject to a derived class, by
2280/// truncating the lvalue's path to the given length.
2281static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2282 const RecordDecl *TruncatedType,
2283 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002284 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002285
2286 // Check we actually point to a derived class object.
2287 if (TruncatedElements == D.Entries.size())
2288 return true;
2289 assert(TruncatedElements >= D.MostDerivedPathLength &&
2290 "not casting to a derived class");
2291 if (!Result.checkSubobject(Info, E, CSK_Derived))
2292 return false;
2293
2294 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002295 const RecordDecl *RD = TruncatedType;
2296 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002297 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002298 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2299 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002300 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002301 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002302 else
Richard Smithd62306a2011-11-10 06:34:14 +00002303 Result.Offset -= Layout.getBaseClassOffset(Base);
2304 RD = Base;
2305 }
Richard Smith027bf112011-11-17 22:56:20 +00002306 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002307 return true;
2308}
2309
John McCalld7bca762012-05-01 00:38:49 +00002310static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002311 const CXXRecordDecl *Derived,
2312 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002313 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002314 if (!RL) {
2315 if (Derived->isInvalidDecl()) return false;
2316 RL = &Info.Ctx.getASTRecordLayout(Derived);
2317 }
2318
Richard Smithd62306a2011-11-10 06:34:14 +00002319 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002320 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002321 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002322}
2323
Richard Smitha8105bc2012-01-06 16:39:00 +00002324static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002325 const CXXRecordDecl *DerivedDecl,
2326 const CXXBaseSpecifier *Base) {
2327 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2328
John McCalld7bca762012-05-01 00:38:49 +00002329 if (!Base->isVirtual())
2330 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002331
Richard Smitha8105bc2012-01-06 16:39:00 +00002332 SubobjectDesignator &D = Obj.Designator;
2333 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002334 return false;
2335
Richard Smitha8105bc2012-01-06 16:39:00 +00002336 // Extract most-derived object and corresponding type.
2337 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2338 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2339 return false;
2340
2341 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002342 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002343 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2344 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002345 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002346 return true;
2347}
2348
Richard Smith84401042013-06-03 05:03:02 +00002349static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2350 QualType Type, LValue &Result) {
2351 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2352 PathE = E->path_end();
2353 PathI != PathE; ++PathI) {
2354 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2355 *PathI))
2356 return false;
2357 Type = (*PathI)->getType();
2358 }
2359 return true;
2360}
2361
Richard Smithd62306a2011-11-10 06:34:14 +00002362/// Update LVal to refer to the given field, which must be a member of the type
2363/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002364static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002365 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002366 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002367 if (!RL) {
2368 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002369 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002370 }
Richard Smithd62306a2011-11-10 06:34:14 +00002371
2372 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002373 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002374 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002375 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002376}
2377
Richard Smith1b78b3d2012-01-25 22:15:11 +00002378/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002379static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002380 LValue &LVal,
2381 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002382 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002383 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002384 return false;
2385 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002386}
2387
Richard Smithd62306a2011-11-10 06:34:14 +00002388/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002389static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2390 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002391 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2392 // extension.
2393 if (Type->isVoidType() || Type->isFunctionType()) {
2394 Size = CharUnits::One();
2395 return true;
2396 }
2397
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002398 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002399 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002400 return false;
2401 }
2402
Richard Smithd62306a2011-11-10 06:34:14 +00002403 if (!Type->isConstantSizeType()) {
2404 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002405 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002406 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002407 return false;
2408 }
2409
2410 Size = Info.Ctx.getTypeSizeInChars(Type);
2411 return true;
2412}
2413
2414/// Update a pointer value to model pointer arithmetic.
2415/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002416/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002417/// \param LVal - The pointer value to be updated.
2418/// \param EltTy - The pointee type represented by LVal.
2419/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002420static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2421 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002422 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002423 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002424 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002425 return false;
2426
Yaxun Liu402804b2016-12-15 08:09:08 +00002427 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002428 return true;
2429}
2430
Richard Smithd6cc1982017-01-31 02:23:02 +00002431static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2432 LValue &LVal, QualType EltTy,
2433 int64_t Adjustment) {
2434 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2435 APSInt::get(Adjustment));
2436}
2437
Richard Smith66c96992012-02-18 22:04:06 +00002438/// Update an lvalue to refer to a component of a complex number.
2439/// \param Info - Information about the ongoing evaluation.
2440/// \param LVal - The lvalue to be updated.
2441/// \param EltTy - The complex number's component type.
2442/// \param Imag - False for the real component, true for the imaginary.
2443static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2444 LValue &LVal, QualType EltTy,
2445 bool Imag) {
2446 if (Imag) {
2447 CharUnits SizeOfComponent;
2448 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2449 return false;
2450 LVal.Offset += SizeOfComponent;
2451 }
2452 LVal.addComplex(Info, E, EltTy, Imag);
2453 return true;
2454}
2455
Faisal Vali051e3a22017-02-16 04:12:21 +00002456static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2457 QualType Type, const LValue &LVal,
2458 APValue &RVal);
2459
Richard Smith27908702011-10-24 17:54:18 +00002460/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002461///
2462/// \param Info Information about the ongoing evaluation.
2463/// \param E An expression to be used when printing diagnostics.
2464/// \param VD The variable whose initializer should be obtained.
2465/// \param Frame The frame in which the variable was created. Must be null
2466/// if this variable is not local to the evaluation.
2467/// \param Result Filled in with a pointer to the value of the variable.
2468static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2469 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002470 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002471
Richard Smith254a73d2011-10-28 22:34:42 +00002472 // If this is a parameter to an active constexpr function call, perform
2473 // argument substitution.
2474 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002475 // Assume arguments of a potential constant expression are unknown
2476 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002477 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002478 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002479 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002480 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002481 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002482 }
Richard Smith3229b742013-05-05 21:17:10 +00002483 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002484 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002485 }
Richard Smith27908702011-10-24 17:54:18 +00002486
Richard Smithd9f663b2013-04-22 15:31:51 +00002487 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002488 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002489 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2490 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002491 if (!Result) {
2492 // Assume variables referenced within a lambda's call operator that were
2493 // not declared within the call operator are captures and during checking
2494 // of a potential constant expression, assume they are unknown constant
2495 // expressions.
2496 assert(isLambdaCallOperator(Frame->Callee) &&
2497 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2498 "missing value for local variable");
2499 if (Info.checkingPotentialConstantExpression())
2500 return false;
2501 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002502 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002503 diag::note_unimplemented_constexpr_lambda_feature_ast)
2504 << "captures not currently allowed";
2505 return false;
2506 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002507 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002508 }
2509
Richard Smithd0b4dd62011-12-19 06:19:21 +00002510 // Dig out the initializer, and use the declaration which it's attached to.
2511 const Expr *Init = VD->getAnyInitializer(VD);
2512 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002513 // If we're checking a potential constant expression, the variable could be
2514 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002515 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002516 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002517 return false;
2518 }
2519
Richard Smithd62306a2011-11-10 06:34:14 +00002520 // If we're currently evaluating the initializer of this declaration, use that
2521 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002522 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002523 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002524 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002525 }
2526
Richard Smithcecf1842011-11-01 21:06:14 +00002527 // Never evaluate the initializer of a weak variable. We can't be sure that
2528 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002529 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002530 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002531 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002532 }
Richard Smithcecf1842011-11-01 21:06:14 +00002533
Richard Smithd0b4dd62011-12-19 06:19:21 +00002534 // Check that we can fold the initializer. In C++, we will have already done
2535 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002536 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002537 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002538 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002539 Notes.size() + 1) << VD;
2540 Info.Note(VD->getLocation(), diag::note_declared_at);
2541 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002542 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002543 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002544 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002545 Notes.size() + 1) << VD;
2546 Info.Note(VD->getLocation(), diag::note_declared_at);
2547 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002548 }
Richard Smith27908702011-10-24 17:54:18 +00002549
Richard Smith3229b742013-05-05 21:17:10 +00002550 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002551 return true;
Richard Smith27908702011-10-24 17:54:18 +00002552}
2553
Richard Smith11562c52011-10-28 17:51:58 +00002554static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002555 Qualifiers Quals = T.getQualifiers();
2556 return Quals.hasConst() && !Quals.hasVolatile();
2557}
2558
Richard Smithe97cbd72011-11-11 04:05:33 +00002559/// Get the base index of the given base class within an APValue representing
2560/// the given derived class.
2561static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2562 const CXXRecordDecl *Base) {
2563 Base = Base->getCanonicalDecl();
2564 unsigned Index = 0;
2565 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2566 E = Derived->bases_end(); I != E; ++I, ++Index) {
2567 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2568 return Index;
2569 }
2570
2571 llvm_unreachable("base class missing from derived class's bases list");
2572}
2573
Richard Smith3da88fa2013-04-26 14:36:30 +00002574/// Extract the value of a character from a string literal.
2575static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2576 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002577 // FIXME: Support MakeStringConstant
2578 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2579 std::string Str;
2580 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2581 assert(Index <= Str.size() && "Index too large");
2582 return APSInt::getUnsigned(Str.c_str()[Index]);
2583 }
2584
Alexey Bataevec474782014-10-09 08:45:04 +00002585 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2586 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002587 const StringLiteral *S = cast<StringLiteral>(Lit);
2588 const ConstantArrayType *CAT =
2589 Info.Ctx.getAsConstantArrayType(S->getType());
2590 assert(CAT && "string literal isn't an array");
2591 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002592 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002593
2594 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002595 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002596 if (Index < S->getLength())
2597 Value = S->getCodeUnit(Index);
2598 return Value;
2599}
2600
Richard Smith3da88fa2013-04-26 14:36:30 +00002601// Expand a string literal into an array of characters.
2602static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2603 APValue &Result) {
2604 const StringLiteral *S = cast<StringLiteral>(Lit);
2605 const ConstantArrayType *CAT =
2606 Info.Ctx.getAsConstantArrayType(S->getType());
2607 assert(CAT && "string literal isn't an array");
2608 QualType CharType = CAT->getElementType();
2609 assert(CharType->isIntegerType() && "unexpected character type");
2610
2611 unsigned Elts = CAT->getSize().getZExtValue();
2612 Result = APValue(APValue::UninitArray(),
2613 std::min(S->getLength(), Elts), Elts);
2614 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2615 CharType->isUnsignedIntegerType());
2616 if (Result.hasArrayFiller())
2617 Result.getArrayFiller() = APValue(Value);
2618 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2619 Value = S->getCodeUnit(I);
2620 Result.getArrayInitializedElt(I) = APValue(Value);
2621 }
2622}
2623
2624// Expand an array so that it has more than Index filled elements.
2625static void expandArray(APValue &Array, unsigned Index) {
2626 unsigned Size = Array.getArraySize();
2627 assert(Index < Size);
2628
2629 // Always at least double the number of elements for which we store a value.
2630 unsigned OldElts = Array.getArrayInitializedElts();
2631 unsigned NewElts = std::max(Index+1, OldElts * 2);
2632 NewElts = std::min(Size, std::max(NewElts, 8u));
2633
2634 // Copy the data across.
2635 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2636 for (unsigned I = 0; I != OldElts; ++I)
2637 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2638 for (unsigned I = OldElts; I != NewElts; ++I)
2639 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2640 if (NewValue.hasArrayFiller())
2641 NewValue.getArrayFiller() = Array.getArrayFiller();
2642 Array.swap(NewValue);
2643}
2644
Richard Smithb01fe402014-09-16 01:24:02 +00002645/// Determine whether a type would actually be read by an lvalue-to-rvalue
2646/// conversion. If it's of class type, we may assume that the copy operation
2647/// is trivial. Note that this is never true for a union type with fields
2648/// (because the copy always "reads" the active member) and always true for
2649/// a non-class type.
2650static bool isReadByLvalueToRvalueConversion(QualType T) {
2651 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2652 if (!RD || (RD->isUnion() && !RD->field_empty()))
2653 return true;
2654 if (RD->isEmpty())
2655 return false;
2656
2657 for (auto *Field : RD->fields())
2658 if (isReadByLvalueToRvalueConversion(Field->getType()))
2659 return true;
2660
2661 for (auto &BaseSpec : RD->bases())
2662 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2663 return true;
2664
2665 return false;
2666}
2667
2668/// Diagnose an attempt to read from any unreadable field within the specified
2669/// type, which might be a class type.
2670static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2671 QualType T) {
2672 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2673 if (!RD)
2674 return false;
2675
2676 if (!RD->hasMutableFields())
2677 return false;
2678
2679 for (auto *Field : RD->fields()) {
2680 // If we're actually going to read this field in some way, then it can't
2681 // be mutable. If we're in a union, then assigning to a mutable field
2682 // (even an empty one) can change the active member, so that's not OK.
2683 // FIXME: Add core issue number for the union case.
2684 if (Field->isMutable() &&
2685 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002686 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002687 Info.Note(Field->getLocation(), diag::note_declared_at);
2688 return true;
2689 }
2690
2691 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2692 return true;
2693 }
2694
2695 for (auto &BaseSpec : RD->bases())
2696 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2697 return true;
2698
2699 // All mutable fields were empty, and thus not actually read.
2700 return false;
2701}
2702
Richard Smith861b5b52013-05-07 23:34:45 +00002703/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002704enum AccessKinds {
2705 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002706 AK_Assign,
2707 AK_Increment,
2708 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002709};
2710
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002711namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002712/// A handle to a complete object (an object that is not a subobject of
2713/// another object).
2714struct CompleteObject {
2715 /// The value of the complete object.
2716 APValue *Value;
2717 /// The type of the complete object.
2718 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002719 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002720
Craig Topper36250ad2014-05-12 05:36:57 +00002721 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002722 CompleteObject(APValue *Value, QualType Type,
2723 bool LifetimeStartedInEvaluation)
2724 : Value(Value), Type(Type),
2725 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002726 assert(Value && "missing value for complete object");
2727 }
2728
Aaron Ballman67347662015-02-15 22:00:28 +00002729 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002730};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002731} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002732
Richard Smith3da88fa2013-04-26 14:36:30 +00002733/// Find the designated sub-object of an rvalue.
2734template<typename SubobjectHandler>
2735typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002736findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002737 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002738 if (Sub.Invalid)
2739 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002740 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002741 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002742 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002743 Info.FFDiag(E, Sub.isOnePastTheEnd()
2744 ? diag::note_constexpr_access_past_end
2745 : diag::note_constexpr_access_unsized_array)
2746 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002747 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002748 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002749 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002750 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002751
Richard Smith3229b742013-05-05 21:17:10 +00002752 APValue *O = Obj.Value;
2753 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002754 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002755 const bool MayReadMutableMembers =
2756 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002757
Richard Smithd62306a2011-11-10 06:34:14 +00002758 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002759 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2760 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002761 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002762 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002763 return handler.failed();
2764 }
2765
Richard Smith49ca8aa2013-08-06 07:09:20 +00002766 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002767 // If we are reading an object of class type, there may still be more
2768 // things we need to check: if there are any mutable subobjects, we
2769 // cannot perform this read. (This only happens when performing a trivial
2770 // copy or assignment.)
2771 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002772 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002773 return handler.failed();
2774
Richard Smith49ca8aa2013-08-06 07:09:20 +00002775 if (!handler.found(*O, ObjType))
2776 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002777
Richard Smith49ca8aa2013-08-06 07:09:20 +00002778 // If we modified a bit-field, truncate it to the right width.
2779 if (handler.AccessKind != AK_Read &&
2780 LastField && LastField->isBitField() &&
2781 !truncateBitfieldValue(Info, E, *O, LastField))
2782 return false;
2783
2784 return true;
2785 }
2786
Craig Topper36250ad2014-05-12 05:36:57 +00002787 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002788 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002789 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002790 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002791 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002792 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002793 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002794 // Note, it should not be possible to form a pointer with a valid
2795 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002796 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002797 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002798 << handler.AccessKind;
2799 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002800 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002801 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002802 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002803
2804 ObjType = CAT->getElementType();
2805
Richard Smith14a94132012-02-17 03:35:37 +00002806 // An array object is represented as either an Array APValue or as an
2807 // LValue which refers to a string literal.
2808 if (O->isLValue()) {
2809 assert(I == N - 1 && "extracting subobject of character?");
2810 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002811 if (handler.AccessKind != AK_Read)
2812 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2813 *O);
2814 else
2815 return handler.foundString(*O, ObjType, Index);
2816 }
2817
2818 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002819 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002820 else if (handler.AccessKind != AK_Read) {
2821 expandArray(*O, Index);
2822 O = &O->getArrayInitializedElt(Index);
2823 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002824 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002825 } else if (ObjType->isAnyComplexType()) {
2826 // Next subobject is a complex number.
2827 uint64_t Index = Sub.Entries[I].ArrayIndex;
2828 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002829 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002830 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002831 << handler.AccessKind;
2832 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002833 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002834 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002835 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002836
2837 bool WasConstQualified = ObjType.isConstQualified();
2838 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2839 if (WasConstQualified)
2840 ObjType.addConst();
2841
Richard Smith66c96992012-02-18 22:04:06 +00002842 assert(I == N - 1 && "extracting subobject of scalar?");
2843 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002844 return handler.found(Index ? O->getComplexIntImag()
2845 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002846 } else {
2847 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002848 return handler.found(Index ? O->getComplexFloatImag()
2849 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002850 }
Richard Smithd62306a2011-11-10 06:34:14 +00002851 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002852 // In C++14 onwards, it is permitted to read a mutable member whose
2853 // lifetime began within the evaluation.
2854 // FIXME: Should we also allow this in C++11?
2855 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2856 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002857 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002858 << Field;
2859 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002860 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002861 }
2862
Richard Smithd62306a2011-11-10 06:34:14 +00002863 // Next subobject is a class, struct or union field.
2864 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2865 if (RD->isUnion()) {
2866 const FieldDecl *UnionField = O->getUnionField();
2867 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002868 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002869 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002870 << handler.AccessKind << Field << !UnionField << UnionField;
2871 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002872 }
Richard Smithd62306a2011-11-10 06:34:14 +00002873 O = &O->getUnionValue();
2874 } else
2875 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002876
2877 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002878 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002879 if (WasConstQualified && !Field->isMutable())
2880 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002881
2882 if (ObjType.isVolatileQualified()) {
2883 if (Info.getLangOpts().CPlusPlus) {
2884 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002885 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002886 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002887 Info.Note(Field->getLocation(), diag::note_declared_at);
2888 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002889 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002890 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002891 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002892 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002893
2894 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002895 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002896 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002897 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2898 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2899 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002900
2901 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002902 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002903 if (WasConstQualified)
2904 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002905 }
2906 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002907}
2908
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002909namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002910struct ExtractSubobjectHandler {
2911 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002912 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002913
2914 static const AccessKinds AccessKind = AK_Read;
2915
2916 typedef bool result_type;
2917 bool failed() { return false; }
2918 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002919 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002920 return true;
2921 }
2922 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002923 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002924 return true;
2925 }
2926 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002927 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002928 return true;
2929 }
2930 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002931 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002932 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2933 return true;
2934 }
2935};
Richard Smith3229b742013-05-05 21:17:10 +00002936} // end anonymous namespace
2937
Richard Smith3da88fa2013-04-26 14:36:30 +00002938const AccessKinds ExtractSubobjectHandler::AccessKind;
2939
2940/// Extract the designated sub-object of an rvalue.
2941static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002942 const CompleteObject &Obj,
2943 const SubobjectDesignator &Sub,
2944 APValue &Result) {
2945 ExtractSubobjectHandler Handler = { Info, Result };
2946 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002947}
2948
Richard Smith3229b742013-05-05 21:17:10 +00002949namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002950struct ModifySubobjectHandler {
2951 EvalInfo &Info;
2952 APValue &NewVal;
2953 const Expr *E;
2954
2955 typedef bool result_type;
2956 static const AccessKinds AccessKind = AK_Assign;
2957
2958 bool checkConst(QualType QT) {
2959 // Assigning to a const object has undefined behavior.
2960 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002961 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002962 return false;
2963 }
2964 return true;
2965 }
2966
2967 bool failed() { return false; }
2968 bool found(APValue &Subobj, QualType SubobjType) {
2969 if (!checkConst(SubobjType))
2970 return false;
2971 // We've been given ownership of NewVal, so just swap it in.
2972 Subobj.swap(NewVal);
2973 return true;
2974 }
2975 bool found(APSInt &Value, QualType SubobjType) {
2976 if (!checkConst(SubobjType))
2977 return false;
2978 if (!NewVal.isInt()) {
2979 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002980 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002981 return false;
2982 }
2983 Value = NewVal.getInt();
2984 return true;
2985 }
2986 bool found(APFloat &Value, QualType SubobjType) {
2987 if (!checkConst(SubobjType))
2988 return false;
2989 Value = NewVal.getFloat();
2990 return true;
2991 }
2992 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2993 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2994 }
2995};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002996} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002997
Richard Smith3229b742013-05-05 21:17:10 +00002998const AccessKinds ModifySubobjectHandler::AccessKind;
2999
Richard Smith3da88fa2013-04-26 14:36:30 +00003000/// Update the designated sub-object of an rvalue to the given value.
3001static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003002 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003003 const SubobjectDesignator &Sub,
3004 APValue &NewVal) {
3005 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003006 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003007}
3008
Richard Smith84f6dcf2012-02-02 01:16:57 +00003009/// Find the position where two subobject designators diverge, or equivalently
3010/// the length of the common initial subsequence.
3011static unsigned FindDesignatorMismatch(QualType ObjType,
3012 const SubobjectDesignator &A,
3013 const SubobjectDesignator &B,
3014 bool &WasArrayIndex) {
3015 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3016 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003017 if (!ObjType.isNull() &&
3018 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003019 // Next subobject is an array element.
3020 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3021 WasArrayIndex = true;
3022 return I;
3023 }
Richard Smith66c96992012-02-18 22:04:06 +00003024 if (ObjType->isAnyComplexType())
3025 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3026 else
3027 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003028 } else {
3029 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3030 WasArrayIndex = false;
3031 return I;
3032 }
3033 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3034 // Next subobject is a field.
3035 ObjType = FD->getType();
3036 else
3037 // Next subobject is a base class.
3038 ObjType = QualType();
3039 }
3040 }
3041 WasArrayIndex = false;
3042 return I;
3043}
3044
3045/// Determine whether the given subobject designators refer to elements of the
3046/// same array object.
3047static bool AreElementsOfSameArray(QualType ObjType,
3048 const SubobjectDesignator &A,
3049 const SubobjectDesignator &B) {
3050 if (A.Entries.size() != B.Entries.size())
3051 return false;
3052
George Burgess IVa51c4072015-10-16 01:49:01 +00003053 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003054 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3055 // A is a subobject of the array element.
3056 return false;
3057
3058 // If A (and B) designates an array element, the last entry will be the array
3059 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3060 // of length 1' case, and the entire path must match.
3061 bool WasArrayIndex;
3062 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3063 return CommonLength >= A.Entries.size() - IsArray;
3064}
3065
Richard Smith3229b742013-05-05 21:17:10 +00003066/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003067static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3068 AccessKinds AK, const LValue &LVal,
3069 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003070 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003071 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003072 return CompleteObject();
3073 }
3074
Craig Topper36250ad2014-05-12 05:36:57 +00003075 CallStackFrame *Frame = nullptr;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003076 if (LVal.getLValueCallIndex()) {
3077 Frame = Info.getCallFrame(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003078 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003079 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003080 << AK << LVal.Base.is<const ValueDecl*>();
3081 NoteLValueLocation(Info, LVal.Base);
3082 return CompleteObject();
3083 }
Richard Smith3229b742013-05-05 21:17:10 +00003084 }
3085
3086 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3087 // is not a constant expression (even if the object is non-volatile). We also
3088 // apply this rule to C++98, in order to conform to the expected 'volatile'
3089 // semantics.
3090 if (LValType.isVolatileQualified()) {
3091 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003092 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003093 << AK << LValType;
3094 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003095 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003096 return CompleteObject();
3097 }
3098
3099 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003100 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003101 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003102 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003103
3104 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3105 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3106 // In C++11, constexpr, non-volatile variables initialized with constant
3107 // expressions are constant expressions too. Inside constexpr functions,
3108 // parameters are constant expressions even if they're non-const.
3109 // In C++1y, objects local to a constant expression (those with a Frame) are
3110 // both readable and writable inside constant expressions.
3111 // In C, such things can also be folded, although they are not ICEs.
3112 const VarDecl *VD = dyn_cast<VarDecl>(D);
3113 if (VD) {
3114 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3115 VD = VDef;
3116 }
3117 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003118 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003119 return CompleteObject();
3120 }
3121
3122 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003123 if (BaseType.isVolatileQualified()) {
3124 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003125 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003126 << AK << 1 << VD;
3127 Info.Note(VD->getLocation(), diag::note_declared_at);
3128 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003129 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003130 }
3131 return CompleteObject();
3132 }
3133
3134 // Unless we're looking at a local variable or argument in a constexpr call,
3135 // the variable we're reading must be const.
3136 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003137 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003138 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3139 // OK, we can read and modify an object if we're in the process of
3140 // evaluating its initializer, because its lifetime began in this
3141 // evaluation.
3142 } else if (AK != AK_Read) {
3143 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003144 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003145 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003146 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003147 // OK, we can read this variable.
3148 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003149 // In OpenCL if a variable is in constant address space it is a const value.
3150 if (!(BaseType.isConstQualified() ||
3151 (Info.getLangOpts().OpenCL &&
3152 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003153 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003154 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003155 Info.Note(VD->getLocation(), diag::note_declared_at);
3156 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003157 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003158 }
3159 return CompleteObject();
3160 }
3161 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3162 // We support folding of const floating-point types, in order to make
3163 // static const data members of such types (supported as an extension)
3164 // more useful.
3165 if (Info.getLangOpts().CPlusPlus11) {
3166 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3167 Info.Note(VD->getLocation(), diag::note_declared_at);
3168 } else {
3169 Info.CCEDiag(E);
3170 }
George Burgess IVb5316982016-12-27 05:33:20 +00003171 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3172 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3173 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003174 } else {
3175 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003176 if (Info.checkingPotentialConstantExpression() &&
3177 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3178 // The definition of this variable could be constexpr. We can't
3179 // access it right now, but may be able to in future.
3180 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003181 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003182 Info.Note(VD->getLocation(), diag::note_declared_at);
3183 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003184 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003185 }
3186 return CompleteObject();
3187 }
3188 }
3189
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003190 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003191 return CompleteObject();
3192 } else {
3193 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3194
3195 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003196 if (const MaterializeTemporaryExpr *MTE =
3197 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3198 assert(MTE->getStorageDuration() == SD_Static &&
3199 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003200
Richard Smithe6c01442013-06-05 00:46:14 +00003201 // Per C++1y [expr.const]p2:
3202 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3203 // - a [...] glvalue of integral or enumeration type that refers to
3204 // a non-volatile const object [...]
3205 // [...]
3206 // - a [...] glvalue of literal type that refers to a non-volatile
3207 // object whose lifetime began within the evaluation of e.
3208 //
3209 // C++11 misses the 'began within the evaluation of e' check and
3210 // instead allows all temporaries, including things like:
3211 // int &&r = 1;
3212 // int x = ++r;
3213 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003214 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003215 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3216 const ValueDecl *ED = MTE->getExtendingDecl();
3217 if (!(BaseType.isConstQualified() &&
3218 BaseType->isIntegralOrEnumerationType()) &&
3219 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003220 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003221 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3222 return CompleteObject();
3223 }
3224
3225 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3226 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003227 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003228 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003229 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003230 return CompleteObject();
3231 }
3232 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003233 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003234 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003235 }
Richard Smith3229b742013-05-05 21:17:10 +00003236
3237 // Volatile temporary objects cannot be accessed in constant expressions.
3238 if (BaseType.isVolatileQualified()) {
3239 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003240 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003241 << AK << 0;
3242 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3243 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003244 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003245 }
3246 return CompleteObject();
3247 }
3248 }
3249
Richard Smith7525ff62013-05-09 07:14:00 +00003250 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003251 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003252 // object under construction.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003253 if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3254 LVal.getLValueCallIndex(),
3255 LVal.getLValueVersion())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003256 BaseType = Info.Ctx.getCanonicalType(BaseType);
3257 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003258 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003259 }
3260
Richard Smith9defb7d2018-02-21 03:38:30 +00003261 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003262 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003263 //
3264 // FIXME: Not all local state is mutable. Allow local constant subobjects
3265 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003266 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3267 Info.EvalStatus.HasSideEffects) ||
3268 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003269 return CompleteObject();
3270
Richard Smith9defb7d2018-02-21 03:38:30 +00003271 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003272}
3273
Richard Smith243ef902013-05-05 23:31:59 +00003274/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3275/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3276/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003277///
3278/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003279/// \param Conv - The expression for which we are performing the conversion.
3280/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003281/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3282/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003283/// \param LVal - The glvalue on which we are attempting to perform this action.
3284/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003285static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003286 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003287 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003288 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003289 return false;
3290
Richard Smith3229b742013-05-05 21:17:10 +00003291 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003292 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003293 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003294 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3295 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3296 // initializer until now for such expressions. Such an expression can't be
3297 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003298 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003299 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003300 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003301 }
Richard Smith3229b742013-05-05 21:17:10 +00003302 APValue Lit;
3303 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3304 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003305 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003306 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003307 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003308 // We represent a string literal array as an lvalue pointing at the
3309 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003310 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003311 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003312 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003313 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003314 }
Richard Smith11562c52011-10-28 17:51:58 +00003315 }
3316
Richard Smith3229b742013-05-05 21:17:10 +00003317 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3318 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003319}
3320
3321/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003322static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003323 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003324 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003325 return false;
3326
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003327 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003328 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003329 return false;
3330 }
3331
Richard Smith3229b742013-05-05 21:17:10 +00003332 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003333 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3334}
3335
3336namespace {
3337struct CompoundAssignSubobjectHandler {
3338 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003339 const Expr *E;
3340 QualType PromotedLHSType;
3341 BinaryOperatorKind Opcode;
3342 const APValue &RHS;
3343
3344 static const AccessKinds AccessKind = AK_Assign;
3345
3346 typedef bool result_type;
3347
3348 bool checkConst(QualType QT) {
3349 // Assigning to a const object has undefined behavior.
3350 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003351 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003352 return false;
3353 }
3354 return true;
3355 }
3356
3357 bool failed() { return false; }
3358 bool found(APValue &Subobj, QualType SubobjType) {
3359 switch (Subobj.getKind()) {
3360 case APValue::Int:
3361 return found(Subobj.getInt(), SubobjType);
3362 case APValue::Float:
3363 return found(Subobj.getFloat(), SubobjType);
3364 case APValue::ComplexInt:
3365 case APValue::ComplexFloat:
3366 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003367 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003368 return false;
3369 case APValue::LValue:
3370 return foundPointer(Subobj, SubobjType);
3371 default:
3372 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003373 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003374 return false;
3375 }
3376 }
3377 bool found(APSInt &Value, QualType SubobjType) {
3378 if (!checkConst(SubobjType))
3379 return false;
3380
3381 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3382 // We don't support compound assignment on integer-cast-to-pointer
3383 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003384 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003385 return false;
3386 }
3387
3388 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3389 SubobjType, Value);
3390 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3391 return false;
3392 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3393 return true;
3394 }
3395 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003396 return checkConst(SubobjType) &&
3397 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3398 Value) &&
3399 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3400 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003401 }
3402 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3403 if (!checkConst(SubobjType))
3404 return false;
3405
3406 QualType PointeeType;
3407 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3408 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003409
3410 if (PointeeType.isNull() || !RHS.isInt() ||
3411 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003412 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003413 return false;
3414 }
3415
Richard Smithd6cc1982017-01-31 02:23:02 +00003416 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003417 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003418 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003419
3420 LValue LVal;
3421 LVal.setFrom(Info.Ctx, Subobj);
3422 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3423 return false;
3424 LVal.moveInto(Subobj);
3425 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003426 }
3427 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3428 llvm_unreachable("shouldn't encounter string elements here");
3429 }
3430};
3431} // end anonymous namespace
3432
3433const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3434
3435/// Perform a compound assignment of LVal <op>= RVal.
3436static bool handleCompoundAssignment(
3437 EvalInfo &Info, const Expr *E,
3438 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3439 BinaryOperatorKind Opcode, const APValue &RVal) {
3440 if (LVal.Designator.Invalid)
3441 return false;
3442
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003443 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003444 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003445 return false;
3446 }
3447
3448 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3449 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3450 RVal };
3451 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3452}
3453
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003454namespace {
3455struct IncDecSubobjectHandler {
3456 EvalInfo &Info;
3457 const UnaryOperator *E;
3458 AccessKinds AccessKind;
3459 APValue *Old;
3460
Richard Smith243ef902013-05-05 23:31:59 +00003461 typedef bool result_type;
3462
3463 bool checkConst(QualType QT) {
3464 // Assigning to a const object has undefined behavior.
3465 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003466 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003467 return false;
3468 }
3469 return true;
3470 }
3471
3472 bool failed() { return false; }
3473 bool found(APValue &Subobj, QualType SubobjType) {
3474 // Stash the old value. Also clear Old, so we don't clobber it later
3475 // if we're post-incrementing a complex.
3476 if (Old) {
3477 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003478 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003479 }
3480
3481 switch (Subobj.getKind()) {
3482 case APValue::Int:
3483 return found(Subobj.getInt(), SubobjType);
3484 case APValue::Float:
3485 return found(Subobj.getFloat(), SubobjType);
3486 case APValue::ComplexInt:
3487 return found(Subobj.getComplexIntReal(),
3488 SubobjType->castAs<ComplexType>()->getElementType()
3489 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3490 case APValue::ComplexFloat:
3491 return found(Subobj.getComplexFloatReal(),
3492 SubobjType->castAs<ComplexType>()->getElementType()
3493 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3494 case APValue::LValue:
3495 return foundPointer(Subobj, SubobjType);
3496 default:
3497 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003498 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003499 return false;
3500 }
3501 }
3502 bool found(APSInt &Value, QualType SubobjType) {
3503 if (!checkConst(SubobjType))
3504 return false;
3505
3506 if (!SubobjType->isIntegerType()) {
3507 // We don't support increment / decrement on integer-cast-to-pointer
3508 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003509 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003510 return false;
3511 }
3512
3513 if (Old) *Old = APValue(Value);
3514
3515 // bool arithmetic promotes to int, and the conversion back to bool
3516 // doesn't reduce mod 2^n, so special-case it.
3517 if (SubobjType->isBooleanType()) {
3518 if (AccessKind == AK_Increment)
3519 Value = 1;
3520 else
3521 Value = !Value;
3522 return true;
3523 }
3524
3525 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003526 if (AccessKind == AK_Increment) {
3527 ++Value;
3528
3529 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3530 APSInt ActualValue(Value, /*IsUnsigned*/true);
3531 return HandleOverflow(Info, E, ActualValue, SubobjType);
3532 }
3533 } else {
3534 --Value;
3535
3536 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3537 unsigned BitWidth = Value.getBitWidth();
3538 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3539 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003540 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003541 }
3542 }
3543 return true;
3544 }
3545 bool found(APFloat &Value, QualType SubobjType) {
3546 if (!checkConst(SubobjType))
3547 return false;
3548
3549 if (Old) *Old = APValue(Value);
3550
3551 APFloat One(Value.getSemantics(), 1);
3552 if (AccessKind == AK_Increment)
3553 Value.add(One, APFloat::rmNearestTiesToEven);
3554 else
3555 Value.subtract(One, APFloat::rmNearestTiesToEven);
3556 return true;
3557 }
3558 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3559 if (!checkConst(SubobjType))
3560 return false;
3561
3562 QualType PointeeType;
3563 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3564 PointeeType = PT->getPointeeType();
3565 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003566 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003567 return false;
3568 }
3569
3570 LValue LVal;
3571 LVal.setFrom(Info.Ctx, Subobj);
3572 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3573 AccessKind == AK_Increment ? 1 : -1))
3574 return false;
3575 LVal.moveInto(Subobj);
3576 return true;
3577 }
3578 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3579 llvm_unreachable("shouldn't encounter string elements here");
3580 }
3581};
3582} // end anonymous namespace
3583
3584/// Perform an increment or decrement on LVal.
3585static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3586 QualType LValType, bool IsIncrement, APValue *Old) {
3587 if (LVal.Designator.Invalid)
3588 return false;
3589
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003590 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003591 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003592 return false;
3593 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003594
3595 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3596 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3597 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3598 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3599}
3600
Richard Smithe97cbd72011-11-11 04:05:33 +00003601/// Build an lvalue for the object argument of a member function call.
3602static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3603 LValue &This) {
3604 if (Object->getType()->isPointerType())
3605 return EvaluatePointer(Object, This, Info);
3606
3607 if (Object->isGLValue())
3608 return EvaluateLValue(Object, This, Info);
3609
Richard Smithd9f663b2013-04-22 15:31:51 +00003610 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003611 return EvaluateTemporary(Object, This, Info);
3612
Faisal Valie690b7a2016-07-02 22:34:24 +00003613 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003614 return false;
3615}
3616
3617/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3618/// lvalue referring to the result.
3619///
3620/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003621/// \param LV - An lvalue referring to the base of the member pointer.
3622/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003623/// \param IncludeMember - Specifies whether the member itself is included in
3624/// the resulting LValue subobject designator. This is not possible when
3625/// creating a bound member function.
3626/// \return The field or method declaration to which the member pointer refers,
3627/// or 0 if evaluation fails.
3628static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003629 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003630 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003631 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003632 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003633 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003634 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003635 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003636
3637 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3638 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003639 if (!MemPtr.getDecl()) {
3640 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003641 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003642 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003643 }
Richard Smith253c2a32012-01-27 01:14:48 +00003644
Richard Smith027bf112011-11-17 22:56:20 +00003645 if (MemPtr.isDerivedMember()) {
3646 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003647 // The end of the derived-to-base path for the base object must match the
3648 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003649 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003650 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003651 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003652 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003653 }
Richard Smith027bf112011-11-17 22:56:20 +00003654 unsigned PathLengthToMember =
3655 LV.Designator.Entries.size() - MemPtr.Path.size();
3656 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3657 const CXXRecordDecl *LVDecl = getAsBaseClass(
3658 LV.Designator.Entries[PathLengthToMember + I]);
3659 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003660 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003661 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003662 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003663 }
Richard Smith027bf112011-11-17 22:56:20 +00003664 }
3665
3666 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003667 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003668 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003669 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003670 } else if (!MemPtr.Path.empty()) {
3671 // Extend the LValue path with the member pointer's path.
3672 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3673 MemPtr.Path.size() + IncludeMember);
3674
3675 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003676 if (const PointerType *PT = LVType->getAs<PointerType>())
3677 LVType = PT->getPointeeType();
3678 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3679 assert(RD && "member pointer access on non-class-type expression");
3680 // The first class in the path is that of the lvalue.
3681 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3682 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003683 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003684 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003685 RD = Base;
3686 }
3687 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003688 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3689 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003690 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003691 }
3692
3693 // Add the member. Note that we cannot build bound member functions here.
3694 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003695 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003696 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003697 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003698 } else if (const IndirectFieldDecl *IFD =
3699 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003700 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003701 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003702 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003703 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003704 }
Richard Smith027bf112011-11-17 22:56:20 +00003705 }
3706
3707 return MemPtr.getDecl();
3708}
3709
Richard Smith84401042013-06-03 05:03:02 +00003710static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3711 const BinaryOperator *BO,
3712 LValue &LV,
3713 bool IncludeMember = true) {
3714 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3715
3716 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003717 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003718 MemberPtr MemPtr;
3719 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3720 }
Craig Topper36250ad2014-05-12 05:36:57 +00003721 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003722 }
3723
3724 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3725 BO->getRHS(), IncludeMember);
3726}
3727
Richard Smith027bf112011-11-17 22:56:20 +00003728/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3729/// the provided lvalue, which currently refers to the base object.
3730static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3731 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003732 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003733 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003734 return false;
3735
Richard Smitha8105bc2012-01-06 16:39:00 +00003736 QualType TargetQT = E->getType();
3737 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3738 TargetQT = PT->getPointeeType();
3739
3740 // Check this cast lands within the final derived-to-base subobject path.
3741 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003742 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003743 << D.MostDerivedType << TargetQT;
3744 return false;
3745 }
3746
Richard Smith027bf112011-11-17 22:56:20 +00003747 // Check the type of the final cast. We don't need to check the path,
3748 // since a cast can only be formed if the path is unique.
3749 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003750 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3751 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003752 if (NewEntriesSize == D.MostDerivedPathLength)
3753 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3754 else
Richard Smith027bf112011-11-17 22:56:20 +00003755 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003756 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003757 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003758 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003759 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003760 }
Richard Smith027bf112011-11-17 22:56:20 +00003761
3762 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003763 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003764}
3765
Mike Stump876387b2009-10-27 22:09:17 +00003766namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003767enum EvalStmtResult {
3768 /// Evaluation failed.
3769 ESR_Failed,
3770 /// Hit a 'return' statement.
3771 ESR_Returned,
3772 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003773 ESR_Succeeded,
3774 /// Hit a 'continue' statement.
3775 ESR_Continue,
3776 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003777 ESR_Break,
3778 /// Still scanning for 'case' or 'default' statement.
3779 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003780};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003781}
Richard Smith254a73d2011-10-28 22:34:42 +00003782
Richard Smith97fcf4b2016-08-14 23:15:52 +00003783static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3784 // We don't need to evaluate the initializer for a static local.
3785 if (!VD->hasLocalStorage())
3786 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003787
Richard Smith97fcf4b2016-08-14 23:15:52 +00003788 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003789 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00003790
Richard Smith97fcf4b2016-08-14 23:15:52 +00003791 const Expr *InitE = VD->getInit();
3792 if (!InitE) {
3793 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3794 << false << VD->getType();
3795 Val = APValue();
3796 return false;
3797 }
Richard Smith51f03172013-06-20 03:00:05 +00003798
Richard Smith97fcf4b2016-08-14 23:15:52 +00003799 if (InitE->isValueDependent())
3800 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003801
Richard Smith97fcf4b2016-08-14 23:15:52 +00003802 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3803 // Wipe out any partially-computed value, to allow tracking that this
3804 // evaluation failed.
3805 Val = APValue();
3806 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003807 }
3808
3809 return true;
3810}
3811
Richard Smith97fcf4b2016-08-14 23:15:52 +00003812static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3813 bool OK = true;
3814
3815 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3816 OK &= EvaluateVarDecl(Info, VD);
3817
3818 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3819 for (auto *BD : DD->bindings())
3820 if (auto *VD = BD->getHoldingVar())
3821 OK &= EvaluateDecl(Info, VD);
3822
3823 return OK;
3824}
3825
3826
Richard Smith4e18ca52013-05-06 05:56:11 +00003827/// Evaluate a condition (either a variable declaration or an expression).
3828static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3829 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003830 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003831 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3832 return false;
3833 return EvaluateAsBooleanCondition(Cond, Result, Info);
3834}
3835
Richard Smith89210072016-04-04 23:29:43 +00003836namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003837/// \brief A location where the result (returned value) of evaluating a
3838/// statement should be stored.
3839struct StmtResult {
3840 /// The APValue that should be filled in with the returned value.
3841 APValue &Value;
3842 /// The location containing the result, if any (used to support RVO).
3843 const LValue *Slot;
3844};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003845
3846struct TempVersionRAII {
3847 CallStackFrame &Frame;
3848
3849 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3850 Frame.pushTempVersion();
3851 }
3852
3853 ~TempVersionRAII() {
3854 Frame.popTempVersion();
3855 }
3856};
3857
Richard Smith89210072016-04-04 23:29:43 +00003858}
Richard Smith52a980a2015-08-28 02:43:42 +00003859
3860static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003861 const Stmt *S,
3862 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003863
3864/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003865static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003866 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003867 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003868 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003869 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003870 case ESR_Break:
3871 return ESR_Succeeded;
3872 case ESR_Succeeded:
3873 case ESR_Continue:
3874 return ESR_Continue;
3875 case ESR_Failed:
3876 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003877 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003878 return ESR;
3879 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003880 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003881}
3882
Richard Smith496ddcf2013-05-12 17:32:42 +00003883/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003884static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003885 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003886 BlockScopeRAII Scope(Info);
3887
Richard Smith496ddcf2013-05-12 17:32:42 +00003888 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003889 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003890 {
3891 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003892 if (const Stmt *Init = SS->getInit()) {
3893 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3894 if (ESR != ESR_Succeeded)
3895 return ESR;
3896 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003897 if (SS->getConditionVariable() &&
3898 !EvaluateDecl(Info, SS->getConditionVariable()))
3899 return ESR_Failed;
3900 if (!EvaluateInteger(SS->getCond(), Value, Info))
3901 return ESR_Failed;
3902 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003903
3904 // Find the switch case corresponding to the value of the condition.
3905 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003906 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003907 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3908 SC = SC->getNextSwitchCase()) {
3909 if (isa<DefaultStmt>(SC)) {
3910 Found = SC;
3911 continue;
3912 }
3913
3914 const CaseStmt *CS = cast<CaseStmt>(SC);
3915 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3916 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3917 : LHS;
3918 if (LHS <= Value && Value <= RHS) {
3919 Found = SC;
3920 break;
3921 }
3922 }
3923
3924 if (!Found)
3925 return ESR_Succeeded;
3926
3927 // Search the switch body for the switch case and evaluate it from there.
3928 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3929 case ESR_Break:
3930 return ESR_Succeeded;
3931 case ESR_Succeeded:
3932 case ESR_Continue:
3933 case ESR_Failed:
3934 case ESR_Returned:
3935 return ESR;
3936 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003937 // This can only happen if the switch case is nested within a statement
3938 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003939 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003940 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003941 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003942 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003943}
3944
Richard Smith254a73d2011-10-28 22:34:42 +00003945// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003946static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003947 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003948 if (!Info.nextStep(S))
3949 return ESR_Failed;
3950
Richard Smith496ddcf2013-05-12 17:32:42 +00003951 // If we're hunting down a 'case' or 'default' label, recurse through
3952 // substatements until we hit the label.
3953 if (Case) {
3954 // FIXME: We don't start the lifetime of objects whose initialization we
3955 // jump over. However, such objects must be of class type with a trivial
3956 // default constructor that initialize all subobjects, so must be empty,
3957 // so this almost never matters.
3958 switch (S->getStmtClass()) {
3959 case Stmt::CompoundStmtClass:
3960 // FIXME: Precompute which substatement of a compound statement we
3961 // would jump to, and go straight there rather than performing a
3962 // linear scan each time.
3963 case Stmt::LabelStmtClass:
3964 case Stmt::AttributedStmtClass:
3965 case Stmt::DoStmtClass:
3966 break;
3967
3968 case Stmt::CaseStmtClass:
3969 case Stmt::DefaultStmtClass:
3970 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003971 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003972 break;
3973
3974 case Stmt::IfStmtClass: {
3975 // FIXME: Precompute which side of an 'if' we would jump to, and go
3976 // straight there rather than scanning both sides.
3977 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003978
3979 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3980 // preceded by our switch label.
3981 BlockScopeRAII Scope(Info);
3982
Richard Smith496ddcf2013-05-12 17:32:42 +00003983 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3984 if (ESR != ESR_CaseNotFound || !IS->getElse())
3985 return ESR;
3986 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3987 }
3988
3989 case Stmt::WhileStmtClass: {
3990 EvalStmtResult ESR =
3991 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3992 if (ESR != ESR_Continue)
3993 return ESR;
3994 break;
3995 }
3996
3997 case Stmt::ForStmtClass: {
3998 const ForStmt *FS = cast<ForStmt>(S);
3999 EvalStmtResult ESR =
4000 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4001 if (ESR != ESR_Continue)
4002 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004003 if (FS->getInc()) {
4004 FullExpressionRAII IncScope(Info);
4005 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4006 return ESR_Failed;
4007 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004008 break;
4009 }
4010
4011 case Stmt::DeclStmtClass:
4012 // FIXME: If the variable has initialization that can't be jumped over,
4013 // bail out of any immediately-surrounding compound-statement too.
4014 default:
4015 return ESR_CaseNotFound;
4016 }
4017 }
4018
Richard Smith254a73d2011-10-28 22:34:42 +00004019 switch (S->getStmtClass()) {
4020 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004021 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004022 // Don't bother evaluating beyond an expression-statement which couldn't
4023 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004024 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004025 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004026 return ESR_Failed;
4027 return ESR_Succeeded;
4028 }
4029
Faisal Valie690b7a2016-07-02 22:34:24 +00004030 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00004031 return ESR_Failed;
4032
4033 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004034 return ESR_Succeeded;
4035
Richard Smithd9f663b2013-04-22 15:31:51 +00004036 case Stmt::DeclStmtClass: {
4037 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004038 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004039 // Each declaration initialization is its own full-expression.
4040 // FIXME: This isn't quite right; if we're performing aggregate
4041 // initialization, each braced subexpression is its own full-expression.
4042 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004043 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004044 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004045 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004046 return ESR_Succeeded;
4047 }
4048
Richard Smith357362d2011-12-13 06:39:58 +00004049 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004050 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004051 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004052 if (RetExpr &&
4053 !(Result.Slot
4054 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4055 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004056 return ESR_Failed;
4057 return ESR_Returned;
4058 }
Richard Smith254a73d2011-10-28 22:34:42 +00004059
4060 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004061 BlockScopeRAII Scope(Info);
4062
Richard Smith254a73d2011-10-28 22:34:42 +00004063 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004064 for (const auto *BI : CS->body()) {
4065 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004066 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004067 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004068 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004069 return ESR;
4070 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004071 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004072 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004073
4074 case Stmt::IfStmtClass: {
4075 const IfStmt *IS = cast<IfStmt>(S);
4076
4077 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004078 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004079 if (const Stmt *Init = IS->getInit()) {
4080 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4081 if (ESR != ESR_Succeeded)
4082 return ESR;
4083 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004084 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004085 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004086 return ESR_Failed;
4087
4088 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4089 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4090 if (ESR != ESR_Succeeded)
4091 return ESR;
4092 }
4093 return ESR_Succeeded;
4094 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004095
4096 case Stmt::WhileStmtClass: {
4097 const WhileStmt *WS = cast<WhileStmt>(S);
4098 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004099 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004100 bool Continue;
4101 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4102 Continue))
4103 return ESR_Failed;
4104 if (!Continue)
4105 break;
4106
4107 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4108 if (ESR != ESR_Continue)
4109 return ESR;
4110 }
4111 return ESR_Succeeded;
4112 }
4113
4114 case Stmt::DoStmtClass: {
4115 const DoStmt *DS = cast<DoStmt>(S);
4116 bool Continue;
4117 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004118 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004119 if (ESR != ESR_Continue)
4120 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004121 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004122
Richard Smith08d6a2c2013-07-24 07:11:57 +00004123 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004124 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4125 return ESR_Failed;
4126 } while (Continue);
4127 return ESR_Succeeded;
4128 }
4129
4130 case Stmt::ForStmtClass: {
4131 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004132 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004133 if (FS->getInit()) {
4134 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4135 if (ESR != ESR_Succeeded)
4136 return ESR;
4137 }
4138 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004139 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004140 bool Continue = true;
4141 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4142 FS->getCond(), Continue))
4143 return ESR_Failed;
4144 if (!Continue)
4145 break;
4146
4147 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4148 if (ESR != ESR_Continue)
4149 return ESR;
4150
Richard Smith08d6a2c2013-07-24 07:11:57 +00004151 if (FS->getInc()) {
4152 FullExpressionRAII IncScope(Info);
4153 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4154 return ESR_Failed;
4155 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004156 }
4157 return ESR_Succeeded;
4158 }
4159
Richard Smith896e0d72013-05-06 06:51:17 +00004160 case Stmt::CXXForRangeStmtClass: {
4161 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004162 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004163
4164 // Initialize the __range variable.
4165 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4166 if (ESR != ESR_Succeeded)
4167 return ESR;
4168
4169 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004170 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4171 if (ESR != ESR_Succeeded)
4172 return ESR;
4173 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004174 if (ESR != ESR_Succeeded)
4175 return ESR;
4176
4177 while (true) {
4178 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004179 {
4180 bool Continue = true;
4181 FullExpressionRAII CondExpr(Info);
4182 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4183 return ESR_Failed;
4184 if (!Continue)
4185 break;
4186 }
Richard Smith896e0d72013-05-06 06:51:17 +00004187
4188 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004189 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004190 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4191 if (ESR != ESR_Succeeded)
4192 return ESR;
4193
4194 // Loop body.
4195 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4196 if (ESR != ESR_Continue)
4197 return ESR;
4198
4199 // Increment: ++__begin
4200 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4201 return ESR_Failed;
4202 }
4203
4204 return ESR_Succeeded;
4205 }
4206
Richard Smith496ddcf2013-05-12 17:32:42 +00004207 case Stmt::SwitchStmtClass:
4208 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4209
Richard Smith4e18ca52013-05-06 05:56:11 +00004210 case Stmt::ContinueStmtClass:
4211 return ESR_Continue;
4212
4213 case Stmt::BreakStmtClass:
4214 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004215
4216 case Stmt::LabelStmtClass:
4217 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4218
4219 case Stmt::AttributedStmtClass:
4220 // As a general principle, C++11 attributes can be ignored without
4221 // any semantic impact.
4222 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4223 Case);
4224
4225 case Stmt::CaseStmtClass:
4226 case Stmt::DefaultStmtClass:
4227 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004228 }
4229}
4230
Richard Smithcc36f692011-12-22 02:22:31 +00004231/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4232/// default constructor. If so, we'll fold it whether or not it's marked as
4233/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4234/// so we need special handling.
4235static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004236 const CXXConstructorDecl *CD,
4237 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004238 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4239 return false;
4240
Richard Smith66e05fe2012-01-18 05:21:49 +00004241 // Value-initialization does not call a trivial default constructor, so such a
4242 // call is a core constant expression whether or not the constructor is
4243 // constexpr.
4244 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004245 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004246 // FIXME: If DiagDecl is an implicitly-declared special member function,
4247 // we should be much more explicit about why it's not constexpr.
4248 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4249 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4250 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004251 } else {
4252 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4253 }
4254 }
4255 return true;
4256}
4257
Richard Smith357362d2011-12-13 06:39:58 +00004258/// CheckConstexprFunction - Check that a function can be called in a constant
4259/// expression.
4260static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4261 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004262 const FunctionDecl *Definition,
4263 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004264 // Potential constant expressions can contain calls to declared, but not yet
4265 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004266 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004267 Declaration->isConstexpr())
4268 return false;
4269
Richard Smith0838f3a2013-05-14 05:18:44 +00004270 // Bail out with no diagnostic if the function declaration itself is invalid.
4271 // We will have produced a relevant diagnostic while parsing it.
4272 if (Declaration->isInvalidDecl())
4273 return false;
4274
Richard Smith357362d2011-12-13 06:39:58 +00004275 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004276 if (Definition && Definition->isConstexpr() &&
4277 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004278 return true;
4279
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004280 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004281 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004282
Richard Smith5179eb72016-06-28 19:03:57 +00004283 // If this function is not constexpr because it is an inherited
4284 // non-constexpr constructor, diagnose that directly.
4285 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4286 if (CD && CD->isInheritingConstructor()) {
4287 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004288 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004289 DiagDecl = CD = Inherited;
4290 }
4291
4292 // FIXME: If DiagDecl is an implicitly-declared special member function
4293 // or an inheriting constructor, we should be much more explicit about why
4294 // it's not constexpr.
4295 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004296 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004297 << CD->getInheritedConstructor().getConstructor()->getParent();
4298 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004299 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004300 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004301 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4302 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004303 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004304 }
4305 return false;
4306}
4307
Richard Smithbe6dd812014-11-19 21:27:17 +00004308/// Determine if a class has any fields that might need to be copied by a
4309/// trivial copy or move operation.
4310static bool hasFields(const CXXRecordDecl *RD) {
4311 if (!RD || RD->isEmpty())
4312 return false;
4313 for (auto *FD : RD->fields()) {
4314 if (FD->isUnnamedBitfield())
4315 continue;
4316 return true;
4317 }
4318 for (auto &Base : RD->bases())
4319 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4320 return true;
4321 return false;
4322}
4323
Richard Smithd62306a2011-11-10 06:34:14 +00004324namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004325typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004326}
4327
4328/// EvaluateArgs - Evaluate the arguments to a function call.
4329static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4330 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004331 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004332 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004333 I != E; ++I) {
4334 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4335 // If we're checking for a potential constant expression, evaluate all
4336 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004337 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004338 return false;
4339 Success = false;
4340 }
4341 }
4342 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004343}
4344
Richard Smith254a73d2011-10-28 22:34:42 +00004345/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004346static bool HandleFunctionCall(SourceLocation CallLoc,
4347 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004348 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004349 EvalInfo &Info, APValue &Result,
4350 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004351 ArgVector ArgValues(Args.size());
4352 if (!EvaluateArgs(Args, ArgValues, Info))
4353 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004354
Richard Smith253c2a32012-01-27 01:14:48 +00004355 if (!Info.CheckCallLimit(CallLoc))
4356 return false;
4357
4358 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004359
4360 // For a trivial copy or move assignment, perform an APValue copy. This is
4361 // essential for unions, where the operations performed by the assignment
4362 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004363 //
4364 // Skip this for non-union classes with no fields; in that case, the defaulted
4365 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004366 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004367 if (MD && MD->isDefaulted() &&
4368 (MD->getParent()->isUnion() ||
4369 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004370 assert(This &&
4371 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4372 LValue RHS;
4373 RHS.setFrom(Info.Ctx, ArgValues[0]);
4374 APValue RHSValue;
4375 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4376 RHS, RHSValue))
4377 return false;
4378 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4379 RHSValue))
4380 return false;
4381 This->moveInto(Result);
4382 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004383 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00004384 // We're in a lambda; determine the lambda capture field maps unless we're
4385 // just constexpr checking a lambda's call operator. constexpr checking is
4386 // done before the captures have been added to the closure object (unless
4387 // we're inferring constexpr-ness), so we don't have access to them in this
4388 // case. But since we don't need the captures to constexpr check, we can
4389 // just ignore them.
4390 if (!Info.checkingPotentialConstantExpression())
4391 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4392 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004393 }
4394
Richard Smith52a980a2015-08-28 02:43:42 +00004395 StmtResult Ret = {Result, ResultSlot};
4396 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004397 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004398 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004399 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004400 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004401 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004402 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004403}
4404
Richard Smithd62306a2011-11-10 06:34:14 +00004405/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004406static bool HandleConstructorCall(const Expr *E, const LValue &This,
4407 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004408 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004409 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004410 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004411 if (!Info.CheckCallLimit(CallLoc))
4412 return false;
4413
Richard Smith3607ffe2012-02-13 03:54:03 +00004414 const CXXRecordDecl *RD = Definition->getParent();
4415 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004416 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004417 return false;
4418 }
4419
Erik Pilkington42925492017-10-04 00:18:55 +00004420 EvalInfo::EvaluatingConstructorRAII EvalObj(
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004421 Info, {This.getLValueBase(),
4422 {This.getLValueCallIndex(), This.getLValueVersion()}});
Richard Smith5179eb72016-06-28 19:03:57 +00004423 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004424
Richard Smith52a980a2015-08-28 02:43:42 +00004425 // FIXME: Creating an APValue just to hold a nonexistent return value is
4426 // wasteful.
4427 APValue RetVal;
4428 StmtResult Ret = {RetVal, nullptr};
4429
Richard Smith5179eb72016-06-28 19:03:57 +00004430 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004431 if (Definition->isDelegatingConstructor()) {
4432 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004433 {
4434 FullExpressionRAII InitScope(Info);
4435 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4436 return false;
4437 }
Richard Smith52a980a2015-08-28 02:43:42 +00004438 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004439 }
4440
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004441 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004442 // essential for unions (or classes with anonymous union members), where the
4443 // operations performed by the constructor cannot be represented by
4444 // ctor-initializers.
4445 //
4446 // Skip this for empty non-union classes; we should not perform an
4447 // lvalue-to-rvalue conversion on them because their copy constructor does not
4448 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004449 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004450 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004451 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004452 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004453 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004454 return handleLValueToRValueConversion(
4455 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4456 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004457 }
4458
4459 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004460 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004461 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004462 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004463
John McCalld7bca762012-05-01 00:38:49 +00004464 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004465 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4466
Richard Smith08d6a2c2013-07-24 07:11:57 +00004467 // A scope for temporaries lifetime-extended by reference members.
4468 BlockScopeRAII LifetimeExtendedScope(Info);
4469
Richard Smith253c2a32012-01-27 01:14:48 +00004470 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004471 unsigned BasesSeen = 0;
4472#ifndef NDEBUG
4473 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4474#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004475 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004476 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004477 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004478 APValue *Value = &Result;
4479
4480 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004481 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004482 if (I->isBaseInitializer()) {
4483 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004484#ifndef NDEBUG
4485 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004486 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004487 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4488 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4489 "base class initializers not in expected order");
4490 ++BaseIt;
4491#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004492 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004493 BaseType->getAsCXXRecordDecl(), &Layout))
4494 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004495 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004496 } else if ((FD = I->getMember())) {
4497 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004498 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004499 if (RD->isUnion()) {
4500 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004501 Value = &Result.getUnionValue();
4502 } else {
4503 Value = &Result.getStructField(FD->getFieldIndex());
4504 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004505 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004506 // Walk the indirect field decl's chain to find the object to initialize,
4507 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004508 auto IndirectFieldChain = IFD->chain();
4509 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004510 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004511 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4512 // Switch the union field if it differs. This happens if we had
4513 // preceding zero-initialization, and we're now initializing a union
4514 // subobject other than the first.
4515 // FIXME: In this case, the values of the other subobjects are
4516 // specified, since zero-initialization sets all padding bits to zero.
4517 if (Value->isUninit() ||
4518 (Value->isUnion() && Value->getUnionField() != FD)) {
4519 if (CD->isUnion())
4520 *Value = APValue(FD);
4521 else
4522 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004523 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004524 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004525 // Store Subobject as its parent before updating it for the last element
4526 // in the chain.
4527 if (C == IndirectFieldChain.back())
4528 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004529 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004530 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004531 if (CD->isUnion())
4532 Value = &Value->getUnionValue();
4533 else
4534 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004535 }
Richard Smithd62306a2011-11-10 06:34:14 +00004536 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004537 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004538 }
Richard Smith253c2a32012-01-27 01:14:48 +00004539
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004540 // Need to override This for implicit field initializers as in this case
4541 // This refers to innermost anonymous struct/union containing initializer,
4542 // not to currently constructed class.
4543 const Expr *Init = I->getInit();
4544 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4545 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004546 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004547 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4548 (FD && FD->isBitField() &&
4549 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004550 // If we're checking for a potential constant expression, evaluate all
4551 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004552 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004553 return false;
4554 Success = false;
4555 }
Richard Smithd62306a2011-11-10 06:34:14 +00004556 }
4557
Richard Smithd9f663b2013-04-22 15:31:51 +00004558 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004559 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004560}
4561
Richard Smith5179eb72016-06-28 19:03:57 +00004562static bool HandleConstructorCall(const Expr *E, const LValue &This,
4563 ArrayRef<const Expr*> Args,
4564 const CXXConstructorDecl *Definition,
4565 EvalInfo &Info, APValue &Result) {
4566 ArgVector ArgValues(Args.size());
4567 if (!EvaluateArgs(Args, ArgValues, Info))
4568 return false;
4569
4570 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4571 Info, Result);
4572}
4573
Eli Friedman9a156e52008-11-12 09:44:48 +00004574//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004575// Generic Evaluation
4576//===----------------------------------------------------------------------===//
4577namespace {
4578
Aaron Ballman68af21c2014-01-03 19:26:43 +00004579template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004580class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004581 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004582private:
Richard Smith52a980a2015-08-28 02:43:42 +00004583 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004584 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004585 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004586 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004587 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004588 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004589 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004590
Richard Smith17100ba2012-02-16 02:46:34 +00004591 // Check whether a conditional operator with a non-constant condition is a
4592 // potential constant expression. If neither arm is a potential constant
4593 // expression, then the conditional operator is not either.
4594 template<typename ConditionalOperator>
4595 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004596 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004597
4598 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004599 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004600 {
Richard Smith17100ba2012-02-16 02:46:34 +00004601 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004602 StmtVisitorTy::Visit(E->getFalseExpr());
4603 if (Diag.empty())
4604 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004605 }
Richard Smith17100ba2012-02-16 02:46:34 +00004606
George Burgess IV8c892b52016-05-25 22:31:54 +00004607 {
4608 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004609 Diag.clear();
4610 StmtVisitorTy::Visit(E->getTrueExpr());
4611 if (Diag.empty())
4612 return;
4613 }
4614
4615 Error(E, diag::note_constexpr_conditional_never_const);
4616 }
4617
4618
4619 template<typename ConditionalOperator>
4620 bool HandleConditionalOperator(const ConditionalOperator *E) {
4621 bool BoolResult;
4622 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004623 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004624 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004625 return false;
4626 }
4627 if (Info.noteFailure()) {
4628 StmtVisitorTy::Visit(E->getTrueExpr());
4629 StmtVisitorTy::Visit(E->getFalseExpr());
4630 }
Richard Smith17100ba2012-02-16 02:46:34 +00004631 return false;
4632 }
4633
4634 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4635 return StmtVisitorTy::Visit(EvalExpr);
4636 }
4637
Peter Collingbournee9200682011-05-13 03:29:01 +00004638protected:
4639 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004640 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004641 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4642
Richard Smith92b1ce02011-12-12 09:28:41 +00004643 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004644 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004645 }
4646
Aaron Ballman68af21c2014-01-03 19:26:43 +00004647 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004648
4649public:
4650 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4651
4652 EvalInfo &getEvalInfo() { return Info; }
4653
Richard Smithf57d8cb2011-12-09 22:58:01 +00004654 /// Report an evaluation error. This should only be called when an error is
4655 /// first discovered. When propagating an error, just return false.
4656 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004657 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004658 return false;
4659 }
4660 bool Error(const Expr *E) {
4661 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4662 }
4663
Aaron Ballman68af21c2014-01-03 19:26:43 +00004664 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004665 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004666 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004667 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004668 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004669 }
4670
Aaron Ballman68af21c2014-01-03 19:26:43 +00004671 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004672 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004673 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004674 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004675 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004676 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004677 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004678 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004679 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004680 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004681 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004682 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004683 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4684 TempVersionRAII RAII(*Info.CurrentCall);
4685 return StmtVisitorTy::Visit(E->getExpr());
4686 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004687 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004688 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00004689 // The initializer may not have been parsed yet, or might be erroneous.
4690 if (!E->getExpr())
4691 return Error(E);
4692 return StmtVisitorTy::Visit(E->getExpr());
4693 }
Richard Smith5894a912011-12-19 22:12:41 +00004694 // We cannot create any objects for which cleanups are required, so there is
4695 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004696 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004697 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004698
Aaron Ballman68af21c2014-01-03 19:26:43 +00004699 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004700 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4701 return static_cast<Derived*>(this)->VisitCastExpr(E);
4702 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004703 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004704 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4705 return static_cast<Derived*>(this)->VisitCastExpr(E);
4706 }
4707
Aaron Ballman68af21c2014-01-03 19:26:43 +00004708 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004709 switch (E->getOpcode()) {
4710 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004711 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004712
4713 case BO_Comma:
4714 VisitIgnoredValue(E->getLHS());
4715 return StmtVisitorTy::Visit(E->getRHS());
4716
4717 case BO_PtrMemD:
4718 case BO_PtrMemI: {
4719 LValue Obj;
4720 if (!HandleMemberPointerAccess(Info, E, Obj))
4721 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004722 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004723 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004724 return false;
4725 return DerivedSuccess(Result, E);
4726 }
4727 }
4728 }
4729
Aaron Ballman68af21c2014-01-03 19:26:43 +00004730 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004731 // Evaluate and cache the common expression. We treat it as a temporary,
4732 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004733 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004734 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004735 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004736
Richard Smith17100ba2012-02-16 02:46:34 +00004737 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004738 }
4739
Aaron Ballman68af21c2014-01-03 19:26:43 +00004740 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004741 bool IsBcpCall = false;
4742 // If the condition (ignoring parens) is a __builtin_constant_p call,
4743 // the result is a constant expression if it can be folded without
4744 // side-effects. This is an important GNU extension. See GCC PR38377
4745 // for discussion.
4746 if (const CallExpr *CallCE =
4747 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004748 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004749 IsBcpCall = true;
4750
4751 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4752 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004753 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004754 return false;
4755
Richard Smith6d4c6582013-11-05 22:18:15 +00004756 FoldConstant Fold(Info, IsBcpCall);
4757 if (!HandleConditionalOperator(E)) {
4758 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004759 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004760 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004761
4762 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004763 }
4764
Aaron Ballman68af21c2014-01-03 19:26:43 +00004765 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004766 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00004767 return DerivedSuccess(*Value, E);
4768
4769 const Expr *Source = E->getSourceExpr();
4770 if (!Source)
4771 return Error(E);
4772 if (Source == E) { // sanity checking.
4773 assert(0 && "OpaqueValueExpr recursively refers to itself");
4774 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004775 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004776 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004777 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004778
Aaron Ballman68af21c2014-01-03 19:26:43 +00004779 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004780 APValue Result;
4781 if (!handleCallExpr(E, Result, nullptr))
4782 return false;
4783 return DerivedSuccess(Result, E);
4784 }
4785
4786 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004787 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004788 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004789 QualType CalleeType = Callee->getType();
4790
Craig Topper36250ad2014-05-12 05:36:57 +00004791 const FunctionDecl *FD = nullptr;
4792 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004793 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004794 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004795
Richard Smithe97cbd72011-11-11 04:05:33 +00004796 // Extract function decl and 'this' pointer from the callee.
4797 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004798 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004799 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4800 // Explicit bound member calls, such as x.f() or p->g();
4801 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004802 return false;
4803 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004804 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004805 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004806 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4807 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004808 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4809 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004810 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004811 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004812 return Error(Callee);
4813
4814 FD = dyn_cast<FunctionDecl>(Member);
4815 if (!FD)
4816 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004817 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004818 LValue Call;
4819 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004820 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004821
Richard Smitha8105bc2012-01-06 16:39:00 +00004822 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004823 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004824 FD = dyn_cast_or_null<FunctionDecl>(
4825 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004826 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004827 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004828 // Don't call function pointers which have been cast to some other type.
4829 // Per DR (no number yet), the caller and callee can differ in noexcept.
4830 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4831 CalleeType->getPointeeType(), FD->getType())) {
4832 return Error(E);
4833 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004834
4835 // Overloaded operator calls to member functions are represented as normal
4836 // calls with '*this' as the first argument.
4837 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4838 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004839 // FIXME: When selecting an implicit conversion for an overloaded
4840 // operator delete, we sometimes try to evaluate calls to conversion
4841 // operators without a 'this' parameter!
4842 if (Args.empty())
4843 return Error(E);
4844
Nick Lewycky13073a62017-06-12 21:15:44 +00004845 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004846 return false;
4847 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004848 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004849 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004850 // Map the static invoker for the lambda back to the call operator.
4851 // Conveniently, we don't have to slice out the 'this' argument (as is
4852 // being done for the non-static case), since a static member function
4853 // doesn't have an implicit argument passed in.
4854 const CXXRecordDecl *ClosureClass = MD->getParent();
4855 assert(
4856 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4857 "Number of captures must be zero for conversion to function-ptr");
4858
4859 const CXXMethodDecl *LambdaCallOp =
4860 ClosureClass->getLambdaCallOperator();
4861
4862 // Set 'FD', the function that will be called below, to the call
4863 // operator. If the closure object represents a generic lambda, find
4864 // the corresponding specialization of the call operator.
4865
4866 if (ClosureClass->isGenericLambda()) {
4867 assert(MD->isFunctionTemplateSpecialization() &&
4868 "A generic lambda's static-invoker function must be a "
4869 "template specialization");
4870 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4871 FunctionTemplateDecl *CallOpTemplate =
4872 LambdaCallOp->getDescribedFunctionTemplate();
4873 void *InsertPos = nullptr;
4874 FunctionDecl *CorrespondingCallOpSpecialization =
4875 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4876 assert(CorrespondingCallOpSpecialization &&
4877 "We must always have a function call operator specialization "
4878 "that corresponds to our static invoker specialization");
4879 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4880 } else
4881 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004882 }
4883
Daniel Jasperffdee092017-05-02 19:21:42 +00004884
Richard Smithe97cbd72011-11-11 04:05:33 +00004885 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004886 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004887
Richard Smith47b34932012-02-01 02:39:43 +00004888 if (This && !This->checkSubobject(Info, E, CSK_This))
4889 return false;
4890
Richard Smith3607ffe2012-02-13 03:54:03 +00004891 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4892 // calls to such functions in constant expressions.
4893 if (This && !HasQualifier &&
4894 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4895 return Error(E, diag::note_constexpr_virtual_call);
4896
Craig Topper36250ad2014-05-12 05:36:57 +00004897 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004898 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004899
Nick Lewycky13073a62017-06-12 21:15:44 +00004900 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4901 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004902 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004903 return false;
4904
Richard Smith52a980a2015-08-28 02:43:42 +00004905 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004906 }
4907
Aaron Ballman68af21c2014-01-03 19:26:43 +00004908 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004909 return StmtVisitorTy::Visit(E->getInitializer());
4910 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004911 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004912 if (E->getNumInits() == 0)
4913 return DerivedZeroInitialization(E);
4914 if (E->getNumInits() == 1)
4915 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004916 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004917 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004918 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004919 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004920 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004921 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004922 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004923 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004924 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004925 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004926 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004927
Richard Smithd62306a2011-11-10 06:34:14 +00004928 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004929 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004930 assert(!E->isArrow() && "missing call to bound member function?");
4931
Richard Smith2e312c82012-03-03 22:46:17 +00004932 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004933 if (!Evaluate(Val, Info, E->getBase()))
4934 return false;
4935
4936 QualType BaseTy = E->getBase()->getType();
4937
4938 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004939 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004940 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004941 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004942 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4943
Richard Smith9defb7d2018-02-21 03:38:30 +00004944 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00004945 SubobjectDesignator Designator(BaseTy);
4946 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004947
Richard Smith3229b742013-05-05 21:17:10 +00004948 APValue Result;
4949 return extractSubobject(Info, E, Obj, Designator, Result) &&
4950 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004951 }
4952
Aaron Ballman68af21c2014-01-03 19:26:43 +00004953 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004954 switch (E->getCastKind()) {
4955 default:
4956 break;
4957
Richard Smitha23ab512013-05-23 00:30:41 +00004958 case CK_AtomicToNonAtomic: {
4959 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004960 // This does not need to be done in place even for class/array types:
4961 // atomic-to-non-atomic conversion implies copying the object
4962 // representation.
4963 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004964 return false;
4965 return DerivedSuccess(AtomicVal, E);
4966 }
4967
Richard Smith11562c52011-10-28 17:51:58 +00004968 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004969 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004970 return StmtVisitorTy::Visit(E->getSubExpr());
4971
4972 case CK_LValueToRValue: {
4973 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004974 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4975 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004976 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004977 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004978 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004979 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004980 return false;
4981 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004982 }
4983 }
4984
Richard Smithf57d8cb2011-12-09 22:58:01 +00004985 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004986 }
4987
Aaron Ballman68af21c2014-01-03 19:26:43 +00004988 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004989 return VisitUnaryPostIncDec(UO);
4990 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004991 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004992 return VisitUnaryPostIncDec(UO);
4993 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004994 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004995 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004996 return Error(UO);
4997
4998 LValue LVal;
4999 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5000 return false;
5001 APValue RVal;
5002 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5003 UO->isIncrementOp(), &RVal))
5004 return false;
5005 return DerivedSuccess(RVal, UO);
5006 }
5007
Aaron Ballman68af21c2014-01-03 19:26:43 +00005008 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005009 // We will have checked the full-expressions inside the statement expression
5010 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005011 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005012 return Error(E);
5013
Richard Smith08d6a2c2013-07-24 07:11:57 +00005014 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005015 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005016 if (CS->body_empty())
5017 return true;
5018
Richard Smith51f03172013-06-20 03:00:05 +00005019 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5020 BE = CS->body_end();
5021 /**/; ++BI) {
5022 if (BI + 1 == BE) {
5023 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5024 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005025 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00005026 diag::note_constexpr_stmt_expr_unsupported);
5027 return false;
5028 }
5029 return this->Visit(FinalExpr);
5030 }
5031
5032 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005033 StmtResult Result = { ReturnValue, nullptr };
5034 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005035 if (ESR != ESR_Succeeded) {
5036 // FIXME: If the statement-expression terminated due to 'return',
5037 // 'break', or 'continue', it would be nice to propagate that to
5038 // the outer statement evaluation rather than bailing out.
5039 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00005040 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00005041 diag::note_constexpr_stmt_expr_unsupported);
5042 return false;
5043 }
5044 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005045
5046 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005047 }
5048
Richard Smith4a678122011-10-24 18:44:57 +00005049 /// Visit a value which is evaluated, but whose value is ignored.
5050 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005051 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005052 }
David Majnemere9807b22016-02-26 04:23:19 +00005053
5054 /// Potentially visit a MemberExpr's base expression.
5055 void VisitIgnoredBaseExpression(const Expr *E) {
5056 // While MSVC doesn't evaluate the base expression, it does diagnose the
5057 // presence of side-effecting behavior.
5058 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5059 return;
5060 VisitIgnoredValue(E);
5061 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005062};
5063
Eric Fiselier0683c0e2018-05-07 21:07:10 +00005064} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00005065
5066//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005067// Common base class for lvalue and temporary evaluation.
5068//===----------------------------------------------------------------------===//
5069namespace {
5070template<class Derived>
5071class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005072 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005073protected:
5074 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005075 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005076 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005077 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005078
5079 bool Success(APValue::LValueBase B) {
5080 Result.set(B);
5081 return true;
5082 }
5083
George Burgess IVf9013bf2017-02-10 22:52:29 +00005084 bool evaluatePointer(const Expr *E, LValue &Result) {
5085 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5086 }
5087
Richard Smith027bf112011-11-17 22:56:20 +00005088public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005089 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5090 : ExprEvaluatorBaseTy(Info), Result(Result),
5091 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005092
Richard Smith2e312c82012-03-03 22:46:17 +00005093 bool Success(const APValue &V, const Expr *E) {
5094 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005095 return true;
5096 }
Richard Smith027bf112011-11-17 22:56:20 +00005097
Richard Smith027bf112011-11-17 22:56:20 +00005098 bool VisitMemberExpr(const MemberExpr *E) {
5099 // Handle non-static data members.
5100 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005101 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005102 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005103 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005104 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005105 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005106 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005107 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005108 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005109 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005110 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005111 BaseTy = E->getBase()->getType();
5112 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005113 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005114 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005115 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005116 Result.setInvalid(E);
5117 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005118 }
Richard Smith027bf112011-11-17 22:56:20 +00005119
Richard Smith1b78b3d2012-01-25 22:15:11 +00005120 const ValueDecl *MD = E->getMemberDecl();
5121 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5122 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5123 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5124 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005125 if (!HandleLValueMember(this->Info, E, Result, FD))
5126 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005127 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005128 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5129 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005130 } else
5131 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005132
Richard Smith1b78b3d2012-01-25 22:15:11 +00005133 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005134 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005135 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005136 RefValue))
5137 return false;
5138 return Success(RefValue, E);
5139 }
5140 return true;
5141 }
5142
5143 bool VisitBinaryOperator(const BinaryOperator *E) {
5144 switch (E->getOpcode()) {
5145 default:
5146 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5147
5148 case BO_PtrMemD:
5149 case BO_PtrMemI:
5150 return HandleMemberPointerAccess(this->Info, E, Result);
5151 }
5152 }
5153
5154 bool VisitCastExpr(const CastExpr *E) {
5155 switch (E->getCastKind()) {
5156 default:
5157 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5158
5159 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005160 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005161 if (!this->Visit(E->getSubExpr()))
5162 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005163
5164 // Now figure out the necessary offset to add to the base LV to get from
5165 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005166 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5167 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005168 }
5169 }
5170};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005171}
Richard Smith027bf112011-11-17 22:56:20 +00005172
5173//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005174// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005175//
5176// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5177// function designators (in C), decl references to void objects (in C), and
5178// temporaries (if building with -Wno-address-of-temporary).
5179//
5180// LValue evaluation produces values comprising a base expression of one of the
5181// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005182// - Declarations
5183// * VarDecl
5184// * FunctionDecl
5185// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005186// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005187// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005188// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005189// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005190// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005191// * ObjCEncodeExpr
5192// * AddrLabelExpr
5193// * BlockExpr
5194// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005195// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005196// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005197// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005198// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5199// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005200// * A MaterializeTemporaryExpr that has static storage duration, with no
5201// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005202// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005203//===----------------------------------------------------------------------===//
5204namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005205class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005206 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005207public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005208 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5209 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005210
Richard Smith11562c52011-10-28 17:51:58 +00005211 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005212 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005213
Peter Collingbournee9200682011-05-13 03:29:01 +00005214 bool VisitDeclRefExpr(const DeclRefExpr *E);
5215 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005216 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005217 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5218 bool VisitMemberExpr(const MemberExpr *E);
5219 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5220 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005221 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005222 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005223 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5224 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005225 bool VisitUnaryReal(const UnaryOperator *E);
5226 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005227 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5228 return VisitUnaryPreIncDec(UO);
5229 }
5230 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5231 return VisitUnaryPreIncDec(UO);
5232 }
Richard Smith3229b742013-05-05 21:17:10 +00005233 bool VisitBinAssign(const BinaryOperator *BO);
5234 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005235
Peter Collingbournee9200682011-05-13 03:29:01 +00005236 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005237 switch (E->getCastKind()) {
5238 default:
Richard Smith027bf112011-11-17 22:56:20 +00005239 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005240
Eli Friedmance3e02a2011-10-11 00:13:24 +00005241 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005242 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005243 if (!Visit(E->getSubExpr()))
5244 return false;
5245 Result.Designator.setInvalid();
5246 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005247
Richard Smith027bf112011-11-17 22:56:20 +00005248 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005249 if (!Visit(E->getSubExpr()))
5250 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005251 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005252 }
5253 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005254};
5255} // end anonymous namespace
5256
Richard Smith11562c52011-10-28 17:51:58 +00005257/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005258/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005259/// * function designators in C, and
5260/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005261/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005262static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5263 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005264 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005265 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005266 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005267}
5268
Peter Collingbournee9200682011-05-13 03:29:01 +00005269bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005270 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005271 return Success(FD);
5272 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005273 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005274 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005275 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005276 return Error(E);
5277}
Richard Smith733237d2011-10-24 23:14:33 +00005278
Faisal Vali0528a312016-11-13 06:09:16 +00005279
Richard Smith11562c52011-10-28 17:51:58 +00005280bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005281
5282 // If we are within a lambda's call operator, check whether the 'VD' referred
5283 // to within 'E' actually represents a lambda-capture that maps to a
5284 // data-member/field within the closure object, and if so, evaluate to the
5285 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00005286 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5287 isa<DeclRefExpr>(E) &&
5288 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5289 // We don't always have a complete capture-map when checking or inferring if
5290 // the function call operator meets the requirements of a constexpr function
5291 // - but we don't need to evaluate the captures to determine constexprness
5292 // (dcl.constexpr C++17).
5293 if (Info.checkingPotentialConstantExpression())
5294 return false;
5295
Faisal Vali051e3a22017-02-16 04:12:21 +00005296 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005297 // Start with 'Result' referring to the complete closure object...
5298 Result = *Info.CurrentCall->This;
5299 // ... then update it to refer to the field of the closure object
5300 // that represents the capture.
5301 if (!HandleLValueMember(Info, E, Result, FD))
5302 return false;
5303 // And if the field is of reference type, update 'Result' to refer to what
5304 // the field refers to.
5305 if (FD->getType()->isReferenceType()) {
5306 APValue RVal;
5307 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5308 RVal))
5309 return false;
5310 Result.setFrom(Info.Ctx, RVal);
5311 }
5312 return true;
5313 }
5314 }
Craig Topper36250ad2014-05-12 05:36:57 +00005315 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005316 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5317 // Only if a local variable was declared in the function currently being
5318 // evaluated, do we expect to be able to find its value in the current
5319 // frame. (Otherwise it was likely declared in an enclosing context and
5320 // could either have a valid evaluatable value (for e.g. a constexpr
5321 // variable) or be ill-formed (and trigger an appropriate evaluation
5322 // diagnostic)).
5323 if (Info.CurrentCall->Callee &&
5324 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5325 Frame = Info.CurrentCall;
5326 }
5327 }
Richard Smith3229b742013-05-05 21:17:10 +00005328
Richard Smithfec09922011-11-01 16:57:24 +00005329 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005330 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005331 Result.set({VD, Frame->Index,
5332 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00005333 return true;
5334 }
Richard Smithce40ad62011-11-12 22:28:03 +00005335 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005336 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005337
Richard Smith3229b742013-05-05 21:17:10 +00005338 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005339 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005340 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005341 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005342 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005343 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005344 return false;
5345 }
Richard Smith3229b742013-05-05 21:17:10 +00005346 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005347}
5348
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005349bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5350 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005351 // Walk through the expression to find the materialized temporary itself.
5352 SmallVector<const Expr *, 2> CommaLHSs;
5353 SmallVector<SubobjectAdjustment, 2> Adjustments;
5354 const Expr *Inner = E->GetTemporaryExpr()->
5355 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005356
Richard Smith84401042013-06-03 05:03:02 +00005357 // If we passed any comma operators, evaluate their LHSs.
5358 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5359 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5360 return false;
5361
Richard Smithe6c01442013-06-05 00:46:14 +00005362 // A materialized temporary with static storage duration can appear within the
5363 // result of a constant expression evaluation, so we need to preserve its
5364 // value for use outside this evaluation.
5365 APValue *Value;
5366 if (E->getStorageDuration() == SD_Static) {
5367 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005368 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005369 Result.set(E);
5370 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005371 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5372 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00005373 }
5374
Richard Smithea4ad5d2013-06-06 08:19:16 +00005375 QualType Type = Inner->getType();
5376
Richard Smith84401042013-06-03 05:03:02 +00005377 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005378 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5379 (E->getStorageDuration() == SD_Static &&
5380 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5381 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005382 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005383 }
Richard Smith84401042013-06-03 05:03:02 +00005384
5385 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005386 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5387 --I;
5388 switch (Adjustments[I].Kind) {
5389 case SubobjectAdjustment::DerivedToBaseAdjustment:
5390 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5391 Type, Result))
5392 return false;
5393 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5394 break;
5395
5396 case SubobjectAdjustment::FieldAdjustment:
5397 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5398 return false;
5399 Type = Adjustments[I].Field->getType();
5400 break;
5401
5402 case SubobjectAdjustment::MemberPointerAdjustment:
5403 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5404 Adjustments[I].Ptr.RHS))
5405 return false;
5406 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5407 break;
5408 }
5409 }
5410
5411 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005412}
5413
Peter Collingbournee9200682011-05-13 03:29:01 +00005414bool
5415LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005416 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5417 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005418 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5419 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005420 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005421}
5422
Richard Smith6e525142011-12-27 12:18:28 +00005423bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005424 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005425 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005426
Faisal Valie690b7a2016-07-02 22:34:24 +00005427 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005428 << E->getExprOperand()->getType()
5429 << E->getExprOperand()->getSourceRange();
5430 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005431}
5432
Francois Pichet0066db92012-04-16 04:08:35 +00005433bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5434 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005435}
Francois Pichet0066db92012-04-16 04:08:35 +00005436
Peter Collingbournee9200682011-05-13 03:29:01 +00005437bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005438 // Handle static data members.
5439 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005440 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005441 return VisitVarDecl(E, VD);
5442 }
5443
Richard Smith254a73d2011-10-28 22:34:42 +00005444 // Handle static member functions.
5445 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5446 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005447 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005448 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005449 }
5450 }
5451
Richard Smithd62306a2011-11-10 06:34:14 +00005452 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005453 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005454}
5455
Peter Collingbournee9200682011-05-13 03:29:01 +00005456bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005457 // FIXME: Deal with vectors as array subscript bases.
5458 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005459 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005460
Nick Lewyckyad888682017-04-27 07:27:36 +00005461 bool Success = true;
5462 if (!evaluatePointer(E->getBase(), Result)) {
5463 if (!Info.noteFailure())
5464 return false;
5465 Success = false;
5466 }
Mike Stump11289f42009-09-09 15:08:12 +00005467
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005468 APSInt Index;
5469 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005470 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005471
Nick Lewyckyad888682017-04-27 07:27:36 +00005472 return Success &&
5473 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005474}
Eli Friedman9a156e52008-11-12 09:44:48 +00005475
Peter Collingbournee9200682011-05-13 03:29:01 +00005476bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005477 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005478}
5479
Richard Smith66c96992012-02-18 22:04:06 +00005480bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5481 if (!Visit(E->getSubExpr()))
5482 return false;
5483 // __real is a no-op on scalar lvalues.
5484 if (E->getSubExpr()->getType()->isAnyComplexType())
5485 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5486 return true;
5487}
5488
5489bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5490 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5491 "lvalue __imag__ on scalar?");
5492 if (!Visit(E->getSubExpr()))
5493 return false;
5494 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5495 return true;
5496}
5497
Richard Smith243ef902013-05-05 23:31:59 +00005498bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005499 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005500 return Error(UO);
5501
5502 if (!this->Visit(UO->getSubExpr()))
5503 return false;
5504
Richard Smith243ef902013-05-05 23:31:59 +00005505 return handleIncDec(
5506 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005507 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005508}
5509
5510bool LValueExprEvaluator::VisitCompoundAssignOperator(
5511 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005512 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005513 return Error(CAO);
5514
Richard Smith3229b742013-05-05 21:17:10 +00005515 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005516
5517 // The overall lvalue result is the result of evaluating the LHS.
5518 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005519 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005520 Evaluate(RHS, this->Info, CAO->getRHS());
5521 return false;
5522 }
5523
Richard Smith3229b742013-05-05 21:17:10 +00005524 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5525 return false;
5526
Richard Smith43e77732013-05-07 04:50:00 +00005527 return handleCompoundAssignment(
5528 this->Info, CAO,
5529 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5530 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005531}
5532
5533bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005534 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005535 return Error(E);
5536
Richard Smith3229b742013-05-05 21:17:10 +00005537 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005538
5539 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005540 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005541 Evaluate(NewVal, this->Info, E->getRHS());
5542 return false;
5543 }
5544
Richard Smith3229b742013-05-05 21:17:10 +00005545 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5546 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005547
5548 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005549 NewVal);
5550}
5551
Eli Friedman9a156e52008-11-12 09:44:48 +00005552//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005553// Pointer Evaluation
5554//===----------------------------------------------------------------------===//
5555
George Burgess IVe3763372016-12-22 02:50:20 +00005556/// \brief Attempts to compute the number of bytes available at the pointer
5557/// returned by a function with the alloc_size attribute. Returns true if we
5558/// were successful. Places an unsigned number into `Result`.
5559///
5560/// This expects the given CallExpr to be a call to a function with an
5561/// alloc_size attribute.
5562static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5563 const CallExpr *Call,
5564 llvm::APInt &Result) {
5565 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5566
Joel E. Denny81508102018-03-13 14:51:22 +00005567 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5568 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005569 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5570 if (Call->getNumArgs() <= SizeArgNo)
5571 return false;
5572
5573 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5574 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5575 return false;
5576 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5577 return false;
5578 Into = Into.zextOrSelf(BitsInSizeT);
5579 return true;
5580 };
5581
5582 APSInt SizeOfElem;
5583 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5584 return false;
5585
Joel E. Denny81508102018-03-13 14:51:22 +00005586 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005587 Result = std::move(SizeOfElem);
5588 return true;
5589 }
5590
5591 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00005592 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005593 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5594 return false;
5595
5596 bool Overflow;
5597 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5598 if (Overflow)
5599 return false;
5600
5601 Result = std::move(BytesAvailable);
5602 return true;
5603}
5604
5605/// \brief Convenience function. LVal's base must be a call to an alloc_size
5606/// function.
5607static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5608 const LValue &LVal,
5609 llvm::APInt &Result) {
5610 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5611 "Can't get the size of a non alloc_size function");
5612 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5613 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5614 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5615}
5616
5617/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5618/// a function with the alloc_size attribute. If it was possible to do so, this
5619/// function will return true, make Result's Base point to said function call,
5620/// and mark Result's Base as invalid.
5621static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5622 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005623 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005624 return false;
5625
5626 // Because we do no form of static analysis, we only support const variables.
5627 //
5628 // Additionally, we can't support parameters, nor can we support static
5629 // variables (in the latter case, use-before-assign isn't UB; in the former,
5630 // we have no clue what they'll be assigned to).
5631 const auto *VD =
5632 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5633 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5634 return false;
5635
5636 const Expr *Init = VD->getAnyInitializer();
5637 if (!Init)
5638 return false;
5639
5640 const Expr *E = Init->IgnoreParens();
5641 if (!tryUnwrapAllocSizeCall(E))
5642 return false;
5643
5644 // Store E instead of E unwrapped so that the type of the LValue's base is
5645 // what the user wanted.
5646 Result.setInvalid(E);
5647
5648 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005649 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005650 return true;
5651}
5652
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005653namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005654class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005655 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005656 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005657 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005658
Peter Collingbournee9200682011-05-13 03:29:01 +00005659 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005660 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005661 return true;
5662 }
George Burgess IVe3763372016-12-22 02:50:20 +00005663
George Burgess IVf9013bf2017-02-10 22:52:29 +00005664 bool evaluateLValue(const Expr *E, LValue &Result) {
5665 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5666 }
5667
5668 bool evaluatePointer(const Expr *E, LValue &Result) {
5669 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5670 }
5671
George Burgess IVe3763372016-12-22 02:50:20 +00005672 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005673public:
Mike Stump11289f42009-09-09 15:08:12 +00005674
George Burgess IVf9013bf2017-02-10 22:52:29 +00005675 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5676 : ExprEvaluatorBaseTy(info), Result(Result),
5677 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005678
Richard Smith2e312c82012-03-03 22:46:17 +00005679 bool Success(const APValue &V, const Expr *E) {
5680 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005681 return true;
5682 }
Richard Smithfddd3842011-12-30 21:15:51 +00005683 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005684 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5685 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005686 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005687 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005688
John McCall45d55e42010-05-07 21:00:08 +00005689 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005690 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005691 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005692 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005693 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005694 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5695 if (Info.noteFailure())
5696 EvaluateIgnoredValue(Info, E->getSubExpr());
5697 return Error(E);
5698 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005699 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005700 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005701 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005702 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005703 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005704 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005705 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005706 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005707 }
Richard Smithd62306a2011-11-10 06:34:14 +00005708 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005709 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005710 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005711 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005712 if (!Info.CurrentCall->This) {
5713 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005714 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005715 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005716 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005717 return false;
5718 }
Richard Smithd62306a2011-11-10 06:34:14 +00005719 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005720 // If we are inside a lambda's call operator, the 'this' expression refers
5721 // to the enclosing '*this' object (either by value or reference) which is
5722 // either copied into the closure object's field that represents the '*this'
5723 // or refers to '*this'.
5724 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5725 // Update 'Result' to refer to the data member/field of the closure object
5726 // that represents the '*this' capture.
5727 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005728 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005729 return false;
5730 // If we captured '*this' by reference, replace the field with its referent.
5731 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5732 ->isPointerType()) {
5733 APValue RVal;
5734 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5735 RVal))
5736 return false;
5737
5738 Result.setFrom(Info.Ctx, RVal);
5739 }
5740 }
Richard Smithd62306a2011-11-10 06:34:14 +00005741 return true;
5742 }
John McCallc07a0c72011-02-17 10:25:35 +00005743
Eli Friedman449fe542009-03-23 04:56:01 +00005744 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005745};
Chris Lattner05706e882008-07-11 18:11:29 +00005746} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005747
George Burgess IVf9013bf2017-02-10 22:52:29 +00005748static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5749 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005750 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005751 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005752}
5753
John McCall45d55e42010-05-07 21:00:08 +00005754bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005755 if (E->getOpcode() != BO_Add &&
5756 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005757 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005758
Chris Lattner05706e882008-07-11 18:11:29 +00005759 const Expr *PExp = E->getLHS();
5760 const Expr *IExp = E->getRHS();
5761 if (IExp->getType()->isPointerType())
5762 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005763
George Burgess IVf9013bf2017-02-10 22:52:29 +00005764 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005765 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005766 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005767
John McCall45d55e42010-05-07 21:00:08 +00005768 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005769 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005770 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005771
Richard Smith96e0c102011-11-04 02:25:55 +00005772 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005773 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005774
Ted Kremenek28831752012-08-23 20:46:57 +00005775 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005776 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005777}
Eli Friedman9a156e52008-11-12 09:44:48 +00005778
John McCall45d55e42010-05-07 21:00:08 +00005779bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005780 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005781}
Mike Stump11289f42009-09-09 15:08:12 +00005782
Peter Collingbournee9200682011-05-13 03:29:01 +00005783bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5784 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005785
Eli Friedman847a2bc2009-12-27 05:43:15 +00005786 switch (E->getCastKind()) {
5787 default:
5788 break;
5789
John McCalle3027922010-08-25 11:45:40 +00005790 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005791 case CK_CPointerToObjCPointerCast:
5792 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005793 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005794 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005795 if (!Visit(SubExpr))
5796 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005797 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5798 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5799 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005800 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005801 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005802 if (SubExpr->getType()->isVoidPointerType())
5803 CCEDiag(E, diag::note_constexpr_invalid_cast)
5804 << 3 << SubExpr->getType();
5805 else
5806 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5807 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005808 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5809 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005810 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005811
Anders Carlsson18275092010-10-31 20:41:46 +00005812 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005813 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005814 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005815 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005816 if (!Result.Base && Result.Offset.isZero())
5817 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005818
Richard Smithd62306a2011-11-10 06:34:14 +00005819 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005820 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005821 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5822 castAs<PointerType>()->getPointeeType(),
5823 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005824
Richard Smith027bf112011-11-17 22:56:20 +00005825 case CK_BaseToDerived:
5826 if (!Visit(E->getSubExpr()))
5827 return false;
5828 if (!Result.Base && Result.Offset.isZero())
5829 return true;
5830 return HandleBaseToDerivedCast(Info, E, Result);
5831
Richard Smith0b0a0b62011-10-29 20:57:55 +00005832 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005833 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005834 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005835
John McCalle3027922010-08-25 11:45:40 +00005836 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005837 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5838
Richard Smith2e312c82012-03-03 22:46:17 +00005839 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005840 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005841 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005842
John McCall45d55e42010-05-07 21:00:08 +00005843 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005844 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5845 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005846 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005847 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005848 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00005849 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005850 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005851 return true;
5852 } else {
5853 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005854 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005855 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005856 }
5857 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005858
5859 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005860 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005861 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005862 return false;
5863 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005864 APValue &Value = createTemporary(SubExpr, false, Result,
5865 *Info.CurrentCall);
5866 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005867 return false;
5868 }
Richard Smith96e0c102011-11-04 02:25:55 +00005869 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005870 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5871 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005872 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005873 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005874 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005875 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005876 }
Richard Smithdd785442011-10-31 20:57:44 +00005877
John McCalle3027922010-08-25 11:45:40 +00005878 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005879 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005880
5881 case CK_LValueToRValue: {
5882 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005883 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005884 return false;
5885
5886 APValue RVal;
5887 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5888 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5889 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005890 return InvalidBaseOK &&
5891 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005892 return Success(RVal, E);
5893 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005894 }
5895
Richard Smith11562c52011-10-28 17:51:58 +00005896 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005897}
Chris Lattner05706e882008-07-11 18:11:29 +00005898
Hal Finkel0dd05d42014-10-03 17:18:37 +00005899static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5900 // C++ [expr.alignof]p3:
5901 // When alignof is applied to a reference type, the result is the
5902 // alignment of the referenced type.
5903 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5904 T = Ref->getPointeeType();
5905
5906 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005907 if (T.getQualifiers().hasUnaligned())
5908 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005909 return Info.Ctx.toCharUnitsFromBits(
5910 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5911}
5912
5913static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5914 E = E->IgnoreParens();
5915
5916 // The kinds of expressions that we have special-case logic here for
5917 // should be kept up to date with the special checks for those
5918 // expressions in Sema.
5919
5920 // alignof decl is always accepted, even if it doesn't make sense: we default
5921 // to 1 in those cases.
5922 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5923 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5924 /*RefAsPointee*/true);
5925
5926 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5927 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5928 /*RefAsPointee*/true);
5929
5930 return GetAlignOfType(Info, E->getType());
5931}
5932
George Burgess IVe3763372016-12-22 02:50:20 +00005933// To be clear: this happily visits unsupported builtins. Better name welcomed.
5934bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5935 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5936 return true;
5937
George Burgess IVf9013bf2017-02-10 22:52:29 +00005938 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005939 return false;
5940
5941 Result.setInvalid(E);
5942 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005943 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005944 return true;
5945}
5946
Peter Collingbournee9200682011-05-13 03:29:01 +00005947bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005948 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005949 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005950
Richard Smith6328cbd2016-11-16 00:57:23 +00005951 if (unsigned BuiltinOp = E->getBuiltinCallee())
5952 return VisitBuiltinCallExpr(E, BuiltinOp);
5953
George Burgess IVe3763372016-12-22 02:50:20 +00005954 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005955}
5956
5957bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5958 unsigned BuiltinOp) {
5959 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005960 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005961 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005962 case Builtin::BI__builtin_assume_aligned: {
5963 // We need to be very careful here because: if the pointer does not have the
5964 // asserted alignment, then the behavior is undefined, and undefined
5965 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005966 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005967 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005968
Hal Finkel0dd05d42014-10-03 17:18:37 +00005969 LValue OffsetResult(Result);
5970 APSInt Alignment;
5971 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5972 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005973 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005974
5975 if (E->getNumArgs() > 2) {
5976 APSInt Offset;
5977 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5978 return false;
5979
Richard Smith642a2362017-01-30 23:30:26 +00005980 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005981 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5982 }
5983
5984 // If there is a base object, then it must have the correct alignment.
5985 if (OffsetResult.Base) {
5986 CharUnits BaseAlignment;
5987 if (const ValueDecl *VD =
5988 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5989 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5990 } else {
5991 BaseAlignment =
5992 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5993 }
5994
5995 if (BaseAlignment < Align) {
5996 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005997 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005998 CCEDiag(E->getArg(0),
5999 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00006000 << (unsigned)BaseAlignment.getQuantity()
6001 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006002 return false;
6003 }
6004 }
6005
6006 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006007 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006008 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006009
Richard Smith642a2362017-01-30 23:30:26 +00006010 (OffsetResult.Base
6011 ? CCEDiag(E->getArg(0),
6012 diag::note_constexpr_baa_insufficient_alignment) << 1
6013 : CCEDiag(E->getArg(0),
6014 diag::note_constexpr_baa_value_insufficient_alignment))
6015 << (int)OffsetResult.Offset.getQuantity()
6016 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006017 return false;
6018 }
6019
6020 return true;
6021 }
Richard Smithe9507952016-11-12 01:39:56 +00006022
6023 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006024 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006025 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006026 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006027 if (Info.getLangOpts().CPlusPlus11)
6028 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6029 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006030 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006031 else
6032 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006033 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006034 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006035 case Builtin::BI__builtin_wcschr:
6036 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006037 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006038 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006039 if (!Visit(E->getArg(0)))
6040 return false;
6041 APSInt Desired;
6042 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6043 return false;
6044 uint64_t MaxLength = uint64_t(-1);
6045 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006046 BuiltinOp != Builtin::BIwcschr &&
6047 BuiltinOp != Builtin::BI__builtin_strchr &&
6048 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006049 APSInt N;
6050 if (!EvaluateInteger(E->getArg(2), N, Info))
6051 return false;
6052 MaxLength = N.getExtValue();
6053 }
6054
Richard Smith8110c9d2016-11-29 19:45:17 +00006055 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00006056
Richard Smith8110c9d2016-11-29 19:45:17 +00006057 // Figure out what value we're actually looking for (after converting to
6058 // the corresponding unsigned type if necessary).
6059 uint64_t DesiredVal;
6060 bool StopAtNull = false;
6061 switch (BuiltinOp) {
6062 case Builtin::BIstrchr:
6063 case Builtin::BI__builtin_strchr:
6064 // strchr compares directly to the passed integer, and therefore
6065 // always fails if given an int that is not a char.
6066 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6067 E->getArg(1)->getType(),
6068 Desired),
6069 Desired))
6070 return ZeroInitialization(E);
6071 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006072 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006073 case Builtin::BImemchr:
6074 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006075 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006076 // memchr compares by converting both sides to unsigned char. That's also
6077 // correct for strchr if we get this far (to cope with plain char being
6078 // unsigned in the strchr case).
6079 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6080 break;
Richard Smithe9507952016-11-12 01:39:56 +00006081
Richard Smith8110c9d2016-11-29 19:45:17 +00006082 case Builtin::BIwcschr:
6083 case Builtin::BI__builtin_wcschr:
6084 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006085 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006086 case Builtin::BIwmemchr:
6087 case Builtin::BI__builtin_wmemchr:
6088 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6089 DesiredVal = Desired.getZExtValue();
6090 break;
6091 }
Richard Smithe9507952016-11-12 01:39:56 +00006092
6093 for (; MaxLength; --MaxLength) {
6094 APValue Char;
6095 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6096 !Char.isInt())
6097 return false;
6098 if (Char.getInt().getZExtValue() == DesiredVal)
6099 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006100 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006101 break;
6102 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6103 return false;
6104 }
6105 // Not found: return nullptr.
6106 return ZeroInitialization(E);
6107 }
6108
Richard Smith6cbd65d2013-07-11 02:27:57 +00006109 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006110 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006111 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006112}
Chris Lattner05706e882008-07-11 18:11:29 +00006113
6114//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006115// Member Pointer Evaluation
6116//===----------------------------------------------------------------------===//
6117
6118namespace {
6119class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006120 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006121 MemberPtr &Result;
6122
6123 bool Success(const ValueDecl *D) {
6124 Result = MemberPtr(D);
6125 return true;
6126 }
6127public:
6128
6129 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6130 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6131
Richard Smith2e312c82012-03-03 22:46:17 +00006132 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006133 Result.setFrom(V);
6134 return true;
6135 }
Richard Smithfddd3842011-12-30 21:15:51 +00006136 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006137 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006138 }
6139
6140 bool VisitCastExpr(const CastExpr *E);
6141 bool VisitUnaryAddrOf(const UnaryOperator *E);
6142};
6143} // end anonymous namespace
6144
6145static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6146 EvalInfo &Info) {
6147 assert(E->isRValue() && E->getType()->isMemberPointerType());
6148 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6149}
6150
6151bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6152 switch (E->getCastKind()) {
6153 default:
6154 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6155
6156 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006157 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006158 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006159
6160 case CK_BaseToDerivedMemberPointer: {
6161 if (!Visit(E->getSubExpr()))
6162 return false;
6163 if (E->path_empty())
6164 return true;
6165 // Base-to-derived member pointer casts store the path in derived-to-base
6166 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6167 // the wrong end of the derived->base arc, so stagger the path by one class.
6168 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6169 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6170 PathI != PathE; ++PathI) {
6171 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6172 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6173 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006174 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006175 }
6176 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6177 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006178 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006179 return true;
6180 }
6181
6182 case CK_DerivedToBaseMemberPointer:
6183 if (!Visit(E->getSubExpr()))
6184 return false;
6185 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6186 PathE = E->path_end(); PathI != PathE; ++PathI) {
6187 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6188 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6189 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006190 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006191 }
6192 return true;
6193 }
6194}
6195
6196bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6197 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6198 // member can be formed.
6199 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6200}
6201
6202//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006203// Record Evaluation
6204//===----------------------------------------------------------------------===//
6205
6206namespace {
6207 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006208 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006209 const LValue &This;
6210 APValue &Result;
6211 public:
6212
6213 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6214 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6215
Richard Smith2e312c82012-03-03 22:46:17 +00006216 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006217 Result = V;
6218 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006219 }
Richard Smithb8348f52016-05-12 22:16:28 +00006220 bool ZeroInitialization(const Expr *E) {
6221 return ZeroInitialization(E, E->getType());
6222 }
6223 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006224
Richard Smith52a980a2015-08-28 02:43:42 +00006225 bool VisitCallExpr(const CallExpr *E) {
6226 return handleCallExpr(E, Result, &This);
6227 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006228 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006229 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006230 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6231 return VisitCXXConstructExpr(E, E->getType());
6232 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006233 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006234 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006235 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006236 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006237
6238 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006239 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006240}
Richard Smithd62306a2011-11-10 06:34:14 +00006241
Richard Smithfddd3842011-12-30 21:15:51 +00006242/// Perform zero-initialization on an object of non-union class type.
6243/// C++11 [dcl.init]p5:
6244/// To zero-initialize an object or reference of type T means:
6245/// [...]
6246/// -- if T is a (possibly cv-qualified) non-union class type,
6247/// each non-static data member and each base-class subobject is
6248/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006249static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6250 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006251 const LValue &This, APValue &Result) {
6252 assert(!RD->isUnion() && "Expected non-union class type");
6253 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6254 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006255 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006256
John McCalld7bca762012-05-01 00:38:49 +00006257 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006258 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6259
6260 if (CD) {
6261 unsigned Index = 0;
6262 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006263 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006264 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6265 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006266 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6267 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006268 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006269 Result.getStructBase(Index)))
6270 return false;
6271 }
6272 }
6273
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006274 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006275 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006276 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006277 continue;
6278
6279 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006280 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006281 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006282
David Blaikie2d7c57e2012-04-30 02:36:29 +00006283 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006284 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006285 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006286 return false;
6287 }
6288
6289 return true;
6290}
6291
Richard Smithb8348f52016-05-12 22:16:28 +00006292bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6293 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006294 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006295 if (RD->isUnion()) {
6296 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6297 // object's first non-static named data member is zero-initialized
6298 RecordDecl::field_iterator I = RD->field_begin();
6299 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006300 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006301 return true;
6302 }
6303
6304 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006305 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006306 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006307 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006308 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006309 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006310 }
6311
Richard Smith5d108602012-02-17 00:44:16 +00006312 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006313 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006314 return false;
6315 }
6316
Richard Smitha8105bc2012-01-06 16:39:00 +00006317 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006318}
6319
Richard Smithe97cbd72011-11-11 04:05:33 +00006320bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6321 switch (E->getCastKind()) {
6322 default:
6323 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6324
6325 case CK_ConstructorConversion:
6326 return Visit(E->getSubExpr());
6327
6328 case CK_DerivedToBase:
6329 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006330 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006331 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006332 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006333 if (!DerivedObject.isStruct())
6334 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006335
6336 // Derived-to-base rvalue conversion: just slice off the derived part.
6337 APValue *Value = &DerivedObject;
6338 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6339 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6340 PathE = E->path_end(); PathI != PathE; ++PathI) {
6341 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6342 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6343 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6344 RD = Base;
6345 }
6346 Result = *Value;
6347 return true;
6348 }
6349 }
6350}
6351
Richard Smithd62306a2011-11-10 06:34:14 +00006352bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006353 if (E->isTransparent())
6354 return Visit(E->getInit(0));
6355
Richard Smithd62306a2011-11-10 06:34:14 +00006356 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006357 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006358 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6359
6360 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006361 const FieldDecl *Field = E->getInitializedFieldInUnion();
6362 Result = APValue(Field);
6363 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006364 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006365
6366 // If the initializer list for a union does not contain any elements, the
6367 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006368 // FIXME: The element should be initialized from an initializer list.
6369 // Is this difference ever observable for initializer lists which
6370 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006371 ImplicitValueInitExpr VIE(Field->getType());
6372 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6373
Richard Smithd62306a2011-11-10 06:34:14 +00006374 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006375 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6376 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006377
6378 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6379 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6380 isa<CXXDefaultInitExpr>(InitExpr));
6381
Richard Smithb228a862012-02-15 02:18:13 +00006382 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006383 }
6384
Richard Smith872307e2016-03-08 22:17:41 +00006385 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006386 if (Result.isUninit())
6387 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6388 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006389 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006390 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006391
6392 // Initialize base classes.
6393 if (CXXRD) {
6394 for (const auto &Base : CXXRD->bases()) {
6395 assert(ElementNo < E->getNumInits() && "missing init for base class");
6396 const Expr *Init = E->getInit(ElementNo);
6397
6398 LValue Subobject = This;
6399 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6400 return false;
6401
6402 APValue &FieldVal = Result.getStructBase(ElementNo);
6403 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006404 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006405 return false;
6406 Success = false;
6407 }
6408 ++ElementNo;
6409 }
6410 }
6411
6412 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006413 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006414 // Anonymous bit-fields are not considered members of the class for
6415 // purposes of aggregate initialization.
6416 if (Field->isUnnamedBitfield())
6417 continue;
6418
6419 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006420
Richard Smith253c2a32012-01-27 01:14:48 +00006421 bool HaveInit = ElementNo < E->getNumInits();
6422
6423 // FIXME: Diagnostics here should point to the end of the initializer
6424 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006425 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006426 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006427 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006428
6429 // Perform an implicit value-initialization for members beyond the end of
6430 // the initializer list.
6431 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006432 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006433
Richard Smith852c9db2013-04-20 22:23:05 +00006434 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6435 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6436 isa<CXXDefaultInitExpr>(Init));
6437
Richard Smith49ca8aa2013-08-06 07:09:20 +00006438 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6439 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6440 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006441 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006442 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006443 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006444 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006445 }
6446 }
6447
Richard Smith253c2a32012-01-27 01:14:48 +00006448 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006449}
6450
Richard Smithb8348f52016-05-12 22:16:28 +00006451bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6452 QualType T) {
6453 // Note that E's type is not necessarily the type of our class here; we might
6454 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006455 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006456 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6457
Richard Smithfddd3842011-12-30 21:15:51 +00006458 bool ZeroInit = E->requiresZeroInitialization();
6459 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006460 // If we've already performed zero-initialization, we're already done.
6461 if (!Result.isUninit())
6462 return true;
6463
Richard Smithda3f4fd2014-03-05 23:32:50 +00006464 // We can get here in two different ways:
6465 // 1) We're performing value-initialization, and should zero-initialize
6466 // the object, or
6467 // 2) We're performing default-initialization of an object with a trivial
6468 // constexpr default constructor, in which case we should start the
6469 // lifetimes of all the base subobjects (there can be no data member
6470 // subobjects in this case) per [basic.life]p1.
6471 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006472 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006473 }
6474
Craig Topper36250ad2014-05-12 05:36:57 +00006475 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006476 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006477
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006478 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006479 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006480
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006481 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006482 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006483 if (const MaterializeTemporaryExpr *ME
6484 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6485 return Visit(ME->GetTemporaryExpr());
6486
Richard Smithb8348f52016-05-12 22:16:28 +00006487 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006488 return false;
6489
Craig Topper5fc8fc22014-08-27 06:28:36 +00006490 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006491 return HandleConstructorCall(E, This, Args,
6492 cast<CXXConstructorDecl>(Definition), Info,
6493 Result);
6494}
6495
6496bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6497 const CXXInheritedCtorInitExpr *E) {
6498 if (!Info.CurrentCall) {
6499 assert(Info.checkingPotentialConstantExpression());
6500 return false;
6501 }
6502
6503 const CXXConstructorDecl *FD = E->getConstructor();
6504 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6505 return false;
6506
6507 const FunctionDecl *Definition = nullptr;
6508 auto Body = FD->getBody(Definition);
6509
6510 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6511 return false;
6512
6513 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006514 cast<CXXConstructorDecl>(Definition), Info,
6515 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006516}
6517
Richard Smithcc1b96d2013-06-12 22:31:48 +00006518bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6519 const CXXStdInitializerListExpr *E) {
6520 const ConstantArrayType *ArrayType =
6521 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6522
6523 LValue Array;
6524 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6525 return false;
6526
6527 // Get a pointer to the first element of the array.
6528 Array.addArray(Info, E, ArrayType);
6529
6530 // FIXME: Perform the checks on the field types in SemaInit.
6531 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6532 RecordDecl::field_iterator Field = Record->field_begin();
6533 if (Field == Record->field_end())
6534 return Error(E);
6535
6536 // Start pointer.
6537 if (!Field->getType()->isPointerType() ||
6538 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6539 ArrayType->getElementType()))
6540 return Error(E);
6541
6542 // FIXME: What if the initializer_list type has base classes, etc?
6543 Result = APValue(APValue::UninitStruct(), 0, 2);
6544 Array.moveInto(Result.getStructField(0));
6545
6546 if (++Field == Record->field_end())
6547 return Error(E);
6548
6549 if (Field->getType()->isPointerType() &&
6550 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6551 ArrayType->getElementType())) {
6552 // End pointer.
6553 if (!HandleLValueArrayAdjustment(Info, E, Array,
6554 ArrayType->getElementType(),
6555 ArrayType->getSize().getZExtValue()))
6556 return false;
6557 Array.moveInto(Result.getStructField(1));
6558 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6559 // Length.
6560 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6561 else
6562 return Error(E);
6563
6564 if (++Field != Record->field_end())
6565 return Error(E);
6566
6567 return true;
6568}
6569
Faisal Valic72a08c2017-01-09 03:02:53 +00006570bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6571 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6572 if (ClosureClass->isInvalidDecl()) return false;
6573
6574 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006575
Faisal Vali051e3a22017-02-16 04:12:21 +00006576 const size_t NumFields =
6577 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006578
6579 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6580 E->capture_init_end()) &&
6581 "The number of lambda capture initializers should equal the number of "
6582 "fields within the closure type");
6583
Faisal Vali051e3a22017-02-16 04:12:21 +00006584 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6585 // Iterate through all the lambda's closure object's fields and initialize
6586 // them.
6587 auto *CaptureInitIt = E->capture_init_begin();
6588 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6589 bool Success = true;
6590 for (const auto *Field : ClosureClass->fields()) {
6591 assert(CaptureInitIt != E->capture_init_end());
6592 // Get the initializer for this field
6593 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006594
Faisal Vali051e3a22017-02-16 04:12:21 +00006595 // If there is no initializer, either this is a VLA or an error has
6596 // occurred.
6597 if (!CurFieldInit)
6598 return Error(E);
6599
6600 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6601 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6602 if (!Info.keepEvaluatingAfterFailure())
6603 return false;
6604 Success = false;
6605 }
6606 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006607 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006608 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006609}
6610
Richard Smithd62306a2011-11-10 06:34:14 +00006611static bool EvaluateRecord(const Expr *E, const LValue &This,
6612 APValue &Result, EvalInfo &Info) {
6613 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006614 "can't evaluate expression as a record rvalue");
6615 return RecordExprEvaluator(Info, This, Result).Visit(E);
6616}
6617
6618//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006619// Temporary Evaluation
6620//
6621// Temporaries are represented in the AST as rvalues, but generally behave like
6622// lvalues. The full-object of which the temporary is a subobject is implicitly
6623// materialized so that a reference can bind to it.
6624//===----------------------------------------------------------------------===//
6625namespace {
6626class TemporaryExprEvaluator
6627 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6628public:
6629 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006630 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006631
6632 /// Visit an expression which constructs the value of this temporary.
6633 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006634 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6635 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006636 }
6637
6638 bool VisitCastExpr(const CastExpr *E) {
6639 switch (E->getCastKind()) {
6640 default:
6641 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6642
6643 case CK_ConstructorConversion:
6644 return VisitConstructExpr(E->getSubExpr());
6645 }
6646 }
6647 bool VisitInitListExpr(const InitListExpr *E) {
6648 return VisitConstructExpr(E);
6649 }
6650 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6651 return VisitConstructExpr(E);
6652 }
6653 bool VisitCallExpr(const CallExpr *E) {
6654 return VisitConstructExpr(E);
6655 }
Richard Smith513955c2014-12-17 19:24:30 +00006656 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6657 return VisitConstructExpr(E);
6658 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006659 bool VisitLambdaExpr(const LambdaExpr *E) {
6660 return VisitConstructExpr(E);
6661 }
Richard Smith027bf112011-11-17 22:56:20 +00006662};
6663} // end anonymous namespace
6664
6665/// Evaluate an expression of record type as a temporary.
6666static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006667 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006668 return TemporaryExprEvaluator(Info, Result).Visit(E);
6669}
6670
6671//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006672// Vector Evaluation
6673//===----------------------------------------------------------------------===//
6674
6675namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006676 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006677 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006678 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006679 public:
Mike Stump11289f42009-09-09 15:08:12 +00006680
Richard Smith2d406342011-10-22 21:10:00 +00006681 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6682 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006683
Craig Topper9798b932015-09-29 04:30:05 +00006684 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006685 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6686 // FIXME: remove this APValue copy.
6687 Result = APValue(V.data(), V.size());
6688 return true;
6689 }
Richard Smith2e312c82012-03-03 22:46:17 +00006690 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006691 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006692 Result = V;
6693 return true;
6694 }
Richard Smithfddd3842011-12-30 21:15:51 +00006695 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006696
Richard Smith2d406342011-10-22 21:10:00 +00006697 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006698 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006699 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006700 bool VisitInitListExpr(const InitListExpr *E);
6701 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006702 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006703 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006704 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006705 };
6706} // end anonymous namespace
6707
6708static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006709 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006710 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006711}
6712
George Burgess IV533ff002015-12-11 00:23:35 +00006713bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006714 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006715 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006716
Richard Smith161f09a2011-12-06 22:44:34 +00006717 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006718 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006719
Eli Friedmanc757de22011-03-25 00:43:55 +00006720 switch (E->getCastKind()) {
6721 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006722 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006723 if (SETy->isIntegerType()) {
6724 APSInt IntResult;
6725 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006726 return false;
6727 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006728 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006729 APFloat FloatResult(0.0);
6730 if (!EvaluateFloat(SE, FloatResult, Info))
6731 return false;
6732 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006733 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006734 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006735 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006736
6737 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006738 SmallVector<APValue, 4> Elts(NElts, Val);
6739 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006740 }
Eli Friedman803acb32011-12-22 03:51:45 +00006741 case CK_BitCast: {
6742 // Evaluate the operand into an APInt we can extract from.
6743 llvm::APInt SValInt;
6744 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6745 return false;
6746 // Extract the elements
6747 QualType EltTy = VTy->getElementType();
6748 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6749 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6750 SmallVector<APValue, 4> Elts;
6751 if (EltTy->isRealFloatingType()) {
6752 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006753 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006754 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006755 FloatEltSize = 80;
6756 for (unsigned i = 0; i < NElts; i++) {
6757 llvm::APInt Elt;
6758 if (BigEndian)
6759 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6760 else
6761 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006762 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006763 }
6764 } else if (EltTy->isIntegerType()) {
6765 for (unsigned i = 0; i < NElts; i++) {
6766 llvm::APInt Elt;
6767 if (BigEndian)
6768 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6769 else
6770 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6771 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6772 }
6773 } else {
6774 return Error(E);
6775 }
6776 return Success(Elts, E);
6777 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006778 default:
Richard Smith11562c52011-10-28 17:51:58 +00006779 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006780 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006781}
6782
Richard Smith2d406342011-10-22 21:10:00 +00006783bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006784VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006785 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006786 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006787 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006788
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006789 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006790 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006791
Eli Friedmanb9c71292012-01-03 23:24:20 +00006792 // The number of initializers can be less than the number of
6793 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006794 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006795 // should be initialized with zeroes.
6796 unsigned CountInits = 0, CountElts = 0;
6797 while (CountElts < NumElements) {
6798 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006799 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006800 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006801 APValue v;
6802 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6803 return Error(E);
6804 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006805 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006806 Elements.push_back(v.getVectorElt(j));
6807 CountElts += vlen;
6808 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006809 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006810 if (CountInits < NumInits) {
6811 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006812 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006813 } else // trailing integer zero.
6814 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6815 Elements.push_back(APValue(sInt));
6816 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006817 } else {
6818 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006819 if (CountInits < NumInits) {
6820 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006821 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006822 } else // trailing float zero.
6823 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6824 Elements.push_back(APValue(f));
6825 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006826 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006827 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006828 }
Richard Smith2d406342011-10-22 21:10:00 +00006829 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006830}
6831
Richard Smith2d406342011-10-22 21:10:00 +00006832bool
Richard Smithfddd3842011-12-30 21:15:51 +00006833VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006834 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006835 QualType EltTy = VT->getElementType();
6836 APValue ZeroElement;
6837 if (EltTy->isIntegerType())
6838 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6839 else
6840 ZeroElement =
6841 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6842
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006843 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006844 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006845}
6846
Richard Smith2d406342011-10-22 21:10:00 +00006847bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006848 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006849 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006850}
6851
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006852//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006853// Array Evaluation
6854//===----------------------------------------------------------------------===//
6855
6856namespace {
6857 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006858 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006859 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006860 APValue &Result;
6861 public:
6862
Richard Smithd62306a2011-11-10 06:34:14 +00006863 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6864 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006865
6866 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006867 assert((V.isArray() || V.isLValue()) &&
6868 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006869 Result = V;
6870 return true;
6871 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006872
Richard Smithfddd3842011-12-30 21:15:51 +00006873 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006874 const ConstantArrayType *CAT =
6875 Info.Ctx.getAsConstantArrayType(E->getType());
6876 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006877 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006878
6879 Result = APValue(APValue::UninitArray(), 0,
6880 CAT->getSize().getZExtValue());
6881 if (!Result.hasArrayFiller()) return true;
6882
Richard Smithfddd3842011-12-30 21:15:51 +00006883 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006884 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006885 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006886 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006887 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006888 }
6889
Richard Smith52a980a2015-08-28 02:43:42 +00006890 bool VisitCallExpr(const CallExpr *E) {
6891 return handleCallExpr(E, Result, &This);
6892 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006893 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006894 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006895 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006896 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6897 const LValue &Subobject,
6898 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006899 };
6900} // end anonymous namespace
6901
Richard Smithd62306a2011-11-10 06:34:14 +00006902static bool EvaluateArray(const Expr *E, const LValue &This,
6903 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006904 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006905 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006906}
6907
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006908// Return true iff the given array filler may depend on the element index.
6909static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
6910 // For now, just whitelist non-class value-initialization and initialization
6911 // lists comprised of them.
6912 if (isa<ImplicitValueInitExpr>(FillerExpr))
6913 return false;
6914 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
6915 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
6916 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
6917 return true;
6918 }
6919 return false;
6920 }
6921 return true;
6922}
6923
Richard Smithf3e9e432011-11-07 09:22:26 +00006924bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6925 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6926 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006927 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006928
Richard Smithca2cfbf2011-12-22 01:07:19 +00006929 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6930 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006931 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006932 LValue LV;
6933 if (!EvaluateLValue(E->getInit(0), LV, Info))
6934 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006935 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006936 LV.moveInto(Val);
6937 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006938 }
6939
Richard Smith253c2a32012-01-27 01:14:48 +00006940 bool Success = true;
6941
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006942 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6943 "zero-initialized array shouldn't have any initialized elts");
6944 APValue Filler;
6945 if (Result.isArray() && Result.hasArrayFiller())
6946 Filler = Result.getArrayFiller();
6947
Richard Smith9543c5e2013-04-22 14:44:29 +00006948 unsigned NumEltsToInit = E->getNumInits();
6949 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006950 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006951
6952 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006953 // array element.
6954 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00006955 NumEltsToInit = NumElts;
6956
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006957 DEBUG(llvm::dbgs() << "The number of elements to initialize: " <<
6958 NumEltsToInit << ".\n");
6959
Richard Smith9543c5e2013-04-22 14:44:29 +00006960 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006961
6962 // If the array was previously zero-initialized, preserve the
6963 // zero-initialized values.
6964 if (!Filler.isUninit()) {
6965 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6966 Result.getArrayInitializedElt(I) = Filler;
6967 if (Result.hasArrayFiller())
6968 Result.getArrayFiller() = Filler;
6969 }
6970
Richard Smithd62306a2011-11-10 06:34:14 +00006971 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006972 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006973 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6974 const Expr *Init =
6975 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006976 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006977 Info, Subobject, Init) ||
6978 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006979 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006980 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006981 return false;
6982 Success = false;
6983 }
Richard Smithd62306a2011-11-10 06:34:14 +00006984 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006985
Richard Smith9543c5e2013-04-22 14:44:29 +00006986 if (!Result.hasArrayFiller())
6987 return Success;
6988
6989 // If we get here, we have a trivial filler, which we can just evaluate
6990 // once and splat over the rest of the array elements.
6991 assert(FillerExpr && "no array filler for incomplete init list");
6992 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6993 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006994}
6995
Richard Smith410306b2016-12-12 02:53:20 +00006996bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6997 if (E->getCommonExpr() &&
6998 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6999 Info, E->getCommonExpr()->getSourceExpr()))
7000 return false;
7001
7002 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7003
7004 uint64_t Elements = CAT->getSize().getZExtValue();
7005 Result = APValue(APValue::UninitArray(), Elements, Elements);
7006
7007 LValue Subobject = This;
7008 Subobject.addArray(Info, E, CAT);
7009
7010 bool Success = true;
7011 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7012 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7013 Info, Subobject, E->getSubExpr()) ||
7014 !HandleLValueArrayAdjustment(Info, E, Subobject,
7015 CAT->getElementType(), 1)) {
7016 if (!Info.noteFailure())
7017 return false;
7018 Success = false;
7019 }
7020 }
7021
7022 return Success;
7023}
7024
Richard Smith027bf112011-11-17 22:56:20 +00007025bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00007026 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7027}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007028
Richard Smith9543c5e2013-04-22 14:44:29 +00007029bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7030 const LValue &Subobject,
7031 APValue *Value,
7032 QualType Type) {
7033 bool HadZeroInit = !Value->isUninit();
7034
7035 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7036 unsigned N = CAT->getSize().getZExtValue();
7037
7038 // Preserve the array filler if we had prior zero-initialization.
7039 APValue Filler =
7040 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7041 : APValue();
7042
7043 *Value = APValue(APValue::UninitArray(), N, N);
7044
7045 if (HadZeroInit)
7046 for (unsigned I = 0; I != N; ++I)
7047 Value->getArrayInitializedElt(I) = Filler;
7048
7049 // Initialize the elements.
7050 LValue ArrayElt = Subobject;
7051 ArrayElt.addArray(Info, E, CAT);
7052 for (unsigned I = 0; I != N; ++I)
7053 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7054 CAT->getElementType()) ||
7055 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7056 CAT->getElementType(), 1))
7057 return false;
7058
7059 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007060 }
Richard Smith027bf112011-11-17 22:56:20 +00007061
Richard Smith9543c5e2013-04-22 14:44:29 +00007062 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00007063 return Error(E);
7064
Richard Smithb8348f52016-05-12 22:16:28 +00007065 return RecordExprEvaluator(Info, Subobject, *Value)
7066 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00007067}
7068
Richard Smithf3e9e432011-11-07 09:22:26 +00007069//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007070// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007071//
7072// As a GNU extension, we support casting pointers to sufficiently-wide integer
7073// types and back in constant folding. Integer values are thus represented
7074// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00007075//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007076
7077namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007078class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007079 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00007080 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007081public:
Richard Smith2e312c82012-03-03 22:46:17 +00007082 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007083 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007084
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007085 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007086 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007087 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007088 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007089 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007090 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007091 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007092 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007093 return true;
7094 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007095 bool Success(const llvm::APSInt &SI, const Expr *E) {
7096 return Success(SI, E, Result);
7097 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007098
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007099 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00007100 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007101 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007102 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007103 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007104 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007105 Result.getInt().setIsUnsigned(
7106 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007107 return true;
7108 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007109 bool Success(const llvm::APInt &I, const Expr *E) {
7110 return Success(I, E, Result);
7111 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007112
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007113 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007114 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007115 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007116 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007117 return true;
7118 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007119 bool Success(uint64_t Value, const Expr *E) {
7120 return Success(Value, E, Result);
7121 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007122
Ken Dyckdbc01912011-03-11 02:13:43 +00007123 bool Success(CharUnits Size, const Expr *E) {
7124 return Success(Size.getQuantity(), E);
7125 }
7126
Richard Smith2e312c82012-03-03 22:46:17 +00007127 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007128 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007129 Result = V;
7130 return true;
7131 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007132 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007133 }
Mike Stump11289f42009-09-09 15:08:12 +00007134
Richard Smithfddd3842011-12-30 21:15:51 +00007135 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007136
Peter Collingbournee9200682011-05-13 03:29:01 +00007137 //===--------------------------------------------------------------------===//
7138 // Visitor Methods
7139 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007140
Chris Lattner7174bf32008-07-12 00:38:25 +00007141 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007142 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007143 }
7144 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007145 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007146 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007147
7148 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7149 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007150 if (CheckReferencedDecl(E, E->getDecl()))
7151 return true;
7152
7153 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007154 }
7155 bool VisitMemberExpr(const MemberExpr *E) {
7156 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007157 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007158 return true;
7159 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007160
7161 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007162 }
7163
Peter Collingbournee9200682011-05-13 03:29:01 +00007164 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007165 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007166 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007167 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007168 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007169
Peter Collingbournee9200682011-05-13 03:29:01 +00007170 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007171 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007172
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007173 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007174 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007175 }
Mike Stump11289f42009-09-09 15:08:12 +00007176
Ted Kremeneke65b0862012-03-06 20:05:56 +00007177 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7178 return Success(E->getValue(), E);
7179 }
Richard Smith410306b2016-12-12 02:53:20 +00007180
7181 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7182 if (Info.ArrayInitIndex == uint64_t(-1)) {
7183 // We were asked to evaluate this subexpression independent of the
7184 // enclosing ArrayInitLoopExpr. We can't do that.
7185 Info.FFDiag(E);
7186 return false;
7187 }
7188 return Success(Info.ArrayInitIndex, E);
7189 }
Daniel Jasperffdee092017-05-02 19:21:42 +00007190
Richard Smith4ce706a2011-10-11 21:43:33 +00007191 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007192 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007193 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007194 }
7195
Douglas Gregor29c42f22012-02-24 07:38:34 +00007196 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7197 return Success(E->getValue(), E);
7198 }
7199
John Wiegley6242b6a2011-04-28 00:16:57 +00007200 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7201 return Success(E->getValue(), E);
7202 }
7203
John Wiegleyf9f65842011-04-25 06:54:41 +00007204 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7205 return Success(E->getValue(), E);
7206 }
7207
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007208 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007209 bool VisitUnaryImag(const UnaryOperator *E);
7210
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007211 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007212 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007213
Eli Friedman4e7a2412009-02-27 04:45:43 +00007214 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007215};
Chris Lattner05706e882008-07-11 18:11:29 +00007216} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007217
Richard Smith11562c52011-10-28 17:51:58 +00007218/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7219/// produce either the integer value or a pointer.
7220///
7221/// GCC has a heinous extension which folds casts between pointer types and
7222/// pointer-sized integral types. We support this by allowing the evaluation of
7223/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7224/// Some simple arithmetic on such values is supported (they are treated much
7225/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007226static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007227 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007228 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007229 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007230}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007231
Richard Smithf57d8cb2011-12-09 22:58:01 +00007232static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007233 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007234 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007235 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007236 if (!Val.isInt()) {
7237 // FIXME: It would be better to produce the diagnostic for casting
7238 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007239 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007240 return false;
7241 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007242 Result = Val.getInt();
7243 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007244}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007245
Richard Smithf57d8cb2011-12-09 22:58:01 +00007246/// Check whether the given declaration can be directly converted to an integral
7247/// rvalue. If not, no diagnostic is produced; there are other things we can
7248/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007249bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007250 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007251 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007252 // Check for signedness/width mismatches between E type and ECD value.
7253 bool SameSign = (ECD->getInitVal().isSigned()
7254 == E->getType()->isSignedIntegerOrEnumerationType());
7255 bool SameWidth = (ECD->getInitVal().getBitWidth()
7256 == Info.Ctx.getIntWidth(E->getType()));
7257 if (SameSign && SameWidth)
7258 return Success(ECD->getInitVal(), E);
7259 else {
7260 // Get rid of mismatch (otherwise Success assertions will fail)
7261 // by computing a new value matching the type of E.
7262 llvm::APSInt Val = ECD->getInitVal();
7263 if (!SameSign)
7264 Val.setIsSigned(!ECD->getInitVal().isSigned());
7265 if (!SameWidth)
7266 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7267 return Success(Val, E);
7268 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007269 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007270 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007271}
7272
Chris Lattner86ee2862008-10-06 06:40:35 +00007273/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7274/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007275static int EvaluateBuiltinClassifyType(const CallExpr *E,
7276 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007277 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007278 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007279 enum gcc_type_class {
7280 no_type_class = -1,
7281 void_type_class, integer_type_class, char_type_class,
7282 enumeral_type_class, boolean_type_class,
7283 pointer_type_class, reference_type_class, offset_type_class,
7284 real_type_class, complex_type_class,
7285 function_type_class, method_type_class,
7286 record_type_class, union_type_class,
7287 array_type_class, string_type_class,
7288 lang_type_class
7289 };
Mike Stump11289f42009-09-09 15:08:12 +00007290
7291 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007292 // ideal, however it is what gcc does.
7293 if (E->getNumArgs() == 0)
7294 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007295
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007296 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7297 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7298
7299 switch (CanTy->getTypeClass()) {
7300#define TYPE(ID, BASE)
7301#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7302#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7303#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7304#include "clang/AST/TypeNodes.def"
7305 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7306
7307 case Type::Builtin:
7308 switch (BT->getKind()) {
7309#define BUILTIN_TYPE(ID, SINGLETON_ID)
7310#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7311#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7312#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7313#include "clang/AST/BuiltinTypes.def"
7314 case BuiltinType::Void:
7315 return void_type_class;
7316
7317 case BuiltinType::Bool:
7318 return boolean_type_class;
7319
7320 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7321 case BuiltinType::UChar:
7322 case BuiltinType::UShort:
7323 case BuiltinType::UInt:
7324 case BuiltinType::ULong:
7325 case BuiltinType::ULongLong:
7326 case BuiltinType::UInt128:
7327 return integer_type_class;
7328
7329 case BuiltinType::NullPtr:
7330 return pointer_type_class;
7331
7332 case BuiltinType::WChar_U:
Richard Smith3a8244d2018-05-01 05:02:45 +00007333 case BuiltinType::Char8:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007334 case BuiltinType::Char16:
7335 case BuiltinType::Char32:
7336 case BuiltinType::ObjCId:
7337 case BuiltinType::ObjCClass:
7338 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007339#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7340 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007341#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007342 case BuiltinType::OCLSampler:
7343 case BuiltinType::OCLEvent:
7344 case BuiltinType::OCLClkEvent:
7345 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007346 case BuiltinType::OCLReserveID:
7347 case BuiltinType::Dependent:
7348 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7349 };
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007350 break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007351
7352 case Type::Enum:
7353 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7354 break;
7355
7356 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007357 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007358 break;
7359
7360 case Type::MemberPointer:
7361 if (CanTy->isMemberDataPointerType())
7362 return offset_type_class;
7363 else {
7364 // We expect member pointers to be either data or function pointers,
7365 // nothing else.
7366 assert(CanTy->isMemberFunctionPointerType());
7367 return method_type_class;
7368 }
7369
7370 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007371 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007372
7373 case Type::FunctionNoProto:
7374 case Type::FunctionProto:
7375 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7376
7377 case Type::Record:
7378 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7379 switch (RT->getDecl()->getTagKind()) {
7380 case TagTypeKind::TTK_Struct:
7381 case TagTypeKind::TTK_Class:
7382 case TagTypeKind::TTK_Interface:
7383 return record_type_class;
7384
7385 case TagTypeKind::TTK_Enum:
7386 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7387
7388 case TagTypeKind::TTK_Union:
7389 return union_type_class;
7390 }
7391 }
David Blaikie83d382b2011-09-23 05:06:16 +00007392 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007393
7394 case Type::ConstantArray:
7395 case Type::VariableArray:
7396 case Type::IncompleteArray:
7397 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7398
7399 case Type::BlockPointer:
7400 case Type::LValueReference:
7401 case Type::RValueReference:
7402 case Type::Vector:
7403 case Type::ExtVector:
7404 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007405 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007406 case Type::ObjCObject:
7407 case Type::ObjCInterface:
7408 case Type::ObjCObjectPointer:
7409 case Type::Pipe:
7410 case Type::Atomic:
7411 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7412 }
7413
7414 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007415}
7416
Richard Smith5fab0c92011-12-28 19:48:30 +00007417/// EvaluateBuiltinConstantPForLValue - Determine the result of
7418/// __builtin_constant_p when applied to the given lvalue.
7419///
7420/// An lvalue is only "constant" if it is a pointer or reference to the first
7421/// character of a string literal.
7422template<typename LValue>
7423static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007424 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007425 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7426}
7427
7428/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7429/// GCC as we can manage.
7430static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7431 QualType ArgType = Arg->getType();
7432
7433 // __builtin_constant_p always has one operand. The rules which gcc follows
7434 // are not precisely documented, but are as follows:
7435 //
7436 // - If the operand is of integral, floating, complex or enumeration type,
7437 // and can be folded to a known value of that type, it returns 1.
7438 // - If the operand and can be folded to a pointer to the first character
7439 // of a string literal (or such a pointer cast to an integral type), it
7440 // returns 1.
7441 //
7442 // Otherwise, it returns 0.
7443 //
7444 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7445 // its support for this does not currently work.
7446 if (ArgType->isIntegralOrEnumerationType()) {
7447 Expr::EvalResult Result;
7448 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7449 return false;
7450
7451 APValue &V = Result.Val;
7452 if (V.getKind() == APValue::Int)
7453 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007454 if (V.getKind() == APValue::LValue)
7455 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007456 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7457 return Arg->isEvaluatable(Ctx);
7458 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7459 LValue LV;
7460 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007461 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007462 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7463 : EvaluatePointer(Arg, LV, Info)) &&
7464 !Status.HasSideEffects)
7465 return EvaluateBuiltinConstantPForLValue(LV);
7466 }
7467
7468 // Anything else isn't considered to be sufficiently constant.
7469 return false;
7470}
7471
John McCall95007602010-05-10 23:27:23 +00007472/// Retrieves the "underlying object type" of the given expression,
7473/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007474static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007475 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7476 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007477 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007478 } else if (const Expr *E = B.get<const Expr*>()) {
7479 if (isa<CompoundLiteralExpr>(E))
7480 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007481 }
7482
7483 return QualType();
7484}
7485
George Burgess IV3a03fab2015-09-04 21:28:13 +00007486/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007487/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007488/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007489/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7490///
7491/// Always returns an RValue with a pointer representation.
7492static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7493 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7494
7495 auto *NoParens = E->IgnoreParens();
7496 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007497 if (Cast == nullptr)
7498 return NoParens;
7499
7500 // We only conservatively allow a few kinds of casts, because this code is
7501 // inherently a simple solution that seeks to support the common case.
7502 auto CastKind = Cast->getCastKind();
7503 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7504 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007505 return NoParens;
7506
7507 auto *SubExpr = Cast->getSubExpr();
7508 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7509 return NoParens;
7510 return ignorePointerCastsAndParens(SubExpr);
7511}
7512
George Burgess IVa51c4072015-10-16 01:49:01 +00007513/// Checks to see if the given LValue's Designator is at the end of the LValue's
7514/// record layout. e.g.
7515/// struct { struct { int a, b; } fst, snd; } obj;
7516/// obj.fst // no
7517/// obj.snd // yes
7518/// obj.fst.a // no
7519/// obj.fst.b // no
7520/// obj.snd.a // no
7521/// obj.snd.b // yes
7522///
7523/// Please note: this function is specialized for how __builtin_object_size
7524/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007525///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007526/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7527/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007528static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7529 assert(!LVal.Designator.Invalid);
7530
George Burgess IV4168d752016-06-27 19:40:41 +00007531 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7532 const RecordDecl *Parent = FD->getParent();
7533 Invalid = Parent->isInvalidDecl();
7534 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007535 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007536 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007537 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7538 };
7539
7540 auto &Base = LVal.getLValueBase();
7541 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7542 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007543 bool Invalid;
7544 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7545 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007546 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007547 for (auto *FD : IFD->chain()) {
7548 bool Invalid;
7549 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7550 return Invalid;
7551 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007552 }
7553 }
7554
George Burgess IVe3763372016-12-22 02:50:20 +00007555 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007556 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007557 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007558 // If we don't know the array bound, conservatively assume we're looking at
7559 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007560 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007561 if (BaseType->isIncompleteArrayType())
7562 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7563 else
7564 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007565 }
7566
7567 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7568 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007569 if (BaseType->isArrayType()) {
7570 // Because __builtin_object_size treats arrays as objects, we can ignore
7571 // the index iff this is the last array in the Designator.
7572 if (I + 1 == E)
7573 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007574 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7575 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007576 if (Index + 1 != CAT->getSize())
7577 return false;
7578 BaseType = CAT->getElementType();
7579 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007580 const auto *CT = BaseType->castAs<ComplexType>();
7581 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007582 if (Index != 1)
7583 return false;
7584 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007585 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007586 bool Invalid;
7587 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7588 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007589 BaseType = FD->getType();
7590 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007591 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007592 return false;
7593 }
7594 }
7595 return true;
7596}
7597
George Burgess IVe3763372016-12-22 02:50:20 +00007598/// Tests to see if the LValue has a user-specified designator (that isn't
7599/// necessarily valid). Note that this always returns 'true' if the LValue has
7600/// an unsized array as its first designator entry, because there's currently no
7601/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007602static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007603 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007604 return false;
7605
George Burgess IVe3763372016-12-22 02:50:20 +00007606 if (!LVal.Designator.Entries.empty())
7607 return LVal.Designator.isMostDerivedAnUnsizedArray();
7608
George Burgess IVa51c4072015-10-16 01:49:01 +00007609 if (!LVal.InvalidBase)
7610 return true;
7611
George Burgess IVe3763372016-12-22 02:50:20 +00007612 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7613 // the LValueBase.
7614 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7615 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007616}
7617
George Burgess IVe3763372016-12-22 02:50:20 +00007618/// Attempts to detect a user writing into a piece of memory that's impossible
7619/// to figure out the size of by just using types.
7620static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7621 const SubobjectDesignator &Designator = LVal.Designator;
7622 // Notes:
7623 // - Users can only write off of the end when we have an invalid base. Invalid
7624 // bases imply we don't know where the memory came from.
7625 // - We used to be a bit more aggressive here; we'd only be conservative if
7626 // the array at the end was flexible, or if it had 0 or 1 elements. This
7627 // broke some common standard library extensions (PR30346), but was
7628 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7629 // with some sort of whitelist. OTOH, it seems that GCC is always
7630 // conservative with the last element in structs (if it's an array), so our
7631 // current behavior is more compatible than a whitelisting approach would
7632 // be.
7633 return LVal.InvalidBase &&
7634 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7635 Designator.MostDerivedIsArrayElement &&
7636 isDesignatorAtObjectEnd(Ctx, LVal);
7637}
7638
7639/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7640/// Fails if the conversion would cause loss of precision.
7641static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7642 CharUnits &Result) {
7643 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7644 if (Int.ugt(CharUnitsMax))
7645 return false;
7646 Result = CharUnits::fromQuantity(Int.getZExtValue());
7647 return true;
7648}
7649
7650/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7651/// determine how many bytes exist from the beginning of the object to either
7652/// the end of the current subobject, or the end of the object itself, depending
7653/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007654///
George Burgess IVe3763372016-12-22 02:50:20 +00007655/// If this returns false, the value of Result is undefined.
7656static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7657 unsigned Type, const LValue &LVal,
7658 CharUnits &EndOffset) {
7659 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007660
George Burgess IV7fb7e362017-01-03 23:35:19 +00007661 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7662 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7663 return false;
7664 return HandleSizeof(Info, ExprLoc, Ty, Result);
7665 };
7666
George Burgess IVe3763372016-12-22 02:50:20 +00007667 // We want to evaluate the size of the entire object. This is a valid fallback
7668 // for when Type=1 and the designator is invalid, because we're asked for an
7669 // upper-bound.
7670 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7671 // Type=3 wants a lower bound, so we can't fall back to this.
7672 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007673 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007674
7675 llvm::APInt APEndOffset;
7676 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7677 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7678 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7679
7680 if (LVal.InvalidBase)
7681 return false;
7682
7683 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007684 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007685 }
7686
George Burgess IVe3763372016-12-22 02:50:20 +00007687 // We want to evaluate the size of a subobject.
7688 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007689
7690 // The following is a moderately common idiom in C:
7691 //
7692 // struct Foo { int a; char c[1]; };
7693 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7694 // strcpy(&F->c[0], Bar);
7695 //
George Burgess IVe3763372016-12-22 02:50:20 +00007696 // In order to not break too much legacy code, we need to support it.
7697 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7698 // If we can resolve this to an alloc_size call, we can hand that back,
7699 // because we know for certain how many bytes there are to write to.
7700 llvm::APInt APEndOffset;
7701 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7702 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7703 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7704
7705 // If we cannot determine the size of the initial allocation, then we can't
7706 // given an accurate upper-bound. However, we are still able to give
7707 // conservative lower-bounds for Type=3.
7708 if (Type == 1)
7709 return false;
7710 }
7711
7712 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007713 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007714 return false;
7715
George Burgess IVe3763372016-12-22 02:50:20 +00007716 // According to the GCC documentation, we want the size of the subobject
7717 // denoted by the pointer. But that's not quite right -- what we actually
7718 // want is the size of the immediately-enclosing array, if there is one.
7719 int64_t ElemsRemaining;
7720 if (Designator.MostDerivedIsArrayElement &&
7721 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7722 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7723 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7724 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7725 } else {
7726 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7727 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007728
George Burgess IVe3763372016-12-22 02:50:20 +00007729 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7730 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007731}
7732
George Burgess IVe3763372016-12-22 02:50:20 +00007733/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7734/// returns true and stores the result in @p Size.
7735///
7736/// If @p WasError is non-null, this will report whether the failure to evaluate
7737/// is to be treated as an Error in IntExprEvaluator.
7738static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7739 EvalInfo &Info, uint64_t &Size) {
7740 // Determine the denoted object.
7741 LValue LVal;
7742 {
7743 // The operand of __builtin_object_size is never evaluated for side-effects.
7744 // If there are any, but we can determine the pointed-to object anyway, then
7745 // ignore the side-effects.
7746 SpeculativeEvaluationRAII SpeculativeEval(Info);
7747 FoldOffsetRAII Fold(Info);
7748
7749 if (E->isGLValue()) {
7750 // It's possible for us to be given GLValues if we're called via
7751 // Expr::tryEvaluateObjectSize.
7752 APValue RVal;
7753 if (!EvaluateAsRValue(Info, E, RVal))
7754 return false;
7755 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007756 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7757 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007758 return false;
7759 }
7760
7761 // If we point to before the start of the object, there are no accessible
7762 // bytes.
7763 if (LVal.getLValueOffset().isNegative()) {
7764 Size = 0;
7765 return true;
7766 }
7767
7768 CharUnits EndOffset;
7769 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7770 return false;
7771
7772 // If we've fallen outside of the end offset, just pretend there's nothing to
7773 // write to/read from.
7774 if (EndOffset <= LVal.getLValueOffset())
7775 Size = 0;
7776 else
7777 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7778 return true;
John McCall95007602010-05-10 23:27:23 +00007779}
7780
Peter Collingbournee9200682011-05-13 03:29:01 +00007781bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007782 if (unsigned BuiltinOp = E->getBuiltinCallee())
7783 return VisitBuiltinCallExpr(E, BuiltinOp);
7784
7785 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7786}
7787
7788bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7789 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007790 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007791 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007792 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007793
7794 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007795 // The type was checked when we built the expression.
7796 unsigned Type =
7797 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7798 assert(Type <= 3 && "unexpected type");
7799
George Burgess IVe3763372016-12-22 02:50:20 +00007800 uint64_t Size;
7801 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7802 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007803
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007804 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007805 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007806
Richard Smith01ade172012-05-23 04:13:20 +00007807 // Expression had no side effects, but we couldn't statically determine the
7808 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007809 switch (Info.EvalMode) {
7810 case EvalInfo::EM_ConstantExpression:
7811 case EvalInfo::EM_PotentialConstantExpression:
7812 case EvalInfo::EM_ConstantFold:
7813 case EvalInfo::EM_EvaluateForOverflow:
7814 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007815 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007816 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007817 return Error(E);
7818 case EvalInfo::EM_ConstantExpressionUnevaluated:
7819 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007820 // Reduce it to a constant now.
7821 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007822 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007823
7824 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007825 }
7826
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007827 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007828 case Builtin::BI__builtin_bswap32:
7829 case Builtin::BI__builtin_bswap64: {
7830 APSInt Val;
7831 if (!EvaluateInteger(E->getArg(0), Val, Info))
7832 return false;
7833
7834 return Success(Val.byteSwap(), E);
7835 }
7836
Richard Smith8889a3d2013-06-13 06:26:32 +00007837 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007838 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007839
7840 // FIXME: BI__builtin_clrsb
7841 // FIXME: BI__builtin_clrsbl
7842 // FIXME: BI__builtin_clrsbll
7843
Richard Smith80b3c8e2013-06-13 05:04:16 +00007844 case Builtin::BI__builtin_clz:
7845 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007846 case Builtin::BI__builtin_clzll:
7847 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007848 APSInt Val;
7849 if (!EvaluateInteger(E->getArg(0), Val, Info))
7850 return false;
7851 if (!Val)
7852 return Error(E);
7853
7854 return Success(Val.countLeadingZeros(), E);
7855 }
7856
Richard Smith8889a3d2013-06-13 06:26:32 +00007857 case Builtin::BI__builtin_constant_p:
7858 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7859
Richard Smith80b3c8e2013-06-13 05:04:16 +00007860 case Builtin::BI__builtin_ctz:
7861 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007862 case Builtin::BI__builtin_ctzll:
7863 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007864 APSInt Val;
7865 if (!EvaluateInteger(E->getArg(0), Val, Info))
7866 return false;
7867 if (!Val)
7868 return Error(E);
7869
7870 return Success(Val.countTrailingZeros(), E);
7871 }
7872
Richard Smith8889a3d2013-06-13 06:26:32 +00007873 case Builtin::BI__builtin_eh_return_data_regno: {
7874 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7875 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7876 return Success(Operand, E);
7877 }
7878
7879 case Builtin::BI__builtin_expect:
7880 return Visit(E->getArg(0));
7881
7882 case Builtin::BI__builtin_ffs:
7883 case Builtin::BI__builtin_ffsl:
7884 case Builtin::BI__builtin_ffsll: {
7885 APSInt Val;
7886 if (!EvaluateInteger(E->getArg(0), Val, Info))
7887 return false;
7888
7889 unsigned N = Val.countTrailingZeros();
7890 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7891 }
7892
7893 case Builtin::BI__builtin_fpclassify: {
7894 APFloat Val(0.0);
7895 if (!EvaluateFloat(E->getArg(5), Val, Info))
7896 return false;
7897 unsigned Arg;
7898 switch (Val.getCategory()) {
7899 case APFloat::fcNaN: Arg = 0; break;
7900 case APFloat::fcInfinity: Arg = 1; break;
7901 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7902 case APFloat::fcZero: Arg = 4; break;
7903 }
7904 return Visit(E->getArg(Arg));
7905 }
7906
7907 case Builtin::BI__builtin_isinf_sign: {
7908 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007909 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007910 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7911 }
7912
Richard Smithea3019d2013-10-15 19:07:14 +00007913 case Builtin::BI__builtin_isinf: {
7914 APFloat Val(0.0);
7915 return EvaluateFloat(E->getArg(0), Val, Info) &&
7916 Success(Val.isInfinity() ? 1 : 0, E);
7917 }
7918
7919 case Builtin::BI__builtin_isfinite: {
7920 APFloat Val(0.0);
7921 return EvaluateFloat(E->getArg(0), Val, Info) &&
7922 Success(Val.isFinite() ? 1 : 0, E);
7923 }
7924
7925 case Builtin::BI__builtin_isnan: {
7926 APFloat Val(0.0);
7927 return EvaluateFloat(E->getArg(0), Val, Info) &&
7928 Success(Val.isNaN() ? 1 : 0, E);
7929 }
7930
7931 case Builtin::BI__builtin_isnormal: {
7932 APFloat Val(0.0);
7933 return EvaluateFloat(E->getArg(0), Val, Info) &&
7934 Success(Val.isNormal() ? 1 : 0, E);
7935 }
7936
Richard Smith8889a3d2013-06-13 06:26:32 +00007937 case Builtin::BI__builtin_parity:
7938 case Builtin::BI__builtin_parityl:
7939 case Builtin::BI__builtin_parityll: {
7940 APSInt Val;
7941 if (!EvaluateInteger(E->getArg(0), Val, Info))
7942 return false;
7943
7944 return Success(Val.countPopulation() % 2, E);
7945 }
7946
Richard Smith80b3c8e2013-06-13 05:04:16 +00007947 case Builtin::BI__builtin_popcount:
7948 case Builtin::BI__builtin_popcountl:
7949 case Builtin::BI__builtin_popcountll: {
7950 APSInt Val;
7951 if (!EvaluateInteger(E->getArg(0), Val, Info))
7952 return false;
7953
7954 return Success(Val.countPopulation(), E);
7955 }
7956
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007957 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007958 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007959 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007960 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007961 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007962 << /*isConstexpr*/0 << /*isConstructor*/0
7963 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007964 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007965 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007966 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007967 case Builtin::BI__builtin_strlen:
7968 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007969 // As an extension, we support __builtin_strlen() as a constant expression,
7970 // and support folding strlen() to a constant.
7971 LValue String;
7972 if (!EvaluatePointer(E->getArg(0), String, Info))
7973 return false;
7974
Richard Smith8110c9d2016-11-29 19:45:17 +00007975 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7976
Richard Smithe6c19f22013-11-15 02:10:04 +00007977 // Fast path: if it's a string literal, search the string value.
7978 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7979 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007980 // The string literal may have embedded null characters. Find the first
7981 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007982 StringRef Str = S->getBytes();
7983 int64_t Off = String.Offset.getQuantity();
7984 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007985 S->getCharByteWidth() == 1 &&
7986 // FIXME: Add fast-path for wchar_t too.
7987 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007988 Str = Str.substr(Off);
7989
7990 StringRef::size_type Pos = Str.find(0);
7991 if (Pos != StringRef::npos)
7992 Str = Str.substr(0, Pos);
7993
7994 return Success(Str.size(), E);
7995 }
7996
7997 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007998 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007999
8000 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00008001 for (uint64_t Strlen = 0; /**/; ++Strlen) {
8002 APValue Char;
8003 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8004 !Char.isInt())
8005 return false;
8006 if (!Char.getInt())
8007 return Success(Strlen, E);
8008 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8009 return false;
8010 }
8011 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008012
Richard Smithe151bab2016-11-11 23:43:35 +00008013 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008014 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008015 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008016 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008017 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008018 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008019 // A call to strlen is not a constant expression.
8020 if (Info.getLangOpts().CPlusPlus11)
8021 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8022 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008023 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00008024 else
8025 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008026 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00008027 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008028 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008029 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008030 case Builtin::BI__builtin_wcsncmp:
8031 case Builtin::BI__builtin_memcmp:
8032 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00008033 LValue String1, String2;
8034 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8035 !EvaluatePointer(E->getArg(1), String2, Info))
8036 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008037
8038 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8039
Richard Smithe151bab2016-11-11 23:43:35 +00008040 uint64_t MaxLength = uint64_t(-1);
8041 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008042 BuiltinOp != Builtin::BIwcscmp &&
8043 BuiltinOp != Builtin::BI__builtin_strcmp &&
8044 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00008045 APSInt N;
8046 if (!EvaluateInteger(E->getArg(2), N, Info))
8047 return false;
8048 MaxLength = N.getExtValue();
8049 }
8050 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008051 BuiltinOp != Builtin::BIwmemcmp &&
8052 BuiltinOp != Builtin::BI__builtin_memcmp &&
8053 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00008054 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8055 BuiltinOp == Builtin::BIwcsncmp ||
8056 BuiltinOp == Builtin::BIwmemcmp ||
8057 BuiltinOp == Builtin::BI__builtin_wcscmp ||
8058 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8059 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Richard Smithe151bab2016-11-11 23:43:35 +00008060 for (; MaxLength; --MaxLength) {
8061 APValue Char1, Char2;
8062 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
8063 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
8064 !Char1.isInt() || !Char2.isInt())
8065 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00008066 if (Char1.getInt() != Char2.getInt()) {
8067 if (IsWide) // wmemcmp compares with wchar_t signedness.
8068 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8069 // memcmp always compares unsigned chars.
8070 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8071 }
Richard Smithe151bab2016-11-11 23:43:35 +00008072 if (StopAtNull && !Char1.getInt())
8073 return Success(0, E);
8074 assert(!(StopAtNull && !Char2.getInt()));
8075 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
8076 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
8077 return false;
8078 }
8079 // We hit the strncmp / memcmp limit.
8080 return Success(0, E);
8081 }
8082
Richard Smith01ba47d2012-04-13 00:45:38 +00008083 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00008084 case Builtin::BI__atomic_is_lock_free:
8085 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00008086 APSInt SizeVal;
8087 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8088 return false;
8089
8090 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8091 // of two less than the maximum inline atomic width, we know it is
8092 // lock-free. If the size isn't a power of two, or greater than the
8093 // maximum alignment where we promote atomics, we know it is not lock-free
8094 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8095 // the answer can only be determined at runtime; for example, 16-byte
8096 // atomics have lock-free implementations on some, but not all,
8097 // x86-64 processors.
8098
8099 // Check power-of-two.
8100 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00008101 if (Size.isPowerOfTwo()) {
8102 // Check against inlining width.
8103 unsigned InlineWidthBits =
8104 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8105 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8106 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8107 Size == CharUnits::One() ||
8108 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8109 Expr::NPC_NeverValueDependent))
8110 // OK, we will inline appropriately-aligned operations of this size,
8111 // and _Atomic(T) is appropriately-aligned.
8112 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008113
Richard Smith01ba47d2012-04-13 00:45:38 +00008114 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8115 castAs<PointerType>()->getPointeeType();
8116 if (!PointeeType->isIncompleteType() &&
8117 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8118 // OK, we will inline operations on this object.
8119 return Success(1, E);
8120 }
8121 }
8122 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008123
Richard Smith01ba47d2012-04-13 00:45:38 +00008124 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8125 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008126 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008127 case Builtin::BIomp_is_initial_device:
8128 // We can decide statically which value the runtime would return if called.
8129 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008130 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008131}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008132
Richard Smith8b3497e2011-10-31 01:37:14 +00008133static bool HasSameBase(const LValue &A, const LValue &B) {
8134 if (!A.getLValueBase())
8135 return !B.getLValueBase();
8136 if (!B.getLValueBase())
8137 return false;
8138
Richard Smithce40ad62011-11-12 22:28:03 +00008139 if (A.getLValueBase().getOpaqueValue() !=
8140 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008141 const Decl *ADecl = GetLValueBaseDecl(A);
8142 if (!ADecl)
8143 return false;
8144 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00008145 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00008146 return false;
8147 }
8148
8149 return IsGlobalLValue(A.getLValueBase()) ||
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00008150 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
8151 A.getLValueVersion() == B.getLValueVersion());
Richard Smith8b3497e2011-10-31 01:37:14 +00008152}
8153
Richard Smithd20f1e62014-10-21 23:01:04 +00008154/// \brief Determine whether this is a pointer past the end of the complete
8155/// object referred to by the lvalue.
8156static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8157 const LValue &LV) {
8158 // A null pointer can be viewed as being "past the end" but we don't
8159 // choose to look at it that way here.
8160 if (!LV.getLValueBase())
8161 return false;
8162
8163 // If the designator is valid and refers to a subobject, we're not pointing
8164 // past the end.
8165 if (!LV.getLValueDesignator().Invalid &&
8166 !LV.getLValueDesignator().isOnePastTheEnd())
8167 return false;
8168
David Majnemerc378ca52015-08-29 08:32:55 +00008169 // A pointer to an incomplete type might be past-the-end if the type's size is
8170 // zero. We cannot tell because the type is incomplete.
8171 QualType Ty = getType(LV.getLValueBase());
8172 if (Ty->isIncompleteType())
8173 return true;
8174
Richard Smithd20f1e62014-10-21 23:01:04 +00008175 // We're a past-the-end pointer if we point to the byte after the object,
8176 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008177 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008178 return LV.getLValueOffset() == Size;
8179}
8180
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008181namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008182
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008183/// \brief Data recursive integer evaluator of certain binary operators.
8184///
8185/// We use a data recursive algorithm for binary operators so that we are able
8186/// to handle extreme cases of chained binary operators without causing stack
8187/// overflow.
8188class DataRecursiveIntBinOpEvaluator {
8189 struct EvalResult {
8190 APValue Val;
8191 bool Failed;
8192
8193 EvalResult() : Failed(false) { }
8194
8195 void swap(EvalResult &RHS) {
8196 Val.swap(RHS.Val);
8197 Failed = RHS.Failed;
8198 RHS.Failed = false;
8199 }
8200 };
8201
8202 struct Job {
8203 const Expr *E;
8204 EvalResult LHSResult; // meaningful only for binary operator expression.
8205 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008206
David Blaikie73726062015-08-12 23:09:24 +00008207 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008208 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008209
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008210 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008211 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008212 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008213
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008214 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008215 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008216 };
8217
8218 SmallVector<Job, 16> Queue;
8219
8220 IntExprEvaluator &IntEval;
8221 EvalInfo &Info;
8222 APValue &FinalResult;
8223
8224public:
8225 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8226 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8227
8228 /// \brief True if \param E is a binary operator that we are going to handle
8229 /// data recursively.
8230 /// We handle binary operators that are comma, logical, or that have operands
8231 /// with integral or enumeration type.
8232 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008233 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8234 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +00008235 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008236 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008237 }
8238
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008239 bool Traverse(const BinaryOperator *E) {
8240 enqueue(E);
8241 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008242 while (!Queue.empty())
8243 process(PrevResult);
8244
8245 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008246
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008247 FinalResult.swap(PrevResult.Val);
8248 return true;
8249 }
8250
8251private:
8252 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8253 return IntEval.Success(Value, E, Result);
8254 }
8255 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8256 return IntEval.Success(Value, E, Result);
8257 }
8258 bool Error(const Expr *E) {
8259 return IntEval.Error(E);
8260 }
8261 bool Error(const Expr *E, diag::kind D) {
8262 return IntEval.Error(E, D);
8263 }
8264
8265 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8266 return Info.CCEDiag(E, D);
8267 }
8268
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008269 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8270 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008271 bool &SuppressRHSDiags);
8272
8273 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8274 const BinaryOperator *E, APValue &Result);
8275
8276 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8277 Result.Failed = !Evaluate(Result.Val, Info, E);
8278 if (Result.Failed)
8279 Result.Val = APValue();
8280 }
8281
Richard Trieuba4d0872012-03-21 23:30:30 +00008282 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008283
8284 void enqueue(const Expr *E) {
8285 E = E->IgnoreParens();
8286 Queue.resize(Queue.size()+1);
8287 Queue.back().E = E;
8288 Queue.back().Kind = Job::AnyExprKind;
8289 }
8290};
8291
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008292}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008293
8294bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008295 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008296 bool &SuppressRHSDiags) {
8297 if (E->getOpcode() == BO_Comma) {
8298 // Ignore LHS but note if we could not evaluate it.
8299 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008300 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008301 return true;
8302 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008303
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008304 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008305 bool LHSAsBool;
8306 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008307 // We were able to evaluate the LHS, see if we can get away with not
8308 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008309 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8310 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008311 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008312 }
8313 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008314 LHSResult.Failed = true;
8315
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008316 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008317 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008318 if (!Info.noteSideEffect())
8319 return false;
8320
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008321 // We can't evaluate the LHS; however, sometimes the result
8322 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8323 // Don't ignore RHS and suppress diagnostics from this arm.
8324 SuppressRHSDiags = true;
8325 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008326
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008327 return true;
8328 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008329
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008330 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8331 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008332
George Burgess IVa145e252016-05-25 22:38:36 +00008333 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008334 return false; // Ignore RHS;
8335
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008336 return true;
8337}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008338
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008339static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8340 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008341 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8342 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8343 // offsets.
8344 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8345 CharUnits &Offset = LVal.getLValueOffset();
8346 uint64_t Offset64 = Offset.getQuantity();
8347 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8348 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8349 : Offset64 + Index64);
8350}
8351
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008352bool DataRecursiveIntBinOpEvaluator::
8353 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8354 const BinaryOperator *E, APValue &Result) {
8355 if (E->getOpcode() == BO_Comma) {
8356 if (RHSResult.Failed)
8357 return false;
8358 Result = RHSResult.Val;
8359 return true;
8360 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008361
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008362 if (E->isLogicalOp()) {
8363 bool lhsResult, rhsResult;
8364 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8365 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008366
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008367 if (LHSIsOK) {
8368 if (RHSIsOK) {
8369 if (E->getOpcode() == BO_LOr)
8370 return Success(lhsResult || rhsResult, E, Result);
8371 else
8372 return Success(lhsResult && rhsResult, E, Result);
8373 }
8374 } else {
8375 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008376 // We can't evaluate the LHS; however, sometimes the result
8377 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8378 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008379 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008380 }
8381 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008382
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008383 return false;
8384 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008385
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008386 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8387 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008388
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008389 if (LHSResult.Failed || RHSResult.Failed)
8390 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008391
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008392 const APValue &LHSVal = LHSResult.Val;
8393 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008394
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008395 // Handle cases like (unsigned long)&a + 4.
8396 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8397 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008398 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008399 return true;
8400 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008401
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008402 // Handle cases like 4 + (unsigned long)&a
8403 if (E->getOpcode() == BO_Add &&
8404 RHSVal.isLValue() && LHSVal.isInt()) {
8405 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008406 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008407 return true;
8408 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008409
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008410 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8411 // Handle (intptr_t)&&A - (intptr_t)&&B.
8412 if (!LHSVal.getLValueOffset().isZero() ||
8413 !RHSVal.getLValueOffset().isZero())
8414 return false;
8415 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8416 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8417 if (!LHSExpr || !RHSExpr)
8418 return false;
8419 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8420 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8421 if (!LHSAddrExpr || !RHSAddrExpr)
8422 return false;
8423 // Make sure both labels come from the same function.
8424 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8425 RHSAddrExpr->getLabel()->getDeclContext())
8426 return false;
8427 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8428 return true;
8429 }
Richard Smith43e77732013-05-07 04:50:00 +00008430
8431 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008432 if (!LHSVal.isInt() || !RHSVal.isInt())
8433 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008434
8435 // Set up the width and signedness manually, in case it can't be deduced
8436 // from the operation we're performing.
8437 // FIXME: Don't do this in the cases where we can deduce it.
8438 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8439 E->getType()->isUnsignedIntegerOrEnumerationType());
8440 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8441 RHSVal.getInt(), Value))
8442 return false;
8443 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008444}
8445
Richard Trieuba4d0872012-03-21 23:30:30 +00008446void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008447 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008448
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008449 switch (job.Kind) {
8450 case Job::AnyExprKind: {
8451 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8452 if (shouldEnqueue(Bop)) {
8453 job.Kind = Job::BinOpKind;
8454 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008455 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008456 }
8457 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008458
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008459 EvaluateExpr(job.E, Result);
8460 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008461 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008462 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008463
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008464 case Job::BinOpKind: {
8465 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008466 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008467 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008468 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008469 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008470 }
8471 if (SuppressRHSDiags)
8472 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008473 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008474 job.Kind = Job::BinOpVisitedLHSKind;
8475 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008476 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008477 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008478
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008479 case Job::BinOpVisitedLHSKind: {
8480 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8481 EvalResult RHS;
8482 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008483 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008484 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008485 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008486 }
8487 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008488
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008489 llvm_unreachable("Invalid Job::Kind!");
8490}
8491
George Burgess IV8c892b52016-05-25 22:31:54 +00008492namespace {
8493/// Used when we determine that we should fail, but can keep evaluating prior to
8494/// noting that we had a failure.
8495class DelayedNoteFailureRAII {
8496 EvalInfo &Info;
8497 bool NoteFailure;
8498
8499public:
8500 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8501 : Info(Info), NoteFailure(NoteFailure) {}
8502 ~DelayedNoteFailureRAII() {
8503 if (NoteFailure) {
8504 bool ContinueAfterFailure = Info.noteFailure();
8505 (void)ContinueAfterFailure;
8506 assert(ContinueAfterFailure &&
8507 "Shouldn't have kept evaluating on failure.");
8508 }
8509 }
8510};
8511}
8512
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008513template <class SuccessCB, class AfterCB>
8514static bool
8515EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
8516 SuccessCB &&Success, AfterCB &&DoAfter) {
8517 assert(E->isComparisonOp() && "expected comparison operator");
8518 assert((E->getOpcode() == BO_Cmp ||
8519 E->getType()->isIntegralOrEnumerationType()) &&
8520 "unsupported binary expression evaluation");
8521 auto Error = [&](const Expr *E) {
8522 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8523 return false;
8524 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008525
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008526 using CCR = ComparisonCategoryResult;
8527 bool IsRelational = E->isRelationalOp();
8528 bool IsEquality = E->isEqualityOp();
8529 if (E->getOpcode() == BO_Cmp) {
8530 const ComparisonCategoryInfo &CmpInfo =
8531 Info.Ctx.CompCategories.getInfoForType(E->getType());
8532 IsRelational = CmpInfo.isOrdered();
8533 IsEquality = CmpInfo.isEquality();
8534 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00008535
Anders Carlssonacc79812008-11-16 07:17:21 +00008536 QualType LHSTy = E->getLHS()->getType();
8537 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008538
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008539 if (LHSTy->isIntegralOrEnumerationType() &&
8540 RHSTy->isIntegralOrEnumerationType()) {
8541 APSInt LHS, RHS;
8542 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
8543 if (!LHSOK && !Info.noteFailure())
8544 return false;
8545 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
8546 return false;
8547 if (LHS < RHS)
8548 return Success(CCR::Less, E);
8549 if (LHS > RHS)
8550 return Success(CCR::Greater, E);
8551 return Success(CCR::Equal, E);
8552 }
8553
Chandler Carruthb29a7432014-10-11 11:03:30 +00008554 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008555 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008556 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008557 if (E->isAssignmentOp()) {
8558 LValue LV;
8559 EvaluateLValue(E->getLHS(), LV, Info);
8560 LHSOK = false;
8561 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008562 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8563 if (LHSOK) {
8564 LHS.makeComplexFloat();
8565 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8566 }
8567 } else {
8568 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8569 }
George Burgess IVa145e252016-05-25 22:38:36 +00008570 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008571 return false;
8572
Chandler Carruthb29a7432014-10-11 11:03:30 +00008573 if (E->getRHS()->getType()->isRealFloatingType()) {
8574 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8575 return false;
8576 RHS.makeComplexFloat();
8577 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8578 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008579 return false;
8580
8581 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008582 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008583 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008584 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008585 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008586 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
8587 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008588 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008589 assert(IsEquality && "invalid complex comparison");
8590 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8591 LHS.getComplexIntImag() == RHS.getComplexIntImag();
8592 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008593 }
8594 }
Mike Stump11289f42009-09-09 15:08:12 +00008595
Anders Carlssonacc79812008-11-16 07:17:21 +00008596 if (LHSTy->isRealFloatingType() &&
8597 RHSTy->isRealFloatingType()) {
8598 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008599
Richard Smith253c2a32012-01-27 01:14:48 +00008600 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008601 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008602 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008603
Richard Smith253c2a32012-01-27 01:14:48 +00008604 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008605 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008606
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008607 assert(E->isComparisonOp() && "Invalid binary operator!");
8608 auto GetCmpRes = [&]() {
8609 switch (LHS.compare(RHS)) {
8610 case APFloat::cmpEqual:
8611 return CCR::Equal;
8612 case APFloat::cmpLessThan:
8613 return CCR::Less;
8614 case APFloat::cmpGreaterThan:
8615 return CCR::Greater;
8616 case APFloat::cmpUnordered:
8617 return CCR::Unordered;
8618 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +00008619 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008620 };
8621 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008622 }
Mike Stump11289f42009-09-09 15:08:12 +00008623
Eli Friedmana38da572009-04-28 19:17:36 +00008624 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008625 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +00008626
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008627 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8628 if (!LHSOK && !Info.noteFailure())
8629 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008630
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008631 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8632 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008633
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008634 // Reject differing bases from the normal codepath; we special-case
8635 // comparisons to null.
8636 if (!HasSameBase(LHSValue, RHSValue)) {
8637 // Inequalities and subtractions between unrelated pointers have
8638 // unspecified or undefined behavior.
8639 if (!IsEquality)
8640 return Error(E);
8641 // A constant address may compare equal to the address of a symbol.
8642 // The one exception is that address of an object cannot compare equal
8643 // to a null pointer constant.
8644 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8645 (!RHSValue.Base && !RHSValue.Offset.isZero()))
8646 return Error(E);
8647 // It's implementation-defined whether distinct literals will have
8648 // distinct addresses. In clang, the result of such a comparison is
8649 // unspecified, so it is not a constant expression. However, we do know
8650 // that the address of a literal will be non-null.
8651 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8652 LHSValue.Base && RHSValue.Base)
8653 return Error(E);
8654 // We can't tell whether weak symbols will end up pointing to the same
8655 // object.
8656 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
8657 return Error(E);
8658 // We can't compare the address of the start of one object with the
8659 // past-the-end address of another object, per C++ DR1652.
8660 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8661 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8662 (RHSValue.Base && RHSValue.Offset.isZero() &&
8663 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8664 return Error(E);
8665 // We can't tell whether an object is at the same address as another
8666 // zero sized object.
8667 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8668 (LHSValue.Base && isZeroSized(RHSValue)))
8669 return Error(E);
8670 return Success(CCR::Nonequal, E);
8671 }
Eli Friedman64004332009-03-23 04:38:34 +00008672
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008673 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8674 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +00008675
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008676 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8677 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +00008678
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008679 // C++11 [expr.rel]p3:
8680 // Pointers to void (after pointer conversions) can be compared, with a
8681 // result defined as follows: If both pointers represent the same
8682 // address or are both the null pointer value, the result is true if the
8683 // operator is <= or >= and false otherwise; otherwise the result is
8684 // unspecified.
8685 // We interpret this as applying to pointers to *cv* void.
8686 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
8687 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +00008688
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008689 // C++11 [expr.rel]p2:
8690 // - If two pointers point to non-static data members of the same object,
8691 // or to subobjects or array elements fo such members, recursively, the
8692 // pointer to the later declared member compares greater provided the
8693 // two members have the same access control and provided their class is
8694 // not a union.
8695 // [...]
8696 // - Otherwise pointer comparisons are unspecified.
8697 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
8698 bool WasArrayIndex;
8699 unsigned Mismatch = FindDesignatorMismatch(
8700 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
8701 // At the point where the designators diverge, the comparison has a
8702 // specified value if:
8703 // - we are comparing array indices
8704 // - we are comparing fields of a union, or fields with the same access
8705 // Otherwise, the result is unspecified and thus the comparison is not a
8706 // constant expression.
8707 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8708 Mismatch < RHSDesignator.Entries.size()) {
8709 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8710 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8711 if (!LF && !RF)
8712 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8713 else if (!LF)
8714 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00008715 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8716 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008717 else if (!RF)
8718 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00008719 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8720 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008721 else if (!LF->getParent()->isUnion() &&
8722 LF->getAccess() != RF->getAccess())
8723 Info.CCEDiag(E,
8724 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +00008725 << LF << LF->getAccess() << RF << RF->getAccess()
8726 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +00008727 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008728 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008729
8730 // The comparison here must be unsigned, and performed with the same
8731 // width as the pointer.
8732 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8733 uint64_t CompareLHS = LHSOffset.getQuantity();
8734 uint64_t CompareRHS = RHSOffset.getQuantity();
8735 assert(PtrSize <= 64 && "Unexpected pointer width");
8736 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8737 CompareLHS &= Mask;
8738 CompareRHS &= Mask;
8739
8740 // If there is a base and this is a relational operator, we can only
8741 // compare pointers within the object in question; otherwise, the result
8742 // depends on where the object is located in memory.
8743 if (!LHSValue.Base.isNull() && IsRelational) {
8744 QualType BaseTy = getType(LHSValue.Base);
8745 if (BaseTy->isIncompleteType())
8746 return Error(E);
8747 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8748 uint64_t OffsetLimit = Size.getQuantity();
8749 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8750 return Error(E);
8751 }
8752
8753 if (CompareLHS < CompareRHS)
8754 return Success(CCR::Less, E);
8755 if (CompareLHS > CompareRHS)
8756 return Success(CCR::Greater, E);
8757 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008758 }
Richard Smith7bb00672012-02-01 01:42:44 +00008759
8760 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008761 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +00008762 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8763
8764 MemberPtr LHSValue, RHSValue;
8765
8766 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008767 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008768 return false;
8769
8770 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8771 return false;
8772
8773 // C++11 [expr.eq]p2:
8774 // If both operands are null, they compare equal. Otherwise if only one is
8775 // null, they compare unequal.
8776 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8777 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008778 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00008779 }
8780
8781 // Otherwise if either is a pointer to a virtual member function, the
8782 // result is unspecified.
8783 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8784 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008785 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00008786 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8787 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008788 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00008789
8790 // Otherwise they compare equal if and only if they would refer to the
8791 // same member of the same most derived object or the same subobject if
8792 // they were dereferenced with a hypothetical object of the associated
8793 // class type.
8794 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008795 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00008796 }
8797
Richard Smithab44d9b2012-02-14 22:35:28 +00008798 if (LHSTy->isNullPtrType()) {
8799 assert(E->isComparisonOp() && "unexpected nullptr operation");
8800 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8801 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8802 // are compared, the result is true of the operator is <=, >= or ==, and
8803 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008804 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +00008805 }
8806
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008807 return DoAfter();
8808}
8809
8810bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
8811 if (!CheckLiteralType(Info, E))
8812 return false;
8813
8814 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
8815 const BinaryOperator *E) {
8816 // Evaluation succeeded. Lookup the information for the comparison category
8817 // type and fetch the VarDecl for the result.
8818 const ComparisonCategoryInfo &CmpInfo =
8819 Info.Ctx.CompCategories.getInfoForType(E->getType());
8820 const VarDecl *VD =
8821 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
8822 // Check and evaluate the result as a constant expression.
8823 LValue LV;
8824 LV.set(VD);
8825 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
8826 return false;
8827 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
8828 };
8829 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
8830 return ExprEvaluatorBaseTy::VisitBinCmp(E);
8831 });
8832}
8833
8834bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8835 // We don't call noteFailure immediately because the assignment happens after
8836 // we evaluate LHS and RHS.
8837 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
8838 return Error(E);
8839
8840 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
8841 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8842 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
8843
8844 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
8845 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008846 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008847
8848 if (E->isComparisonOp()) {
8849 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
8850 // comparisons and then translating the result.
8851 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
8852 const BinaryOperator *E) {
8853 using CCR = ComparisonCategoryResult;
8854 bool IsEqual = ResKind == CCR::Equal,
8855 IsLess = ResKind == CCR::Less,
8856 IsGreater = ResKind == CCR::Greater;
8857 auto Op = E->getOpcode();
8858 switch (Op) {
8859 default:
8860 llvm_unreachable("unsupported binary operator");
8861 case BO_EQ:
8862 case BO_NE:
8863 return Success(IsEqual == (Op == BO_EQ), E);
8864 case BO_LT: return Success(IsLess, E);
8865 case BO_GT: return Success(IsGreater, E);
8866 case BO_LE: return Success(IsEqual || IsLess, E);
8867 case BO_GE: return Success(IsEqual || IsGreater, E);
8868 }
8869 };
8870 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
8871 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8872 });
8873 }
8874
8875 QualType LHSTy = E->getLHS()->getType();
8876 QualType RHSTy = E->getRHS()->getType();
8877
8878 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
8879 E->getOpcode() == BO_Sub) {
8880 LValue LHSValue, RHSValue;
8881
8882 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8883 if (!LHSOK && !Info.noteFailure())
8884 return false;
8885
8886 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8887 return false;
8888
8889 // Reject differing bases from the normal codepath; we special-case
8890 // comparisons to null.
8891 if (!HasSameBase(LHSValue, RHSValue)) {
8892 // Handle &&A - &&B.
8893 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
8894 return Error(E);
8895 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
8896 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
8897 if (!LHSExpr || !RHSExpr)
8898 return Error(E);
8899 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8900 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8901 if (!LHSAddrExpr || !RHSAddrExpr)
8902 return Error(E);
8903 // Make sure both labels come from the same function.
8904 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8905 RHSAddrExpr->getLabel()->getDeclContext())
8906 return Error(E);
8907 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
8908 }
8909 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8910 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8911
8912 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8913 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8914
8915 // C++11 [expr.add]p6:
8916 // Unless both pointers point to elements of the same array object, or
8917 // one past the last element of the array object, the behavior is
8918 // undefined.
8919 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8920 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
8921 RHSDesignator))
8922 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8923
8924 QualType Type = E->getLHS()->getType();
8925 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
8926
8927 CharUnits ElementSize;
8928 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
8929 return false;
8930
8931 // As an extension, a type may have zero size (empty struct or union in
8932 // C, array of zero length). Pointer subtraction in such cases has
8933 // undefined behavior, so is not constant.
8934 if (ElementSize.isZero()) {
8935 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
8936 << ElementType;
8937 return false;
8938 }
8939
8940 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8941 // and produce incorrect results when it overflows. Such behavior
8942 // appears to be non-conforming, but is common, so perhaps we should
8943 // assume the standard intended for such cases to be undefined behavior
8944 // and check for them.
8945
8946 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8947 // overflow in the final conversion to ptrdiff_t.
8948 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8949 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8950 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
8951 false);
8952 APSInt TrueResult = (LHS - RHS) / ElemSize;
8953 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8954
8955 if (Result.extend(65) != TrueResult &&
8956 !HandleOverflow(Info, E, TrueResult, E->getType()))
8957 return false;
8958 return Success(Result, E);
8959 }
8960
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008961 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008962}
8963
Peter Collingbournee190dee2011-03-11 19:24:49 +00008964/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8965/// a result as the expression's type.
8966bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8967 const UnaryExprOrTypeTraitExpr *E) {
8968 switch(E->getKind()) {
8969 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008970 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008971 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008972 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008973 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008974 }
Eli Friedman64004332009-03-23 04:38:34 +00008975
Peter Collingbournee190dee2011-03-11 19:24:49 +00008976 case UETT_VecStep: {
8977 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008978
Peter Collingbournee190dee2011-03-11 19:24:49 +00008979 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008980 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008981
Peter Collingbournee190dee2011-03-11 19:24:49 +00008982 // The vec_step built-in functions that take a 3-component
8983 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8984 if (n == 3)
8985 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008986
Peter Collingbournee190dee2011-03-11 19:24:49 +00008987 return Success(n, E);
8988 } else
8989 return Success(1, E);
8990 }
8991
8992 case UETT_SizeOf: {
8993 QualType SrcTy = E->getTypeOfArgument();
8994 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8995 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008996 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8997 SrcTy = Ref->getPointeeType();
8998
Richard Smithd62306a2011-11-10 06:34:14 +00008999 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00009000 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00009001 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00009002 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009003 }
Alexey Bataev00396512015-07-02 03:40:19 +00009004 case UETT_OpenMPRequiredSimdAlign:
9005 assert(E->isArgumentType());
9006 return Success(
9007 Info.Ctx.toCharUnitsFromBits(
9008 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9009 .getQuantity(),
9010 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009011 }
9012
9013 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00009014}
9015
Peter Collingbournee9200682011-05-13 03:29:01 +00009016bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009017 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00009018 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00009019 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009020 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00009021 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00009022 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00009023 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00009024 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00009025 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00009026 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00009027 APSInt IdxResult;
9028 if (!EvaluateInteger(Idx, IdxResult, Info))
9029 return false;
9030 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9031 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009032 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009033 CurrentType = AT->getElementType();
9034 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9035 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00009036 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00009037 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009038
James Y Knight7281c352015-12-29 22:31:18 +00009039 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00009040 FieldDecl *MemberDecl = ON.getField();
9041 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009042 if (!RT)
9043 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009044 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009045 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00009046 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00009047 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00009048 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00009049 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00009050 CurrentType = MemberDecl->getType().getNonReferenceType();
9051 break;
9052 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009053
James Y Knight7281c352015-12-29 22:31:18 +00009054 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00009055 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00009056
James Y Knight7281c352015-12-29 22:31:18 +00009057 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00009058 CXXBaseSpecifier *BaseSpec = ON.getBase();
9059 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00009060 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009061
9062 // Find the layout of the class whose base we are looking into.
9063 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009064 if (!RT)
9065 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009066 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009067 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00009068 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9069
9070 // Find the base class itself.
9071 CurrentType = BaseSpec->getType();
9072 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9073 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009074 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00009075
Douglas Gregord1702062010-04-29 00:18:15 +00009076 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00009077 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00009078 break;
9079 }
Douglas Gregor882211c2010-04-28 22:16:22 +00009080 }
9081 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009082 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009083}
9084
Chris Lattnere13042c2008-07-11 19:10:17 +00009085bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009086 switch (E->getOpcode()) {
9087 default:
9088 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9089 // See C99 6.6p3.
9090 return Error(E);
9091 case UO_Extension:
9092 // FIXME: Should extension allow i-c-e extension expressions in its scope?
9093 // If so, we could clear the diagnostic ID.
9094 return Visit(E->getSubExpr());
9095 case UO_Plus:
9096 // The result is just the value.
9097 return Visit(E->getSubExpr());
9098 case UO_Minus: {
9099 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00009100 return false;
9101 if (!Result.isInt()) return Error(E);
9102 const APSInt &Value = Result.getInt();
9103 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9104 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9105 E->getType()))
9106 return false;
Richard Smithfe800032012-01-31 04:08:20 +00009107 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009108 }
9109 case UO_Not: {
9110 if (!Visit(E->getSubExpr()))
9111 return false;
9112 if (!Result.isInt()) return Error(E);
9113 return Success(~Result.getInt(), E);
9114 }
9115 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00009116 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00009117 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00009118 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009119 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00009120 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009121 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009122}
Mike Stump11289f42009-09-09 15:08:12 +00009123
Chris Lattner477c4be2008-07-12 01:15:53 +00009124/// HandleCast - This is used to evaluate implicit or explicit casts where the
9125/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00009126bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9127 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009128 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00009129 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009130
Eli Friedmanc757de22011-03-25 00:43:55 +00009131 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00009132 case CK_BaseToDerived:
9133 case CK_DerivedToBase:
9134 case CK_UncheckedDerivedToBase:
9135 case CK_Dynamic:
9136 case CK_ToUnion:
9137 case CK_ArrayToPointerDecay:
9138 case CK_FunctionToPointerDecay:
9139 case CK_NullToPointer:
9140 case CK_NullToMemberPointer:
9141 case CK_BaseToDerivedMemberPointer:
9142 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00009143 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00009144 case CK_ConstructorConversion:
9145 case CK_IntegralToPointer:
9146 case CK_ToVoid:
9147 case CK_VectorSplat:
9148 case CK_IntegralToFloating:
9149 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009150 case CK_CPointerToObjCPointerCast:
9151 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009152 case CK_AnyPointerToBlockPointerCast:
9153 case CK_ObjCObjectLValueCast:
9154 case CK_FloatingRealToComplex:
9155 case CK_FloatingComplexToReal:
9156 case CK_FloatingComplexCast:
9157 case CK_FloatingComplexToIntegralComplex:
9158 case CK_IntegralRealToComplex:
9159 case CK_IntegralComplexCast:
9160 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00009161 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009162 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009163 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009164 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009165 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009166 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00009167 llvm_unreachable("invalid cast kind for integral value");
9168
Eli Friedman9faf2f92011-03-25 19:07:11 +00009169 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009170 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009171 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00009172 case CK_ARCProduceObject:
9173 case CK_ARCConsumeObject:
9174 case CK_ARCReclaimReturnedObject:
9175 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009176 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009177 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009178
Richard Smith4ef685b2012-01-17 21:17:26 +00009179 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009180 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009181 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009182 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009183 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009184
9185 case CK_MemberPointerToBoolean:
9186 case CK_PointerToBoolean:
9187 case CK_IntegralToBoolean:
9188 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009189 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009190 case CK_FloatingComplexToBoolean:
9191 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009192 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009193 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009194 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009195 uint64_t IntResult = BoolResult;
9196 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9197 IntResult = (uint64_t)-1;
9198 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009199 }
9200
Eli Friedmanc757de22011-03-25 00:43:55 +00009201 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009202 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009203 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009204
Eli Friedman742421e2009-02-20 01:15:07 +00009205 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009206 // Allow casts of address-of-label differences if they are no-ops
9207 // or narrowing. (The narrowing case isn't actually guaranteed to
9208 // be constant-evaluatable except in some narrow cases which are hard
9209 // to detect here. We let it through on the assumption the user knows
9210 // what they are doing.)
9211 if (Result.isAddrLabelDiff())
9212 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009213 // Only allow casts of lvalues if they are lossless.
9214 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9215 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009216
Richard Smith911e1422012-01-30 22:27:01 +00009217 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9218 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009219 }
Mike Stump11289f42009-09-09 15:08:12 +00009220
Eli Friedmanc757de22011-03-25 00:43:55 +00009221 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009222 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9223
John McCall45d55e42010-05-07 21:00:08 +00009224 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009225 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009226 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009227
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009228 if (LV.getLValueBase()) {
9229 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009230 // FIXME: Allow a larger integer size than the pointer size, and allow
9231 // narrowing back down to pointer width in subsequent integral casts.
9232 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009233 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009234 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009235
Richard Smithcf74da72011-11-16 07:18:12 +00009236 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009237 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009238 return true;
9239 }
9240
Yaxun Liu402804b2016-12-15 08:09:08 +00009241 uint64_t V;
9242 if (LV.isNullPointer())
9243 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9244 else
9245 V = LV.getLValueOffset().getQuantity();
9246
9247 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009248 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009249 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009250
Eli Friedmanc757de22011-03-25 00:43:55 +00009251 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009252 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009253 if (!EvaluateComplex(SubExpr, C, Info))
9254 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009255 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009256 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009257
Eli Friedmanc757de22011-03-25 00:43:55 +00009258 case CK_FloatingToIntegral: {
9259 APFloat F(0.0);
9260 if (!EvaluateFloat(SubExpr, F, Info))
9261 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009262
Richard Smith357362d2011-12-13 06:39:58 +00009263 APSInt Value;
9264 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9265 return false;
9266 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009267 }
9268 }
Mike Stump11289f42009-09-09 15:08:12 +00009269
Eli Friedmanc757de22011-03-25 00:43:55 +00009270 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009271}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009272
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009273bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9274 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009275 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009276 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9277 return false;
9278 if (!LV.isComplexInt())
9279 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009280 return Success(LV.getComplexIntReal(), E);
9281 }
9282
9283 return Visit(E->getSubExpr());
9284}
9285
Eli Friedman4e7a2412009-02-27 04:45:43 +00009286bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009287 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009288 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009289 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9290 return false;
9291 if (!LV.isComplexInt())
9292 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009293 return Success(LV.getComplexIntImag(), E);
9294 }
9295
Richard Smith4a678122011-10-24 18:44:57 +00009296 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009297 return Success(0, E);
9298}
9299
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009300bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9301 return Success(E->getPackLength(), E);
9302}
9303
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009304bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9305 return Success(E->getValue(), E);
9306}
9307
Chris Lattner05706e882008-07-11 18:11:29 +00009308//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009309// Float Evaluation
9310//===----------------------------------------------------------------------===//
9311
9312namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009313class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009314 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009315 APFloat &Result;
9316public:
9317 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009318 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009319
Richard Smith2e312c82012-03-03 22:46:17 +00009320 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009321 Result = V.getFloat();
9322 return true;
9323 }
Eli Friedman24c01542008-08-22 00:06:13 +00009324
Richard Smithfddd3842011-12-30 21:15:51 +00009325 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009326 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9327 return true;
9328 }
9329
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009330 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009331
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009332 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009333 bool VisitBinaryOperator(const BinaryOperator *E);
9334 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009335 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009336
John McCallb1fb0d32010-05-07 22:08:54 +00009337 bool VisitUnaryReal(const UnaryOperator *E);
9338 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009339
Richard Smithfddd3842011-12-30 21:15:51 +00009340 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009341};
9342} // end anonymous namespace
9343
9344static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009345 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009346 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009347}
9348
Jay Foad39c79802011-01-12 09:06:06 +00009349static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009350 QualType ResultTy,
9351 const Expr *Arg,
9352 bool SNaN,
9353 llvm::APFloat &Result) {
9354 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9355 if (!S) return false;
9356
9357 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9358
9359 llvm::APInt fill;
9360
9361 // Treat empty strings as if they were zero.
9362 if (S->getString().empty())
9363 fill = llvm::APInt(32, 0);
9364 else if (S->getString().getAsInteger(0, fill))
9365 return false;
9366
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009367 if (Context.getTargetInfo().isNan2008()) {
9368 if (SNaN)
9369 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9370 else
9371 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9372 } else {
9373 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9374 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9375 // a different encoding to what became a standard in 2008, and for pre-
9376 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9377 // sNaN. This is now known as "legacy NaN" encoding.
9378 if (SNaN)
9379 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9380 else
9381 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9382 }
9383
John McCall16291492010-02-28 13:00:19 +00009384 return true;
9385}
9386
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009387bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009388 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009389 default:
9390 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9391
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009392 case Builtin::BI__builtin_huge_val:
9393 case Builtin::BI__builtin_huge_valf:
9394 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009395 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009396 case Builtin::BI__builtin_inf:
9397 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009398 case Builtin::BI__builtin_infl:
9399 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009400 const llvm::fltSemantics &Sem =
9401 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009402 Result = llvm::APFloat::getInf(Sem);
9403 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009404 }
Mike Stump11289f42009-09-09 15:08:12 +00009405
John McCall16291492010-02-28 13:00:19 +00009406 case Builtin::BI__builtin_nans:
9407 case Builtin::BI__builtin_nansf:
9408 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009409 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009410 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9411 true, Result))
9412 return Error(E);
9413 return true;
John McCall16291492010-02-28 13:00:19 +00009414
Chris Lattner0b7282e2008-10-06 06:31:58 +00009415 case Builtin::BI__builtin_nan:
9416 case Builtin::BI__builtin_nanf:
9417 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009418 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +00009419 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009420 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009421 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9422 false, Result))
9423 return Error(E);
9424 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009425
9426 case Builtin::BI__builtin_fabs:
9427 case Builtin::BI__builtin_fabsf:
9428 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009429 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009430 if (!EvaluateFloat(E->getArg(0), Result, Info))
9431 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009432
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009433 if (Result.isNegative())
9434 Result.changeSign();
9435 return true;
9436
Richard Smith8889a3d2013-06-13 06:26:32 +00009437 // FIXME: Builtin::BI__builtin_powi
9438 // FIXME: Builtin::BI__builtin_powif
9439 // FIXME: Builtin::BI__builtin_powil
9440
Mike Stump11289f42009-09-09 15:08:12 +00009441 case Builtin::BI__builtin_copysign:
9442 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009443 case Builtin::BI__builtin_copysignl:
9444 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009445 APFloat RHS(0.);
9446 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9447 !EvaluateFloat(E->getArg(1), RHS, Info))
9448 return false;
9449 Result.copySign(RHS);
9450 return true;
9451 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009452 }
9453}
9454
John McCallb1fb0d32010-05-07 22:08:54 +00009455bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009456 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9457 ComplexValue CV;
9458 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9459 return false;
9460 Result = CV.FloatReal;
9461 return true;
9462 }
9463
9464 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009465}
9466
9467bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009468 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9469 ComplexValue CV;
9470 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9471 return false;
9472 Result = CV.FloatImag;
9473 return true;
9474 }
9475
Richard Smith4a678122011-10-24 18:44:57 +00009476 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009477 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9478 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009479 return true;
9480}
9481
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009482bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009483 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009484 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009485 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009486 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009487 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009488 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9489 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009490 Result.changeSign();
9491 return true;
9492 }
9493}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009494
Eli Friedman24c01542008-08-22 00:06:13 +00009495bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009496 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9497 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009498
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009499 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009500 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009501 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009502 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009503 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9504 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009505}
9506
9507bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9508 Result = E->getValue();
9509 return true;
9510}
9511
Peter Collingbournee9200682011-05-13 03:29:01 +00009512bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9513 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009514
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009515 switch (E->getCastKind()) {
9516 default:
Richard Smith11562c52011-10-28 17:51:58 +00009517 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009518
9519 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009520 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009521 return EvaluateInteger(SubExpr, IntResult, Info) &&
9522 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9523 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009524 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009525
9526 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009527 if (!Visit(SubExpr))
9528 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009529 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9530 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009531 }
John McCalld7646252010-11-14 08:17:51 +00009532
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009533 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009534 ComplexValue V;
9535 if (!EvaluateComplex(SubExpr, V, Info))
9536 return false;
9537 Result = V.getComplexFloatReal();
9538 return true;
9539 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009540 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009541}
9542
Eli Friedman24c01542008-08-22 00:06:13 +00009543//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009544// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009545//===----------------------------------------------------------------------===//
9546
9547namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009548class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009549 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009550 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009551
Anders Carlsson537969c2008-11-16 20:27:53 +00009552public:
John McCall93d91dc2010-05-07 17:22:02 +00009553 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009554 : ExprEvaluatorBaseTy(info), Result(Result) {}
9555
Richard Smith2e312c82012-03-03 22:46:17 +00009556 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009557 Result.setFrom(V);
9558 return true;
9559 }
Mike Stump11289f42009-09-09 15:08:12 +00009560
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009561 bool ZeroInitialization(const Expr *E);
9562
Anders Carlsson537969c2008-11-16 20:27:53 +00009563 //===--------------------------------------------------------------------===//
9564 // Visitor Methods
9565 //===--------------------------------------------------------------------===//
9566
Peter Collingbournee9200682011-05-13 03:29:01 +00009567 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009568 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009569 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009570 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009571 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009572};
9573} // end anonymous namespace
9574
John McCall93d91dc2010-05-07 17:22:02 +00009575static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9576 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009577 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009578 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009579}
9580
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009581bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009582 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009583 if (ElemTy->isRealFloatingType()) {
9584 Result.makeComplexFloat();
9585 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9586 Result.FloatReal = Zero;
9587 Result.FloatImag = Zero;
9588 } else {
9589 Result.makeComplexInt();
9590 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9591 Result.IntReal = Zero;
9592 Result.IntImag = Zero;
9593 }
9594 return true;
9595}
9596
Peter Collingbournee9200682011-05-13 03:29:01 +00009597bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9598 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009599
9600 if (SubExpr->getType()->isRealFloatingType()) {
9601 Result.makeComplexFloat();
9602 APFloat &Imag = Result.FloatImag;
9603 if (!EvaluateFloat(SubExpr, Imag, Info))
9604 return false;
9605
9606 Result.FloatReal = APFloat(Imag.getSemantics());
9607 return true;
9608 } else {
9609 assert(SubExpr->getType()->isIntegerType() &&
9610 "Unexpected imaginary literal.");
9611
9612 Result.makeComplexInt();
9613 APSInt &Imag = Result.IntImag;
9614 if (!EvaluateInteger(SubExpr, Imag, Info))
9615 return false;
9616
9617 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9618 return true;
9619 }
9620}
9621
Peter Collingbournee9200682011-05-13 03:29:01 +00009622bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009623
John McCallfcef3cf2010-12-14 17:51:41 +00009624 switch (E->getCastKind()) {
9625 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009626 case CK_BaseToDerived:
9627 case CK_DerivedToBase:
9628 case CK_UncheckedDerivedToBase:
9629 case CK_Dynamic:
9630 case CK_ToUnion:
9631 case CK_ArrayToPointerDecay:
9632 case CK_FunctionToPointerDecay:
9633 case CK_NullToPointer:
9634 case CK_NullToMemberPointer:
9635 case CK_BaseToDerivedMemberPointer:
9636 case CK_DerivedToBaseMemberPointer:
9637 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009638 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009639 case CK_ConstructorConversion:
9640 case CK_IntegralToPointer:
9641 case CK_PointerToIntegral:
9642 case CK_PointerToBoolean:
9643 case CK_ToVoid:
9644 case CK_VectorSplat:
9645 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009646 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009647 case CK_IntegralToBoolean:
9648 case CK_IntegralToFloating:
9649 case CK_FloatingToIntegral:
9650 case CK_FloatingToBoolean:
9651 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009652 case CK_CPointerToObjCPointerCast:
9653 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009654 case CK_AnyPointerToBlockPointerCast:
9655 case CK_ObjCObjectLValueCast:
9656 case CK_FloatingComplexToReal:
9657 case CK_FloatingComplexToBoolean:
9658 case CK_IntegralComplexToReal:
9659 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009660 case CK_ARCProduceObject:
9661 case CK_ARCConsumeObject:
9662 case CK_ARCReclaimReturnedObject:
9663 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009664 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009665 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009666 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009667 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009668 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009669 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009670 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009671 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009672
John McCallfcef3cf2010-12-14 17:51:41 +00009673 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009674 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009675 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009676 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009677
9678 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009679 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009680 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009681 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009682
9683 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009684 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009685 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009686 return false;
9687
John McCallfcef3cf2010-12-14 17:51:41 +00009688 Result.makeComplexFloat();
9689 Result.FloatImag = APFloat(Real.getSemantics());
9690 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009691 }
9692
John McCallfcef3cf2010-12-14 17:51:41 +00009693 case CK_FloatingComplexCast: {
9694 if (!Visit(E->getSubExpr()))
9695 return false;
9696
9697 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9698 QualType From
9699 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9700
Richard Smith357362d2011-12-13 06:39:58 +00009701 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9702 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009703 }
9704
9705 case CK_FloatingComplexToIntegralComplex: {
9706 if (!Visit(E->getSubExpr()))
9707 return false;
9708
9709 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9710 QualType From
9711 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9712 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009713 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9714 To, Result.IntReal) &&
9715 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9716 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009717 }
9718
9719 case CK_IntegralRealToComplex: {
9720 APSInt &Real = Result.IntReal;
9721 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9722 return false;
9723
9724 Result.makeComplexInt();
9725 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9726 return true;
9727 }
9728
9729 case CK_IntegralComplexCast: {
9730 if (!Visit(E->getSubExpr()))
9731 return false;
9732
9733 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9734 QualType From
9735 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9736
Richard Smith911e1422012-01-30 22:27:01 +00009737 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9738 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009739 return true;
9740 }
9741
9742 case CK_IntegralComplexToFloatingComplex: {
9743 if (!Visit(E->getSubExpr()))
9744 return false;
9745
Ted Kremenek28831752012-08-23 20:46:57 +00009746 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009747 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009748 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009749 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009750 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9751 To, Result.FloatReal) &&
9752 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9753 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009754 }
9755 }
9756
9757 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009758}
9759
John McCall93d91dc2010-05-07 17:22:02 +00009760bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009761 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009762 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9763
Chandler Carrutha216cad2014-10-11 00:57:18 +00009764 // Track whether the LHS or RHS is real at the type system level. When this is
9765 // the case we can simplify our evaluation strategy.
9766 bool LHSReal = false, RHSReal = false;
9767
9768 bool LHSOK;
9769 if (E->getLHS()->getType()->isRealFloatingType()) {
9770 LHSReal = true;
9771 APFloat &Real = Result.FloatReal;
9772 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9773 if (LHSOK) {
9774 Result.makeComplexFloat();
9775 Result.FloatImag = APFloat(Real.getSemantics());
9776 }
9777 } else {
9778 LHSOK = Visit(E->getLHS());
9779 }
George Burgess IVa145e252016-05-25 22:38:36 +00009780 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009781 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009782
John McCall93d91dc2010-05-07 17:22:02 +00009783 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009784 if (E->getRHS()->getType()->isRealFloatingType()) {
9785 RHSReal = true;
9786 APFloat &Real = RHS.FloatReal;
9787 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9788 return false;
9789 RHS.makeComplexFloat();
9790 RHS.FloatImag = APFloat(Real.getSemantics());
9791 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009792 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009793
Chandler Carrutha216cad2014-10-11 00:57:18 +00009794 assert(!(LHSReal && RHSReal) &&
9795 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009796 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009797 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009798 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009799 if (Result.isComplexFloat()) {
9800 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9801 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009802 if (LHSReal)
9803 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9804 else if (!RHSReal)
9805 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9806 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009807 } else {
9808 Result.getComplexIntReal() += RHS.getComplexIntReal();
9809 Result.getComplexIntImag() += RHS.getComplexIntImag();
9810 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009811 break;
John McCalle3027922010-08-25 11:45:40 +00009812 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009813 if (Result.isComplexFloat()) {
9814 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9815 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009816 if (LHSReal) {
9817 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9818 Result.getComplexFloatImag().changeSign();
9819 } else if (!RHSReal) {
9820 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9821 APFloat::rmNearestTiesToEven);
9822 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009823 } else {
9824 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9825 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9826 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009827 break;
John McCalle3027922010-08-25 11:45:40 +00009828 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009829 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009830 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009831 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009832 // following naming scheme:
9833 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009834 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009835 APFloat &A = LHS.getComplexFloatReal();
9836 APFloat &B = LHS.getComplexFloatImag();
9837 APFloat &C = RHS.getComplexFloatReal();
9838 APFloat &D = RHS.getComplexFloatImag();
9839 APFloat &ResR = Result.getComplexFloatReal();
9840 APFloat &ResI = Result.getComplexFloatImag();
9841 if (LHSReal) {
9842 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9843 ResR = A * C;
9844 ResI = A * D;
9845 } else if (RHSReal) {
9846 ResR = C * A;
9847 ResI = C * B;
9848 } else {
9849 // In the fully general case, we need to handle NaNs and infinities
9850 // robustly.
9851 APFloat AC = A * C;
9852 APFloat BD = B * D;
9853 APFloat AD = A * D;
9854 APFloat BC = B * C;
9855 ResR = AC - BD;
9856 ResI = AD + BC;
9857 if (ResR.isNaN() && ResI.isNaN()) {
9858 bool Recalc = false;
9859 if (A.isInfinity() || B.isInfinity()) {
9860 A = APFloat::copySign(
9861 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9862 B = APFloat::copySign(
9863 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9864 if (C.isNaN())
9865 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9866 if (D.isNaN())
9867 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9868 Recalc = true;
9869 }
9870 if (C.isInfinity() || D.isInfinity()) {
9871 C = APFloat::copySign(
9872 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9873 D = APFloat::copySign(
9874 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9875 if (A.isNaN())
9876 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9877 if (B.isNaN())
9878 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9879 Recalc = true;
9880 }
9881 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9882 AD.isInfinity() || BC.isInfinity())) {
9883 if (A.isNaN())
9884 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9885 if (B.isNaN())
9886 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9887 if (C.isNaN())
9888 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9889 if (D.isNaN())
9890 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9891 Recalc = true;
9892 }
9893 if (Recalc) {
9894 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9895 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9896 }
9897 }
9898 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009899 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009900 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009901 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009902 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9903 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009904 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009905 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9906 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9907 }
9908 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009909 case BO_Div:
9910 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009911 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009912 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009913 // following naming scheme:
9914 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009915 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009916 APFloat &A = LHS.getComplexFloatReal();
9917 APFloat &B = LHS.getComplexFloatImag();
9918 APFloat &C = RHS.getComplexFloatReal();
9919 APFloat &D = RHS.getComplexFloatImag();
9920 APFloat &ResR = Result.getComplexFloatReal();
9921 APFloat &ResI = Result.getComplexFloatImag();
9922 if (RHSReal) {
9923 ResR = A / C;
9924 ResI = B / C;
9925 } else {
9926 if (LHSReal) {
9927 // No real optimizations we can do here, stub out with zero.
9928 B = APFloat::getZero(A.getSemantics());
9929 }
9930 int DenomLogB = 0;
9931 APFloat MaxCD = maxnum(abs(C), abs(D));
9932 if (MaxCD.isFinite()) {
9933 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009934 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9935 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009936 }
9937 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009938 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9939 APFloat::rmNearestTiesToEven);
9940 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9941 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009942 if (ResR.isNaN() && ResI.isNaN()) {
9943 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9944 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9945 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9946 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9947 D.isFinite()) {
9948 A = APFloat::copySign(
9949 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9950 B = APFloat::copySign(
9951 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9952 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9953 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9954 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9955 C = APFloat::copySign(
9956 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9957 D = APFloat::copySign(
9958 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9959 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9960 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9961 }
9962 }
9963 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009964 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009965 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9966 return Error(E, diag::note_expr_divide_by_zero);
9967
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009968 ComplexValue LHS = Result;
9969 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9970 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9971 Result.getComplexIntReal() =
9972 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9973 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9974 Result.getComplexIntImag() =
9975 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9976 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9977 }
9978 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009979 }
9980
John McCall93d91dc2010-05-07 17:22:02 +00009981 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009982}
9983
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009984bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9985 // Get the operand value into 'Result'.
9986 if (!Visit(E->getSubExpr()))
9987 return false;
9988
9989 switch (E->getOpcode()) {
9990 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009991 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009992 case UO_Extension:
9993 return true;
9994 case UO_Plus:
9995 // The result is always just the subexpr.
9996 return true;
9997 case UO_Minus:
9998 if (Result.isComplexFloat()) {
9999 Result.getComplexFloatReal().changeSign();
10000 Result.getComplexFloatImag().changeSign();
10001 }
10002 else {
10003 Result.getComplexIntReal() = -Result.getComplexIntReal();
10004 Result.getComplexIntImag() = -Result.getComplexIntImag();
10005 }
10006 return true;
10007 case UO_Not:
10008 if (Result.isComplexFloat())
10009 Result.getComplexFloatImag().changeSign();
10010 else
10011 Result.getComplexIntImag() = -Result.getComplexIntImag();
10012 return true;
10013 }
10014}
10015
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010016bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10017 if (E->getNumInits() == 2) {
10018 if (E->getType()->isComplexType()) {
10019 Result.makeComplexFloat();
10020 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10021 return false;
10022 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10023 return false;
10024 } else {
10025 Result.makeComplexInt();
10026 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10027 return false;
10028 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10029 return false;
10030 }
10031 return true;
10032 }
10033 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10034}
10035
Anders Carlsson537969c2008-11-16 20:27:53 +000010036//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000010037// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10038// implicit conversion.
10039//===----------------------------------------------------------------------===//
10040
10041namespace {
10042class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000010043 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010044 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000010045 APValue &Result;
10046public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010047 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10048 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000010049
10050 bool Success(const APValue &V, const Expr *E) {
10051 Result = V;
10052 return true;
10053 }
10054
10055 bool ZeroInitialization(const Expr *E) {
10056 ImplicitValueInitExpr VIE(
10057 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010058 // For atomic-qualified class (and array) types in C++, initialize the
10059 // _Atomic-wrapped subobject directly, in-place.
10060 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10061 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000010062 }
10063
10064 bool VisitCastExpr(const CastExpr *E) {
10065 switch (E->getCastKind()) {
10066 default:
10067 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10068 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010069 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10070 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000010071 }
10072 }
10073};
10074} // end anonymous namespace
10075
Richard Smith64cb9ca2017-02-22 22:09:50 +000010076static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10077 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000010078 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010079 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000010080}
10081
10082//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000010083// Void expression evaluation, primarily for a cast to void on the LHS of a
10084// comma operator
10085//===----------------------------------------------------------------------===//
10086
10087namespace {
10088class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010089 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000010090public:
10091 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10092
Richard Smith2e312c82012-03-03 22:46:17 +000010093 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000010094
Richard Smith7cd577b2017-08-17 19:35:50 +000010095 bool ZeroInitialization(const Expr *E) { return true; }
10096
Richard Smith42d3af92011-12-07 00:43:50 +000010097 bool VisitCastExpr(const CastExpr *E) {
10098 switch (E->getCastKind()) {
10099 default:
10100 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10101 case CK_ToVoid:
10102 VisitIgnoredValue(E->getSubExpr());
10103 return true;
10104 }
10105 }
Hal Finkela8443c32014-07-17 14:49:58 +000010106
10107 bool VisitCallExpr(const CallExpr *E) {
10108 switch (E->getBuiltinCallee()) {
10109 default:
10110 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10111 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000010112 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000010113 // The argument is not evaluated!
10114 return true;
10115 }
10116 }
Richard Smith42d3af92011-12-07 00:43:50 +000010117};
10118} // end anonymous namespace
10119
10120static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10121 assert(E->isRValue() && E->getType()->isVoidType());
10122 return VoidExprEvaluator(Info).Visit(E);
10123}
10124
10125//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000010126// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000010127//===----------------------------------------------------------------------===//
10128
Richard Smith2e312c82012-03-03 22:46:17 +000010129static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000010130 // In C, function designators are not lvalues, but we evaluate them as if they
10131 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000010132 QualType T = E->getType();
10133 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000010134 LValue LV;
10135 if (!EvaluateLValue(E, LV, Info))
10136 return false;
10137 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010138 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010139 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000010140 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010141 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010142 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010143 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010144 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000010145 LValue LV;
10146 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010147 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010148 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010149 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000010150 llvm::APFloat F(0.0);
10151 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010152 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000010153 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000010154 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000010155 ComplexValue C;
10156 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010157 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010158 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010159 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000010160 MemberPtr P;
10161 if (!EvaluateMemberPointer(E, P, Info))
10162 return false;
10163 P.moveInto(Result);
10164 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000010165 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010166 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010167 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010168 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000010169 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010170 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010171 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010172 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010173 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010174 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000010175 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010176 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010177 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010178 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010179 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010180 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010181 if (!EvaluateVoid(E, Info))
10182 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010183 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010184 QualType Unqual = T.getAtomicUnqualifiedType();
10185 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10186 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010187 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010188 if (!EvaluateAtomic(E, &LV, Value, Info))
10189 return false;
10190 } else {
10191 if (!EvaluateAtomic(E, nullptr, Result, Info))
10192 return false;
10193 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010194 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010195 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010196 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010197 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010198 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010199 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010200 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010201
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010202 return true;
10203}
10204
Richard Smithb228a862012-02-15 02:18:13 +000010205/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10206/// cases, the in-place evaluation is essential, since later initializers for
10207/// an object can indirectly refer to subobjects which were initialized earlier.
10208static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010209 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010210 assert(!E->isValueDependent());
10211
Richard Smith7525ff62013-05-09 07:14:00 +000010212 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010213 return false;
10214
10215 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010216 // Evaluate arrays and record types in-place, so that later initializers can
10217 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010218 QualType T = E->getType();
10219 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010220 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010221 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010222 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010223 else if (T->isAtomicType()) {
10224 QualType Unqual = T.getAtomicUnqualifiedType();
10225 if (Unqual->isArrayType() || Unqual->isRecordType())
10226 return EvaluateAtomic(E, &This, Result, Info);
10227 }
Richard Smithed5165f2011-11-04 05:33:44 +000010228 }
10229
10230 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010231 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010232}
10233
Richard Smithf57d8cb2011-12-09 22:58:01 +000010234/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10235/// lvalue-to-rvalue cast if it is an lvalue.
10236static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010237 if (E->getType().isNull())
10238 return false;
10239
Nick Lewyckyc190f962017-05-02 01:06:16 +000010240 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010241 return false;
10242
Richard Smith2e312c82012-03-03 22:46:17 +000010243 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010244 return false;
10245
10246 if (E->isGLValue()) {
10247 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010248 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010249 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010250 return false;
10251 }
10252
Richard Smith2e312c82012-03-03 22:46:17 +000010253 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010254 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010255}
Richard Smith11562c52011-10-28 17:51:58 +000010256
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010257static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010258 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010259 // Fast-path evaluations of integer literals, since we sometimes see files
10260 // containing vast quantities of these.
10261 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10262 Result.Val = APValue(APSInt(L->getValue(),
10263 L->getType()->isUnsignedIntegerType()));
10264 IsConst = true;
10265 return true;
10266 }
James Dennett0492ef02014-03-14 17:44:10 +000010267
10268 // This case should be rare, but we need to check it before we check on
10269 // the type below.
10270 if (Exp->getType().isNull()) {
10271 IsConst = false;
10272 return true;
10273 }
Daniel Jasperffdee092017-05-02 19:21:42 +000010274
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010275 // FIXME: Evaluating values of large array and record types can cause
10276 // performance problems. Only do so in C++11 for now.
10277 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10278 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010279 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010280 IsConst = false;
10281 return true;
10282 }
10283 return false;
10284}
10285
10286
Richard Smith7b553f12011-10-29 00:50:52 +000010287/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010288/// any crazy technique (that has nothing to do with language standards) that
10289/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010290/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10291/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010292bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010293 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010294 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010295 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010296
Richard Smith6d4c6582013-11-05 22:18:15 +000010297 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010298 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010299}
10300
Jay Foad39c79802011-01-12 09:06:06 +000010301bool Expr::EvaluateAsBooleanCondition(bool &Result,
10302 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010303 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010304 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010305 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010306}
10307
Richard Smithce8eca52015-12-08 03:21:47 +000010308static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10309 Expr::SideEffectsKind SEK) {
10310 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10311 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10312}
10313
Richard Smith5fab0c92011-12-28 19:48:30 +000010314bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10315 SideEffectsKind AllowSideEffects) const {
10316 if (!getType()->isIntegralOrEnumerationType())
10317 return false;
10318
Richard Smith11562c52011-10-28 17:51:58 +000010319 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010320 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010321 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010322 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010323
Richard Smith11562c52011-10-28 17:51:58 +000010324 Result = ExprResult.Val.getInt();
10325 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010326}
10327
Richard Trieube234c32016-04-21 21:04:55 +000010328bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10329 SideEffectsKind AllowSideEffects) const {
10330 if (!getType()->isRealFloatingType())
10331 return false;
10332
10333 EvalResult ExprResult;
10334 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10335 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10336 return false;
10337
10338 Result = ExprResult.Val.getFloat();
10339 return true;
10340}
10341
Jay Foad39c79802011-01-12 09:06:06 +000010342bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010343 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010344
John McCall45d55e42010-05-07 21:00:08 +000010345 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010346 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10347 !CheckLValueConstantExpression(Info, getExprLoc(),
10348 Ctx.getLValueReferenceType(getType()), LV))
10349 return false;
10350
Richard Smith2e312c82012-03-03 22:46:17 +000010351 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010352 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010353}
10354
Richard Smithd0b4dd62011-12-19 06:19:21 +000010355bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10356 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010357 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010358 // FIXME: Evaluating initializers for large array and record types can cause
10359 // performance problems. Only do so in C++11 for now.
10360 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010361 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010362 return false;
10363
Richard Smithd0b4dd62011-12-19 06:19:21 +000010364 Expr::EvalStatus EStatus;
10365 EStatus.Diag = &Notes;
10366
Richard Smith0c6124b2015-12-03 01:36:22 +000010367 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10368 ? EvalInfo::EM_ConstantExpression
10369 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010370 InitInfo.setEvaluatingDecl(VD, Value);
10371
10372 LValue LVal;
10373 LVal.set(VD);
10374
Richard Smithfddd3842011-12-30 21:15:51 +000010375 // C++11 [basic.start.init]p2:
10376 // Variables with static storage duration or thread storage duration shall be
10377 // zero-initialized before any other initialization takes place.
10378 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010379 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010380 !VD->getType()->isReferenceType()) {
10381 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010382 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010383 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010384 return false;
10385 }
10386
Richard Smith7525ff62013-05-09 07:14:00 +000010387 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10388 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010389 EStatus.HasSideEffects)
10390 return false;
10391
10392 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10393 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010394}
10395
Richard Smith7b553f12011-10-29 00:50:52 +000010396/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10397/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010398bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010399 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010400 return EvaluateAsRValue(Result, Ctx) &&
10401 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010402}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010403
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010404APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010405 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010406 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010407 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010408 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010409 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010410 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010411 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010412
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010413 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010414}
John McCall864e3962010-05-07 05:32:02 +000010415
Richard Smithe9ff7702013-11-05 22:23:30 +000010416void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010417 bool IsConst;
10418 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010419 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010420 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010421 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10422 }
10423}
10424
Richard Smithe6c01442013-06-05 00:46:14 +000010425bool Expr::EvalResult::isGlobalLValue() const {
10426 assert(Val.isLValue());
10427 return IsGlobalLValue(Val.getLValueBase());
10428}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010429
10430
John McCall864e3962010-05-07 05:32:02 +000010431/// isIntegerConstantExpr - this recursive routine will test if an expression is
10432/// an integer constant expression.
10433
10434/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10435/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010436
10437// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010438// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10439// and a (possibly null) SourceLocation indicating the location of the problem.
10440//
John McCall864e3962010-05-07 05:32:02 +000010441// Note that to reduce code duplication, this helper does no evaluation
10442// itself; the caller checks whether the expression is evaluatable, and
10443// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010444// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010445
Dan Gohman28ade552010-07-26 21:25:24 +000010446namespace {
10447
Richard Smith9e575da2012-12-28 13:25:52 +000010448enum ICEKind {
10449 /// This expression is an ICE.
10450 IK_ICE,
10451 /// This expression is not an ICE, but if it isn't evaluated, it's
10452 /// a legal subexpression for an ICE. This return value is used to handle
10453 /// the comma operator in C99 mode, and non-constant subexpressions.
10454 IK_ICEIfUnevaluated,
10455 /// This expression is not an ICE, and is not a legal subexpression for one.
10456 IK_NotICE
10457};
10458
John McCall864e3962010-05-07 05:32:02 +000010459struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010460 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010461 SourceLocation Loc;
10462
Richard Smith9e575da2012-12-28 13:25:52 +000010463 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010464};
10465
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010466}
Dan Gohman28ade552010-07-26 21:25:24 +000010467
Richard Smith9e575da2012-12-28 13:25:52 +000010468static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10469
10470static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010471
Craig Toppera31a8822013-08-22 07:09:37 +000010472static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010473 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010474 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010475 !EVResult.Val.isInt())
10476 return ICEDiag(IK_NotICE, E->getLocStart());
10477
John McCall864e3962010-05-07 05:32:02 +000010478 return NoDiag();
10479}
10480
Craig Toppera31a8822013-08-22 07:09:37 +000010481static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010482 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010483 if (!E->getType()->isIntegralOrEnumerationType())
10484 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010485
10486 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010487#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010488#define STMT(Node, Base) case Expr::Node##Class:
10489#define EXPR(Node, Base)
10490#include "clang/AST/StmtNodes.inc"
10491 case Expr::PredefinedExprClass:
10492 case Expr::FloatingLiteralClass:
10493 case Expr::ImaginaryLiteralClass:
10494 case Expr::StringLiteralClass:
10495 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010496 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010497 case Expr::MemberExprClass:
10498 case Expr::CompoundAssignOperatorClass:
10499 case Expr::CompoundLiteralExprClass:
10500 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010501 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010502 case Expr::ArrayInitLoopExprClass:
10503 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010504 case Expr::NoInitExprClass:
10505 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010506 case Expr::ImplicitValueInitExprClass:
10507 case Expr::ParenListExprClass:
10508 case Expr::VAArgExprClass:
10509 case Expr::AddrLabelExprClass:
10510 case Expr::StmtExprClass:
10511 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010512 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010513 case Expr::CXXDynamicCastExprClass:
10514 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010515 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010516 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010517 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010518 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010519 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010520 case Expr::CXXThisExprClass:
10521 case Expr::CXXThrowExprClass:
10522 case Expr::CXXNewExprClass:
10523 case Expr::CXXDeleteExprClass:
10524 case Expr::CXXPseudoDestructorExprClass:
10525 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010526 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010527 case Expr::DependentScopeDeclRefExprClass:
10528 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010529 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010530 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010531 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010532 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010533 case Expr::CXXTemporaryObjectExprClass:
10534 case Expr::CXXUnresolvedConstructExprClass:
10535 case Expr::CXXDependentScopeMemberExprClass:
10536 case Expr::UnresolvedMemberExprClass:
10537 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010538 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010539 case Expr::ObjCArrayLiteralClass:
10540 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010541 case Expr::ObjCEncodeExprClass:
10542 case Expr::ObjCMessageExprClass:
10543 case Expr::ObjCSelectorExprClass:
10544 case Expr::ObjCProtocolExprClass:
10545 case Expr::ObjCIvarRefExprClass:
10546 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010547 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010548 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010549 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010550 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010551 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010552 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010553 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010554 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010555 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010556 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010557 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010558 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010559 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010560 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010561 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010562 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010563 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010564 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010565 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010566 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010567 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010568 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010569
Richard Smithf137f932014-01-25 20:50:08 +000010570 case Expr::InitListExprClass: {
10571 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10572 // form "T x = { a };" is equivalent to "T x = a;".
10573 // Unless we're initializing a reference, T is a scalar as it is known to be
10574 // of integral or enumeration type.
10575 if (E->isRValue())
10576 if (cast<InitListExpr>(E)->getNumInits() == 1)
10577 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10578 return ICEDiag(IK_NotICE, E->getLocStart());
10579 }
10580
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010581 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010582 case Expr::GNUNullExprClass:
10583 // GCC considers the GNU __null value to be an integral constant expression.
10584 return NoDiag();
10585
John McCall7c454bb2011-07-15 05:09:51 +000010586 case Expr::SubstNonTypeTemplateParmExprClass:
10587 return
10588 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10589
John McCall864e3962010-05-07 05:32:02 +000010590 case Expr::ParenExprClass:
10591 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010592 case Expr::GenericSelectionExprClass:
10593 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010594 case Expr::IntegerLiteralClass:
10595 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010596 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010597 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010598 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010599 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010600 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010601 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010602 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010603 return NoDiag();
10604 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010605 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010606 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10607 // constant expressions, but they can never be ICEs because an ICE cannot
10608 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010609 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010610 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010611 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010612 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010613 }
Richard Smith6365c912012-02-24 22:12:32 +000010614 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010615 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10616 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000010617 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010618 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010619 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010620 // Parameter variables are never constants. Without this check,
10621 // getAnyInitializer() can find a default argument, which leads
10622 // to chaos.
10623 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010624 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010625
10626 // C++ 7.1.5.1p2
10627 // A variable of non-volatile const-qualified integral or enumeration
10628 // type initialized by an ICE can be used in ICEs.
10629 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010630 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010631 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010632
Richard Smithd0b4dd62011-12-19 06:19:21 +000010633 const VarDecl *VD;
10634 // Look for a declaration of this variable that has an initializer, and
10635 // check whether it is an ICE.
10636 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10637 return NoDiag();
10638 else
Richard Smith9e575da2012-12-28 13:25:52 +000010639 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010640 }
10641 }
Richard Smith9e575da2012-12-28 13:25:52 +000010642 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010643 }
John McCall864e3962010-05-07 05:32:02 +000010644 case Expr::UnaryOperatorClass: {
10645 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10646 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010647 case UO_PostInc:
10648 case UO_PostDec:
10649 case UO_PreInc:
10650 case UO_PreDec:
10651 case UO_AddrOf:
10652 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010653 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010654 // C99 6.6/3 allows increment and decrement within unevaluated
10655 // subexpressions of constant expressions, but they can never be ICEs
10656 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010657 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010658 case UO_Extension:
10659 case UO_LNot:
10660 case UO_Plus:
10661 case UO_Minus:
10662 case UO_Not:
10663 case UO_Real:
10664 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010665 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010666 }
Richard Smith9e575da2012-12-28 13:25:52 +000010667
John McCall864e3962010-05-07 05:32:02 +000010668 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010669 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010670 }
10671 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010672 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10673 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10674 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10675 // compliance: we should warn earlier for offsetof expressions with
10676 // array subscripts that aren't ICEs, and if the array subscripts
10677 // are ICEs, the value of the offsetof must be an integer constant.
10678 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010679 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010680 case Expr::UnaryExprOrTypeTraitExprClass: {
10681 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10682 if ((Exp->getKind() == UETT_SizeOf) &&
10683 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010684 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010685 return NoDiag();
10686 }
10687 case Expr::BinaryOperatorClass: {
10688 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10689 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010690 case BO_PtrMemD:
10691 case BO_PtrMemI:
10692 case BO_Assign:
10693 case BO_MulAssign:
10694 case BO_DivAssign:
10695 case BO_RemAssign:
10696 case BO_AddAssign:
10697 case BO_SubAssign:
10698 case BO_ShlAssign:
10699 case BO_ShrAssign:
10700 case BO_AndAssign:
10701 case BO_XorAssign:
10702 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010703 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10704 // constant expressions, but they can never be ICEs because an ICE cannot
10705 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010706 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010707
John McCalle3027922010-08-25 11:45:40 +000010708 case BO_Mul:
10709 case BO_Div:
10710 case BO_Rem:
10711 case BO_Add:
10712 case BO_Sub:
10713 case BO_Shl:
10714 case BO_Shr:
10715 case BO_LT:
10716 case BO_GT:
10717 case BO_LE:
10718 case BO_GE:
10719 case BO_EQ:
10720 case BO_NE:
10721 case BO_And:
10722 case BO_Xor:
10723 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010724 case BO_Comma:
10725 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000010726 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10727 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010728 if (Exp->getOpcode() == BO_Div ||
10729 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010730 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010731 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010732 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010733 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010734 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010735 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010736 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010737 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010738 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010739 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010740 }
10741 }
10742 }
John McCalle3027922010-08-25 11:45:40 +000010743 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010744 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010745 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10746 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010747 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10748 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010749 } else {
10750 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010751 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010752 }
10753 }
Richard Smith9e575da2012-12-28 13:25:52 +000010754 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010755 }
John McCalle3027922010-08-25 11:45:40 +000010756 case BO_LAnd:
10757 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010758 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10759 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010760 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010761 // Rare case where the RHS has a comma "side-effect"; we need
10762 // to actually check the condition to see whether the side
10763 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010764 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010765 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010766 return RHSResult;
10767 return NoDiag();
10768 }
10769
Richard Smith9e575da2012-12-28 13:25:52 +000010770 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010771 }
10772 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010773 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010774 }
10775 case Expr::ImplicitCastExprClass:
10776 case Expr::CStyleCastExprClass:
10777 case Expr::CXXFunctionalCastExprClass:
10778 case Expr::CXXStaticCastExprClass:
10779 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010780 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010781 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010782 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010783 if (isa<ExplicitCastExpr>(E)) {
10784 if (const FloatingLiteral *FL
10785 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10786 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10787 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10788 APSInt IgnoredVal(DestWidth, !DestSigned);
10789 bool Ignored;
10790 // If the value does not fit in the destination type, the behavior is
10791 // undefined, so we are not required to treat it as a constant
10792 // expression.
10793 if (FL->getValue().convertToInteger(IgnoredVal,
10794 llvm::APFloat::rmTowardZero,
10795 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010796 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010797 return NoDiag();
10798 }
10799 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010800 switch (cast<CastExpr>(E)->getCastKind()) {
10801 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010802 case CK_AtomicToNonAtomic:
10803 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010804 case CK_NoOp:
10805 case CK_IntegralToBoolean:
10806 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010807 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010808 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010809 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010810 }
John McCall864e3962010-05-07 05:32:02 +000010811 }
John McCallc07a0c72011-02-17 10:25:35 +000010812 case Expr::BinaryConditionalOperatorClass: {
10813 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10814 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010815 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010816 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010817 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10818 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10819 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010820 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010821 return FalseResult;
10822 }
John McCall864e3962010-05-07 05:32:02 +000010823 case Expr::ConditionalOperatorClass: {
10824 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10825 // If the condition (ignoring parens) is a __builtin_constant_p call,
10826 // then only the true side is actually considered in an integer constant
10827 // expression, and it is fully evaluated. This is an important GNU
10828 // extension. See GCC PR38377 for discussion.
10829 if (const CallExpr *CallCE
10830 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010831 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010832 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010833 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010834 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010835 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010836
Richard Smithf57d8cb2011-12-09 22:58:01 +000010837 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10838 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010839
Richard Smith9e575da2012-12-28 13:25:52 +000010840 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010841 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010842 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010843 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010844 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010845 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010846 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010847 return NoDiag();
10848 // Rare case where the diagnostics depend on which side is evaluated
10849 // Note that if we get here, CondResult is 0, and at least one of
10850 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010851 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010852 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010853 return TrueResult;
10854 }
10855 case Expr::CXXDefaultArgExprClass:
10856 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010857 case Expr::CXXDefaultInitExprClass:
10858 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010859 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010860 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010861 }
10862 }
10863
David Blaikiee4d798f2012-01-20 21:50:17 +000010864 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010865}
10866
Richard Smithf57d8cb2011-12-09 22:58:01 +000010867/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010868static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010869 const Expr *E,
10870 llvm::APSInt *Value,
10871 SourceLocation *Loc) {
10872 if (!E->getType()->isIntegralOrEnumerationType()) {
10873 if (Loc) *Loc = E->getExprLoc();
10874 return false;
10875 }
10876
Richard Smith66e05fe2012-01-18 05:21:49 +000010877 APValue Result;
10878 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010879 return false;
10880
Richard Smith98710fc2014-11-13 23:03:19 +000010881 if (!Result.isInt()) {
10882 if (Loc) *Loc = E->getExprLoc();
10883 return false;
10884 }
10885
Richard Smith66e05fe2012-01-18 05:21:49 +000010886 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010887 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010888}
10889
Craig Toppera31a8822013-08-22 07:09:37 +000010890bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10891 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010892 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010893 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010894
Richard Smith9e575da2012-12-28 13:25:52 +000010895 ICEDiag D = CheckICE(this, Ctx);
10896 if (D.Kind != IK_ICE) {
10897 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010898 return false;
10899 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010900 return true;
10901}
10902
Craig Toppera31a8822013-08-22 07:09:37 +000010903bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010904 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010905 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010906 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10907
10908 if (!isIntegerConstantExpr(Ctx, Loc))
10909 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010910 // The only possible side-effects here are due to UB discovered in the
10911 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10912 // required to treat the expression as an ICE, so we produce the folded
10913 // value.
10914 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010915 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010916 return true;
10917}
Richard Smith66e05fe2012-01-18 05:21:49 +000010918
Craig Toppera31a8822013-08-22 07:09:37 +000010919bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010920 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010921}
10922
Craig Toppera31a8822013-08-22 07:09:37 +000010923bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010924 SourceLocation *Loc) const {
10925 // We support this checking in C++98 mode in order to diagnose compatibility
10926 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010927 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010928
Richard Smith98a0a492012-02-14 21:38:30 +000010929 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010930 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010931 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010932 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010933 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010934
10935 APValue Scratch;
10936 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10937
10938 if (!Diags.empty()) {
10939 IsConstExpr = false;
10940 if (Loc) *Loc = Diags[0].first;
10941 } else if (!IsConstExpr) {
10942 // FIXME: This shouldn't happen.
10943 if (Loc) *Loc = getExprLoc();
10944 }
10945
10946 return IsConstExpr;
10947}
Richard Smith253c2a32012-01-27 01:14:48 +000010948
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010949bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10950 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010951 ArrayRef<const Expr*> Args,
10952 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010953 Expr::EvalStatus Status;
10954 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10955
George Burgess IV177399e2017-01-09 04:12:14 +000010956 LValue ThisVal;
10957 const LValue *ThisPtr = nullptr;
10958 if (This) {
10959#ifndef NDEBUG
10960 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10961 assert(MD && "Don't provide `this` for non-methods.");
10962 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10963#endif
10964 if (EvaluateObjectArgument(Info, This, ThisVal))
10965 ThisPtr = &ThisVal;
10966 if (Info.EvalStatus.HasSideEffects)
10967 return false;
10968 }
10969
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010970 ArgVector ArgValues(Args.size());
10971 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10972 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010973 if ((*I)->isValueDependent() ||
10974 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010975 // If evaluation fails, throw away the argument entirely.
10976 ArgValues[I - Args.begin()] = APValue();
10977 if (Info.EvalStatus.HasSideEffects)
10978 return false;
10979 }
10980
10981 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010982 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010983 ArgValues.data());
10984 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10985}
10986
Richard Smith253c2a32012-01-27 01:14:48 +000010987bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010988 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010989 PartialDiagnosticAt> &Diags) {
10990 // FIXME: It would be useful to check constexpr function templates, but at the
10991 // moment the constant expression evaluator cannot cope with the non-rigorous
10992 // ASTs which we build for dependent expressions.
10993 if (FD->isDependentContext())
10994 return true;
10995
10996 Expr::EvalStatus Status;
10997 Status.Diag = &Diags;
10998
Richard Smith6d4c6582013-11-05 22:18:15 +000010999 EvalInfo Info(FD->getASTContext(), Status,
11000 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000011001
11002 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000011003 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000011004
Richard Smith7525ff62013-05-09 07:14:00 +000011005 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000011006 // is a temporary being used as the 'this' pointer.
11007 LValue This;
11008 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011009 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000011010
Richard Smith253c2a32012-01-27 01:14:48 +000011011 ArrayRef<const Expr*> Args;
11012
Richard Smith2e312c82012-03-03 22:46:17 +000011013 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000011014 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11015 // Evaluate the call as a constant initializer, to allow the construction
11016 // of objects of non-literal types.
11017 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000011018 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11019 } else {
11020 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000011021 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000011022 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000011023 }
Richard Smith253c2a32012-01-27 01:14:48 +000011024
11025 return Diags.empty();
11026}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011027
11028bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11029 const FunctionDecl *FD,
11030 SmallVectorImpl<
11031 PartialDiagnosticAt> &Diags) {
11032 Expr::EvalStatus Status;
11033 Status.Diag = &Diags;
11034
11035 EvalInfo Info(FD->getASTContext(), Status,
11036 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
11037
11038 // Fabricate a call stack frame to give the arguments a plausible cover story.
11039 ArrayRef<const Expr*> Args;
11040 ArgVector ArgValues(0);
11041 bool Success = EvaluateArgs(Args, ArgValues, Info);
11042 (void)Success;
11043 assert(Success &&
11044 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000011045 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011046
11047 APValue ResultScratch;
11048 Evaluate(ResultScratch, Info, E);
11049 return Diags.empty();
11050}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011051
11052bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11053 unsigned Type) const {
11054 if (!getType()->isPointerType())
11055 return false;
11056
11057 Expr::EvalStatus Status;
11058 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000011059 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011060}