blob: 590ebba997fad49aaf1fd0c517aa792e3d51e933 [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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000689 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000690 /// fold (not just why it's not strictly a constant expression)?
691 bool HasFoldFailureDiagnostic;
692
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000693 /// Whether or not we're currently speculatively evaluating.
George Burgess IV8c892b52016-05-25 22:31:54 +0000694 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,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001723 QualType Type, const LValue &LVal,
1724 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001725 bool IsReferenceType = Type->isReferenceType();
1726
Richard Smith357362d2011-12-13 06:39:58 +00001727 APValue::LValueBase Base = LVal.getLValueBase();
1728 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1729
Richard Smith0dea49e2012-02-18 04:58:18 +00001730 // Check that the object is a global. Note that the fake 'this' object we
1731 // manufacture when checking potential constant expressions is conservatively
1732 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001733 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001734 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001735 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001736 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001737 << IsReferenceType << !Designator.Entries.empty()
1738 << !!VD << VD;
1739 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001740 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001741 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001742 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001743 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001744 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001745 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001746 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001747 LVal.getLValueCallIndex() == 0) &&
1748 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001749
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001750 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1751 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001752 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001753 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001754 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001755
Hans Wennborg82dd8772014-06-25 22:19:48 +00001756 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001757 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001758 return false;
1759 }
1760 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1761 // __declspec(dllimport) must be handled very carefully:
1762 // We must never initialize an expression with the thunk in C++.
1763 // Doing otherwise would allow the same id-expression to yield
1764 // different addresses for the same function in different translation
1765 // units. However, this means that we must dynamically initialize the
1766 // expression with the contents of the import address table at runtime.
1767 //
1768 // The C language has no notion of ODR; furthermore, it has no notion of
1769 // dynamic initialization. This means that we are permitted to
1770 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001771 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1772 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001773 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001774 }
1775 }
1776
Richard Smitha8105bc2012-01-06 16:39:00 +00001777 // Allow address constant expressions to be past-the-end pointers. This is
1778 // an extension: the standard requires them to point to an object.
1779 if (!IsReferenceType)
1780 return true;
1781
1782 // A reference constant expression must refer to an object.
1783 if (!Base) {
1784 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001785 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001786 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001787 }
1788
Richard Smith357362d2011-12-13 06:39:58 +00001789 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001790 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001791 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001792 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001793 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001794 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001795 }
1796
Richard Smith80815602011-11-07 05:07:52 +00001797 return true;
1798}
1799
Reid Klecknercd016d82017-07-07 22:04:29 +00001800/// Member pointers are constant expressions unless they point to a
1801/// non-virtual dllimport member function.
1802static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1803 SourceLocation Loc,
1804 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001805 const APValue &Value,
1806 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00001807 const ValueDecl *Member = Value.getMemberPointerDecl();
1808 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1809 if (!FD)
1810 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001811 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1812 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00001813}
1814
Richard Smithfddd3842011-12-30 21:15:51 +00001815/// Check that this core constant expression is of literal type, and if not,
1816/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001817static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001818 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001819 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001820 return true;
1821
Richard Smith7525ff62013-05-09 07:14:00 +00001822 // C++1y: A constant initializer for an object o [...] may also invoke
1823 // constexpr constructors for o and its subobjects even if those objects
1824 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001825 //
1826 // C++11 missed this detail for aggregates, so classes like this:
1827 // struct foo_t { union { int i; volatile int j; } u; };
1828 // are not (obviously) initializable like so:
1829 // __attribute__((__require_constant_initialization__))
1830 // static const foo_t x = {{0}};
1831 // because "i" is a subobject with non-literal initialization (due to the
1832 // volatile member of the union). See:
1833 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1834 // Therefore, we use the C++1y behavior.
1835 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001836 return true;
1837
Richard Smithfddd3842011-12-30 21:15:51 +00001838 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001839 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001840 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001841 << E->getType();
1842 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001843 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001844 return false;
1845}
1846
Richard Smith0b0a0b62011-10-29 20:57:55 +00001847/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001848/// constant expression. If not, report an appropriate diagnostic. Does not
1849/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001850static bool
1851CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1852 const APValue &Value,
1853 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
Richard Smith1a90f592013-06-18 17:51:51 +00001854 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001855 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001856 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001857 return false;
1858 }
1859
Richard Smith77be48a2014-07-31 06:31:19 +00001860 // We allow _Atomic(T) to be initialized from anything that T can be
1861 // initialized from.
1862 if (const AtomicType *AT = Type->getAs<AtomicType>())
1863 Type = AT->getValueType();
1864
Richard Smithb228a862012-02-15 02:18:13 +00001865 // Core issue 1454: For a literal constant expression of array or class type,
1866 // each subobject of its value shall have been initialized by a constant
1867 // expression.
1868 if (Value.isArray()) {
1869 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1870 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1871 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001872 Value.getArrayInitializedElt(I), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001873 return false;
1874 }
1875 if (!Value.hasArrayFiller())
1876 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001877 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1878 Usage);
Richard Smith80815602011-11-07 05:07:52 +00001879 }
Richard Smithb228a862012-02-15 02:18:13 +00001880 if (Value.isUnion() && Value.getUnionField()) {
1881 return CheckConstantExpression(Info, DiagLoc,
1882 Value.getUnionField()->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001883 Value.getUnionValue(), Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001884 }
1885 if (Value.isStruct()) {
1886 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1887 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1888 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001889 for (const CXXBaseSpecifier &BS : CD->bases()) {
1890 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
1891 Value.getStructBase(BaseIndex), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001892 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001893 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00001894 }
1895 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001896 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001897 if (I->isUnnamedBitfield())
1898 continue;
1899
David Blaikie2d7c57e2012-04-30 02:36:29 +00001900 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001901 Value.getStructField(I->getFieldIndex()),
1902 Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001903 return false;
1904 }
1905 }
1906
1907 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001908 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001909 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00001910 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001911 }
1912
Reid Klecknercd016d82017-07-07 22:04:29 +00001913 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00001914 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00001915
Richard Smithb228a862012-02-15 02:18:13 +00001916 // Everything else is fine.
1917 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001918}
1919
Benjamin Kramer8407df72015-03-09 16:47:52 +00001920static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001921 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001922}
1923
1924static bool IsLiteralLValue(const LValue &Value) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001925 if (Value.getLValueCallIndex())
Richard Smithe6c01442013-06-05 00:46:14 +00001926 return false;
1927 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1928 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001929}
1930
Richard Smithcecf1842011-11-01 21:06:14 +00001931static bool IsWeakLValue(const LValue &Value) {
1932 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001933 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001934}
1935
David Majnemerb5116032014-12-09 23:32:34 +00001936static bool isZeroSized(const LValue &Value) {
1937 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001938 if (Decl && isa<VarDecl>(Decl)) {
1939 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001940 if (Ty->isArrayType())
1941 return Ty->isIncompleteType() ||
1942 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001943 }
1944 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001945}
1946
Richard Smith2e312c82012-03-03 22:46:17 +00001947static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001948 // A null base expression indicates a null pointer. These are always
1949 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001950 if (!Value.getLValueBase()) {
1951 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001952 return true;
1953 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001954
Richard Smith027bf112011-11-17 22:56:20 +00001955 // We have a non-null base. These are generally known to be true, but if it's
1956 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001957 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001958 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001959 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001960}
1961
Richard Smith2e312c82012-03-03 22:46:17 +00001962static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001963 switch (Val.getKind()) {
1964 case APValue::Uninitialized:
1965 return false;
1966 case APValue::Int:
1967 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001968 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001969 case APValue::Float:
1970 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001971 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001972 case APValue::ComplexInt:
1973 Result = Val.getComplexIntReal().getBoolValue() ||
1974 Val.getComplexIntImag().getBoolValue();
1975 return true;
1976 case APValue::ComplexFloat:
1977 Result = !Val.getComplexFloatReal().isZero() ||
1978 !Val.getComplexFloatImag().isZero();
1979 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001980 case APValue::LValue:
1981 return EvalPointerValueAsBool(Val, Result);
1982 case APValue::MemberPointer:
1983 Result = Val.getMemberPointerDecl();
1984 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001985 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001986 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001987 case APValue::Struct:
1988 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001989 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001990 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001991 }
1992
Richard Smith11562c52011-10-28 17:51:58 +00001993 llvm_unreachable("unknown APValue kind");
1994}
1995
1996static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1997 EvalInfo &Info) {
1998 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001999 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002000 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002001 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002002 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002003}
2004
Richard Smith357362d2011-12-13 06:39:58 +00002005template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002006static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002007 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002008 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002009 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002010 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002011}
2012
2013static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2014 QualType SrcType, const APFloat &Value,
2015 QualType DestType, APSInt &Result) {
2016 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002017 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002018 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002019
Richard Smith357362d2011-12-13 06:39:58 +00002020 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002021 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002022 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2023 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002024 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002025 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002026}
2027
Richard Smith357362d2011-12-13 06:39:58 +00002028static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2029 QualType SrcType, QualType DestType,
2030 APFloat &Result) {
2031 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002032 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002033 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2034 APFloat::rmNearestTiesToEven, &ignored)
2035 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002036 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002037 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002038}
2039
Richard Smith911e1422012-01-30 22:27:01 +00002040static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2041 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002042 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002043 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002044 APSInt Result = Value;
2045 // Figure out if this is a truncate, extend or noop cast.
2046 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00002047 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002048 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002049 return Result;
2050}
2051
Richard Smith357362d2011-12-13 06:39:58 +00002052static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2053 QualType SrcType, const APSInt &Value,
2054 QualType DestType, APFloat &Result) {
2055 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2056 if (Result.convertFromAPInt(Value, Value.isSigned(),
2057 APFloat::rmNearestTiesToEven)
2058 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002059 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002060 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002061}
2062
Richard Smith49ca8aa2013-08-06 07:09:20 +00002063static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2064 APValue &Value, const FieldDecl *FD) {
2065 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2066
2067 if (!Value.isInt()) {
2068 // Trying to store a pointer-cast-to-integer into a bitfield.
2069 // FIXME: In this case, we should provide the diagnostic for casting
2070 // a pointer to an integer.
2071 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002072 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002073 return false;
2074 }
2075
2076 APSInt &Int = Value.getInt();
2077 unsigned OldBitWidth = Int.getBitWidth();
2078 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2079 if (NewBitWidth < OldBitWidth)
2080 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2081 return true;
2082}
2083
Eli Friedman803acb32011-12-22 03:51:45 +00002084static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2085 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002086 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002087 if (!Evaluate(SVal, Info, E))
2088 return false;
2089 if (SVal.isInt()) {
2090 Res = SVal.getInt();
2091 return true;
2092 }
2093 if (SVal.isFloat()) {
2094 Res = SVal.getFloat().bitcastToAPInt();
2095 return true;
2096 }
2097 if (SVal.isVector()) {
2098 QualType VecTy = E->getType();
2099 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2100 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2101 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2102 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2103 Res = llvm::APInt::getNullValue(VecSize);
2104 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2105 APValue &Elt = SVal.getVectorElt(i);
2106 llvm::APInt EltAsInt;
2107 if (Elt.isInt()) {
2108 EltAsInt = Elt.getInt();
2109 } else if (Elt.isFloat()) {
2110 EltAsInt = Elt.getFloat().bitcastToAPInt();
2111 } else {
2112 // Don't try to handle vectors of anything other than int or float
2113 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002114 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002115 return false;
2116 }
2117 unsigned BaseEltSize = EltAsInt.getBitWidth();
2118 if (BigEndian)
2119 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2120 else
2121 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2122 }
2123 return true;
2124 }
2125 // Give up if the input isn't an int, float, or vector. For example, we
2126 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002127 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002128 return false;
2129}
2130
Richard Smith43e77732013-05-07 04:50:00 +00002131/// Perform the given integer operation, which is known to need at most BitWidth
2132/// bits, and check for overflow in the original type (if that type was not an
2133/// unsigned type).
2134template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002135static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2136 const APSInt &LHS, const APSInt &RHS,
2137 unsigned BitWidth, Operation Op,
2138 APSInt &Result) {
2139 if (LHS.isUnsigned()) {
2140 Result = Op(LHS, RHS);
2141 return true;
2142 }
Richard Smith43e77732013-05-07 04:50:00 +00002143
2144 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002145 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002146 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002147 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002148 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002149 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002150 << Result.toString(10) << E->getType();
2151 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002152 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002153 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002154 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002155}
2156
2157/// Perform the given binary integer operation.
2158static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2159 BinaryOperatorKind Opcode, APSInt RHS,
2160 APSInt &Result) {
2161 switch (Opcode) {
2162 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002163 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002164 return false;
2165 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002166 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2167 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002168 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002169 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2170 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002171 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002172 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2173 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002174 case BO_And: Result = LHS & RHS; return true;
2175 case BO_Xor: Result = LHS ^ RHS; return true;
2176 case BO_Or: Result = LHS | RHS; return true;
2177 case BO_Div:
2178 case BO_Rem:
2179 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002180 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002181 return false;
2182 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002183 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2184 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2185 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002186 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2187 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002188 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2189 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002190 return true;
2191 case BO_Shl: {
2192 if (Info.getLangOpts().OpenCL)
2193 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2194 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2195 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2196 RHS.isUnsigned());
2197 else if (RHS.isSigned() && RHS.isNegative()) {
2198 // During constant-folding, a negative shift is an opposite shift. Such
2199 // a shift is not a constant expression.
2200 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2201 RHS = -RHS;
2202 goto shift_right;
2203 }
2204 shift_left:
2205 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2206 // the shifted type.
2207 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2208 if (SA != RHS) {
2209 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2210 << RHS << E->getType() << LHS.getBitWidth();
2211 } else if (LHS.isSigned()) {
2212 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2213 // operand, and must not overflow the corresponding unsigned type.
2214 if (LHS.isNegative())
2215 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2216 else if (LHS.countLeadingZeros() < SA)
2217 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2218 }
2219 Result = LHS << SA;
2220 return true;
2221 }
2222 case BO_Shr: {
2223 if (Info.getLangOpts().OpenCL)
2224 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2225 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2226 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2227 RHS.isUnsigned());
2228 else if (RHS.isSigned() && RHS.isNegative()) {
2229 // During constant-folding, a negative shift is an opposite shift. Such a
2230 // shift is not a constant expression.
2231 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2232 RHS = -RHS;
2233 goto shift_left;
2234 }
2235 shift_right:
2236 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2237 // shifted type.
2238 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2239 if (SA != RHS)
2240 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2241 << RHS << E->getType() << LHS.getBitWidth();
2242 Result = LHS >> SA;
2243 return true;
2244 }
2245
2246 case BO_LT: Result = LHS < RHS; return true;
2247 case BO_GT: Result = LHS > RHS; return true;
2248 case BO_LE: Result = LHS <= RHS; return true;
2249 case BO_GE: Result = LHS >= RHS; return true;
2250 case BO_EQ: Result = LHS == RHS; return true;
2251 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002252 case BO_Cmp:
2253 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002254 }
2255}
2256
Richard Smith861b5b52013-05-07 23:34:45 +00002257/// Perform the given binary floating-point operation, in-place, on LHS.
2258static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2259 APFloat &LHS, BinaryOperatorKind Opcode,
2260 const APFloat &RHS) {
2261 switch (Opcode) {
2262 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002263 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002264 return false;
2265 case BO_Mul:
2266 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2267 break;
2268 case BO_Add:
2269 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2270 break;
2271 case BO_Sub:
2272 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2273 break;
2274 case BO_Div:
2275 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2276 break;
2277 }
2278
Richard Smith0c6124b2015-12-03 01:36:22 +00002279 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002280 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002281 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002282 }
Richard Smith861b5b52013-05-07 23:34:45 +00002283 return true;
2284}
2285
Richard Smitha8105bc2012-01-06 16:39:00 +00002286/// Cast an lvalue referring to a base subobject to a derived class, by
2287/// truncating the lvalue's path to the given length.
2288static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2289 const RecordDecl *TruncatedType,
2290 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002291 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002292
2293 // Check we actually point to a derived class object.
2294 if (TruncatedElements == D.Entries.size())
2295 return true;
2296 assert(TruncatedElements >= D.MostDerivedPathLength &&
2297 "not casting to a derived class");
2298 if (!Result.checkSubobject(Info, E, CSK_Derived))
2299 return false;
2300
2301 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002302 const RecordDecl *RD = TruncatedType;
2303 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002304 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002305 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2306 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002307 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002308 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002309 else
Richard Smithd62306a2011-11-10 06:34:14 +00002310 Result.Offset -= Layout.getBaseClassOffset(Base);
2311 RD = Base;
2312 }
Richard Smith027bf112011-11-17 22:56:20 +00002313 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002314 return true;
2315}
2316
John McCalld7bca762012-05-01 00:38:49 +00002317static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002318 const CXXRecordDecl *Derived,
2319 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002320 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002321 if (!RL) {
2322 if (Derived->isInvalidDecl()) return false;
2323 RL = &Info.Ctx.getASTRecordLayout(Derived);
2324 }
2325
Richard Smithd62306a2011-11-10 06:34:14 +00002326 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002327 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002328 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002329}
2330
Richard Smitha8105bc2012-01-06 16:39:00 +00002331static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002332 const CXXRecordDecl *DerivedDecl,
2333 const CXXBaseSpecifier *Base) {
2334 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2335
John McCalld7bca762012-05-01 00:38:49 +00002336 if (!Base->isVirtual())
2337 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002338
Richard Smitha8105bc2012-01-06 16:39:00 +00002339 SubobjectDesignator &D = Obj.Designator;
2340 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002341 return false;
2342
Richard Smitha8105bc2012-01-06 16:39:00 +00002343 // Extract most-derived object and corresponding type.
2344 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2345 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2346 return false;
2347
2348 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002349 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002350 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2351 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002352 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002353 return true;
2354}
2355
Richard Smith84401042013-06-03 05:03:02 +00002356static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2357 QualType Type, LValue &Result) {
2358 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2359 PathE = E->path_end();
2360 PathI != PathE; ++PathI) {
2361 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2362 *PathI))
2363 return false;
2364 Type = (*PathI)->getType();
2365 }
2366 return true;
2367}
2368
Richard Smithd62306a2011-11-10 06:34:14 +00002369/// Update LVal to refer to the given field, which must be a member of the type
2370/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002371static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002372 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002373 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002374 if (!RL) {
2375 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002376 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002377 }
Richard Smithd62306a2011-11-10 06:34:14 +00002378
2379 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002380 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002381 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002382 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002383}
2384
Richard Smith1b78b3d2012-01-25 22:15:11 +00002385/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002386static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002387 LValue &LVal,
2388 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002389 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002390 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002391 return false;
2392 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002393}
2394
Richard Smithd62306a2011-11-10 06:34:14 +00002395/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002396static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2397 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002398 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2399 // extension.
2400 if (Type->isVoidType() || Type->isFunctionType()) {
2401 Size = CharUnits::One();
2402 return true;
2403 }
2404
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002405 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002406 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002407 return false;
2408 }
2409
Richard Smithd62306a2011-11-10 06:34:14 +00002410 if (!Type->isConstantSizeType()) {
2411 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002412 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002413 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002414 return false;
2415 }
2416
2417 Size = Info.Ctx.getTypeSizeInChars(Type);
2418 return true;
2419}
2420
2421/// Update a pointer value to model pointer arithmetic.
2422/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002423/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002424/// \param LVal - The pointer value to be updated.
2425/// \param EltTy - The pointee type represented by LVal.
2426/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002427static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2428 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002429 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002430 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002431 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002432 return false;
2433
Yaxun Liu402804b2016-12-15 08:09:08 +00002434 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002435 return true;
2436}
2437
Richard Smithd6cc1982017-01-31 02:23:02 +00002438static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2439 LValue &LVal, QualType EltTy,
2440 int64_t Adjustment) {
2441 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2442 APSInt::get(Adjustment));
2443}
2444
Richard Smith66c96992012-02-18 22:04:06 +00002445/// Update an lvalue to refer to a component of a complex number.
2446/// \param Info - Information about the ongoing evaluation.
2447/// \param LVal - The lvalue to be updated.
2448/// \param EltTy - The complex number's component type.
2449/// \param Imag - False for the real component, true for the imaginary.
2450static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2451 LValue &LVal, QualType EltTy,
2452 bool Imag) {
2453 if (Imag) {
2454 CharUnits SizeOfComponent;
2455 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2456 return false;
2457 LVal.Offset += SizeOfComponent;
2458 }
2459 LVal.addComplex(Info, E, EltTy, Imag);
2460 return true;
2461}
2462
Faisal Vali051e3a22017-02-16 04:12:21 +00002463static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2464 QualType Type, const LValue &LVal,
2465 APValue &RVal);
2466
Richard Smith27908702011-10-24 17:54:18 +00002467/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002468///
2469/// \param Info Information about the ongoing evaluation.
2470/// \param E An expression to be used when printing diagnostics.
2471/// \param VD The variable whose initializer should be obtained.
2472/// \param Frame The frame in which the variable was created. Must be null
2473/// if this variable is not local to the evaluation.
2474/// \param Result Filled in with a pointer to the value of the variable.
2475static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2476 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002477 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002478
Richard Smith254a73d2011-10-28 22:34:42 +00002479 // If this is a parameter to an active constexpr function call, perform
2480 // argument substitution.
2481 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002482 // Assume arguments of a potential constant expression are unknown
2483 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002484 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002485 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002486 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002487 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002488 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002489 }
Richard Smith3229b742013-05-05 21:17:10 +00002490 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002491 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002492 }
Richard Smith27908702011-10-24 17:54:18 +00002493
Richard Smithd9f663b2013-04-22 15:31:51 +00002494 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002495 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002496 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2497 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002498 if (!Result) {
2499 // Assume variables referenced within a lambda's call operator that were
2500 // not declared within the call operator are captures and during checking
2501 // of a potential constant expression, assume they are unknown constant
2502 // expressions.
2503 assert(isLambdaCallOperator(Frame->Callee) &&
2504 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2505 "missing value for local variable");
2506 if (Info.checkingPotentialConstantExpression())
2507 return false;
2508 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002509 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002510 diag::note_unimplemented_constexpr_lambda_feature_ast)
2511 << "captures not currently allowed";
2512 return false;
2513 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002514 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002515 }
2516
Richard Smithd0b4dd62011-12-19 06:19:21 +00002517 // Dig out the initializer, and use the declaration which it's attached to.
2518 const Expr *Init = VD->getAnyInitializer(VD);
2519 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002520 // If we're checking a potential constant expression, the variable could be
2521 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002522 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002523 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002524 return false;
2525 }
2526
Richard Smithd62306a2011-11-10 06:34:14 +00002527 // If we're currently evaluating the initializer of this declaration, use that
2528 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002529 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002530 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002531 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002532 }
2533
Richard Smithcecf1842011-11-01 21:06:14 +00002534 // Never evaluate the initializer of a weak variable. We can't be sure that
2535 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002536 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002537 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002538 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002539 }
Richard Smithcecf1842011-11-01 21:06:14 +00002540
Richard Smithd0b4dd62011-12-19 06:19:21 +00002541 // Check that we can fold the initializer. In C++, we will have already done
2542 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002543 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002544 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002545 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002546 Notes.size() + 1) << VD;
2547 Info.Note(VD->getLocation(), diag::note_declared_at);
2548 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002549 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002550 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002551 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002552 Notes.size() + 1) << VD;
2553 Info.Note(VD->getLocation(), diag::note_declared_at);
2554 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002555 }
Richard Smith27908702011-10-24 17:54:18 +00002556
Richard Smith3229b742013-05-05 21:17:10 +00002557 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002558 return true;
Richard Smith27908702011-10-24 17:54:18 +00002559}
2560
Richard Smith11562c52011-10-28 17:51:58 +00002561static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002562 Qualifiers Quals = T.getQualifiers();
2563 return Quals.hasConst() && !Quals.hasVolatile();
2564}
2565
Richard Smithe97cbd72011-11-11 04:05:33 +00002566/// Get the base index of the given base class within an APValue representing
2567/// the given derived class.
2568static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2569 const CXXRecordDecl *Base) {
2570 Base = Base->getCanonicalDecl();
2571 unsigned Index = 0;
2572 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2573 E = Derived->bases_end(); I != E; ++I, ++Index) {
2574 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2575 return Index;
2576 }
2577
2578 llvm_unreachable("base class missing from derived class's bases list");
2579}
2580
Richard Smith3da88fa2013-04-26 14:36:30 +00002581/// Extract the value of a character from a string literal.
2582static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2583 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002584 // FIXME: Support MakeStringConstant
2585 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2586 std::string Str;
2587 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2588 assert(Index <= Str.size() && "Index too large");
2589 return APSInt::getUnsigned(Str.c_str()[Index]);
2590 }
2591
Alexey Bataevec474782014-10-09 08:45:04 +00002592 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2593 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002594 const StringLiteral *S = cast<StringLiteral>(Lit);
2595 const ConstantArrayType *CAT =
2596 Info.Ctx.getAsConstantArrayType(S->getType());
2597 assert(CAT && "string literal isn't an array");
2598 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002599 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002600
2601 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002602 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002603 if (Index < S->getLength())
2604 Value = S->getCodeUnit(Index);
2605 return Value;
2606}
2607
Richard Smith3da88fa2013-04-26 14:36:30 +00002608// Expand a string literal into an array of characters.
2609static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2610 APValue &Result) {
2611 const StringLiteral *S = cast<StringLiteral>(Lit);
2612 const ConstantArrayType *CAT =
2613 Info.Ctx.getAsConstantArrayType(S->getType());
2614 assert(CAT && "string literal isn't an array");
2615 QualType CharType = CAT->getElementType();
2616 assert(CharType->isIntegerType() && "unexpected character type");
2617
2618 unsigned Elts = CAT->getSize().getZExtValue();
2619 Result = APValue(APValue::UninitArray(),
2620 std::min(S->getLength(), Elts), Elts);
2621 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2622 CharType->isUnsignedIntegerType());
2623 if (Result.hasArrayFiller())
2624 Result.getArrayFiller() = APValue(Value);
2625 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2626 Value = S->getCodeUnit(I);
2627 Result.getArrayInitializedElt(I) = APValue(Value);
2628 }
2629}
2630
2631// Expand an array so that it has more than Index filled elements.
2632static void expandArray(APValue &Array, unsigned Index) {
2633 unsigned Size = Array.getArraySize();
2634 assert(Index < Size);
2635
2636 // Always at least double the number of elements for which we store a value.
2637 unsigned OldElts = Array.getArrayInitializedElts();
2638 unsigned NewElts = std::max(Index+1, OldElts * 2);
2639 NewElts = std::min(Size, std::max(NewElts, 8u));
2640
2641 // Copy the data across.
2642 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2643 for (unsigned I = 0; I != OldElts; ++I)
2644 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2645 for (unsigned I = OldElts; I != NewElts; ++I)
2646 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2647 if (NewValue.hasArrayFiller())
2648 NewValue.getArrayFiller() = Array.getArrayFiller();
2649 Array.swap(NewValue);
2650}
2651
Richard Smithb01fe402014-09-16 01:24:02 +00002652/// Determine whether a type would actually be read by an lvalue-to-rvalue
2653/// conversion. If it's of class type, we may assume that the copy operation
2654/// is trivial. Note that this is never true for a union type with fields
2655/// (because the copy always "reads" the active member) and always true for
2656/// a non-class type.
2657static bool isReadByLvalueToRvalueConversion(QualType T) {
2658 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2659 if (!RD || (RD->isUnion() && !RD->field_empty()))
2660 return true;
2661 if (RD->isEmpty())
2662 return false;
2663
2664 for (auto *Field : RD->fields())
2665 if (isReadByLvalueToRvalueConversion(Field->getType()))
2666 return true;
2667
2668 for (auto &BaseSpec : RD->bases())
2669 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2670 return true;
2671
2672 return false;
2673}
2674
2675/// Diagnose an attempt to read from any unreadable field within the specified
2676/// type, which might be a class type.
2677static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2678 QualType T) {
2679 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2680 if (!RD)
2681 return false;
2682
2683 if (!RD->hasMutableFields())
2684 return false;
2685
2686 for (auto *Field : RD->fields()) {
2687 // If we're actually going to read this field in some way, then it can't
2688 // be mutable. If we're in a union, then assigning to a mutable field
2689 // (even an empty one) can change the active member, so that's not OK.
2690 // FIXME: Add core issue number for the union case.
2691 if (Field->isMutable() &&
2692 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002693 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002694 Info.Note(Field->getLocation(), diag::note_declared_at);
2695 return true;
2696 }
2697
2698 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2699 return true;
2700 }
2701
2702 for (auto &BaseSpec : RD->bases())
2703 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2704 return true;
2705
2706 // All mutable fields were empty, and thus not actually read.
2707 return false;
2708}
2709
Richard Smith861b5b52013-05-07 23:34:45 +00002710/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002711enum AccessKinds {
2712 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002713 AK_Assign,
2714 AK_Increment,
2715 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002716};
2717
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002718namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002719/// A handle to a complete object (an object that is not a subobject of
2720/// another object).
2721struct CompleteObject {
2722 /// The value of the complete object.
2723 APValue *Value;
2724 /// The type of the complete object.
2725 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002726 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002727
Craig Topper36250ad2014-05-12 05:36:57 +00002728 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002729 CompleteObject(APValue *Value, QualType Type,
2730 bool LifetimeStartedInEvaluation)
2731 : Value(Value), Type(Type),
2732 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002733 assert(Value && "missing value for complete object");
2734 }
2735
Aaron Ballman67347662015-02-15 22:00:28 +00002736 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002737};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002738} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002739
Richard Smith3da88fa2013-04-26 14:36:30 +00002740/// Find the designated sub-object of an rvalue.
2741template<typename SubobjectHandler>
2742typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002743findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002744 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002745 if (Sub.Invalid)
2746 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002747 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002748 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002749 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002750 Info.FFDiag(E, Sub.isOnePastTheEnd()
2751 ? diag::note_constexpr_access_past_end
2752 : diag::note_constexpr_access_unsized_array)
2753 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002754 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002755 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002756 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002757 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002758
Richard Smith3229b742013-05-05 21:17:10 +00002759 APValue *O = Obj.Value;
2760 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002761 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002762 const bool MayReadMutableMembers =
2763 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002764
Richard Smithd62306a2011-11-10 06:34:14 +00002765 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002766 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2767 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002768 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002769 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002770 return handler.failed();
2771 }
2772
Richard Smith49ca8aa2013-08-06 07:09:20 +00002773 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002774 // If we are reading an object of class type, there may still be more
2775 // things we need to check: if there are any mutable subobjects, we
2776 // cannot perform this read. (This only happens when performing a trivial
2777 // copy or assignment.)
2778 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002779 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002780 return handler.failed();
2781
Richard Smith49ca8aa2013-08-06 07:09:20 +00002782 if (!handler.found(*O, ObjType))
2783 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002784
Richard Smith49ca8aa2013-08-06 07:09:20 +00002785 // If we modified a bit-field, truncate it to the right width.
2786 if (handler.AccessKind != AK_Read &&
2787 LastField && LastField->isBitField() &&
2788 !truncateBitfieldValue(Info, E, *O, LastField))
2789 return false;
2790
2791 return true;
2792 }
2793
Craig Topper36250ad2014-05-12 05:36:57 +00002794 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002795 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002796 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002797 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002798 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002799 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002800 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002801 // Note, it should not be possible to form a pointer with a valid
2802 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002803 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002804 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002805 << handler.AccessKind;
2806 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002807 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002808 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002809 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002810
2811 ObjType = CAT->getElementType();
2812
Richard Smith14a94132012-02-17 03:35:37 +00002813 // An array object is represented as either an Array APValue or as an
2814 // LValue which refers to a string literal.
2815 if (O->isLValue()) {
2816 assert(I == N - 1 && "extracting subobject of character?");
2817 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002818 if (handler.AccessKind != AK_Read)
2819 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2820 *O);
2821 else
2822 return handler.foundString(*O, ObjType, Index);
2823 }
2824
2825 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002826 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002827 else if (handler.AccessKind != AK_Read) {
2828 expandArray(*O, Index);
2829 O = &O->getArrayInitializedElt(Index);
2830 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002831 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002832 } else if (ObjType->isAnyComplexType()) {
2833 // Next subobject is a complex number.
2834 uint64_t Index = Sub.Entries[I].ArrayIndex;
2835 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002836 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002837 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002838 << handler.AccessKind;
2839 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002840 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002841 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002842 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002843
2844 bool WasConstQualified = ObjType.isConstQualified();
2845 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2846 if (WasConstQualified)
2847 ObjType.addConst();
2848
Richard Smith66c96992012-02-18 22:04:06 +00002849 assert(I == N - 1 && "extracting subobject of scalar?");
2850 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002851 return handler.found(Index ? O->getComplexIntImag()
2852 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002853 } else {
2854 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002855 return handler.found(Index ? O->getComplexFloatImag()
2856 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002857 }
Richard Smithd62306a2011-11-10 06:34:14 +00002858 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002859 // In C++14 onwards, it is permitted to read a mutable member whose
2860 // lifetime began within the evaluation.
2861 // FIXME: Should we also allow this in C++11?
2862 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2863 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002864 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002865 << Field;
2866 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002867 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002868 }
2869
Richard Smithd62306a2011-11-10 06:34:14 +00002870 // Next subobject is a class, struct or union field.
2871 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2872 if (RD->isUnion()) {
2873 const FieldDecl *UnionField = O->getUnionField();
2874 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002875 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002876 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002877 << handler.AccessKind << Field << !UnionField << UnionField;
2878 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002879 }
Richard Smithd62306a2011-11-10 06:34:14 +00002880 O = &O->getUnionValue();
2881 } else
2882 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002883
2884 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002885 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002886 if (WasConstQualified && !Field->isMutable())
2887 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002888
2889 if (ObjType.isVolatileQualified()) {
2890 if (Info.getLangOpts().CPlusPlus) {
2891 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002892 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002893 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002894 Info.Note(Field->getLocation(), diag::note_declared_at);
2895 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002896 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002897 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002898 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002899 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002900
2901 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002902 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002903 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002904 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2905 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2906 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002907
2908 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002909 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002910 if (WasConstQualified)
2911 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002912 }
2913 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002914}
2915
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002916namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002917struct ExtractSubobjectHandler {
2918 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002919 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002920
2921 static const AccessKinds AccessKind = AK_Read;
2922
2923 typedef bool result_type;
2924 bool failed() { return false; }
2925 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002926 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002927 return true;
2928 }
2929 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002930 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002931 return true;
2932 }
2933 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002934 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002935 return true;
2936 }
2937 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002938 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002939 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2940 return true;
2941 }
2942};
Richard Smith3229b742013-05-05 21:17:10 +00002943} // end anonymous namespace
2944
Richard Smith3da88fa2013-04-26 14:36:30 +00002945const AccessKinds ExtractSubobjectHandler::AccessKind;
2946
2947/// Extract the designated sub-object of an rvalue.
2948static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002949 const CompleteObject &Obj,
2950 const SubobjectDesignator &Sub,
2951 APValue &Result) {
2952 ExtractSubobjectHandler Handler = { Info, Result };
2953 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002954}
2955
Richard Smith3229b742013-05-05 21:17:10 +00002956namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002957struct ModifySubobjectHandler {
2958 EvalInfo &Info;
2959 APValue &NewVal;
2960 const Expr *E;
2961
2962 typedef bool result_type;
2963 static const AccessKinds AccessKind = AK_Assign;
2964
2965 bool checkConst(QualType QT) {
2966 // Assigning to a const object has undefined behavior.
2967 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002968 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002969 return false;
2970 }
2971 return true;
2972 }
2973
2974 bool failed() { return false; }
2975 bool found(APValue &Subobj, QualType SubobjType) {
2976 if (!checkConst(SubobjType))
2977 return false;
2978 // We've been given ownership of NewVal, so just swap it in.
2979 Subobj.swap(NewVal);
2980 return true;
2981 }
2982 bool found(APSInt &Value, QualType SubobjType) {
2983 if (!checkConst(SubobjType))
2984 return false;
2985 if (!NewVal.isInt()) {
2986 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002987 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002988 return false;
2989 }
2990 Value = NewVal.getInt();
2991 return true;
2992 }
2993 bool found(APFloat &Value, QualType SubobjType) {
2994 if (!checkConst(SubobjType))
2995 return false;
2996 Value = NewVal.getFloat();
2997 return true;
2998 }
2999 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3000 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
3001 }
3002};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003003} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003004
Richard Smith3229b742013-05-05 21:17:10 +00003005const AccessKinds ModifySubobjectHandler::AccessKind;
3006
Richard Smith3da88fa2013-04-26 14:36:30 +00003007/// Update the designated sub-object of an rvalue to the given value.
3008static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003009 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003010 const SubobjectDesignator &Sub,
3011 APValue &NewVal) {
3012 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003013 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003014}
3015
Richard Smith84f6dcf2012-02-02 01:16:57 +00003016/// Find the position where two subobject designators diverge, or equivalently
3017/// the length of the common initial subsequence.
3018static unsigned FindDesignatorMismatch(QualType ObjType,
3019 const SubobjectDesignator &A,
3020 const SubobjectDesignator &B,
3021 bool &WasArrayIndex) {
3022 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3023 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003024 if (!ObjType.isNull() &&
3025 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003026 // Next subobject is an array element.
3027 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3028 WasArrayIndex = true;
3029 return I;
3030 }
Richard Smith66c96992012-02-18 22:04:06 +00003031 if (ObjType->isAnyComplexType())
3032 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3033 else
3034 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003035 } else {
3036 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3037 WasArrayIndex = false;
3038 return I;
3039 }
3040 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3041 // Next subobject is a field.
3042 ObjType = FD->getType();
3043 else
3044 // Next subobject is a base class.
3045 ObjType = QualType();
3046 }
3047 }
3048 WasArrayIndex = false;
3049 return I;
3050}
3051
3052/// Determine whether the given subobject designators refer to elements of the
3053/// same array object.
3054static bool AreElementsOfSameArray(QualType ObjType,
3055 const SubobjectDesignator &A,
3056 const SubobjectDesignator &B) {
3057 if (A.Entries.size() != B.Entries.size())
3058 return false;
3059
George Burgess IVa51c4072015-10-16 01:49:01 +00003060 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003061 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3062 // A is a subobject of the array element.
3063 return false;
3064
3065 // If A (and B) designates an array element, the last entry will be the array
3066 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3067 // of length 1' case, and the entire path must match.
3068 bool WasArrayIndex;
3069 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3070 return CommonLength >= A.Entries.size() - IsArray;
3071}
3072
Richard Smith3229b742013-05-05 21:17:10 +00003073/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003074static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3075 AccessKinds AK, const LValue &LVal,
3076 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003077 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003078 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003079 return CompleteObject();
3080 }
3081
Craig Topper36250ad2014-05-12 05:36:57 +00003082 CallStackFrame *Frame = nullptr;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003083 if (LVal.getLValueCallIndex()) {
3084 Frame = Info.getCallFrame(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003085 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003086 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003087 << AK << LVal.Base.is<const ValueDecl*>();
3088 NoteLValueLocation(Info, LVal.Base);
3089 return CompleteObject();
3090 }
Richard Smith3229b742013-05-05 21:17:10 +00003091 }
3092
3093 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3094 // is not a constant expression (even if the object is non-volatile). We also
3095 // apply this rule to C++98, in order to conform to the expected 'volatile'
3096 // semantics.
3097 if (LValType.isVolatileQualified()) {
3098 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003099 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003100 << AK << LValType;
3101 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003102 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003103 return CompleteObject();
3104 }
3105
3106 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003107 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003108 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003109 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003110
3111 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3112 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3113 // In C++11, constexpr, non-volatile variables initialized with constant
3114 // expressions are constant expressions too. Inside constexpr functions,
3115 // parameters are constant expressions even if they're non-const.
3116 // In C++1y, objects local to a constant expression (those with a Frame) are
3117 // both readable and writable inside constant expressions.
3118 // In C, such things can also be folded, although they are not ICEs.
3119 const VarDecl *VD = dyn_cast<VarDecl>(D);
3120 if (VD) {
3121 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3122 VD = VDef;
3123 }
3124 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003125 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003126 return CompleteObject();
3127 }
3128
3129 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003130 if (BaseType.isVolatileQualified()) {
3131 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003132 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003133 << AK << 1 << VD;
3134 Info.Note(VD->getLocation(), diag::note_declared_at);
3135 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003136 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003137 }
3138 return CompleteObject();
3139 }
3140
3141 // Unless we're looking at a local variable or argument in a constexpr call,
3142 // the variable we're reading must be const.
3143 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003144 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003145 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3146 // OK, we can read and modify an object if we're in the process of
3147 // evaluating its initializer, because its lifetime began in this
3148 // evaluation.
3149 } else if (AK != AK_Read) {
3150 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003151 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003152 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003153 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003154 // OK, we can read this variable.
3155 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003156 // In OpenCL if a variable is in constant address space it is a const value.
3157 if (!(BaseType.isConstQualified() ||
3158 (Info.getLangOpts().OpenCL &&
3159 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003160 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003161 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003162 Info.Note(VD->getLocation(), diag::note_declared_at);
3163 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003164 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003165 }
3166 return CompleteObject();
3167 }
3168 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3169 // We support folding of const floating-point types, in order to make
3170 // static const data members of such types (supported as an extension)
3171 // more useful.
3172 if (Info.getLangOpts().CPlusPlus11) {
3173 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3174 Info.Note(VD->getLocation(), diag::note_declared_at);
3175 } else {
3176 Info.CCEDiag(E);
3177 }
George Burgess IVb5316982016-12-27 05:33:20 +00003178 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3179 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3180 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003181 } else {
3182 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003183 if (Info.checkingPotentialConstantExpression() &&
3184 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3185 // The definition of this variable could be constexpr. We can't
3186 // access it right now, but may be able to in future.
3187 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003188 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003189 Info.Note(VD->getLocation(), diag::note_declared_at);
3190 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003191 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003192 }
3193 return CompleteObject();
3194 }
3195 }
3196
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003197 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003198 return CompleteObject();
3199 } else {
3200 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3201
3202 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003203 if (const MaterializeTemporaryExpr *MTE =
3204 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3205 assert(MTE->getStorageDuration() == SD_Static &&
3206 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003207
Richard Smithe6c01442013-06-05 00:46:14 +00003208 // Per C++1y [expr.const]p2:
3209 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3210 // - a [...] glvalue of integral or enumeration type that refers to
3211 // a non-volatile const object [...]
3212 // [...]
3213 // - a [...] glvalue of literal type that refers to a non-volatile
3214 // object whose lifetime began within the evaluation of e.
3215 //
3216 // C++11 misses the 'began within the evaluation of e' check and
3217 // instead allows all temporaries, including things like:
3218 // int &&r = 1;
3219 // int x = ++r;
3220 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003221 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003222 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3223 const ValueDecl *ED = MTE->getExtendingDecl();
3224 if (!(BaseType.isConstQualified() &&
3225 BaseType->isIntegralOrEnumerationType()) &&
3226 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003227 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003228 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3229 return CompleteObject();
3230 }
3231
3232 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3233 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003234 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003235 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003236 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003237 return CompleteObject();
3238 }
3239 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003240 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003241 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003242 }
Richard Smith3229b742013-05-05 21:17:10 +00003243
3244 // Volatile temporary objects cannot be accessed in constant expressions.
3245 if (BaseType.isVolatileQualified()) {
3246 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003247 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003248 << AK << 0;
3249 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3250 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003251 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003252 }
3253 return CompleteObject();
3254 }
3255 }
3256
Richard Smith7525ff62013-05-09 07:14:00 +00003257 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003258 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003259 // object under construction.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003260 if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3261 LVal.getLValueCallIndex(),
3262 LVal.getLValueVersion())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003263 BaseType = Info.Ctx.getCanonicalType(BaseType);
3264 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003265 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003266 }
3267
Richard Smith9defb7d2018-02-21 03:38:30 +00003268 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003269 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003270 //
3271 // FIXME: Not all local state is mutable. Allow local constant subobjects
3272 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003273 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3274 Info.EvalStatus.HasSideEffects) ||
3275 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003276 return CompleteObject();
3277
Richard Smith9defb7d2018-02-21 03:38:30 +00003278 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003279}
3280
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003281/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003282/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3283/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003284///
3285/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003286/// \param Conv - The expression for which we are performing the conversion.
3287/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003288/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3289/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003290/// \param LVal - The glvalue on which we are attempting to perform this action.
3291/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003292static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003293 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003294 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003295 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003296 return false;
3297
Richard Smith3229b742013-05-05 21:17:10 +00003298 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003299 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003300 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003301 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3302 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3303 // initializer until now for such expressions. Such an expression can't be
3304 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003305 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003306 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003307 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003308 }
Richard Smith3229b742013-05-05 21:17:10 +00003309 APValue Lit;
3310 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3311 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003312 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003313 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003314 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003315 // We represent a string literal array as an lvalue pointing at the
3316 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003317 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003318 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003319 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003320 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003321 }
Richard Smith11562c52011-10-28 17:51:58 +00003322 }
3323
Richard Smith3229b742013-05-05 21:17:10 +00003324 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3325 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003326}
3327
3328/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003329static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003330 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003331 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003332 return false;
3333
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003334 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003335 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003336 return false;
3337 }
3338
Richard Smith3229b742013-05-05 21:17:10 +00003339 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003340 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3341}
3342
3343namespace {
3344struct CompoundAssignSubobjectHandler {
3345 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003346 const Expr *E;
3347 QualType PromotedLHSType;
3348 BinaryOperatorKind Opcode;
3349 const APValue &RHS;
3350
3351 static const AccessKinds AccessKind = AK_Assign;
3352
3353 typedef bool result_type;
3354
3355 bool checkConst(QualType QT) {
3356 // Assigning to a const object has undefined behavior.
3357 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003358 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003359 return false;
3360 }
3361 return true;
3362 }
3363
3364 bool failed() { return false; }
3365 bool found(APValue &Subobj, QualType SubobjType) {
3366 switch (Subobj.getKind()) {
3367 case APValue::Int:
3368 return found(Subobj.getInt(), SubobjType);
3369 case APValue::Float:
3370 return found(Subobj.getFloat(), SubobjType);
3371 case APValue::ComplexInt:
3372 case APValue::ComplexFloat:
3373 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003374 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003375 return false;
3376 case APValue::LValue:
3377 return foundPointer(Subobj, SubobjType);
3378 default:
3379 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003380 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003381 return false;
3382 }
3383 }
3384 bool found(APSInt &Value, QualType SubobjType) {
3385 if (!checkConst(SubobjType))
3386 return false;
3387
3388 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3389 // We don't support compound assignment on integer-cast-to-pointer
3390 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003391 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003392 return false;
3393 }
3394
3395 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3396 SubobjType, Value);
3397 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3398 return false;
3399 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3400 return true;
3401 }
3402 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003403 return checkConst(SubobjType) &&
3404 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3405 Value) &&
3406 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3407 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003408 }
3409 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3410 if (!checkConst(SubobjType))
3411 return false;
3412
3413 QualType PointeeType;
3414 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3415 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003416
3417 if (PointeeType.isNull() || !RHS.isInt() ||
3418 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003419 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003420 return false;
3421 }
3422
Richard Smithd6cc1982017-01-31 02:23:02 +00003423 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003424 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003425 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003426
3427 LValue LVal;
3428 LVal.setFrom(Info.Ctx, Subobj);
3429 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3430 return false;
3431 LVal.moveInto(Subobj);
3432 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003433 }
3434 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3435 llvm_unreachable("shouldn't encounter string elements here");
3436 }
3437};
3438} // end anonymous namespace
3439
3440const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3441
3442/// Perform a compound assignment of LVal <op>= RVal.
3443static bool handleCompoundAssignment(
3444 EvalInfo &Info, const Expr *E,
3445 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3446 BinaryOperatorKind Opcode, const APValue &RVal) {
3447 if (LVal.Designator.Invalid)
3448 return false;
3449
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003450 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003451 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003452 return false;
3453 }
3454
3455 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3456 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3457 RVal };
3458 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3459}
3460
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003461namespace {
3462struct IncDecSubobjectHandler {
3463 EvalInfo &Info;
3464 const UnaryOperator *E;
3465 AccessKinds AccessKind;
3466 APValue *Old;
3467
Richard Smith243ef902013-05-05 23:31:59 +00003468 typedef bool result_type;
3469
3470 bool checkConst(QualType QT) {
3471 // Assigning to a const object has undefined behavior.
3472 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003473 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003474 return false;
3475 }
3476 return true;
3477 }
3478
3479 bool failed() { return false; }
3480 bool found(APValue &Subobj, QualType SubobjType) {
3481 // Stash the old value. Also clear Old, so we don't clobber it later
3482 // if we're post-incrementing a complex.
3483 if (Old) {
3484 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003485 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003486 }
3487
3488 switch (Subobj.getKind()) {
3489 case APValue::Int:
3490 return found(Subobj.getInt(), SubobjType);
3491 case APValue::Float:
3492 return found(Subobj.getFloat(), SubobjType);
3493 case APValue::ComplexInt:
3494 return found(Subobj.getComplexIntReal(),
3495 SubobjType->castAs<ComplexType>()->getElementType()
3496 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3497 case APValue::ComplexFloat:
3498 return found(Subobj.getComplexFloatReal(),
3499 SubobjType->castAs<ComplexType>()->getElementType()
3500 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3501 case APValue::LValue:
3502 return foundPointer(Subobj, SubobjType);
3503 default:
3504 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003505 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003506 return false;
3507 }
3508 }
3509 bool found(APSInt &Value, QualType SubobjType) {
3510 if (!checkConst(SubobjType))
3511 return false;
3512
3513 if (!SubobjType->isIntegerType()) {
3514 // We don't support increment / decrement on integer-cast-to-pointer
3515 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003516 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003517 return false;
3518 }
3519
3520 if (Old) *Old = APValue(Value);
3521
3522 // bool arithmetic promotes to int, and the conversion back to bool
3523 // doesn't reduce mod 2^n, so special-case it.
3524 if (SubobjType->isBooleanType()) {
3525 if (AccessKind == AK_Increment)
3526 Value = 1;
3527 else
3528 Value = !Value;
3529 return true;
3530 }
3531
3532 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003533 if (AccessKind == AK_Increment) {
3534 ++Value;
3535
3536 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3537 APSInt ActualValue(Value, /*IsUnsigned*/true);
3538 return HandleOverflow(Info, E, ActualValue, SubobjType);
3539 }
3540 } else {
3541 --Value;
3542
3543 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3544 unsigned BitWidth = Value.getBitWidth();
3545 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3546 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003547 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003548 }
3549 }
3550 return true;
3551 }
3552 bool found(APFloat &Value, QualType SubobjType) {
3553 if (!checkConst(SubobjType))
3554 return false;
3555
3556 if (Old) *Old = APValue(Value);
3557
3558 APFloat One(Value.getSemantics(), 1);
3559 if (AccessKind == AK_Increment)
3560 Value.add(One, APFloat::rmNearestTiesToEven);
3561 else
3562 Value.subtract(One, APFloat::rmNearestTiesToEven);
3563 return true;
3564 }
3565 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3566 if (!checkConst(SubobjType))
3567 return false;
3568
3569 QualType PointeeType;
3570 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3571 PointeeType = PT->getPointeeType();
3572 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003573 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003574 return false;
3575 }
3576
3577 LValue LVal;
3578 LVal.setFrom(Info.Ctx, Subobj);
3579 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3580 AccessKind == AK_Increment ? 1 : -1))
3581 return false;
3582 LVal.moveInto(Subobj);
3583 return true;
3584 }
3585 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3586 llvm_unreachable("shouldn't encounter string elements here");
3587 }
3588};
3589} // end anonymous namespace
3590
3591/// Perform an increment or decrement on LVal.
3592static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3593 QualType LValType, bool IsIncrement, APValue *Old) {
3594 if (LVal.Designator.Invalid)
3595 return false;
3596
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003597 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003598 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003599 return false;
3600 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003601
3602 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3603 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3604 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3605 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3606}
3607
Richard Smithe97cbd72011-11-11 04:05:33 +00003608/// Build an lvalue for the object argument of a member function call.
3609static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3610 LValue &This) {
3611 if (Object->getType()->isPointerType())
3612 return EvaluatePointer(Object, This, Info);
3613
3614 if (Object->isGLValue())
3615 return EvaluateLValue(Object, This, Info);
3616
Richard Smithd9f663b2013-04-22 15:31:51 +00003617 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003618 return EvaluateTemporary(Object, This, Info);
3619
Faisal Valie690b7a2016-07-02 22:34:24 +00003620 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003621 return false;
3622}
3623
3624/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3625/// lvalue referring to the result.
3626///
3627/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003628/// \param LV - An lvalue referring to the base of the member pointer.
3629/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003630/// \param IncludeMember - Specifies whether the member itself is included in
3631/// the resulting LValue subobject designator. This is not possible when
3632/// creating a bound member function.
3633/// \return The field or method declaration to which the member pointer refers,
3634/// or 0 if evaluation fails.
3635static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003636 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003637 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003638 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003639 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003640 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003641 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003642 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003643
3644 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3645 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003646 if (!MemPtr.getDecl()) {
3647 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003648 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003649 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003650 }
Richard Smith253c2a32012-01-27 01:14:48 +00003651
Richard Smith027bf112011-11-17 22:56:20 +00003652 if (MemPtr.isDerivedMember()) {
3653 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003654 // The end of the derived-to-base path for the base object must match the
3655 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003656 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003657 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003658 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003659 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003660 }
Richard Smith027bf112011-11-17 22:56:20 +00003661 unsigned PathLengthToMember =
3662 LV.Designator.Entries.size() - MemPtr.Path.size();
3663 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3664 const CXXRecordDecl *LVDecl = getAsBaseClass(
3665 LV.Designator.Entries[PathLengthToMember + I]);
3666 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003667 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003668 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003669 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003670 }
Richard Smith027bf112011-11-17 22:56:20 +00003671 }
3672
3673 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003674 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003675 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003676 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003677 } else if (!MemPtr.Path.empty()) {
3678 // Extend the LValue path with the member pointer's path.
3679 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3680 MemPtr.Path.size() + IncludeMember);
3681
3682 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003683 if (const PointerType *PT = LVType->getAs<PointerType>())
3684 LVType = PT->getPointeeType();
3685 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3686 assert(RD && "member pointer access on non-class-type expression");
3687 // The first class in the path is that of the lvalue.
3688 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3689 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003690 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003691 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003692 RD = Base;
3693 }
3694 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003695 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3696 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003697 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003698 }
3699
3700 // Add the member. Note that we cannot build bound member functions here.
3701 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003702 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003703 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003704 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003705 } else if (const IndirectFieldDecl *IFD =
3706 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003707 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003708 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003709 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003710 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003711 }
Richard Smith027bf112011-11-17 22:56:20 +00003712 }
3713
3714 return MemPtr.getDecl();
3715}
3716
Richard Smith84401042013-06-03 05:03:02 +00003717static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3718 const BinaryOperator *BO,
3719 LValue &LV,
3720 bool IncludeMember = true) {
3721 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3722
3723 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003724 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003725 MemberPtr MemPtr;
3726 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3727 }
Craig Topper36250ad2014-05-12 05:36:57 +00003728 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003729 }
3730
3731 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3732 BO->getRHS(), IncludeMember);
3733}
3734
Richard Smith027bf112011-11-17 22:56:20 +00003735/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3736/// the provided lvalue, which currently refers to the base object.
3737static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3738 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003739 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003740 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003741 return false;
3742
Richard Smitha8105bc2012-01-06 16:39:00 +00003743 QualType TargetQT = E->getType();
3744 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3745 TargetQT = PT->getPointeeType();
3746
3747 // Check this cast lands within the final derived-to-base subobject path.
3748 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003749 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003750 << D.MostDerivedType << TargetQT;
3751 return false;
3752 }
3753
Richard Smith027bf112011-11-17 22:56:20 +00003754 // Check the type of the final cast. We don't need to check the path,
3755 // since a cast can only be formed if the path is unique.
3756 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003757 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3758 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003759 if (NewEntriesSize == D.MostDerivedPathLength)
3760 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3761 else
Richard Smith027bf112011-11-17 22:56:20 +00003762 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003763 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003764 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003765 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003766 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003767 }
Richard Smith027bf112011-11-17 22:56:20 +00003768
3769 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003770 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003771}
3772
Mike Stump876387b2009-10-27 22:09:17 +00003773namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003774enum EvalStmtResult {
3775 /// Evaluation failed.
3776 ESR_Failed,
3777 /// Hit a 'return' statement.
3778 ESR_Returned,
3779 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003780 ESR_Succeeded,
3781 /// Hit a 'continue' statement.
3782 ESR_Continue,
3783 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003784 ESR_Break,
3785 /// Still scanning for 'case' or 'default' statement.
3786 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003787};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003788}
Richard Smith254a73d2011-10-28 22:34:42 +00003789
Richard Smith97fcf4b2016-08-14 23:15:52 +00003790static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3791 // We don't need to evaluate the initializer for a static local.
3792 if (!VD->hasLocalStorage())
3793 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003794
Richard Smith97fcf4b2016-08-14 23:15:52 +00003795 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003796 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00003797
Richard Smith97fcf4b2016-08-14 23:15:52 +00003798 const Expr *InitE = VD->getInit();
3799 if (!InitE) {
3800 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3801 << false << VD->getType();
3802 Val = APValue();
3803 return false;
3804 }
Richard Smith51f03172013-06-20 03:00:05 +00003805
Richard Smith97fcf4b2016-08-14 23:15:52 +00003806 if (InitE->isValueDependent())
3807 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003808
Richard Smith97fcf4b2016-08-14 23:15:52 +00003809 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3810 // Wipe out any partially-computed value, to allow tracking that this
3811 // evaluation failed.
3812 Val = APValue();
3813 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003814 }
3815
3816 return true;
3817}
3818
Richard Smith97fcf4b2016-08-14 23:15:52 +00003819static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3820 bool OK = true;
3821
3822 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3823 OK &= EvaluateVarDecl(Info, VD);
3824
3825 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3826 for (auto *BD : DD->bindings())
3827 if (auto *VD = BD->getHoldingVar())
3828 OK &= EvaluateDecl(Info, VD);
3829
3830 return OK;
3831}
3832
3833
Richard Smith4e18ca52013-05-06 05:56:11 +00003834/// Evaluate a condition (either a variable declaration or an expression).
3835static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3836 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003837 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003838 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3839 return false;
3840 return EvaluateAsBooleanCondition(Cond, Result, Info);
3841}
3842
Richard Smith89210072016-04-04 23:29:43 +00003843namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003844/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00003845/// statement should be stored.
3846struct StmtResult {
3847 /// The APValue that should be filled in with the returned value.
3848 APValue &Value;
3849 /// The location containing the result, if any (used to support RVO).
3850 const LValue *Slot;
3851};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003852
3853struct TempVersionRAII {
3854 CallStackFrame &Frame;
3855
3856 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3857 Frame.pushTempVersion();
3858 }
3859
3860 ~TempVersionRAII() {
3861 Frame.popTempVersion();
3862 }
3863};
3864
Richard Smith89210072016-04-04 23:29:43 +00003865}
Richard Smith52a980a2015-08-28 02:43:42 +00003866
3867static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003868 const Stmt *S,
3869 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003870
3871/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003872static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003873 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003874 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003875 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003876 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003877 case ESR_Break:
3878 return ESR_Succeeded;
3879 case ESR_Succeeded:
3880 case ESR_Continue:
3881 return ESR_Continue;
3882 case ESR_Failed:
3883 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003884 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003885 return ESR;
3886 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003887 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003888}
3889
Richard Smith496ddcf2013-05-12 17:32:42 +00003890/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003891static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003892 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003893 BlockScopeRAII Scope(Info);
3894
Richard Smith496ddcf2013-05-12 17:32:42 +00003895 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003896 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003897 {
3898 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003899 if (const Stmt *Init = SS->getInit()) {
3900 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3901 if (ESR != ESR_Succeeded)
3902 return ESR;
3903 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003904 if (SS->getConditionVariable() &&
3905 !EvaluateDecl(Info, SS->getConditionVariable()))
3906 return ESR_Failed;
3907 if (!EvaluateInteger(SS->getCond(), Value, Info))
3908 return ESR_Failed;
3909 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003910
3911 // Find the switch case corresponding to the value of the condition.
3912 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003913 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003914 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3915 SC = SC->getNextSwitchCase()) {
3916 if (isa<DefaultStmt>(SC)) {
3917 Found = SC;
3918 continue;
3919 }
3920
3921 const CaseStmt *CS = cast<CaseStmt>(SC);
3922 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3923 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3924 : LHS;
3925 if (LHS <= Value && Value <= RHS) {
3926 Found = SC;
3927 break;
3928 }
3929 }
3930
3931 if (!Found)
3932 return ESR_Succeeded;
3933
3934 // Search the switch body for the switch case and evaluate it from there.
3935 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3936 case ESR_Break:
3937 return ESR_Succeeded;
3938 case ESR_Succeeded:
3939 case ESR_Continue:
3940 case ESR_Failed:
3941 case ESR_Returned:
3942 return ESR;
3943 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003944 // This can only happen if the switch case is nested within a statement
3945 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003946 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003947 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003948 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003949 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003950}
3951
Richard Smith254a73d2011-10-28 22:34:42 +00003952// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003953static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003954 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003955 if (!Info.nextStep(S))
3956 return ESR_Failed;
3957
Richard Smith496ddcf2013-05-12 17:32:42 +00003958 // If we're hunting down a 'case' or 'default' label, recurse through
3959 // substatements until we hit the label.
3960 if (Case) {
3961 // FIXME: We don't start the lifetime of objects whose initialization we
3962 // jump over. However, such objects must be of class type with a trivial
3963 // default constructor that initialize all subobjects, so must be empty,
3964 // so this almost never matters.
3965 switch (S->getStmtClass()) {
3966 case Stmt::CompoundStmtClass:
3967 // FIXME: Precompute which substatement of a compound statement we
3968 // would jump to, and go straight there rather than performing a
3969 // linear scan each time.
3970 case Stmt::LabelStmtClass:
3971 case Stmt::AttributedStmtClass:
3972 case Stmt::DoStmtClass:
3973 break;
3974
3975 case Stmt::CaseStmtClass:
3976 case Stmt::DefaultStmtClass:
3977 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003978 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003979 break;
3980
3981 case Stmt::IfStmtClass: {
3982 // FIXME: Precompute which side of an 'if' we would jump to, and go
3983 // straight there rather than scanning both sides.
3984 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003985
3986 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3987 // preceded by our switch label.
3988 BlockScopeRAII Scope(Info);
3989
Richard Smith496ddcf2013-05-12 17:32:42 +00003990 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3991 if (ESR != ESR_CaseNotFound || !IS->getElse())
3992 return ESR;
3993 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3994 }
3995
3996 case Stmt::WhileStmtClass: {
3997 EvalStmtResult ESR =
3998 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3999 if (ESR != ESR_Continue)
4000 return ESR;
4001 break;
4002 }
4003
4004 case Stmt::ForStmtClass: {
4005 const ForStmt *FS = cast<ForStmt>(S);
4006 EvalStmtResult ESR =
4007 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4008 if (ESR != ESR_Continue)
4009 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004010 if (FS->getInc()) {
4011 FullExpressionRAII IncScope(Info);
4012 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4013 return ESR_Failed;
4014 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004015 break;
4016 }
4017
4018 case Stmt::DeclStmtClass:
4019 // FIXME: If the variable has initialization that can't be jumped over,
4020 // bail out of any immediately-surrounding compound-statement too.
4021 default:
4022 return ESR_CaseNotFound;
4023 }
4024 }
4025
Richard Smith254a73d2011-10-28 22:34:42 +00004026 switch (S->getStmtClass()) {
4027 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004028 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004029 // Don't bother evaluating beyond an expression-statement which couldn't
4030 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004031 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004032 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004033 return ESR_Failed;
4034 return ESR_Succeeded;
4035 }
4036
Faisal Valie690b7a2016-07-02 22:34:24 +00004037 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00004038 return ESR_Failed;
4039
4040 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004041 return ESR_Succeeded;
4042
Richard Smithd9f663b2013-04-22 15:31:51 +00004043 case Stmt::DeclStmtClass: {
4044 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004045 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004046 // Each declaration initialization is its own full-expression.
4047 // FIXME: This isn't quite right; if we're performing aggregate
4048 // initialization, each braced subexpression is its own full-expression.
4049 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004050 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004051 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004052 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004053 return ESR_Succeeded;
4054 }
4055
Richard Smith357362d2011-12-13 06:39:58 +00004056 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004057 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004058 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004059 if (RetExpr &&
4060 !(Result.Slot
4061 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4062 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004063 return ESR_Failed;
4064 return ESR_Returned;
4065 }
Richard Smith254a73d2011-10-28 22:34:42 +00004066
4067 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004068 BlockScopeRAII Scope(Info);
4069
Richard Smith254a73d2011-10-28 22:34:42 +00004070 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004071 for (const auto *BI : CS->body()) {
4072 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004073 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004074 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004075 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004076 return ESR;
4077 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004078 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004079 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004080
4081 case Stmt::IfStmtClass: {
4082 const IfStmt *IS = cast<IfStmt>(S);
4083
4084 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004085 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004086 if (const Stmt *Init = IS->getInit()) {
4087 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4088 if (ESR != ESR_Succeeded)
4089 return ESR;
4090 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004091 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004092 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004093 return ESR_Failed;
4094
4095 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4096 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4097 if (ESR != ESR_Succeeded)
4098 return ESR;
4099 }
4100 return ESR_Succeeded;
4101 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004102
4103 case Stmt::WhileStmtClass: {
4104 const WhileStmt *WS = cast<WhileStmt>(S);
4105 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004106 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004107 bool Continue;
4108 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4109 Continue))
4110 return ESR_Failed;
4111 if (!Continue)
4112 break;
4113
4114 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4115 if (ESR != ESR_Continue)
4116 return ESR;
4117 }
4118 return ESR_Succeeded;
4119 }
4120
4121 case Stmt::DoStmtClass: {
4122 const DoStmt *DS = cast<DoStmt>(S);
4123 bool Continue;
4124 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004125 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004126 if (ESR != ESR_Continue)
4127 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004128 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004129
Richard Smith08d6a2c2013-07-24 07:11:57 +00004130 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004131 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4132 return ESR_Failed;
4133 } while (Continue);
4134 return ESR_Succeeded;
4135 }
4136
4137 case Stmt::ForStmtClass: {
4138 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004139 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004140 if (FS->getInit()) {
4141 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4142 if (ESR != ESR_Succeeded)
4143 return ESR;
4144 }
4145 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004146 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004147 bool Continue = true;
4148 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4149 FS->getCond(), Continue))
4150 return ESR_Failed;
4151 if (!Continue)
4152 break;
4153
4154 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4155 if (ESR != ESR_Continue)
4156 return ESR;
4157
Richard Smith08d6a2c2013-07-24 07:11:57 +00004158 if (FS->getInc()) {
4159 FullExpressionRAII IncScope(Info);
4160 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4161 return ESR_Failed;
4162 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004163 }
4164 return ESR_Succeeded;
4165 }
4166
Richard Smith896e0d72013-05-06 06:51:17 +00004167 case Stmt::CXXForRangeStmtClass: {
4168 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004169 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004170
4171 // Initialize the __range variable.
4172 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4173 if (ESR != ESR_Succeeded)
4174 return ESR;
4175
4176 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004177 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4178 if (ESR != ESR_Succeeded)
4179 return ESR;
4180 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004181 if (ESR != ESR_Succeeded)
4182 return ESR;
4183
4184 while (true) {
4185 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004186 {
4187 bool Continue = true;
4188 FullExpressionRAII CondExpr(Info);
4189 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4190 return ESR_Failed;
4191 if (!Continue)
4192 break;
4193 }
Richard Smith896e0d72013-05-06 06:51:17 +00004194
4195 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004196 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004197 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4198 if (ESR != ESR_Succeeded)
4199 return ESR;
4200
4201 // Loop body.
4202 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4203 if (ESR != ESR_Continue)
4204 return ESR;
4205
4206 // Increment: ++__begin
4207 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4208 return ESR_Failed;
4209 }
4210
4211 return ESR_Succeeded;
4212 }
4213
Richard Smith496ddcf2013-05-12 17:32:42 +00004214 case Stmt::SwitchStmtClass:
4215 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4216
Richard Smith4e18ca52013-05-06 05:56:11 +00004217 case Stmt::ContinueStmtClass:
4218 return ESR_Continue;
4219
4220 case Stmt::BreakStmtClass:
4221 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004222
4223 case Stmt::LabelStmtClass:
4224 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4225
4226 case Stmt::AttributedStmtClass:
4227 // As a general principle, C++11 attributes can be ignored without
4228 // any semantic impact.
4229 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4230 Case);
4231
4232 case Stmt::CaseStmtClass:
4233 case Stmt::DefaultStmtClass:
4234 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004235 }
4236}
4237
Richard Smithcc36f692011-12-22 02:22:31 +00004238/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4239/// default constructor. If so, we'll fold it whether or not it's marked as
4240/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4241/// so we need special handling.
4242static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004243 const CXXConstructorDecl *CD,
4244 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004245 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4246 return false;
4247
Richard Smith66e05fe2012-01-18 05:21:49 +00004248 // Value-initialization does not call a trivial default constructor, so such a
4249 // call is a core constant expression whether or not the constructor is
4250 // constexpr.
4251 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004252 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004253 // FIXME: If DiagDecl is an implicitly-declared special member function,
4254 // we should be much more explicit about why it's not constexpr.
4255 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4256 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4257 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004258 } else {
4259 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4260 }
4261 }
4262 return true;
4263}
4264
Richard Smith357362d2011-12-13 06:39:58 +00004265/// CheckConstexprFunction - Check that a function can be called in a constant
4266/// expression.
4267static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4268 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004269 const FunctionDecl *Definition,
4270 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004271 // Potential constant expressions can contain calls to declared, but not yet
4272 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004273 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004274 Declaration->isConstexpr())
4275 return false;
4276
Richard Smith0838f3a2013-05-14 05:18:44 +00004277 // Bail out with no diagnostic if the function declaration itself is invalid.
4278 // We will have produced a relevant diagnostic while parsing it.
4279 if (Declaration->isInvalidDecl())
4280 return false;
4281
Richard Smith357362d2011-12-13 06:39:58 +00004282 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004283 if (Definition && Definition->isConstexpr() &&
4284 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004285 return true;
4286
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004287 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004288 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004289
Richard Smith5179eb72016-06-28 19:03:57 +00004290 // If this function is not constexpr because it is an inherited
4291 // non-constexpr constructor, diagnose that directly.
4292 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4293 if (CD && CD->isInheritingConstructor()) {
4294 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004295 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004296 DiagDecl = CD = Inherited;
4297 }
4298
4299 // FIXME: If DiagDecl is an implicitly-declared special member function
4300 // or an inheriting constructor, we should be much more explicit about why
4301 // it's not constexpr.
4302 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004303 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004304 << CD->getInheritedConstructor().getConstructor()->getParent();
4305 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004306 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004307 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004308 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4309 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004310 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004311 }
4312 return false;
4313}
4314
Richard Smithbe6dd812014-11-19 21:27:17 +00004315/// Determine if a class has any fields that might need to be copied by a
4316/// trivial copy or move operation.
4317static bool hasFields(const CXXRecordDecl *RD) {
4318 if (!RD || RD->isEmpty())
4319 return false;
4320 for (auto *FD : RD->fields()) {
4321 if (FD->isUnnamedBitfield())
4322 continue;
4323 return true;
4324 }
4325 for (auto &Base : RD->bases())
4326 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4327 return true;
4328 return false;
4329}
4330
Richard Smithd62306a2011-11-10 06:34:14 +00004331namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004332typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004333}
4334
4335/// EvaluateArgs - Evaluate the arguments to a function call.
4336static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4337 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004338 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004339 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004340 I != E; ++I) {
4341 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4342 // If we're checking for a potential constant expression, evaluate all
4343 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004344 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004345 return false;
4346 Success = false;
4347 }
4348 }
4349 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004350}
4351
Richard Smith254a73d2011-10-28 22:34:42 +00004352/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004353static bool HandleFunctionCall(SourceLocation CallLoc,
4354 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004355 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004356 EvalInfo &Info, APValue &Result,
4357 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004358 ArgVector ArgValues(Args.size());
4359 if (!EvaluateArgs(Args, ArgValues, Info))
4360 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004361
Richard Smith253c2a32012-01-27 01:14:48 +00004362 if (!Info.CheckCallLimit(CallLoc))
4363 return false;
4364
4365 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004366
4367 // For a trivial copy or move assignment, perform an APValue copy. This is
4368 // essential for unions, where the operations performed by the assignment
4369 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004370 //
4371 // Skip this for non-union classes with no fields; in that case, the defaulted
4372 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004373 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004374 if (MD && MD->isDefaulted() &&
4375 (MD->getParent()->isUnion() ||
4376 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004377 assert(This &&
4378 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4379 LValue RHS;
4380 RHS.setFrom(Info.Ctx, ArgValues[0]);
4381 APValue RHSValue;
4382 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4383 RHS, RHSValue))
4384 return false;
4385 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4386 RHSValue))
4387 return false;
4388 This->moveInto(Result);
4389 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004390 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00004391 // We're in a lambda; determine the lambda capture field maps unless we're
4392 // just constexpr checking a lambda's call operator. constexpr checking is
4393 // done before the captures have been added to the closure object (unless
4394 // we're inferring constexpr-ness), so we don't have access to them in this
4395 // case. But since we don't need the captures to constexpr check, we can
4396 // just ignore them.
4397 if (!Info.checkingPotentialConstantExpression())
4398 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4399 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004400 }
4401
Richard Smith52a980a2015-08-28 02:43:42 +00004402 StmtResult Ret = {Result, ResultSlot};
4403 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004404 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004405 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004406 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004407 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004408 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004409 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004410}
4411
Richard Smithd62306a2011-11-10 06:34:14 +00004412/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004413static bool HandleConstructorCall(const Expr *E, const LValue &This,
4414 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004415 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004416 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004417 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004418 if (!Info.CheckCallLimit(CallLoc))
4419 return false;
4420
Richard Smith3607ffe2012-02-13 03:54:03 +00004421 const CXXRecordDecl *RD = Definition->getParent();
4422 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004423 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004424 return false;
4425 }
4426
Erik Pilkington42925492017-10-04 00:18:55 +00004427 EvalInfo::EvaluatingConstructorRAII EvalObj(
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004428 Info, {This.getLValueBase(),
4429 {This.getLValueCallIndex(), This.getLValueVersion()}});
Richard Smith5179eb72016-06-28 19:03:57 +00004430 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004431
Richard Smith52a980a2015-08-28 02:43:42 +00004432 // FIXME: Creating an APValue just to hold a nonexistent return value is
4433 // wasteful.
4434 APValue RetVal;
4435 StmtResult Ret = {RetVal, nullptr};
4436
Richard Smith5179eb72016-06-28 19:03:57 +00004437 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004438 if (Definition->isDelegatingConstructor()) {
4439 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004440 {
4441 FullExpressionRAII InitScope(Info);
4442 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4443 return false;
4444 }
Richard Smith52a980a2015-08-28 02:43:42 +00004445 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004446 }
4447
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004448 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004449 // essential for unions (or classes with anonymous union members), where the
4450 // operations performed by the constructor cannot be represented by
4451 // ctor-initializers.
4452 //
4453 // Skip this for empty non-union classes; we should not perform an
4454 // lvalue-to-rvalue conversion on them because their copy constructor does not
4455 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004456 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004457 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004458 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004459 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004460 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004461 return handleLValueToRValueConversion(
4462 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4463 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004464 }
4465
4466 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004467 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004468 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004469 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004470
John McCalld7bca762012-05-01 00:38:49 +00004471 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004472 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4473
Richard Smith08d6a2c2013-07-24 07:11:57 +00004474 // A scope for temporaries lifetime-extended by reference members.
4475 BlockScopeRAII LifetimeExtendedScope(Info);
4476
Richard Smith253c2a32012-01-27 01:14:48 +00004477 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004478 unsigned BasesSeen = 0;
4479#ifndef NDEBUG
4480 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4481#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004482 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004483 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004484 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004485 APValue *Value = &Result;
4486
4487 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004488 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004489 if (I->isBaseInitializer()) {
4490 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004491#ifndef NDEBUG
4492 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004493 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004494 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4495 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4496 "base class initializers not in expected order");
4497 ++BaseIt;
4498#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004499 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004500 BaseType->getAsCXXRecordDecl(), &Layout))
4501 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004502 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004503 } else if ((FD = I->getMember())) {
4504 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004505 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004506 if (RD->isUnion()) {
4507 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004508 Value = &Result.getUnionValue();
4509 } else {
4510 Value = &Result.getStructField(FD->getFieldIndex());
4511 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004512 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004513 // Walk the indirect field decl's chain to find the object to initialize,
4514 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004515 auto IndirectFieldChain = IFD->chain();
4516 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004517 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004518 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4519 // Switch the union field if it differs. This happens if we had
4520 // preceding zero-initialization, and we're now initializing a union
4521 // subobject other than the first.
4522 // FIXME: In this case, the values of the other subobjects are
4523 // specified, since zero-initialization sets all padding bits to zero.
4524 if (Value->isUninit() ||
4525 (Value->isUnion() && Value->getUnionField() != FD)) {
4526 if (CD->isUnion())
4527 *Value = APValue(FD);
4528 else
4529 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004530 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004531 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004532 // Store Subobject as its parent before updating it for the last element
4533 // in the chain.
4534 if (C == IndirectFieldChain.back())
4535 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004536 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004537 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004538 if (CD->isUnion())
4539 Value = &Value->getUnionValue();
4540 else
4541 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004542 }
Richard Smithd62306a2011-11-10 06:34:14 +00004543 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004544 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004545 }
Richard Smith253c2a32012-01-27 01:14:48 +00004546
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004547 // Need to override This for implicit field initializers as in this case
4548 // This refers to innermost anonymous struct/union containing initializer,
4549 // not to currently constructed class.
4550 const Expr *Init = I->getInit();
4551 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4552 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004553 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004554 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4555 (FD && FD->isBitField() &&
4556 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004557 // If we're checking for a potential constant expression, evaluate all
4558 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004559 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004560 return false;
4561 Success = false;
4562 }
Richard Smithd62306a2011-11-10 06:34:14 +00004563 }
4564
Richard Smithd9f663b2013-04-22 15:31:51 +00004565 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004566 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004567}
4568
Richard Smith5179eb72016-06-28 19:03:57 +00004569static bool HandleConstructorCall(const Expr *E, const LValue &This,
4570 ArrayRef<const Expr*> Args,
4571 const CXXConstructorDecl *Definition,
4572 EvalInfo &Info, APValue &Result) {
4573 ArgVector ArgValues(Args.size());
4574 if (!EvaluateArgs(Args, ArgValues, Info))
4575 return false;
4576
4577 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4578 Info, Result);
4579}
4580
Eli Friedman9a156e52008-11-12 09:44:48 +00004581//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004582// Generic Evaluation
4583//===----------------------------------------------------------------------===//
4584namespace {
4585
Aaron Ballman68af21c2014-01-03 19:26:43 +00004586template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004587class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004588 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004589private:
Richard Smith52a980a2015-08-28 02:43:42 +00004590 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004591 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004592 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004593 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004594 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004595 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004596 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004597
Richard Smith17100ba2012-02-16 02:46:34 +00004598 // Check whether a conditional operator with a non-constant condition is a
4599 // potential constant expression. If neither arm is a potential constant
4600 // expression, then the conditional operator is not either.
4601 template<typename ConditionalOperator>
4602 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004603 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004604
4605 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004606 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004607 {
Richard Smith17100ba2012-02-16 02:46:34 +00004608 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004609 StmtVisitorTy::Visit(E->getFalseExpr());
4610 if (Diag.empty())
4611 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004612 }
Richard Smith17100ba2012-02-16 02:46:34 +00004613
George Burgess IV8c892b52016-05-25 22:31:54 +00004614 {
4615 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004616 Diag.clear();
4617 StmtVisitorTy::Visit(E->getTrueExpr());
4618 if (Diag.empty())
4619 return;
4620 }
4621
4622 Error(E, diag::note_constexpr_conditional_never_const);
4623 }
4624
4625
4626 template<typename ConditionalOperator>
4627 bool HandleConditionalOperator(const ConditionalOperator *E) {
4628 bool BoolResult;
4629 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004630 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004631 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004632 return false;
4633 }
4634 if (Info.noteFailure()) {
4635 StmtVisitorTy::Visit(E->getTrueExpr());
4636 StmtVisitorTy::Visit(E->getFalseExpr());
4637 }
Richard Smith17100ba2012-02-16 02:46:34 +00004638 return false;
4639 }
4640
4641 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4642 return StmtVisitorTy::Visit(EvalExpr);
4643 }
4644
Peter Collingbournee9200682011-05-13 03:29:01 +00004645protected:
4646 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004647 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004648 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4649
Richard Smith92b1ce02011-12-12 09:28:41 +00004650 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004651 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004652 }
4653
Aaron Ballman68af21c2014-01-03 19:26:43 +00004654 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004655
4656public:
4657 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4658
4659 EvalInfo &getEvalInfo() { return Info; }
4660
Richard Smithf57d8cb2011-12-09 22:58:01 +00004661 /// Report an evaluation error. This should only be called when an error is
4662 /// first discovered. When propagating an error, just return false.
4663 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004664 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004665 return false;
4666 }
4667 bool Error(const Expr *E) {
4668 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4669 }
4670
Aaron Ballman68af21c2014-01-03 19:26:43 +00004671 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004672 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004673 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004674 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004675 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004676 }
4677
Aaron Ballman68af21c2014-01-03 19:26:43 +00004678 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004679 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004680 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004681 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004682 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004683 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004684 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004685 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004686 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004687 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004688 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004689 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004690 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4691 TempVersionRAII RAII(*Info.CurrentCall);
4692 return StmtVisitorTy::Visit(E->getExpr());
4693 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004694 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004695 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00004696 // The initializer may not have been parsed yet, or might be erroneous.
4697 if (!E->getExpr())
4698 return Error(E);
4699 return StmtVisitorTy::Visit(E->getExpr());
4700 }
Richard Smith5894a912011-12-19 22:12:41 +00004701 // We cannot create any objects for which cleanups are required, so there is
4702 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004703 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004704 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004705
Aaron Ballman68af21c2014-01-03 19:26:43 +00004706 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004707 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4708 return static_cast<Derived*>(this)->VisitCastExpr(E);
4709 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004710 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004711 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4712 return static_cast<Derived*>(this)->VisitCastExpr(E);
4713 }
4714
Aaron Ballman68af21c2014-01-03 19:26:43 +00004715 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004716 switch (E->getOpcode()) {
4717 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004718 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004719
4720 case BO_Comma:
4721 VisitIgnoredValue(E->getLHS());
4722 return StmtVisitorTy::Visit(E->getRHS());
4723
4724 case BO_PtrMemD:
4725 case BO_PtrMemI: {
4726 LValue Obj;
4727 if (!HandleMemberPointerAccess(Info, E, Obj))
4728 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004729 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004730 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004731 return false;
4732 return DerivedSuccess(Result, E);
4733 }
4734 }
4735 }
4736
Aaron Ballman68af21c2014-01-03 19:26:43 +00004737 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004738 // Evaluate and cache the common expression. We treat it as a temporary,
4739 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004740 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004741 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004742 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004743
Richard Smith17100ba2012-02-16 02:46:34 +00004744 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004745 }
4746
Aaron Ballman68af21c2014-01-03 19:26:43 +00004747 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004748 bool IsBcpCall = false;
4749 // If the condition (ignoring parens) is a __builtin_constant_p call,
4750 // the result is a constant expression if it can be folded without
4751 // side-effects. This is an important GNU extension. See GCC PR38377
4752 // for discussion.
4753 if (const CallExpr *CallCE =
4754 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004755 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004756 IsBcpCall = true;
4757
4758 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4759 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004760 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004761 return false;
4762
Richard Smith6d4c6582013-11-05 22:18:15 +00004763 FoldConstant Fold(Info, IsBcpCall);
4764 if (!HandleConditionalOperator(E)) {
4765 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004766 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004767 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004768
4769 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004770 }
4771
Aaron Ballman68af21c2014-01-03 19:26:43 +00004772 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004773 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00004774 return DerivedSuccess(*Value, E);
4775
4776 const Expr *Source = E->getSourceExpr();
4777 if (!Source)
4778 return Error(E);
4779 if (Source == E) { // sanity checking.
4780 assert(0 && "OpaqueValueExpr recursively refers to itself");
4781 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004782 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004783 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004784 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004785
Aaron Ballman68af21c2014-01-03 19:26:43 +00004786 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004787 APValue Result;
4788 if (!handleCallExpr(E, Result, nullptr))
4789 return false;
4790 return DerivedSuccess(Result, E);
4791 }
4792
4793 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004794 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004795 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004796 QualType CalleeType = Callee->getType();
4797
Craig Topper36250ad2014-05-12 05:36:57 +00004798 const FunctionDecl *FD = nullptr;
4799 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004800 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004801 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004802
Richard Smithe97cbd72011-11-11 04:05:33 +00004803 // Extract function decl and 'this' pointer from the callee.
4804 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004805 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004806 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4807 // Explicit bound member calls, such as x.f() or p->g();
4808 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004809 return false;
4810 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004811 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004812 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004813 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4814 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004815 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4816 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004817 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004818 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004819 return Error(Callee);
4820
4821 FD = dyn_cast<FunctionDecl>(Member);
4822 if (!FD)
4823 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004824 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004825 LValue Call;
4826 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004827 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004828
Richard Smitha8105bc2012-01-06 16:39:00 +00004829 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004830 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004831 FD = dyn_cast_or_null<FunctionDecl>(
4832 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004833 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004834 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004835 // Don't call function pointers which have been cast to some other type.
4836 // Per DR (no number yet), the caller and callee can differ in noexcept.
4837 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4838 CalleeType->getPointeeType(), FD->getType())) {
4839 return Error(E);
4840 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004841
4842 // Overloaded operator calls to member functions are represented as normal
4843 // calls with '*this' as the first argument.
4844 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4845 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004846 // FIXME: When selecting an implicit conversion for an overloaded
4847 // operator delete, we sometimes try to evaluate calls to conversion
4848 // operators without a 'this' parameter!
4849 if (Args.empty())
4850 return Error(E);
4851
Nick Lewycky13073a62017-06-12 21:15:44 +00004852 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004853 return false;
4854 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004855 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004856 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004857 // Map the static invoker for the lambda back to the call operator.
4858 // Conveniently, we don't have to slice out the 'this' argument (as is
4859 // being done for the non-static case), since a static member function
4860 // doesn't have an implicit argument passed in.
4861 const CXXRecordDecl *ClosureClass = MD->getParent();
4862 assert(
4863 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4864 "Number of captures must be zero for conversion to function-ptr");
4865
4866 const CXXMethodDecl *LambdaCallOp =
4867 ClosureClass->getLambdaCallOperator();
4868
4869 // Set 'FD', the function that will be called below, to the call
4870 // operator. If the closure object represents a generic lambda, find
4871 // the corresponding specialization of the call operator.
4872
4873 if (ClosureClass->isGenericLambda()) {
4874 assert(MD->isFunctionTemplateSpecialization() &&
4875 "A generic lambda's static-invoker function must be a "
4876 "template specialization");
4877 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4878 FunctionTemplateDecl *CallOpTemplate =
4879 LambdaCallOp->getDescribedFunctionTemplate();
4880 void *InsertPos = nullptr;
4881 FunctionDecl *CorrespondingCallOpSpecialization =
4882 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4883 assert(CorrespondingCallOpSpecialization &&
4884 "We must always have a function call operator specialization "
4885 "that corresponds to our static invoker specialization");
4886 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4887 } else
4888 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004889 }
4890
Daniel Jasperffdee092017-05-02 19:21:42 +00004891
Richard Smithe97cbd72011-11-11 04:05:33 +00004892 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004893 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004894
Richard Smith47b34932012-02-01 02:39:43 +00004895 if (This && !This->checkSubobject(Info, E, CSK_This))
4896 return false;
4897
Richard Smith3607ffe2012-02-13 03:54:03 +00004898 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4899 // calls to such functions in constant expressions.
4900 if (This && !HasQualifier &&
4901 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4902 return Error(E, diag::note_constexpr_virtual_call);
4903
Craig Topper36250ad2014-05-12 05:36:57 +00004904 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004905 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004906
Nick Lewycky13073a62017-06-12 21:15:44 +00004907 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4908 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004909 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004910 return false;
4911
Richard Smith52a980a2015-08-28 02:43:42 +00004912 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004913 }
4914
Aaron Ballman68af21c2014-01-03 19:26:43 +00004915 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004916 return StmtVisitorTy::Visit(E->getInitializer());
4917 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004918 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004919 if (E->getNumInits() == 0)
4920 return DerivedZeroInitialization(E);
4921 if (E->getNumInits() == 1)
4922 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004923 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004924 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004925 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004926 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004927 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004928 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004929 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004930 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004931 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004932 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004933 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004934
Richard Smithd62306a2011-11-10 06:34:14 +00004935 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004936 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004937 assert(!E->isArrow() && "missing call to bound member function?");
4938
Richard Smith2e312c82012-03-03 22:46:17 +00004939 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004940 if (!Evaluate(Val, Info, E->getBase()))
4941 return false;
4942
4943 QualType BaseTy = E->getBase()->getType();
4944
4945 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004946 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004947 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004948 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004949 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4950
Richard Smith9defb7d2018-02-21 03:38:30 +00004951 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00004952 SubobjectDesignator Designator(BaseTy);
4953 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004954
Richard Smith3229b742013-05-05 21:17:10 +00004955 APValue Result;
4956 return extractSubobject(Info, E, Obj, Designator, Result) &&
4957 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004958 }
4959
Aaron Ballman68af21c2014-01-03 19:26:43 +00004960 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004961 switch (E->getCastKind()) {
4962 default:
4963 break;
4964
Richard Smitha23ab512013-05-23 00:30:41 +00004965 case CK_AtomicToNonAtomic: {
4966 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004967 // This does not need to be done in place even for class/array types:
4968 // atomic-to-non-atomic conversion implies copying the object
4969 // representation.
4970 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004971 return false;
4972 return DerivedSuccess(AtomicVal, E);
4973 }
4974
Richard Smith11562c52011-10-28 17:51:58 +00004975 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004976 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004977 return StmtVisitorTy::Visit(E->getSubExpr());
4978
4979 case CK_LValueToRValue: {
4980 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004981 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4982 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004983 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004984 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004985 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004986 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004987 return false;
4988 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004989 }
4990 }
4991
Richard Smithf57d8cb2011-12-09 22:58:01 +00004992 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004993 }
4994
Aaron Ballman68af21c2014-01-03 19:26:43 +00004995 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004996 return VisitUnaryPostIncDec(UO);
4997 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004998 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004999 return VisitUnaryPostIncDec(UO);
5000 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005001 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005002 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005003 return Error(UO);
5004
5005 LValue LVal;
5006 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5007 return false;
5008 APValue RVal;
5009 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5010 UO->isIncrementOp(), &RVal))
5011 return false;
5012 return DerivedSuccess(RVal, UO);
5013 }
5014
Aaron Ballman68af21c2014-01-03 19:26:43 +00005015 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005016 // We will have checked the full-expressions inside the statement expression
5017 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005018 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005019 return Error(E);
5020
Richard Smith08d6a2c2013-07-24 07:11:57 +00005021 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005022 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005023 if (CS->body_empty())
5024 return true;
5025
Richard Smith51f03172013-06-20 03:00:05 +00005026 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5027 BE = CS->body_end();
5028 /**/; ++BI) {
5029 if (BI + 1 == BE) {
5030 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5031 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005032 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00005033 diag::note_constexpr_stmt_expr_unsupported);
5034 return false;
5035 }
5036 return this->Visit(FinalExpr);
5037 }
5038
5039 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005040 StmtResult Result = { ReturnValue, nullptr };
5041 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005042 if (ESR != ESR_Succeeded) {
5043 // FIXME: If the statement-expression terminated due to 'return',
5044 // 'break', or 'continue', it would be nice to propagate that to
5045 // the outer statement evaluation rather than bailing out.
5046 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00005047 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00005048 diag::note_constexpr_stmt_expr_unsupported);
5049 return false;
5050 }
5051 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005052
5053 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005054 }
5055
Richard Smith4a678122011-10-24 18:44:57 +00005056 /// Visit a value which is evaluated, but whose value is ignored.
5057 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005058 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005059 }
David Majnemere9807b22016-02-26 04:23:19 +00005060
5061 /// Potentially visit a MemberExpr's base expression.
5062 void VisitIgnoredBaseExpression(const Expr *E) {
5063 // While MSVC doesn't evaluate the base expression, it does diagnose the
5064 // presence of side-effecting behavior.
5065 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5066 return;
5067 VisitIgnoredValue(E);
5068 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005069};
5070
Eric Fiselier0683c0e2018-05-07 21:07:10 +00005071} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00005072
5073//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005074// Common base class for lvalue and temporary evaluation.
5075//===----------------------------------------------------------------------===//
5076namespace {
5077template<class Derived>
5078class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005079 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005080protected:
5081 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005082 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005083 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005084 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005085
5086 bool Success(APValue::LValueBase B) {
5087 Result.set(B);
5088 return true;
5089 }
5090
George Burgess IVf9013bf2017-02-10 22:52:29 +00005091 bool evaluatePointer(const Expr *E, LValue &Result) {
5092 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5093 }
5094
Richard Smith027bf112011-11-17 22:56:20 +00005095public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005096 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5097 : ExprEvaluatorBaseTy(Info), Result(Result),
5098 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005099
Richard Smith2e312c82012-03-03 22:46:17 +00005100 bool Success(const APValue &V, const Expr *E) {
5101 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005102 return true;
5103 }
Richard Smith027bf112011-11-17 22:56:20 +00005104
Richard Smith027bf112011-11-17 22:56:20 +00005105 bool VisitMemberExpr(const MemberExpr *E) {
5106 // Handle non-static data members.
5107 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005108 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005109 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005110 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005111 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005112 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005113 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005114 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005115 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005116 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005117 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005118 BaseTy = E->getBase()->getType();
5119 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005120 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005121 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005122 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005123 Result.setInvalid(E);
5124 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005125 }
Richard Smith027bf112011-11-17 22:56:20 +00005126
Richard Smith1b78b3d2012-01-25 22:15:11 +00005127 const ValueDecl *MD = E->getMemberDecl();
5128 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5129 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5130 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5131 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005132 if (!HandleLValueMember(this->Info, E, Result, FD))
5133 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005134 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005135 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5136 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005137 } else
5138 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005139
Richard Smith1b78b3d2012-01-25 22:15:11 +00005140 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005141 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005142 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005143 RefValue))
5144 return false;
5145 return Success(RefValue, E);
5146 }
5147 return true;
5148 }
5149
5150 bool VisitBinaryOperator(const BinaryOperator *E) {
5151 switch (E->getOpcode()) {
5152 default:
5153 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5154
5155 case BO_PtrMemD:
5156 case BO_PtrMemI:
5157 return HandleMemberPointerAccess(this->Info, E, Result);
5158 }
5159 }
5160
5161 bool VisitCastExpr(const CastExpr *E) {
5162 switch (E->getCastKind()) {
5163 default:
5164 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5165
5166 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005167 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005168 if (!this->Visit(E->getSubExpr()))
5169 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005170
5171 // Now figure out the necessary offset to add to the base LV to get from
5172 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005173 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5174 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005175 }
5176 }
5177};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005178}
Richard Smith027bf112011-11-17 22:56:20 +00005179
5180//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005181// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005182//
5183// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5184// function designators (in C), decl references to void objects (in C), and
5185// temporaries (if building with -Wno-address-of-temporary).
5186//
5187// LValue evaluation produces values comprising a base expression of one of the
5188// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005189// - Declarations
5190// * VarDecl
5191// * FunctionDecl
5192// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005193// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005194// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005195// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005196// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005197// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005198// * ObjCEncodeExpr
5199// * AddrLabelExpr
5200// * BlockExpr
5201// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005202// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005203// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005204// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005205// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5206// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005207// * A MaterializeTemporaryExpr that has static storage duration, with no
5208// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005209// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005210//===----------------------------------------------------------------------===//
5211namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005212class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005213 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005214public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005215 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5216 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005217
Richard Smith11562c52011-10-28 17:51:58 +00005218 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005219 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005220
Peter Collingbournee9200682011-05-13 03:29:01 +00005221 bool VisitDeclRefExpr(const DeclRefExpr *E);
5222 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005223 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005224 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5225 bool VisitMemberExpr(const MemberExpr *E);
5226 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5227 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005228 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005229 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005230 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5231 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005232 bool VisitUnaryReal(const UnaryOperator *E);
5233 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005234 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5235 return VisitUnaryPreIncDec(UO);
5236 }
5237 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5238 return VisitUnaryPreIncDec(UO);
5239 }
Richard Smith3229b742013-05-05 21:17:10 +00005240 bool VisitBinAssign(const BinaryOperator *BO);
5241 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005242
Peter Collingbournee9200682011-05-13 03:29:01 +00005243 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005244 switch (E->getCastKind()) {
5245 default:
Richard Smith027bf112011-11-17 22:56:20 +00005246 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005247
Eli Friedmance3e02a2011-10-11 00:13:24 +00005248 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005249 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005250 if (!Visit(E->getSubExpr()))
5251 return false;
5252 Result.Designator.setInvalid();
5253 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005254
Richard Smith027bf112011-11-17 22:56:20 +00005255 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005256 if (!Visit(E->getSubExpr()))
5257 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005258 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005259 }
5260 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005261};
5262} // end anonymous namespace
5263
Richard Smith11562c52011-10-28 17:51:58 +00005264/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005265/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005266/// * function designators in C, and
5267/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005268/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005269static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5270 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005271 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005272 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005273 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005274}
5275
Peter Collingbournee9200682011-05-13 03:29:01 +00005276bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005277 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005278 return Success(FD);
5279 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005280 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005281 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005282 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005283 return Error(E);
5284}
Richard Smith733237d2011-10-24 23:14:33 +00005285
Faisal Vali0528a312016-11-13 06:09:16 +00005286
Richard Smith11562c52011-10-28 17:51:58 +00005287bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005288
5289 // If we are within a lambda's call operator, check whether the 'VD' referred
5290 // to within 'E' actually represents a lambda-capture that maps to a
5291 // data-member/field within the closure object, and if so, evaluate to the
5292 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00005293 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5294 isa<DeclRefExpr>(E) &&
5295 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5296 // We don't always have a complete capture-map when checking or inferring if
5297 // the function call operator meets the requirements of a constexpr function
5298 // - but we don't need to evaluate the captures to determine constexprness
5299 // (dcl.constexpr C++17).
5300 if (Info.checkingPotentialConstantExpression())
5301 return false;
5302
Faisal Vali051e3a22017-02-16 04:12:21 +00005303 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005304 // Start with 'Result' referring to the complete closure object...
5305 Result = *Info.CurrentCall->This;
5306 // ... then update it to refer to the field of the closure object
5307 // that represents the capture.
5308 if (!HandleLValueMember(Info, E, Result, FD))
5309 return false;
5310 // And if the field is of reference type, update 'Result' to refer to what
5311 // the field refers to.
5312 if (FD->getType()->isReferenceType()) {
5313 APValue RVal;
5314 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5315 RVal))
5316 return false;
5317 Result.setFrom(Info.Ctx, RVal);
5318 }
5319 return true;
5320 }
5321 }
Craig Topper36250ad2014-05-12 05:36:57 +00005322 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005323 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5324 // Only if a local variable was declared in the function currently being
5325 // evaluated, do we expect to be able to find its value in the current
5326 // frame. (Otherwise it was likely declared in an enclosing context and
5327 // could either have a valid evaluatable value (for e.g. a constexpr
5328 // variable) or be ill-formed (and trigger an appropriate evaluation
5329 // diagnostic)).
5330 if (Info.CurrentCall->Callee &&
5331 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5332 Frame = Info.CurrentCall;
5333 }
5334 }
Richard Smith3229b742013-05-05 21:17:10 +00005335
Richard Smithfec09922011-11-01 16:57:24 +00005336 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005337 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005338 Result.set({VD, Frame->Index,
5339 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00005340 return true;
5341 }
Richard Smithce40ad62011-11-12 22:28:03 +00005342 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005343 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005344
Richard Smith3229b742013-05-05 21:17:10 +00005345 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005346 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005347 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005348 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005349 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005350 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005351 return false;
5352 }
Richard Smith3229b742013-05-05 21:17:10 +00005353 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005354}
5355
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005356bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5357 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005358 // Walk through the expression to find the materialized temporary itself.
5359 SmallVector<const Expr *, 2> CommaLHSs;
5360 SmallVector<SubobjectAdjustment, 2> Adjustments;
5361 const Expr *Inner = E->GetTemporaryExpr()->
5362 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005363
Richard Smith84401042013-06-03 05:03:02 +00005364 // If we passed any comma operators, evaluate their LHSs.
5365 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5366 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5367 return false;
5368
Richard Smithe6c01442013-06-05 00:46:14 +00005369 // A materialized temporary with static storage duration can appear within the
5370 // result of a constant expression evaluation, so we need to preserve its
5371 // value for use outside this evaluation.
5372 APValue *Value;
5373 if (E->getStorageDuration() == SD_Static) {
5374 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005375 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005376 Result.set(E);
5377 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005378 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5379 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00005380 }
5381
Richard Smithea4ad5d2013-06-06 08:19:16 +00005382 QualType Type = Inner->getType();
5383
Richard Smith84401042013-06-03 05:03:02 +00005384 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005385 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5386 (E->getStorageDuration() == SD_Static &&
5387 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5388 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005389 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005390 }
Richard Smith84401042013-06-03 05:03:02 +00005391
5392 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005393 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5394 --I;
5395 switch (Adjustments[I].Kind) {
5396 case SubobjectAdjustment::DerivedToBaseAdjustment:
5397 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5398 Type, Result))
5399 return false;
5400 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5401 break;
5402
5403 case SubobjectAdjustment::FieldAdjustment:
5404 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5405 return false;
5406 Type = Adjustments[I].Field->getType();
5407 break;
5408
5409 case SubobjectAdjustment::MemberPointerAdjustment:
5410 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5411 Adjustments[I].Ptr.RHS))
5412 return false;
5413 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5414 break;
5415 }
5416 }
5417
5418 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005419}
5420
Peter Collingbournee9200682011-05-13 03:29:01 +00005421bool
5422LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005423 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5424 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005425 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5426 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005427 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005428}
5429
Richard Smith6e525142011-12-27 12:18:28 +00005430bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005431 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005432 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005433
Faisal Valie690b7a2016-07-02 22:34:24 +00005434 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005435 << E->getExprOperand()->getType()
5436 << E->getExprOperand()->getSourceRange();
5437 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005438}
5439
Francois Pichet0066db92012-04-16 04:08:35 +00005440bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5441 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005442}
Francois Pichet0066db92012-04-16 04:08:35 +00005443
Peter Collingbournee9200682011-05-13 03:29:01 +00005444bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005445 // Handle static data members.
5446 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005447 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005448 return VisitVarDecl(E, VD);
5449 }
5450
Richard Smith254a73d2011-10-28 22:34:42 +00005451 // Handle static member functions.
5452 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5453 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005454 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005455 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005456 }
5457 }
5458
Richard Smithd62306a2011-11-10 06:34:14 +00005459 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005460 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005461}
5462
Peter Collingbournee9200682011-05-13 03:29:01 +00005463bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005464 // FIXME: Deal with vectors as array subscript bases.
5465 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005466 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005467
Nick Lewyckyad888682017-04-27 07:27:36 +00005468 bool Success = true;
5469 if (!evaluatePointer(E->getBase(), Result)) {
5470 if (!Info.noteFailure())
5471 return false;
5472 Success = false;
5473 }
Mike Stump11289f42009-09-09 15:08:12 +00005474
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005475 APSInt Index;
5476 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005477 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005478
Nick Lewyckyad888682017-04-27 07:27:36 +00005479 return Success &&
5480 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005481}
Eli Friedman9a156e52008-11-12 09:44:48 +00005482
Peter Collingbournee9200682011-05-13 03:29:01 +00005483bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005484 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005485}
5486
Richard Smith66c96992012-02-18 22:04:06 +00005487bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5488 if (!Visit(E->getSubExpr()))
5489 return false;
5490 // __real is a no-op on scalar lvalues.
5491 if (E->getSubExpr()->getType()->isAnyComplexType())
5492 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5493 return true;
5494}
5495
5496bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5497 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5498 "lvalue __imag__ on scalar?");
5499 if (!Visit(E->getSubExpr()))
5500 return false;
5501 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5502 return true;
5503}
5504
Richard Smith243ef902013-05-05 23:31:59 +00005505bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005506 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005507 return Error(UO);
5508
5509 if (!this->Visit(UO->getSubExpr()))
5510 return false;
5511
Richard Smith243ef902013-05-05 23:31:59 +00005512 return handleIncDec(
5513 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005514 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005515}
5516
5517bool LValueExprEvaluator::VisitCompoundAssignOperator(
5518 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005519 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005520 return Error(CAO);
5521
Richard Smith3229b742013-05-05 21:17:10 +00005522 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005523
5524 // The overall lvalue result is the result of evaluating the LHS.
5525 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005526 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005527 Evaluate(RHS, this->Info, CAO->getRHS());
5528 return false;
5529 }
5530
Richard Smith3229b742013-05-05 21:17:10 +00005531 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5532 return false;
5533
Richard Smith43e77732013-05-07 04:50:00 +00005534 return handleCompoundAssignment(
5535 this->Info, CAO,
5536 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5537 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005538}
5539
5540bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005541 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005542 return Error(E);
5543
Richard Smith3229b742013-05-05 21:17:10 +00005544 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005545
5546 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005547 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005548 Evaluate(NewVal, this->Info, E->getRHS());
5549 return false;
5550 }
5551
Richard Smith3229b742013-05-05 21:17:10 +00005552 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5553 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005554
5555 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005556 NewVal);
5557}
5558
Eli Friedman9a156e52008-11-12 09:44:48 +00005559//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005560// Pointer Evaluation
5561//===----------------------------------------------------------------------===//
5562
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005563/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00005564/// returned by a function with the alloc_size attribute. Returns true if we
5565/// were successful. Places an unsigned number into `Result`.
5566///
5567/// This expects the given CallExpr to be a call to a function with an
5568/// alloc_size attribute.
5569static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5570 const CallExpr *Call,
5571 llvm::APInt &Result) {
5572 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5573
Joel E. Denny81508102018-03-13 14:51:22 +00005574 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5575 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005576 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5577 if (Call->getNumArgs() <= SizeArgNo)
5578 return false;
5579
5580 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5581 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5582 return false;
5583 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5584 return false;
5585 Into = Into.zextOrSelf(BitsInSizeT);
5586 return true;
5587 };
5588
5589 APSInt SizeOfElem;
5590 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5591 return false;
5592
Joel E. Denny81508102018-03-13 14:51:22 +00005593 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005594 Result = std::move(SizeOfElem);
5595 return true;
5596 }
5597
5598 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00005599 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005600 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5601 return false;
5602
5603 bool Overflow;
5604 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5605 if (Overflow)
5606 return false;
5607
5608 Result = std::move(BytesAvailable);
5609 return true;
5610}
5611
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005612/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00005613/// function.
5614static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5615 const LValue &LVal,
5616 llvm::APInt &Result) {
5617 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5618 "Can't get the size of a non alloc_size function");
5619 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5620 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5621 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5622}
5623
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005624/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00005625/// a function with the alloc_size attribute. If it was possible to do so, this
5626/// function will return true, make Result's Base point to said function call,
5627/// and mark Result's Base as invalid.
5628static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5629 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005630 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005631 return false;
5632
5633 // Because we do no form of static analysis, we only support const variables.
5634 //
5635 // Additionally, we can't support parameters, nor can we support static
5636 // variables (in the latter case, use-before-assign isn't UB; in the former,
5637 // we have no clue what they'll be assigned to).
5638 const auto *VD =
5639 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5640 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5641 return false;
5642
5643 const Expr *Init = VD->getAnyInitializer();
5644 if (!Init)
5645 return false;
5646
5647 const Expr *E = Init->IgnoreParens();
5648 if (!tryUnwrapAllocSizeCall(E))
5649 return false;
5650
5651 // Store E instead of E unwrapped so that the type of the LValue's base is
5652 // what the user wanted.
5653 Result.setInvalid(E);
5654
5655 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005656 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005657 return true;
5658}
5659
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005660namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005661class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005662 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005663 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005664 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005665
Peter Collingbournee9200682011-05-13 03:29:01 +00005666 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005667 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005668 return true;
5669 }
George Burgess IVe3763372016-12-22 02:50:20 +00005670
George Burgess IVf9013bf2017-02-10 22:52:29 +00005671 bool evaluateLValue(const Expr *E, LValue &Result) {
5672 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5673 }
5674
5675 bool evaluatePointer(const Expr *E, LValue &Result) {
5676 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5677 }
5678
George Burgess IVe3763372016-12-22 02:50:20 +00005679 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005680public:
Mike Stump11289f42009-09-09 15:08:12 +00005681
George Burgess IVf9013bf2017-02-10 22:52:29 +00005682 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5683 : ExprEvaluatorBaseTy(info), Result(Result),
5684 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005685
Richard Smith2e312c82012-03-03 22:46:17 +00005686 bool Success(const APValue &V, const Expr *E) {
5687 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005688 return true;
5689 }
Richard Smithfddd3842011-12-30 21:15:51 +00005690 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005691 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5692 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005693 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005694 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005695
John McCall45d55e42010-05-07 21:00:08 +00005696 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005697 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005698 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005699 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005700 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005701 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5702 if (Info.noteFailure())
5703 EvaluateIgnoredValue(Info, E->getSubExpr());
5704 return Error(E);
5705 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005706 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005707 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005708 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005709 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005710 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005711 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005712 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005713 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005714 }
Richard Smithd62306a2011-11-10 06:34:14 +00005715 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005716 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005717 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005718 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005719 if (!Info.CurrentCall->This) {
5720 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005721 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005722 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005723 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005724 return false;
5725 }
Richard Smithd62306a2011-11-10 06:34:14 +00005726 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005727 // If we are inside a lambda's call operator, the 'this' expression refers
5728 // to the enclosing '*this' object (either by value or reference) which is
5729 // either copied into the closure object's field that represents the '*this'
5730 // or refers to '*this'.
5731 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5732 // Update 'Result' to refer to the data member/field of the closure object
5733 // that represents the '*this' capture.
5734 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005735 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005736 return false;
5737 // If we captured '*this' by reference, replace the field with its referent.
5738 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5739 ->isPointerType()) {
5740 APValue RVal;
5741 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5742 RVal))
5743 return false;
5744
5745 Result.setFrom(Info.Ctx, RVal);
5746 }
5747 }
Richard Smithd62306a2011-11-10 06:34:14 +00005748 return true;
5749 }
John McCallc07a0c72011-02-17 10:25:35 +00005750
Eli Friedman449fe542009-03-23 04:56:01 +00005751 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005752};
Chris Lattner05706e882008-07-11 18:11:29 +00005753} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005754
George Burgess IVf9013bf2017-02-10 22:52:29 +00005755static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5756 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005757 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005758 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005759}
5760
John McCall45d55e42010-05-07 21:00:08 +00005761bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005762 if (E->getOpcode() != BO_Add &&
5763 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005764 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005765
Chris Lattner05706e882008-07-11 18:11:29 +00005766 const Expr *PExp = E->getLHS();
5767 const Expr *IExp = E->getRHS();
5768 if (IExp->getType()->isPointerType())
5769 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005770
George Burgess IVf9013bf2017-02-10 22:52:29 +00005771 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005772 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005773 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005774
John McCall45d55e42010-05-07 21:00:08 +00005775 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005776 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005777 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005778
Richard Smith96e0c102011-11-04 02:25:55 +00005779 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005780 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005781
Ted Kremenek28831752012-08-23 20:46:57 +00005782 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005783 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005784}
Eli Friedman9a156e52008-11-12 09:44:48 +00005785
John McCall45d55e42010-05-07 21:00:08 +00005786bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005787 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005788}
Mike Stump11289f42009-09-09 15:08:12 +00005789
Peter Collingbournee9200682011-05-13 03:29:01 +00005790bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5791 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005792
Eli Friedman847a2bc2009-12-27 05:43:15 +00005793 switch (E->getCastKind()) {
5794 default:
5795 break;
5796
John McCalle3027922010-08-25 11:45:40 +00005797 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005798 case CK_CPointerToObjCPointerCast:
5799 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005800 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005801 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005802 if (!Visit(SubExpr))
5803 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005804 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5805 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5806 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005807 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005808 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005809 if (SubExpr->getType()->isVoidPointerType())
5810 CCEDiag(E, diag::note_constexpr_invalid_cast)
5811 << 3 << SubExpr->getType();
5812 else
5813 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5814 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005815 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5816 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005817 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005818
Anders Carlsson18275092010-10-31 20:41:46 +00005819 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005820 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005821 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005822 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005823 if (!Result.Base && Result.Offset.isZero())
5824 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005825
Richard Smithd62306a2011-11-10 06:34:14 +00005826 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005827 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005828 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5829 castAs<PointerType>()->getPointeeType(),
5830 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005831
Richard Smith027bf112011-11-17 22:56:20 +00005832 case CK_BaseToDerived:
5833 if (!Visit(E->getSubExpr()))
5834 return false;
5835 if (!Result.Base && Result.Offset.isZero())
5836 return true;
5837 return HandleBaseToDerivedCast(Info, E, Result);
5838
Richard Smith0b0a0b62011-10-29 20:57:55 +00005839 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005840 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005841 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005842
John McCalle3027922010-08-25 11:45:40 +00005843 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005844 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5845
Richard Smith2e312c82012-03-03 22:46:17 +00005846 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005847 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005848 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005849
John McCall45d55e42010-05-07 21:00:08 +00005850 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005851 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5852 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005853 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005854 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005855 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00005856 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005857 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005858 return true;
5859 } else {
5860 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005861 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005862 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005863 }
5864 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005865
5866 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005867 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005868 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005869 return false;
5870 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005871 APValue &Value = createTemporary(SubExpr, false, Result,
5872 *Info.CurrentCall);
5873 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005874 return false;
5875 }
Richard Smith96e0c102011-11-04 02:25:55 +00005876 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005877 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5878 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005879 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005880 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005881 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005882 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005883 }
Richard Smithdd785442011-10-31 20:57:44 +00005884
John McCalle3027922010-08-25 11:45:40 +00005885 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005886 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005887
5888 case CK_LValueToRValue: {
5889 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005890 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005891 return false;
5892
5893 APValue RVal;
5894 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5895 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5896 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005897 return InvalidBaseOK &&
5898 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005899 return Success(RVal, E);
5900 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005901 }
5902
Richard Smith11562c52011-10-28 17:51:58 +00005903 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005904}
Chris Lattner05706e882008-07-11 18:11:29 +00005905
Hal Finkel0dd05d42014-10-03 17:18:37 +00005906static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5907 // C++ [expr.alignof]p3:
5908 // When alignof is applied to a reference type, the result is the
5909 // alignment of the referenced type.
5910 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5911 T = Ref->getPointeeType();
5912
5913 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005914 if (T.getQualifiers().hasUnaligned())
5915 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005916 return Info.Ctx.toCharUnitsFromBits(
5917 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5918}
5919
5920static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5921 E = E->IgnoreParens();
5922
5923 // The kinds of expressions that we have special-case logic here for
5924 // should be kept up to date with the special checks for those
5925 // expressions in Sema.
5926
5927 // alignof decl is always accepted, even if it doesn't make sense: we default
5928 // to 1 in those cases.
5929 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5930 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5931 /*RefAsPointee*/true);
5932
5933 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5934 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5935 /*RefAsPointee*/true);
5936
5937 return GetAlignOfType(Info, E->getType());
5938}
5939
George Burgess IVe3763372016-12-22 02:50:20 +00005940// To be clear: this happily visits unsupported builtins. Better name welcomed.
5941bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5942 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5943 return true;
5944
George Burgess IVf9013bf2017-02-10 22:52:29 +00005945 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005946 return false;
5947
5948 Result.setInvalid(E);
5949 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005950 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005951 return true;
5952}
5953
Peter Collingbournee9200682011-05-13 03:29:01 +00005954bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005955 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005956 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005957
Richard Smith6328cbd2016-11-16 00:57:23 +00005958 if (unsigned BuiltinOp = E->getBuiltinCallee())
5959 return VisitBuiltinCallExpr(E, BuiltinOp);
5960
George Burgess IVe3763372016-12-22 02:50:20 +00005961 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005962}
5963
5964bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5965 unsigned BuiltinOp) {
5966 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005967 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005968 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005969 case Builtin::BI__builtin_assume_aligned: {
5970 // We need to be very careful here because: if the pointer does not have the
5971 // asserted alignment, then the behavior is undefined, and undefined
5972 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005973 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005974 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005975
Hal Finkel0dd05d42014-10-03 17:18:37 +00005976 LValue OffsetResult(Result);
5977 APSInt Alignment;
5978 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5979 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005980 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005981
5982 if (E->getNumArgs() > 2) {
5983 APSInt Offset;
5984 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5985 return false;
5986
Richard Smith642a2362017-01-30 23:30:26 +00005987 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005988 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5989 }
5990
5991 // If there is a base object, then it must have the correct alignment.
5992 if (OffsetResult.Base) {
5993 CharUnits BaseAlignment;
5994 if (const ValueDecl *VD =
5995 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5996 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5997 } else {
5998 BaseAlignment =
5999 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
6000 }
6001
6002 if (BaseAlignment < Align) {
6003 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00006004 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00006005 CCEDiag(E->getArg(0),
6006 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00006007 << (unsigned)BaseAlignment.getQuantity()
6008 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006009 return false;
6010 }
6011 }
6012
6013 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006014 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006015 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006016
Richard Smith642a2362017-01-30 23:30:26 +00006017 (OffsetResult.Base
6018 ? CCEDiag(E->getArg(0),
6019 diag::note_constexpr_baa_insufficient_alignment) << 1
6020 : CCEDiag(E->getArg(0),
6021 diag::note_constexpr_baa_value_insufficient_alignment))
6022 << (int)OffsetResult.Offset.getQuantity()
6023 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006024 return false;
6025 }
6026
6027 return true;
6028 }
Richard Smithe9507952016-11-12 01:39:56 +00006029
6030 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006031 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006032 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006033 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006034 if (Info.getLangOpts().CPlusPlus11)
6035 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6036 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006037 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006038 else
6039 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006040 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006041 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006042 case Builtin::BI__builtin_wcschr:
6043 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006044 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006045 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006046 if (!Visit(E->getArg(0)))
6047 return false;
6048 APSInt Desired;
6049 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6050 return false;
6051 uint64_t MaxLength = uint64_t(-1);
6052 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006053 BuiltinOp != Builtin::BIwcschr &&
6054 BuiltinOp != Builtin::BI__builtin_strchr &&
6055 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006056 APSInt N;
6057 if (!EvaluateInteger(E->getArg(2), N, Info))
6058 return false;
6059 MaxLength = N.getExtValue();
6060 }
6061
Richard Smith8110c9d2016-11-29 19:45:17 +00006062 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00006063
Richard Smith8110c9d2016-11-29 19:45:17 +00006064 // Figure out what value we're actually looking for (after converting to
6065 // the corresponding unsigned type if necessary).
6066 uint64_t DesiredVal;
6067 bool StopAtNull = false;
6068 switch (BuiltinOp) {
6069 case Builtin::BIstrchr:
6070 case Builtin::BI__builtin_strchr:
6071 // strchr compares directly to the passed integer, and therefore
6072 // always fails if given an int that is not a char.
6073 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6074 E->getArg(1)->getType(),
6075 Desired),
6076 Desired))
6077 return ZeroInitialization(E);
6078 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006079 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006080 case Builtin::BImemchr:
6081 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006082 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006083 // memchr compares by converting both sides to unsigned char. That's also
6084 // correct for strchr if we get this far (to cope with plain char being
6085 // unsigned in the strchr case).
6086 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6087 break;
Richard Smithe9507952016-11-12 01:39:56 +00006088
Richard Smith8110c9d2016-11-29 19:45:17 +00006089 case Builtin::BIwcschr:
6090 case Builtin::BI__builtin_wcschr:
6091 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006092 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006093 case Builtin::BIwmemchr:
6094 case Builtin::BI__builtin_wmemchr:
6095 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6096 DesiredVal = Desired.getZExtValue();
6097 break;
6098 }
Richard Smithe9507952016-11-12 01:39:56 +00006099
6100 for (; MaxLength; --MaxLength) {
6101 APValue Char;
6102 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6103 !Char.isInt())
6104 return false;
6105 if (Char.getInt().getZExtValue() == DesiredVal)
6106 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006107 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006108 break;
6109 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6110 return false;
6111 }
6112 // Not found: return nullptr.
6113 return ZeroInitialization(E);
6114 }
6115
Richard Smith6cbd65d2013-07-11 02:27:57 +00006116 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006117 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006118 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006119}
Chris Lattner05706e882008-07-11 18:11:29 +00006120
6121//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006122// Member Pointer Evaluation
6123//===----------------------------------------------------------------------===//
6124
6125namespace {
6126class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006127 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006128 MemberPtr &Result;
6129
6130 bool Success(const ValueDecl *D) {
6131 Result = MemberPtr(D);
6132 return true;
6133 }
6134public:
6135
6136 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6137 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6138
Richard Smith2e312c82012-03-03 22:46:17 +00006139 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006140 Result.setFrom(V);
6141 return true;
6142 }
Richard Smithfddd3842011-12-30 21:15:51 +00006143 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006144 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006145 }
6146
6147 bool VisitCastExpr(const CastExpr *E);
6148 bool VisitUnaryAddrOf(const UnaryOperator *E);
6149};
6150} // end anonymous namespace
6151
6152static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6153 EvalInfo &Info) {
6154 assert(E->isRValue() && E->getType()->isMemberPointerType());
6155 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6156}
6157
6158bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6159 switch (E->getCastKind()) {
6160 default:
6161 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6162
6163 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006164 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006165 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006166
6167 case CK_BaseToDerivedMemberPointer: {
6168 if (!Visit(E->getSubExpr()))
6169 return false;
6170 if (E->path_empty())
6171 return true;
6172 // Base-to-derived member pointer casts store the path in derived-to-base
6173 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6174 // the wrong end of the derived->base arc, so stagger the path by one class.
6175 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6176 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6177 PathI != PathE; ++PathI) {
6178 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6179 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6180 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006181 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006182 }
6183 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6184 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006185 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006186 return true;
6187 }
6188
6189 case CK_DerivedToBaseMemberPointer:
6190 if (!Visit(E->getSubExpr()))
6191 return false;
6192 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6193 PathE = E->path_end(); PathI != PathE; ++PathI) {
6194 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6195 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6196 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006197 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006198 }
6199 return true;
6200 }
6201}
6202
6203bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6204 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6205 // member can be formed.
6206 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6207}
6208
6209//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006210// Record Evaluation
6211//===----------------------------------------------------------------------===//
6212
6213namespace {
6214 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006215 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006216 const LValue &This;
6217 APValue &Result;
6218 public:
6219
6220 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6221 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6222
Richard Smith2e312c82012-03-03 22:46:17 +00006223 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006224 Result = V;
6225 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006226 }
Richard Smithb8348f52016-05-12 22:16:28 +00006227 bool ZeroInitialization(const Expr *E) {
6228 return ZeroInitialization(E, E->getType());
6229 }
6230 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006231
Richard Smith52a980a2015-08-28 02:43:42 +00006232 bool VisitCallExpr(const CallExpr *E) {
6233 return handleCallExpr(E, Result, &This);
6234 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006235 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006236 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006237 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6238 return VisitCXXConstructExpr(E, E->getType());
6239 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006240 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006241 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006242 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006243 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006244
6245 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006246 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006247}
Richard Smithd62306a2011-11-10 06:34:14 +00006248
Richard Smithfddd3842011-12-30 21:15:51 +00006249/// Perform zero-initialization on an object of non-union class type.
6250/// C++11 [dcl.init]p5:
6251/// To zero-initialize an object or reference of type T means:
6252/// [...]
6253/// -- if T is a (possibly cv-qualified) non-union class type,
6254/// each non-static data member and each base-class subobject is
6255/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006256static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6257 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006258 const LValue &This, APValue &Result) {
6259 assert(!RD->isUnion() && "Expected non-union class type");
6260 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6261 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006262 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006263
John McCalld7bca762012-05-01 00:38:49 +00006264 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006265 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6266
6267 if (CD) {
6268 unsigned Index = 0;
6269 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006270 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006271 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6272 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006273 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6274 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006275 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006276 Result.getStructBase(Index)))
6277 return false;
6278 }
6279 }
6280
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006281 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006282 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006283 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006284 continue;
6285
6286 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006287 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006288 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006289
David Blaikie2d7c57e2012-04-30 02:36:29 +00006290 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006291 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006292 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006293 return false;
6294 }
6295
6296 return true;
6297}
6298
Richard Smithb8348f52016-05-12 22:16:28 +00006299bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6300 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006301 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006302 if (RD->isUnion()) {
6303 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6304 // object's first non-static named data member is zero-initialized
6305 RecordDecl::field_iterator I = RD->field_begin();
6306 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006307 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006308 return true;
6309 }
6310
6311 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006312 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006313 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006314 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006315 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006316 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006317 }
6318
Richard Smith5d108602012-02-17 00:44:16 +00006319 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006320 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006321 return false;
6322 }
6323
Richard Smitha8105bc2012-01-06 16:39:00 +00006324 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006325}
6326
Richard Smithe97cbd72011-11-11 04:05:33 +00006327bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6328 switch (E->getCastKind()) {
6329 default:
6330 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6331
6332 case CK_ConstructorConversion:
6333 return Visit(E->getSubExpr());
6334
6335 case CK_DerivedToBase:
6336 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006337 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006338 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006339 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006340 if (!DerivedObject.isStruct())
6341 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006342
6343 // Derived-to-base rvalue conversion: just slice off the derived part.
6344 APValue *Value = &DerivedObject;
6345 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6346 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6347 PathE = E->path_end(); PathI != PathE; ++PathI) {
6348 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6349 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6350 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6351 RD = Base;
6352 }
6353 Result = *Value;
6354 return true;
6355 }
6356 }
6357}
6358
Richard Smithd62306a2011-11-10 06:34:14 +00006359bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006360 if (E->isTransparent())
6361 return Visit(E->getInit(0));
6362
Richard Smithd62306a2011-11-10 06:34:14 +00006363 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006364 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006365 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6366
6367 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006368 const FieldDecl *Field = E->getInitializedFieldInUnion();
6369 Result = APValue(Field);
6370 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006371 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006372
6373 // If the initializer list for a union does not contain any elements, the
6374 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006375 // FIXME: The element should be initialized from an initializer list.
6376 // Is this difference ever observable for initializer lists which
6377 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006378 ImplicitValueInitExpr VIE(Field->getType());
6379 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6380
Richard Smithd62306a2011-11-10 06:34:14 +00006381 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006382 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6383 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006384
6385 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6386 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6387 isa<CXXDefaultInitExpr>(InitExpr));
6388
Richard Smithb228a862012-02-15 02:18:13 +00006389 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006390 }
6391
Richard Smith872307e2016-03-08 22:17:41 +00006392 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006393 if (Result.isUninit())
6394 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6395 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006396 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006397 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006398
6399 // Initialize base classes.
6400 if (CXXRD) {
6401 for (const auto &Base : CXXRD->bases()) {
6402 assert(ElementNo < E->getNumInits() && "missing init for base class");
6403 const Expr *Init = E->getInit(ElementNo);
6404
6405 LValue Subobject = This;
6406 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6407 return false;
6408
6409 APValue &FieldVal = Result.getStructBase(ElementNo);
6410 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006411 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006412 return false;
6413 Success = false;
6414 }
6415 ++ElementNo;
6416 }
6417 }
6418
6419 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006420 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006421 // Anonymous bit-fields are not considered members of the class for
6422 // purposes of aggregate initialization.
6423 if (Field->isUnnamedBitfield())
6424 continue;
6425
6426 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006427
Richard Smith253c2a32012-01-27 01:14:48 +00006428 bool HaveInit = ElementNo < E->getNumInits();
6429
6430 // FIXME: Diagnostics here should point to the end of the initializer
6431 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006432 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006433 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006434 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006435
6436 // Perform an implicit value-initialization for members beyond the end of
6437 // the initializer list.
6438 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006439 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006440
Richard Smith852c9db2013-04-20 22:23:05 +00006441 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6442 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6443 isa<CXXDefaultInitExpr>(Init));
6444
Richard Smith49ca8aa2013-08-06 07:09:20 +00006445 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6446 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6447 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006448 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006449 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006450 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006451 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006452 }
6453 }
6454
Richard Smith253c2a32012-01-27 01:14:48 +00006455 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006456}
6457
Richard Smithb8348f52016-05-12 22:16:28 +00006458bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6459 QualType T) {
6460 // Note that E's type is not necessarily the type of our class here; we might
6461 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006462 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006463 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6464
Richard Smithfddd3842011-12-30 21:15:51 +00006465 bool ZeroInit = E->requiresZeroInitialization();
6466 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006467 // If we've already performed zero-initialization, we're already done.
6468 if (!Result.isUninit())
6469 return true;
6470
Richard Smithda3f4fd2014-03-05 23:32:50 +00006471 // We can get here in two different ways:
6472 // 1) We're performing value-initialization, and should zero-initialize
6473 // the object, or
6474 // 2) We're performing default-initialization of an object with a trivial
6475 // constexpr default constructor, in which case we should start the
6476 // lifetimes of all the base subobjects (there can be no data member
6477 // subobjects in this case) per [basic.life]p1.
6478 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006479 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006480 }
6481
Craig Topper36250ad2014-05-12 05:36:57 +00006482 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006483 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006484
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006485 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006486 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006487
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006488 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006489 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006490 if (const MaterializeTemporaryExpr *ME
6491 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6492 return Visit(ME->GetTemporaryExpr());
6493
Richard Smithb8348f52016-05-12 22:16:28 +00006494 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006495 return false;
6496
Craig Topper5fc8fc22014-08-27 06:28:36 +00006497 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006498 return HandleConstructorCall(E, This, Args,
6499 cast<CXXConstructorDecl>(Definition), Info,
6500 Result);
6501}
6502
6503bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6504 const CXXInheritedCtorInitExpr *E) {
6505 if (!Info.CurrentCall) {
6506 assert(Info.checkingPotentialConstantExpression());
6507 return false;
6508 }
6509
6510 const CXXConstructorDecl *FD = E->getConstructor();
6511 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6512 return false;
6513
6514 const FunctionDecl *Definition = nullptr;
6515 auto Body = FD->getBody(Definition);
6516
6517 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6518 return false;
6519
6520 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006521 cast<CXXConstructorDecl>(Definition), Info,
6522 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006523}
6524
Richard Smithcc1b96d2013-06-12 22:31:48 +00006525bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6526 const CXXStdInitializerListExpr *E) {
6527 const ConstantArrayType *ArrayType =
6528 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6529
6530 LValue Array;
6531 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6532 return false;
6533
6534 // Get a pointer to the first element of the array.
6535 Array.addArray(Info, E, ArrayType);
6536
6537 // FIXME: Perform the checks on the field types in SemaInit.
6538 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6539 RecordDecl::field_iterator Field = Record->field_begin();
6540 if (Field == Record->field_end())
6541 return Error(E);
6542
6543 // Start pointer.
6544 if (!Field->getType()->isPointerType() ||
6545 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6546 ArrayType->getElementType()))
6547 return Error(E);
6548
6549 // FIXME: What if the initializer_list type has base classes, etc?
6550 Result = APValue(APValue::UninitStruct(), 0, 2);
6551 Array.moveInto(Result.getStructField(0));
6552
6553 if (++Field == Record->field_end())
6554 return Error(E);
6555
6556 if (Field->getType()->isPointerType() &&
6557 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6558 ArrayType->getElementType())) {
6559 // End pointer.
6560 if (!HandleLValueArrayAdjustment(Info, E, Array,
6561 ArrayType->getElementType(),
6562 ArrayType->getSize().getZExtValue()))
6563 return false;
6564 Array.moveInto(Result.getStructField(1));
6565 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6566 // Length.
6567 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6568 else
6569 return Error(E);
6570
6571 if (++Field != Record->field_end())
6572 return Error(E);
6573
6574 return true;
6575}
6576
Faisal Valic72a08c2017-01-09 03:02:53 +00006577bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6578 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6579 if (ClosureClass->isInvalidDecl()) return false;
6580
6581 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006582
Faisal Vali051e3a22017-02-16 04:12:21 +00006583 const size_t NumFields =
6584 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006585
6586 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6587 E->capture_init_end()) &&
6588 "The number of lambda capture initializers should equal the number of "
6589 "fields within the closure type");
6590
Faisal Vali051e3a22017-02-16 04:12:21 +00006591 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6592 // Iterate through all the lambda's closure object's fields and initialize
6593 // them.
6594 auto *CaptureInitIt = E->capture_init_begin();
6595 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6596 bool Success = true;
6597 for (const auto *Field : ClosureClass->fields()) {
6598 assert(CaptureInitIt != E->capture_init_end());
6599 // Get the initializer for this field
6600 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006601
Faisal Vali051e3a22017-02-16 04:12:21 +00006602 // If there is no initializer, either this is a VLA or an error has
6603 // occurred.
6604 if (!CurFieldInit)
6605 return Error(E);
6606
6607 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6608 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6609 if (!Info.keepEvaluatingAfterFailure())
6610 return false;
6611 Success = false;
6612 }
6613 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006614 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006615 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006616}
6617
Richard Smithd62306a2011-11-10 06:34:14 +00006618static bool EvaluateRecord(const Expr *E, const LValue &This,
6619 APValue &Result, EvalInfo &Info) {
6620 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006621 "can't evaluate expression as a record rvalue");
6622 return RecordExprEvaluator(Info, This, Result).Visit(E);
6623}
6624
6625//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006626// Temporary Evaluation
6627//
6628// Temporaries are represented in the AST as rvalues, but generally behave like
6629// lvalues. The full-object of which the temporary is a subobject is implicitly
6630// materialized so that a reference can bind to it.
6631//===----------------------------------------------------------------------===//
6632namespace {
6633class TemporaryExprEvaluator
6634 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6635public:
6636 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006637 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006638
6639 /// Visit an expression which constructs the value of this temporary.
6640 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006641 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6642 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006643 }
6644
6645 bool VisitCastExpr(const CastExpr *E) {
6646 switch (E->getCastKind()) {
6647 default:
6648 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6649
6650 case CK_ConstructorConversion:
6651 return VisitConstructExpr(E->getSubExpr());
6652 }
6653 }
6654 bool VisitInitListExpr(const InitListExpr *E) {
6655 return VisitConstructExpr(E);
6656 }
6657 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6658 return VisitConstructExpr(E);
6659 }
6660 bool VisitCallExpr(const CallExpr *E) {
6661 return VisitConstructExpr(E);
6662 }
Richard Smith513955c2014-12-17 19:24:30 +00006663 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6664 return VisitConstructExpr(E);
6665 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006666 bool VisitLambdaExpr(const LambdaExpr *E) {
6667 return VisitConstructExpr(E);
6668 }
Richard Smith027bf112011-11-17 22:56:20 +00006669};
6670} // end anonymous namespace
6671
6672/// Evaluate an expression of record type as a temporary.
6673static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006674 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006675 return TemporaryExprEvaluator(Info, Result).Visit(E);
6676}
6677
6678//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006679// Vector Evaluation
6680//===----------------------------------------------------------------------===//
6681
6682namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006683 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006684 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006685 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006686 public:
Mike Stump11289f42009-09-09 15:08:12 +00006687
Richard Smith2d406342011-10-22 21:10:00 +00006688 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6689 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006690
Craig Topper9798b932015-09-29 04:30:05 +00006691 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006692 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6693 // FIXME: remove this APValue copy.
6694 Result = APValue(V.data(), V.size());
6695 return true;
6696 }
Richard Smith2e312c82012-03-03 22:46:17 +00006697 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006698 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006699 Result = V;
6700 return true;
6701 }
Richard Smithfddd3842011-12-30 21:15:51 +00006702 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006703
Richard Smith2d406342011-10-22 21:10:00 +00006704 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006705 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006706 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006707 bool VisitInitListExpr(const InitListExpr *E);
6708 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006709 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006710 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006711 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006712 };
6713} // end anonymous namespace
6714
6715static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006716 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006717 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006718}
6719
George Burgess IV533ff002015-12-11 00:23:35 +00006720bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006721 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006722 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006723
Richard Smith161f09a2011-12-06 22:44:34 +00006724 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006725 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006726
Eli Friedmanc757de22011-03-25 00:43:55 +00006727 switch (E->getCastKind()) {
6728 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006729 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006730 if (SETy->isIntegerType()) {
6731 APSInt IntResult;
6732 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006733 return false;
6734 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006735 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006736 APFloat FloatResult(0.0);
6737 if (!EvaluateFloat(SE, FloatResult, Info))
6738 return false;
6739 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006740 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006741 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006742 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006743
6744 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006745 SmallVector<APValue, 4> Elts(NElts, Val);
6746 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006747 }
Eli Friedman803acb32011-12-22 03:51:45 +00006748 case CK_BitCast: {
6749 // Evaluate the operand into an APInt we can extract from.
6750 llvm::APInt SValInt;
6751 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6752 return false;
6753 // Extract the elements
6754 QualType EltTy = VTy->getElementType();
6755 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6756 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6757 SmallVector<APValue, 4> Elts;
6758 if (EltTy->isRealFloatingType()) {
6759 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006760 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006761 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006762 FloatEltSize = 80;
6763 for (unsigned i = 0; i < NElts; i++) {
6764 llvm::APInt Elt;
6765 if (BigEndian)
6766 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6767 else
6768 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006769 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006770 }
6771 } else if (EltTy->isIntegerType()) {
6772 for (unsigned i = 0; i < NElts; i++) {
6773 llvm::APInt Elt;
6774 if (BigEndian)
6775 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6776 else
6777 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6778 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6779 }
6780 } else {
6781 return Error(E);
6782 }
6783 return Success(Elts, E);
6784 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006785 default:
Richard Smith11562c52011-10-28 17:51:58 +00006786 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006787 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006788}
6789
Richard Smith2d406342011-10-22 21:10:00 +00006790bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006791VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006792 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006793 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006794 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006795
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006796 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006797 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006798
Eli Friedmanb9c71292012-01-03 23:24:20 +00006799 // The number of initializers can be less than the number of
6800 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006801 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006802 // should be initialized with zeroes.
6803 unsigned CountInits = 0, CountElts = 0;
6804 while (CountElts < NumElements) {
6805 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006806 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006807 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006808 APValue v;
6809 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6810 return Error(E);
6811 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006812 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006813 Elements.push_back(v.getVectorElt(j));
6814 CountElts += vlen;
6815 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006816 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006817 if (CountInits < NumInits) {
6818 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006819 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006820 } else // trailing integer zero.
6821 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6822 Elements.push_back(APValue(sInt));
6823 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006824 } else {
6825 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006826 if (CountInits < NumInits) {
6827 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006828 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006829 } else // trailing float zero.
6830 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6831 Elements.push_back(APValue(f));
6832 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006833 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006834 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006835 }
Richard Smith2d406342011-10-22 21:10:00 +00006836 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006837}
6838
Richard Smith2d406342011-10-22 21:10:00 +00006839bool
Richard Smithfddd3842011-12-30 21:15:51 +00006840VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006841 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006842 QualType EltTy = VT->getElementType();
6843 APValue ZeroElement;
6844 if (EltTy->isIntegerType())
6845 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6846 else
6847 ZeroElement =
6848 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6849
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006850 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006851 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006852}
6853
Richard Smith2d406342011-10-22 21:10:00 +00006854bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006855 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006856 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006857}
6858
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006859//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006860// Array Evaluation
6861//===----------------------------------------------------------------------===//
6862
6863namespace {
6864 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006865 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006866 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006867 APValue &Result;
6868 public:
6869
Richard Smithd62306a2011-11-10 06:34:14 +00006870 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6871 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006872
6873 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006874 assert((V.isArray() || V.isLValue()) &&
6875 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006876 Result = V;
6877 return true;
6878 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006879
Richard Smithfddd3842011-12-30 21:15:51 +00006880 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006881 const ConstantArrayType *CAT =
6882 Info.Ctx.getAsConstantArrayType(E->getType());
6883 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006884 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006885
6886 Result = APValue(APValue::UninitArray(), 0,
6887 CAT->getSize().getZExtValue());
6888 if (!Result.hasArrayFiller()) return true;
6889
Richard Smithfddd3842011-12-30 21:15:51 +00006890 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006891 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006892 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006893 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006894 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006895 }
6896
Richard Smith52a980a2015-08-28 02:43:42 +00006897 bool VisitCallExpr(const CallExpr *E) {
6898 return handleCallExpr(E, Result, &This);
6899 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006900 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006901 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006902 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006903 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6904 const LValue &Subobject,
6905 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006906 };
6907} // end anonymous namespace
6908
Richard Smithd62306a2011-11-10 06:34:14 +00006909static bool EvaluateArray(const Expr *E, const LValue &This,
6910 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006911 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006912 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006913}
6914
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006915// Return true iff the given array filler may depend on the element index.
6916static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
6917 // For now, just whitelist non-class value-initialization and initialization
6918 // lists comprised of them.
6919 if (isa<ImplicitValueInitExpr>(FillerExpr))
6920 return false;
6921 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
6922 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
6923 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
6924 return true;
6925 }
6926 return false;
6927 }
6928 return true;
6929}
6930
Richard Smithf3e9e432011-11-07 09:22:26 +00006931bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6932 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6933 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006934 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006935
Richard Smithca2cfbf2011-12-22 01:07:19 +00006936 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6937 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006938 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006939 LValue LV;
6940 if (!EvaluateLValue(E->getInit(0), LV, Info))
6941 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006942 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006943 LV.moveInto(Val);
6944 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006945 }
6946
Richard Smith253c2a32012-01-27 01:14:48 +00006947 bool Success = true;
6948
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006949 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6950 "zero-initialized array shouldn't have any initialized elts");
6951 APValue Filler;
6952 if (Result.isArray() && Result.hasArrayFiller())
6953 Filler = Result.getArrayFiller();
6954
Richard Smith9543c5e2013-04-22 14:44:29 +00006955 unsigned NumEltsToInit = E->getNumInits();
6956 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006957 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006958
6959 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006960 // array element.
6961 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00006962 NumEltsToInit = NumElts;
6963
Nicola Zaghen3538b392018-05-15 13:30:56 +00006964 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
6965 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006966
Richard Smith9543c5e2013-04-22 14:44:29 +00006967 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006968
6969 // If the array was previously zero-initialized, preserve the
6970 // zero-initialized values.
6971 if (!Filler.isUninit()) {
6972 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6973 Result.getArrayInitializedElt(I) = Filler;
6974 if (Result.hasArrayFiller())
6975 Result.getArrayFiller() = Filler;
6976 }
6977
Richard Smithd62306a2011-11-10 06:34:14 +00006978 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006979 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006980 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6981 const Expr *Init =
6982 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006983 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006984 Info, Subobject, Init) ||
6985 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006986 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006987 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006988 return false;
6989 Success = false;
6990 }
Richard Smithd62306a2011-11-10 06:34:14 +00006991 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006992
Richard Smith9543c5e2013-04-22 14:44:29 +00006993 if (!Result.hasArrayFiller())
6994 return Success;
6995
6996 // If we get here, we have a trivial filler, which we can just evaluate
6997 // once and splat over the rest of the array elements.
6998 assert(FillerExpr && "no array filler for incomplete init list");
6999 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7000 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00007001}
7002
Richard Smith410306b2016-12-12 02:53:20 +00007003bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7004 if (E->getCommonExpr() &&
7005 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7006 Info, E->getCommonExpr()->getSourceExpr()))
7007 return false;
7008
7009 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7010
7011 uint64_t Elements = CAT->getSize().getZExtValue();
7012 Result = APValue(APValue::UninitArray(), Elements, Elements);
7013
7014 LValue Subobject = This;
7015 Subobject.addArray(Info, E, CAT);
7016
7017 bool Success = true;
7018 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7019 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7020 Info, Subobject, E->getSubExpr()) ||
7021 !HandleLValueArrayAdjustment(Info, E, Subobject,
7022 CAT->getElementType(), 1)) {
7023 if (!Info.noteFailure())
7024 return false;
7025 Success = false;
7026 }
7027 }
7028
7029 return Success;
7030}
7031
Richard Smith027bf112011-11-17 22:56:20 +00007032bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00007033 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7034}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007035
Richard Smith9543c5e2013-04-22 14:44:29 +00007036bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7037 const LValue &Subobject,
7038 APValue *Value,
7039 QualType Type) {
7040 bool HadZeroInit = !Value->isUninit();
7041
7042 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7043 unsigned N = CAT->getSize().getZExtValue();
7044
7045 // Preserve the array filler if we had prior zero-initialization.
7046 APValue Filler =
7047 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7048 : APValue();
7049
7050 *Value = APValue(APValue::UninitArray(), N, N);
7051
7052 if (HadZeroInit)
7053 for (unsigned I = 0; I != N; ++I)
7054 Value->getArrayInitializedElt(I) = Filler;
7055
7056 // Initialize the elements.
7057 LValue ArrayElt = Subobject;
7058 ArrayElt.addArray(Info, E, CAT);
7059 for (unsigned I = 0; I != N; ++I)
7060 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7061 CAT->getElementType()) ||
7062 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7063 CAT->getElementType(), 1))
7064 return false;
7065
7066 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007067 }
Richard Smith027bf112011-11-17 22:56:20 +00007068
Richard Smith9543c5e2013-04-22 14:44:29 +00007069 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00007070 return Error(E);
7071
Richard Smithb8348f52016-05-12 22:16:28 +00007072 return RecordExprEvaluator(Info, Subobject, *Value)
7073 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00007074}
7075
Richard Smithf3e9e432011-11-07 09:22:26 +00007076//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007077// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007078//
7079// As a GNU extension, we support casting pointers to sufficiently-wide integer
7080// types and back in constant folding. Integer values are thus represented
7081// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00007082//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007083
7084namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007085class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007086 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00007087 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007088public:
Richard Smith2e312c82012-03-03 22:46:17 +00007089 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007090 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007091
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007092 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007093 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007094 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007095 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007096 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007097 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007098 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007099 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007100 return true;
7101 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007102 bool Success(const llvm::APSInt &SI, const Expr *E) {
7103 return Success(SI, E, Result);
7104 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007105
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007106 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00007107 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007108 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007109 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007110 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007111 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007112 Result.getInt().setIsUnsigned(
7113 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007114 return true;
7115 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007116 bool Success(const llvm::APInt &I, const Expr *E) {
7117 return Success(I, E, Result);
7118 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007119
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007120 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007121 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007122 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007123 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007124 return true;
7125 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007126 bool Success(uint64_t Value, const Expr *E) {
7127 return Success(Value, E, Result);
7128 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007129
Ken Dyckdbc01912011-03-11 02:13:43 +00007130 bool Success(CharUnits Size, const Expr *E) {
7131 return Success(Size.getQuantity(), E);
7132 }
7133
Richard Smith2e312c82012-03-03 22:46:17 +00007134 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007135 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007136 Result = V;
7137 return true;
7138 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007139 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007140 }
Mike Stump11289f42009-09-09 15:08:12 +00007141
Richard Smithfddd3842011-12-30 21:15:51 +00007142 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007143
Peter Collingbournee9200682011-05-13 03:29:01 +00007144 //===--------------------------------------------------------------------===//
7145 // Visitor Methods
7146 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007147
Chris Lattner7174bf32008-07-12 00:38:25 +00007148 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007149 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007150 }
7151 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007152 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007153 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007154
7155 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7156 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007157 if (CheckReferencedDecl(E, E->getDecl()))
7158 return true;
7159
7160 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007161 }
7162 bool VisitMemberExpr(const MemberExpr *E) {
7163 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007164 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007165 return true;
7166 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007167
7168 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007169 }
7170
Peter Collingbournee9200682011-05-13 03:29:01 +00007171 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007172 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007173 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007174 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007175 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007176
Peter Collingbournee9200682011-05-13 03:29:01 +00007177 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007178 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007179
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007180 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007181 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007182 }
Mike Stump11289f42009-09-09 15:08:12 +00007183
Ted Kremeneke65b0862012-03-06 20:05:56 +00007184 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7185 return Success(E->getValue(), E);
7186 }
Richard Smith410306b2016-12-12 02:53:20 +00007187
7188 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7189 if (Info.ArrayInitIndex == uint64_t(-1)) {
7190 // We were asked to evaluate this subexpression independent of the
7191 // enclosing ArrayInitLoopExpr. We can't do that.
7192 Info.FFDiag(E);
7193 return false;
7194 }
7195 return Success(Info.ArrayInitIndex, E);
7196 }
Daniel Jasperffdee092017-05-02 19:21:42 +00007197
Richard Smith4ce706a2011-10-11 21:43:33 +00007198 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007199 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007200 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007201 }
7202
Douglas Gregor29c42f22012-02-24 07:38:34 +00007203 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7204 return Success(E->getValue(), E);
7205 }
7206
John Wiegley6242b6a2011-04-28 00:16:57 +00007207 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7208 return Success(E->getValue(), E);
7209 }
7210
John Wiegleyf9f65842011-04-25 06:54:41 +00007211 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7212 return Success(E->getValue(), E);
7213 }
7214
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007215 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007216 bool VisitUnaryImag(const UnaryOperator *E);
7217
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007218 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007219 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007220
Eli Friedman4e7a2412009-02-27 04:45:43 +00007221 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007222};
Chris Lattner05706e882008-07-11 18:11:29 +00007223} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007224
Richard Smith11562c52011-10-28 17:51:58 +00007225/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7226/// produce either the integer value or a pointer.
7227///
7228/// GCC has a heinous extension which folds casts between pointer types and
7229/// pointer-sized integral types. We support this by allowing the evaluation of
7230/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7231/// Some simple arithmetic on such values is supported (they are treated much
7232/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007233static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007234 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007235 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007236 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007237}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007238
Richard Smithf57d8cb2011-12-09 22:58:01 +00007239static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007240 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007241 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007242 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007243 if (!Val.isInt()) {
7244 // FIXME: It would be better to produce the diagnostic for casting
7245 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007246 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007247 return false;
7248 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007249 Result = Val.getInt();
7250 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007251}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007252
Richard Smithf57d8cb2011-12-09 22:58:01 +00007253/// Check whether the given declaration can be directly converted to an integral
7254/// rvalue. If not, no diagnostic is produced; there are other things we can
7255/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007256bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007257 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007258 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007259 // Check for signedness/width mismatches between E type and ECD value.
7260 bool SameSign = (ECD->getInitVal().isSigned()
7261 == E->getType()->isSignedIntegerOrEnumerationType());
7262 bool SameWidth = (ECD->getInitVal().getBitWidth()
7263 == Info.Ctx.getIntWidth(E->getType()));
7264 if (SameSign && SameWidth)
7265 return Success(ECD->getInitVal(), E);
7266 else {
7267 // Get rid of mismatch (otherwise Success assertions will fail)
7268 // by computing a new value matching the type of E.
7269 llvm::APSInt Val = ECD->getInitVal();
7270 if (!SameSign)
7271 Val.setIsSigned(!ECD->getInitVal().isSigned());
7272 if (!SameWidth)
7273 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7274 return Success(Val, E);
7275 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007276 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007277 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007278}
7279
Richard Smith08b682b2018-05-23 21:18:00 +00007280/// Values returned by __builtin_classify_type, chosen to match the values
7281/// produced by GCC's builtin.
7282enum class GCCTypeClass {
7283 None = -1,
7284 Void = 0,
7285 Integer = 1,
7286 // GCC reserves 2 for character types, but instead classifies them as
7287 // integers.
7288 Enum = 3,
7289 Bool = 4,
7290 Pointer = 5,
7291 // GCC reserves 6 for references, but appears to never use it (because
7292 // expressions never have reference type, presumably).
7293 PointerToDataMember = 7,
7294 RealFloat = 8,
7295 Complex = 9,
7296 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7297 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7298 // GCC claims to reserve 11 for pointers to member functions, but *actually*
7299 // uses 12 for that purpose, same as for a class or struct. Maybe it
7300 // internally implements a pointer to member as a struct? Who knows.
7301 PointerToMemberFunction = 12, // Not a bug, see above.
7302 ClassOrStruct = 12,
7303 Union = 13,
7304 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7305 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7306 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7307 // literals.
7308};
7309
Chris Lattner86ee2862008-10-06 06:40:35 +00007310/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7311/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00007312static GCCTypeClass
7313EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7314 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00007315
Richard Smith08b682b2018-05-23 21:18:00 +00007316 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007317 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7318
7319 switch (CanTy->getTypeClass()) {
7320#define TYPE(ID, BASE)
7321#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7322#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7323#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7324#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00007325 case Type::Auto:
7326 case Type::DeducedTemplateSpecialization:
7327 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007328
7329 case Type::Builtin:
7330 switch (BT->getKind()) {
7331#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00007332#define SIGNED_TYPE(ID, SINGLETON_ID) \
7333 case BuiltinType::ID: return GCCTypeClass::Integer;
7334#define FLOATING_TYPE(ID, SINGLETON_ID) \
7335 case BuiltinType::ID: return GCCTypeClass::RealFloat;
7336#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7337 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007338#include "clang/AST/BuiltinTypes.def"
7339 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00007340 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007341
7342 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00007343 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007344
Richard Smith08b682b2018-05-23 21:18:00 +00007345 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007346 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00007347 case BuiltinType::WChar_U:
7348 case BuiltinType::Char8:
7349 case BuiltinType::Char16:
7350 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007351 case BuiltinType::UShort:
7352 case BuiltinType::UInt:
7353 case BuiltinType::ULong:
7354 case BuiltinType::ULongLong:
7355 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00007356 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007357
Leonard Chanf921d852018-06-04 16:07:52 +00007358 case BuiltinType::UShortAccum:
7359 case BuiltinType::UAccum:
7360 case BuiltinType::ULongAccum:
7361 return GCCTypeClass::None;
7362
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007363 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007364
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007365 case BuiltinType::ObjCId:
7366 case BuiltinType::ObjCClass:
7367 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007368#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7369 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007370#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007371 case BuiltinType::OCLSampler:
7372 case BuiltinType::OCLEvent:
7373 case BuiltinType::OCLClkEvent:
7374 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007375 case BuiltinType::OCLReserveID:
Richard Smith08b682b2018-05-23 21:18:00 +00007376 return GCCTypeClass::None;
7377
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007378 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00007379 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007380 };
Richard Smith08b682b2018-05-23 21:18:00 +00007381 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007382
7383 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00007384 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007385
7386 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007387 case Type::ConstantArray:
7388 case Type::VariableArray:
7389 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00007390 case Type::FunctionNoProto:
7391 case Type::FunctionProto:
7392 return GCCTypeClass::Pointer;
7393
7394 case Type::MemberPointer:
7395 return CanTy->isMemberDataPointerType()
7396 ? GCCTypeClass::PointerToDataMember
7397 : GCCTypeClass::PointerToMemberFunction;
7398
7399 case Type::Complex:
7400 return GCCTypeClass::Complex;
7401
7402 case Type::Record:
7403 return CanTy->isUnionType() ? GCCTypeClass::Union
7404 : GCCTypeClass::ClassOrStruct;
7405
7406 case Type::Atomic:
7407 // GCC classifies _Atomic T the same as T.
7408 return EvaluateBuiltinClassifyType(
7409 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007410
7411 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007412 case Type::Vector:
7413 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007414 case Type::ObjCObject:
7415 case Type::ObjCInterface:
7416 case Type::ObjCObjectPointer:
7417 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00007418 // GCC classifies vectors as None. We follow its lead and classify all
7419 // other types that don't fit into the regular classification the same way.
7420 return GCCTypeClass::None;
7421
7422 case Type::LValueReference:
7423 case Type::RValueReference:
7424 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007425 }
7426
Richard Smith08b682b2018-05-23 21:18:00 +00007427 llvm_unreachable("unexpected type class");
7428}
7429
7430/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7431/// as GCC.
7432static GCCTypeClass
7433EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7434 // If no argument was supplied, default to None. This isn't
7435 // ideal, however it is what gcc does.
7436 if (E->getNumArgs() == 0)
7437 return GCCTypeClass::None;
7438
7439 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7440 // being an ICE, but still folds it to a constant using the type of the first
7441 // argument.
7442 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00007443}
7444
Richard Smith5fab0c92011-12-28 19:48:30 +00007445/// EvaluateBuiltinConstantPForLValue - Determine the result of
7446/// __builtin_constant_p when applied to the given lvalue.
7447///
7448/// An lvalue is only "constant" if it is a pointer or reference to the first
7449/// character of a string literal.
7450template<typename LValue>
7451static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007452 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007453 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7454}
7455
7456/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7457/// GCC as we can manage.
7458static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7459 QualType ArgType = Arg->getType();
7460
7461 // __builtin_constant_p always has one operand. The rules which gcc follows
7462 // are not precisely documented, but are as follows:
7463 //
7464 // - If the operand is of integral, floating, complex or enumeration type,
7465 // and can be folded to a known value of that type, it returns 1.
7466 // - If the operand and can be folded to a pointer to the first character
7467 // of a string literal (or such a pointer cast to an integral type), it
7468 // returns 1.
7469 //
7470 // Otherwise, it returns 0.
7471 //
7472 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7473 // its support for this does not currently work.
7474 if (ArgType->isIntegralOrEnumerationType()) {
7475 Expr::EvalResult Result;
7476 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7477 return false;
7478
7479 APValue &V = Result.Val;
7480 if (V.getKind() == APValue::Int)
7481 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007482 if (V.getKind() == APValue::LValue)
7483 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007484 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7485 return Arg->isEvaluatable(Ctx);
7486 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7487 LValue LV;
7488 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007489 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007490 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7491 : EvaluatePointer(Arg, LV, Info)) &&
7492 !Status.HasSideEffects)
7493 return EvaluateBuiltinConstantPForLValue(LV);
7494 }
7495
7496 // Anything else isn't considered to be sufficiently constant.
7497 return false;
7498}
7499
John McCall95007602010-05-10 23:27:23 +00007500/// Retrieves the "underlying object type" of the given expression,
7501/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007502static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007503 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7504 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007505 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007506 } else if (const Expr *E = B.get<const Expr*>()) {
7507 if (isa<CompoundLiteralExpr>(E))
7508 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007509 }
7510
7511 return QualType();
7512}
7513
George Burgess IV3a03fab2015-09-04 21:28:13 +00007514/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007515/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007516/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007517/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7518///
7519/// Always returns an RValue with a pointer representation.
7520static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7521 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7522
7523 auto *NoParens = E->IgnoreParens();
7524 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007525 if (Cast == nullptr)
7526 return NoParens;
7527
7528 // We only conservatively allow a few kinds of casts, because this code is
7529 // inherently a simple solution that seeks to support the common case.
7530 auto CastKind = Cast->getCastKind();
7531 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7532 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007533 return NoParens;
7534
7535 auto *SubExpr = Cast->getSubExpr();
7536 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7537 return NoParens;
7538 return ignorePointerCastsAndParens(SubExpr);
7539}
7540
George Burgess IVa51c4072015-10-16 01:49:01 +00007541/// Checks to see if the given LValue's Designator is at the end of the LValue's
7542/// record layout. e.g.
7543/// struct { struct { int a, b; } fst, snd; } obj;
7544/// obj.fst // no
7545/// obj.snd // yes
7546/// obj.fst.a // no
7547/// obj.fst.b // no
7548/// obj.snd.a // no
7549/// obj.snd.b // yes
7550///
7551/// Please note: this function is specialized for how __builtin_object_size
7552/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007553///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007554/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7555/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007556static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7557 assert(!LVal.Designator.Invalid);
7558
George Burgess IV4168d752016-06-27 19:40:41 +00007559 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7560 const RecordDecl *Parent = FD->getParent();
7561 Invalid = Parent->isInvalidDecl();
7562 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007563 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007564 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007565 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7566 };
7567
7568 auto &Base = LVal.getLValueBase();
7569 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7570 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007571 bool Invalid;
7572 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7573 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007574 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007575 for (auto *FD : IFD->chain()) {
7576 bool Invalid;
7577 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7578 return Invalid;
7579 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007580 }
7581 }
7582
George Burgess IVe3763372016-12-22 02:50:20 +00007583 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007584 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007585 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007586 // If we don't know the array bound, conservatively assume we're looking at
7587 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007588 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007589 if (BaseType->isIncompleteArrayType())
7590 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7591 else
7592 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007593 }
7594
7595 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7596 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007597 if (BaseType->isArrayType()) {
7598 // Because __builtin_object_size treats arrays as objects, we can ignore
7599 // the index iff this is the last array in the Designator.
7600 if (I + 1 == E)
7601 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007602 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7603 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007604 if (Index + 1 != CAT->getSize())
7605 return false;
7606 BaseType = CAT->getElementType();
7607 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007608 const auto *CT = BaseType->castAs<ComplexType>();
7609 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007610 if (Index != 1)
7611 return false;
7612 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007613 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007614 bool Invalid;
7615 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7616 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007617 BaseType = FD->getType();
7618 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007619 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007620 return false;
7621 }
7622 }
7623 return true;
7624}
7625
George Burgess IVe3763372016-12-22 02:50:20 +00007626/// Tests to see if the LValue has a user-specified designator (that isn't
7627/// necessarily valid). Note that this always returns 'true' if the LValue has
7628/// an unsized array as its first designator entry, because there's currently no
7629/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007630static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007631 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007632 return false;
7633
George Burgess IVe3763372016-12-22 02:50:20 +00007634 if (!LVal.Designator.Entries.empty())
7635 return LVal.Designator.isMostDerivedAnUnsizedArray();
7636
George Burgess IVa51c4072015-10-16 01:49:01 +00007637 if (!LVal.InvalidBase)
7638 return true;
7639
George Burgess IVe3763372016-12-22 02:50:20 +00007640 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7641 // the LValueBase.
7642 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7643 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007644}
7645
George Burgess IVe3763372016-12-22 02:50:20 +00007646/// Attempts to detect a user writing into a piece of memory that's impossible
7647/// to figure out the size of by just using types.
7648static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7649 const SubobjectDesignator &Designator = LVal.Designator;
7650 // Notes:
7651 // - Users can only write off of the end when we have an invalid base. Invalid
7652 // bases imply we don't know where the memory came from.
7653 // - We used to be a bit more aggressive here; we'd only be conservative if
7654 // the array at the end was flexible, or if it had 0 or 1 elements. This
7655 // broke some common standard library extensions (PR30346), but was
7656 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7657 // with some sort of whitelist. OTOH, it seems that GCC is always
7658 // conservative with the last element in structs (if it's an array), so our
7659 // current behavior is more compatible than a whitelisting approach would
7660 // be.
7661 return LVal.InvalidBase &&
7662 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7663 Designator.MostDerivedIsArrayElement &&
7664 isDesignatorAtObjectEnd(Ctx, LVal);
7665}
7666
7667/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7668/// Fails if the conversion would cause loss of precision.
7669static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7670 CharUnits &Result) {
7671 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7672 if (Int.ugt(CharUnitsMax))
7673 return false;
7674 Result = CharUnits::fromQuantity(Int.getZExtValue());
7675 return true;
7676}
7677
7678/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7679/// determine how many bytes exist from the beginning of the object to either
7680/// the end of the current subobject, or the end of the object itself, depending
7681/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007682///
George Burgess IVe3763372016-12-22 02:50:20 +00007683/// If this returns false, the value of Result is undefined.
7684static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7685 unsigned Type, const LValue &LVal,
7686 CharUnits &EndOffset) {
7687 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007688
George Burgess IV7fb7e362017-01-03 23:35:19 +00007689 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7690 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7691 return false;
7692 return HandleSizeof(Info, ExprLoc, Ty, Result);
7693 };
7694
George Burgess IVe3763372016-12-22 02:50:20 +00007695 // We want to evaluate the size of the entire object. This is a valid fallback
7696 // for when Type=1 and the designator is invalid, because we're asked for an
7697 // upper-bound.
7698 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7699 // Type=3 wants a lower bound, so we can't fall back to this.
7700 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007701 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007702
7703 llvm::APInt APEndOffset;
7704 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7705 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7706 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7707
7708 if (LVal.InvalidBase)
7709 return false;
7710
7711 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007712 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007713 }
7714
George Burgess IVe3763372016-12-22 02:50:20 +00007715 // We want to evaluate the size of a subobject.
7716 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007717
7718 // The following is a moderately common idiom in C:
7719 //
7720 // struct Foo { int a; char c[1]; };
7721 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7722 // strcpy(&F->c[0], Bar);
7723 //
George Burgess IVe3763372016-12-22 02:50:20 +00007724 // In order to not break too much legacy code, we need to support it.
7725 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7726 // If we can resolve this to an alloc_size call, we can hand that back,
7727 // because we know for certain how many bytes there are to write to.
7728 llvm::APInt APEndOffset;
7729 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7730 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7731 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7732
7733 // If we cannot determine the size of the initial allocation, then we can't
7734 // given an accurate upper-bound. However, we are still able to give
7735 // conservative lower-bounds for Type=3.
7736 if (Type == 1)
7737 return false;
7738 }
7739
7740 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007741 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007742 return false;
7743
George Burgess IVe3763372016-12-22 02:50:20 +00007744 // According to the GCC documentation, we want the size of the subobject
7745 // denoted by the pointer. But that's not quite right -- what we actually
7746 // want is the size of the immediately-enclosing array, if there is one.
7747 int64_t ElemsRemaining;
7748 if (Designator.MostDerivedIsArrayElement &&
7749 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7750 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7751 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7752 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7753 } else {
7754 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7755 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007756
George Burgess IVe3763372016-12-22 02:50:20 +00007757 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7758 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007759}
7760
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007761/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00007762/// returns true and stores the result in @p Size.
7763///
7764/// If @p WasError is non-null, this will report whether the failure to evaluate
7765/// is to be treated as an Error in IntExprEvaluator.
7766static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7767 EvalInfo &Info, uint64_t &Size) {
7768 // Determine the denoted object.
7769 LValue LVal;
7770 {
7771 // The operand of __builtin_object_size is never evaluated for side-effects.
7772 // If there are any, but we can determine the pointed-to object anyway, then
7773 // ignore the side-effects.
7774 SpeculativeEvaluationRAII SpeculativeEval(Info);
7775 FoldOffsetRAII Fold(Info);
7776
7777 if (E->isGLValue()) {
7778 // It's possible for us to be given GLValues if we're called via
7779 // Expr::tryEvaluateObjectSize.
7780 APValue RVal;
7781 if (!EvaluateAsRValue(Info, E, RVal))
7782 return false;
7783 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007784 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7785 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007786 return false;
7787 }
7788
7789 // If we point to before the start of the object, there are no accessible
7790 // bytes.
7791 if (LVal.getLValueOffset().isNegative()) {
7792 Size = 0;
7793 return true;
7794 }
7795
7796 CharUnits EndOffset;
7797 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7798 return false;
7799
7800 // If we've fallen outside of the end offset, just pretend there's nothing to
7801 // write to/read from.
7802 if (EndOffset <= LVal.getLValueOffset())
7803 Size = 0;
7804 else
7805 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7806 return true;
John McCall95007602010-05-10 23:27:23 +00007807}
7808
Peter Collingbournee9200682011-05-13 03:29:01 +00007809bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007810 if (unsigned BuiltinOp = E->getBuiltinCallee())
7811 return VisitBuiltinCallExpr(E, BuiltinOp);
7812
7813 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7814}
7815
7816bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7817 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007818 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007819 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007820 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007821
7822 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007823 // The type was checked when we built the expression.
7824 unsigned Type =
7825 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7826 assert(Type <= 3 && "unexpected type");
7827
George Burgess IVe3763372016-12-22 02:50:20 +00007828 uint64_t Size;
7829 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7830 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007831
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007832 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007833 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007834
Richard Smith01ade172012-05-23 04:13:20 +00007835 // Expression had no side effects, but we couldn't statically determine the
7836 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007837 switch (Info.EvalMode) {
7838 case EvalInfo::EM_ConstantExpression:
7839 case EvalInfo::EM_PotentialConstantExpression:
7840 case EvalInfo::EM_ConstantFold:
7841 case EvalInfo::EM_EvaluateForOverflow:
7842 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007843 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007844 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007845 return Error(E);
7846 case EvalInfo::EM_ConstantExpressionUnevaluated:
7847 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007848 // Reduce it to a constant now.
7849 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007850 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007851
7852 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007853 }
7854
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007855 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007856 case Builtin::BI__builtin_bswap32:
7857 case Builtin::BI__builtin_bswap64: {
7858 APSInt Val;
7859 if (!EvaluateInteger(E->getArg(0), Val, Info))
7860 return false;
7861
7862 return Success(Val.byteSwap(), E);
7863 }
7864
Richard Smith8889a3d2013-06-13 06:26:32 +00007865 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00007866 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007867
7868 // FIXME: BI__builtin_clrsb
7869 // FIXME: BI__builtin_clrsbl
7870 // FIXME: BI__builtin_clrsbll
7871
Richard Smith80b3c8e2013-06-13 05:04:16 +00007872 case Builtin::BI__builtin_clz:
7873 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007874 case Builtin::BI__builtin_clzll:
7875 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007876 APSInt Val;
7877 if (!EvaluateInteger(E->getArg(0), Val, Info))
7878 return false;
7879 if (!Val)
7880 return Error(E);
7881
7882 return Success(Val.countLeadingZeros(), E);
7883 }
7884
Richard Smith8889a3d2013-06-13 06:26:32 +00007885 case Builtin::BI__builtin_constant_p:
7886 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7887
Richard Smith80b3c8e2013-06-13 05:04:16 +00007888 case Builtin::BI__builtin_ctz:
7889 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007890 case Builtin::BI__builtin_ctzll:
7891 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007892 APSInt Val;
7893 if (!EvaluateInteger(E->getArg(0), Val, Info))
7894 return false;
7895 if (!Val)
7896 return Error(E);
7897
7898 return Success(Val.countTrailingZeros(), E);
7899 }
7900
Richard Smith8889a3d2013-06-13 06:26:32 +00007901 case Builtin::BI__builtin_eh_return_data_regno: {
7902 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7903 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7904 return Success(Operand, E);
7905 }
7906
7907 case Builtin::BI__builtin_expect:
7908 return Visit(E->getArg(0));
7909
7910 case Builtin::BI__builtin_ffs:
7911 case Builtin::BI__builtin_ffsl:
7912 case Builtin::BI__builtin_ffsll: {
7913 APSInt Val;
7914 if (!EvaluateInteger(E->getArg(0), Val, Info))
7915 return false;
7916
7917 unsigned N = Val.countTrailingZeros();
7918 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7919 }
7920
7921 case Builtin::BI__builtin_fpclassify: {
7922 APFloat Val(0.0);
7923 if (!EvaluateFloat(E->getArg(5), Val, Info))
7924 return false;
7925 unsigned Arg;
7926 switch (Val.getCategory()) {
7927 case APFloat::fcNaN: Arg = 0; break;
7928 case APFloat::fcInfinity: Arg = 1; break;
7929 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7930 case APFloat::fcZero: Arg = 4; break;
7931 }
7932 return Visit(E->getArg(Arg));
7933 }
7934
7935 case Builtin::BI__builtin_isinf_sign: {
7936 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007937 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007938 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7939 }
7940
Richard Smithea3019d2013-10-15 19:07:14 +00007941 case Builtin::BI__builtin_isinf: {
7942 APFloat Val(0.0);
7943 return EvaluateFloat(E->getArg(0), Val, Info) &&
7944 Success(Val.isInfinity() ? 1 : 0, E);
7945 }
7946
7947 case Builtin::BI__builtin_isfinite: {
7948 APFloat Val(0.0);
7949 return EvaluateFloat(E->getArg(0), Val, Info) &&
7950 Success(Val.isFinite() ? 1 : 0, E);
7951 }
7952
7953 case Builtin::BI__builtin_isnan: {
7954 APFloat Val(0.0);
7955 return EvaluateFloat(E->getArg(0), Val, Info) &&
7956 Success(Val.isNaN() ? 1 : 0, E);
7957 }
7958
7959 case Builtin::BI__builtin_isnormal: {
7960 APFloat Val(0.0);
7961 return EvaluateFloat(E->getArg(0), Val, Info) &&
7962 Success(Val.isNormal() ? 1 : 0, E);
7963 }
7964
Richard Smith8889a3d2013-06-13 06:26:32 +00007965 case Builtin::BI__builtin_parity:
7966 case Builtin::BI__builtin_parityl:
7967 case Builtin::BI__builtin_parityll: {
7968 APSInt Val;
7969 if (!EvaluateInteger(E->getArg(0), Val, Info))
7970 return false;
7971
7972 return Success(Val.countPopulation() % 2, E);
7973 }
7974
Richard Smith80b3c8e2013-06-13 05:04:16 +00007975 case Builtin::BI__builtin_popcount:
7976 case Builtin::BI__builtin_popcountl:
7977 case Builtin::BI__builtin_popcountll: {
7978 APSInt Val;
7979 if (!EvaluateInteger(E->getArg(0), Val, Info))
7980 return false;
7981
7982 return Success(Val.countPopulation(), E);
7983 }
7984
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007985 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007986 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007987 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007988 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007989 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007990 << /*isConstexpr*/0 << /*isConstructor*/0
7991 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007992 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007993 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007994 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007995 case Builtin::BI__builtin_strlen:
7996 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007997 // As an extension, we support __builtin_strlen() as a constant expression,
7998 // and support folding strlen() to a constant.
7999 LValue String;
8000 if (!EvaluatePointer(E->getArg(0), String, Info))
8001 return false;
8002
Richard Smith8110c9d2016-11-29 19:45:17 +00008003 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8004
Richard Smithe6c19f22013-11-15 02:10:04 +00008005 // Fast path: if it's a string literal, search the string value.
8006 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8007 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008008 // The string literal may have embedded null characters. Find the first
8009 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00008010 StringRef Str = S->getBytes();
8011 int64_t Off = String.Offset.getQuantity();
8012 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008013 S->getCharByteWidth() == 1 &&
8014 // FIXME: Add fast-path for wchar_t too.
8015 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00008016 Str = Str.substr(Off);
8017
8018 StringRef::size_type Pos = Str.find(0);
8019 if (Pos != StringRef::npos)
8020 Str = Str.substr(0, Pos);
8021
8022 return Success(Str.size(), E);
8023 }
8024
8025 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008026 }
Richard Smithe6c19f22013-11-15 02:10:04 +00008027
8028 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00008029 for (uint64_t Strlen = 0; /**/; ++Strlen) {
8030 APValue Char;
8031 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8032 !Char.isInt())
8033 return false;
8034 if (!Char.getInt())
8035 return Success(Strlen, E);
8036 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8037 return false;
8038 }
8039 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008040
Richard Smithe151bab2016-11-11 23:43:35 +00008041 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008042 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008043 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008044 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008045 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008046 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008047 // A call to strlen is not a constant expression.
8048 if (Info.getLangOpts().CPlusPlus11)
8049 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8050 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008051 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00008052 else
8053 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008054 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00008055 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008056 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008057 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008058 case Builtin::BI__builtin_wcsncmp:
8059 case Builtin::BI__builtin_memcmp:
8060 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00008061 LValue String1, String2;
8062 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8063 !EvaluatePointer(E->getArg(1), String2, Info))
8064 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008065
8066 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8067
Richard Smithe151bab2016-11-11 23:43:35 +00008068 uint64_t MaxLength = uint64_t(-1);
8069 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008070 BuiltinOp != Builtin::BIwcscmp &&
8071 BuiltinOp != Builtin::BI__builtin_strcmp &&
8072 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00008073 APSInt N;
8074 if (!EvaluateInteger(E->getArg(2), N, Info))
8075 return false;
8076 MaxLength = N.getExtValue();
8077 }
8078 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008079 BuiltinOp != Builtin::BIwmemcmp &&
8080 BuiltinOp != Builtin::BI__builtin_memcmp &&
8081 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00008082 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8083 BuiltinOp == Builtin::BIwcsncmp ||
8084 BuiltinOp == Builtin::BIwmemcmp ||
8085 BuiltinOp == Builtin::BI__builtin_wcscmp ||
8086 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8087 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Richard Smithe151bab2016-11-11 23:43:35 +00008088 for (; MaxLength; --MaxLength) {
8089 APValue Char1, Char2;
8090 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
8091 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
8092 !Char1.isInt() || !Char2.isInt())
8093 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00008094 if (Char1.getInt() != Char2.getInt()) {
8095 if (IsWide) // wmemcmp compares with wchar_t signedness.
8096 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8097 // memcmp always compares unsigned chars.
8098 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8099 }
Richard Smithe151bab2016-11-11 23:43:35 +00008100 if (StopAtNull && !Char1.getInt())
8101 return Success(0, E);
8102 assert(!(StopAtNull && !Char2.getInt()));
8103 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
8104 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
8105 return false;
8106 }
8107 // We hit the strncmp / memcmp limit.
8108 return Success(0, E);
8109 }
8110
Richard Smith01ba47d2012-04-13 00:45:38 +00008111 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00008112 case Builtin::BI__atomic_is_lock_free:
8113 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00008114 APSInt SizeVal;
8115 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8116 return false;
8117
8118 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8119 // of two less than the maximum inline atomic width, we know it is
8120 // lock-free. If the size isn't a power of two, or greater than the
8121 // maximum alignment where we promote atomics, we know it is not lock-free
8122 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8123 // the answer can only be determined at runtime; for example, 16-byte
8124 // atomics have lock-free implementations on some, but not all,
8125 // x86-64 processors.
8126
8127 // Check power-of-two.
8128 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00008129 if (Size.isPowerOfTwo()) {
8130 // Check against inlining width.
8131 unsigned InlineWidthBits =
8132 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8133 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8134 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8135 Size == CharUnits::One() ||
8136 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8137 Expr::NPC_NeverValueDependent))
8138 // OK, we will inline appropriately-aligned operations of this size,
8139 // and _Atomic(T) is appropriately-aligned.
8140 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008141
Richard Smith01ba47d2012-04-13 00:45:38 +00008142 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8143 castAs<PointerType>()->getPointeeType();
8144 if (!PointeeType->isIncompleteType() &&
8145 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8146 // OK, we will inline operations on this object.
8147 return Success(1, E);
8148 }
8149 }
8150 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008151
Richard Smith01ba47d2012-04-13 00:45:38 +00008152 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8153 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008154 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008155 case Builtin::BIomp_is_initial_device:
8156 // We can decide statically which value the runtime would return if called.
8157 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008158 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008159}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008160
Richard Smith8b3497e2011-10-31 01:37:14 +00008161static bool HasSameBase(const LValue &A, const LValue &B) {
8162 if (!A.getLValueBase())
8163 return !B.getLValueBase();
8164 if (!B.getLValueBase())
8165 return false;
8166
Richard Smithce40ad62011-11-12 22:28:03 +00008167 if (A.getLValueBase().getOpaqueValue() !=
8168 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008169 const Decl *ADecl = GetLValueBaseDecl(A);
8170 if (!ADecl)
8171 return false;
8172 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00008173 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00008174 return false;
8175 }
8176
8177 return IsGlobalLValue(A.getLValueBase()) ||
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00008178 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
8179 A.getLValueVersion() == B.getLValueVersion());
Richard Smith8b3497e2011-10-31 01:37:14 +00008180}
8181
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008182/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00008183/// object referred to by the lvalue.
8184static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8185 const LValue &LV) {
8186 // A null pointer can be viewed as being "past the end" but we don't
8187 // choose to look at it that way here.
8188 if (!LV.getLValueBase())
8189 return false;
8190
8191 // If the designator is valid and refers to a subobject, we're not pointing
8192 // past the end.
8193 if (!LV.getLValueDesignator().Invalid &&
8194 !LV.getLValueDesignator().isOnePastTheEnd())
8195 return false;
8196
David Majnemerc378ca52015-08-29 08:32:55 +00008197 // A pointer to an incomplete type might be past-the-end if the type's size is
8198 // zero. We cannot tell because the type is incomplete.
8199 QualType Ty = getType(LV.getLValueBase());
8200 if (Ty->isIncompleteType())
8201 return true;
8202
Richard Smithd20f1e62014-10-21 23:01:04 +00008203 // We're a past-the-end pointer if we point to the byte after the object,
8204 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008205 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008206 return LV.getLValueOffset() == Size;
8207}
8208
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008209namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008210
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008211/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008212///
8213/// We use a data recursive algorithm for binary operators so that we are able
8214/// to handle extreme cases of chained binary operators without causing stack
8215/// overflow.
8216class DataRecursiveIntBinOpEvaluator {
8217 struct EvalResult {
8218 APValue Val;
8219 bool Failed;
8220
8221 EvalResult() : Failed(false) { }
8222
8223 void swap(EvalResult &RHS) {
8224 Val.swap(RHS.Val);
8225 Failed = RHS.Failed;
8226 RHS.Failed = false;
8227 }
8228 };
8229
8230 struct Job {
8231 const Expr *E;
8232 EvalResult LHSResult; // meaningful only for binary operator expression.
8233 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008234
David Blaikie73726062015-08-12 23:09:24 +00008235 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008236 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008237
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008238 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008239 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008240 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008241
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008242 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008243 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008244 };
8245
8246 SmallVector<Job, 16> Queue;
8247
8248 IntExprEvaluator &IntEval;
8249 EvalInfo &Info;
8250 APValue &FinalResult;
8251
8252public:
8253 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8254 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8255
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008256 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008257 /// data recursively.
8258 /// We handle binary operators that are comma, logical, or that have operands
8259 /// with integral or enumeration type.
8260 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008261 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8262 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +00008263 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008264 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008265 }
8266
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008267 bool Traverse(const BinaryOperator *E) {
8268 enqueue(E);
8269 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008270 while (!Queue.empty())
8271 process(PrevResult);
8272
8273 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008274
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008275 FinalResult.swap(PrevResult.Val);
8276 return true;
8277 }
8278
8279private:
8280 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8281 return IntEval.Success(Value, E, Result);
8282 }
8283 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8284 return IntEval.Success(Value, E, Result);
8285 }
8286 bool Error(const Expr *E) {
8287 return IntEval.Error(E);
8288 }
8289 bool Error(const Expr *E, diag::kind D) {
8290 return IntEval.Error(E, D);
8291 }
8292
8293 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8294 return Info.CCEDiag(E, D);
8295 }
8296
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008297 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008298 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008299 bool &SuppressRHSDiags);
8300
8301 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8302 const BinaryOperator *E, APValue &Result);
8303
8304 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8305 Result.Failed = !Evaluate(Result.Val, Info, E);
8306 if (Result.Failed)
8307 Result.Val = APValue();
8308 }
8309
Richard Trieuba4d0872012-03-21 23:30:30 +00008310 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008311
8312 void enqueue(const Expr *E) {
8313 E = E->IgnoreParens();
8314 Queue.resize(Queue.size()+1);
8315 Queue.back().E = E;
8316 Queue.back().Kind = Job::AnyExprKind;
8317 }
8318};
8319
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008320}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008321
8322bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008323 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008324 bool &SuppressRHSDiags) {
8325 if (E->getOpcode() == BO_Comma) {
8326 // Ignore LHS but note if we could not evaluate it.
8327 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008328 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008329 return true;
8330 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008331
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008332 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008333 bool LHSAsBool;
8334 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008335 // We were able to evaluate the LHS, see if we can get away with not
8336 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008337 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8338 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008339 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008340 }
8341 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008342 LHSResult.Failed = true;
8343
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008344 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008345 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008346 if (!Info.noteSideEffect())
8347 return false;
8348
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008349 // We can't evaluate the LHS; however, sometimes the result
8350 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8351 // Don't ignore RHS and suppress diagnostics from this arm.
8352 SuppressRHSDiags = true;
8353 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008354
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008355 return true;
8356 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008357
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008358 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8359 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008360
George Burgess IVa145e252016-05-25 22:38:36 +00008361 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008362 return false; // Ignore RHS;
8363
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008364 return true;
8365}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008366
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008367static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8368 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008369 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8370 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8371 // offsets.
8372 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8373 CharUnits &Offset = LVal.getLValueOffset();
8374 uint64_t Offset64 = Offset.getQuantity();
8375 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8376 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8377 : Offset64 + Index64);
8378}
8379
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008380bool DataRecursiveIntBinOpEvaluator::
8381 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8382 const BinaryOperator *E, APValue &Result) {
8383 if (E->getOpcode() == BO_Comma) {
8384 if (RHSResult.Failed)
8385 return false;
8386 Result = RHSResult.Val;
8387 return true;
8388 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008389
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008390 if (E->isLogicalOp()) {
8391 bool lhsResult, rhsResult;
8392 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8393 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008394
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008395 if (LHSIsOK) {
8396 if (RHSIsOK) {
8397 if (E->getOpcode() == BO_LOr)
8398 return Success(lhsResult || rhsResult, E, Result);
8399 else
8400 return Success(lhsResult && rhsResult, E, Result);
8401 }
8402 } else {
8403 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008404 // We can't evaluate the LHS; however, sometimes the result
8405 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8406 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008407 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008408 }
8409 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008410
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008411 return false;
8412 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008413
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008414 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8415 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008416
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008417 if (LHSResult.Failed || RHSResult.Failed)
8418 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008419
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008420 const APValue &LHSVal = LHSResult.Val;
8421 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008422
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008423 // Handle cases like (unsigned long)&a + 4.
8424 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8425 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008426 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008427 return true;
8428 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008429
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008430 // Handle cases like 4 + (unsigned long)&a
8431 if (E->getOpcode() == BO_Add &&
8432 RHSVal.isLValue() && LHSVal.isInt()) {
8433 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008434 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008435 return true;
8436 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008437
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008438 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8439 // Handle (intptr_t)&&A - (intptr_t)&&B.
8440 if (!LHSVal.getLValueOffset().isZero() ||
8441 !RHSVal.getLValueOffset().isZero())
8442 return false;
8443 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8444 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8445 if (!LHSExpr || !RHSExpr)
8446 return false;
8447 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8448 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8449 if (!LHSAddrExpr || !RHSAddrExpr)
8450 return false;
8451 // Make sure both labels come from the same function.
8452 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8453 RHSAddrExpr->getLabel()->getDeclContext())
8454 return false;
8455 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8456 return true;
8457 }
Richard Smith43e77732013-05-07 04:50:00 +00008458
8459 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008460 if (!LHSVal.isInt() || !RHSVal.isInt())
8461 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008462
8463 // Set up the width and signedness manually, in case it can't be deduced
8464 // from the operation we're performing.
8465 // FIXME: Don't do this in the cases where we can deduce it.
8466 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8467 E->getType()->isUnsignedIntegerOrEnumerationType());
8468 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8469 RHSVal.getInt(), Value))
8470 return false;
8471 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008472}
8473
Richard Trieuba4d0872012-03-21 23:30:30 +00008474void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008475 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008476
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008477 switch (job.Kind) {
8478 case Job::AnyExprKind: {
8479 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8480 if (shouldEnqueue(Bop)) {
8481 job.Kind = Job::BinOpKind;
8482 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008483 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008484 }
8485 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008486
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008487 EvaluateExpr(job.E, Result);
8488 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008489 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008490 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008491
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008492 case Job::BinOpKind: {
8493 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008494 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008495 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008496 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008497 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008498 }
8499 if (SuppressRHSDiags)
8500 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008501 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008502 job.Kind = Job::BinOpVisitedLHSKind;
8503 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008504 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008505 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008506
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008507 case Job::BinOpVisitedLHSKind: {
8508 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8509 EvalResult RHS;
8510 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008511 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008512 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008513 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008514 }
8515 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008516
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008517 llvm_unreachable("Invalid Job::Kind!");
8518}
8519
George Burgess IV8c892b52016-05-25 22:31:54 +00008520namespace {
8521/// Used when we determine that we should fail, but can keep evaluating prior to
8522/// noting that we had a failure.
8523class DelayedNoteFailureRAII {
8524 EvalInfo &Info;
8525 bool NoteFailure;
8526
8527public:
8528 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8529 : Info(Info), NoteFailure(NoteFailure) {}
8530 ~DelayedNoteFailureRAII() {
8531 if (NoteFailure) {
8532 bool ContinueAfterFailure = Info.noteFailure();
8533 (void)ContinueAfterFailure;
8534 assert(ContinueAfterFailure &&
8535 "Shouldn't have kept evaluating on failure.");
8536 }
8537 }
8538};
8539}
8540
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008541template <class SuccessCB, class AfterCB>
8542static bool
8543EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
8544 SuccessCB &&Success, AfterCB &&DoAfter) {
8545 assert(E->isComparisonOp() && "expected comparison operator");
8546 assert((E->getOpcode() == BO_Cmp ||
8547 E->getType()->isIntegralOrEnumerationType()) &&
8548 "unsupported binary expression evaluation");
8549 auto Error = [&](const Expr *E) {
8550 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8551 return false;
8552 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008553
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008554 using CCR = ComparisonCategoryResult;
8555 bool IsRelational = E->isRelationalOp();
8556 bool IsEquality = E->isEqualityOp();
8557 if (E->getOpcode() == BO_Cmp) {
8558 const ComparisonCategoryInfo &CmpInfo =
8559 Info.Ctx.CompCategories.getInfoForType(E->getType());
8560 IsRelational = CmpInfo.isOrdered();
8561 IsEquality = CmpInfo.isEquality();
8562 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00008563
Anders Carlssonacc79812008-11-16 07:17:21 +00008564 QualType LHSTy = E->getLHS()->getType();
8565 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008566
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008567 if (LHSTy->isIntegralOrEnumerationType() &&
8568 RHSTy->isIntegralOrEnumerationType()) {
8569 APSInt LHS, RHS;
8570 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
8571 if (!LHSOK && !Info.noteFailure())
8572 return false;
8573 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
8574 return false;
8575 if (LHS < RHS)
8576 return Success(CCR::Less, E);
8577 if (LHS > RHS)
8578 return Success(CCR::Greater, E);
8579 return Success(CCR::Equal, E);
8580 }
8581
Chandler Carruthb29a7432014-10-11 11:03:30 +00008582 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008583 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008584 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008585 if (E->isAssignmentOp()) {
8586 LValue LV;
8587 EvaluateLValue(E->getLHS(), LV, Info);
8588 LHSOK = false;
8589 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008590 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8591 if (LHSOK) {
8592 LHS.makeComplexFloat();
8593 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8594 }
8595 } else {
8596 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8597 }
George Burgess IVa145e252016-05-25 22:38:36 +00008598 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008599 return false;
8600
Chandler Carruthb29a7432014-10-11 11:03:30 +00008601 if (E->getRHS()->getType()->isRealFloatingType()) {
8602 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8603 return false;
8604 RHS.makeComplexFloat();
8605 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8606 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008607 return false;
8608
8609 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008610 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008611 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008612 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008613 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008614 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
8615 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008616 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008617 assert(IsEquality && "invalid complex comparison");
8618 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8619 LHS.getComplexIntImag() == RHS.getComplexIntImag();
8620 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008621 }
8622 }
Mike Stump11289f42009-09-09 15:08:12 +00008623
Anders Carlssonacc79812008-11-16 07:17:21 +00008624 if (LHSTy->isRealFloatingType() &&
8625 RHSTy->isRealFloatingType()) {
8626 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008627
Richard Smith253c2a32012-01-27 01:14:48 +00008628 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008629 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008630 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008631
Richard Smith253c2a32012-01-27 01:14:48 +00008632 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008633 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008634
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008635 assert(E->isComparisonOp() && "Invalid binary operator!");
8636 auto GetCmpRes = [&]() {
8637 switch (LHS.compare(RHS)) {
8638 case APFloat::cmpEqual:
8639 return CCR::Equal;
8640 case APFloat::cmpLessThan:
8641 return CCR::Less;
8642 case APFloat::cmpGreaterThan:
8643 return CCR::Greater;
8644 case APFloat::cmpUnordered:
8645 return CCR::Unordered;
8646 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +00008647 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008648 };
8649 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008650 }
Mike Stump11289f42009-09-09 15:08:12 +00008651
Eli Friedmana38da572009-04-28 19:17:36 +00008652 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008653 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +00008654
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008655 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8656 if (!LHSOK && !Info.noteFailure())
8657 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008658
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008659 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8660 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008661
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008662 // Reject differing bases from the normal codepath; we special-case
8663 // comparisons to null.
8664 if (!HasSameBase(LHSValue, RHSValue)) {
8665 // Inequalities and subtractions between unrelated pointers have
8666 // unspecified or undefined behavior.
8667 if (!IsEquality)
8668 return Error(E);
8669 // A constant address may compare equal to the address of a symbol.
8670 // The one exception is that address of an object cannot compare equal
8671 // to a null pointer constant.
8672 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8673 (!RHSValue.Base && !RHSValue.Offset.isZero()))
8674 return Error(E);
8675 // It's implementation-defined whether distinct literals will have
8676 // distinct addresses. In clang, the result of such a comparison is
8677 // unspecified, so it is not a constant expression. However, we do know
8678 // that the address of a literal will be non-null.
8679 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8680 LHSValue.Base && RHSValue.Base)
8681 return Error(E);
8682 // We can't tell whether weak symbols will end up pointing to the same
8683 // object.
8684 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
8685 return Error(E);
8686 // We can't compare the address of the start of one object with the
8687 // past-the-end address of another object, per C++ DR1652.
8688 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8689 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8690 (RHSValue.Base && RHSValue.Offset.isZero() &&
8691 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8692 return Error(E);
8693 // We can't tell whether an object is at the same address as another
8694 // zero sized object.
8695 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8696 (LHSValue.Base && isZeroSized(RHSValue)))
8697 return Error(E);
8698 return Success(CCR::Nonequal, E);
8699 }
Eli Friedman64004332009-03-23 04:38:34 +00008700
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008701 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8702 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +00008703
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008704 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8705 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +00008706
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008707 // C++11 [expr.rel]p3:
8708 // Pointers to void (after pointer conversions) can be compared, with a
8709 // result defined as follows: If both pointers represent the same
8710 // address or are both the null pointer value, the result is true if the
8711 // operator is <= or >= and false otherwise; otherwise the result is
8712 // unspecified.
8713 // We interpret this as applying to pointers to *cv* void.
8714 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
8715 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +00008716
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008717 // C++11 [expr.rel]p2:
8718 // - If two pointers point to non-static data members of the same object,
8719 // or to subobjects or array elements fo such members, recursively, the
8720 // pointer to the later declared member compares greater provided the
8721 // two members have the same access control and provided their class is
8722 // not a union.
8723 // [...]
8724 // - Otherwise pointer comparisons are unspecified.
8725 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
8726 bool WasArrayIndex;
8727 unsigned Mismatch = FindDesignatorMismatch(
8728 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
8729 // At the point where the designators diverge, the comparison has a
8730 // specified value if:
8731 // - we are comparing array indices
8732 // - we are comparing fields of a union, or fields with the same access
8733 // Otherwise, the result is unspecified and thus the comparison is not a
8734 // constant expression.
8735 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8736 Mismatch < RHSDesignator.Entries.size()) {
8737 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8738 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8739 if (!LF && !RF)
8740 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8741 else if (!LF)
8742 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00008743 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8744 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008745 else if (!RF)
8746 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00008747 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8748 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008749 else if (!LF->getParent()->isUnion() &&
8750 LF->getAccess() != RF->getAccess())
8751 Info.CCEDiag(E,
8752 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +00008753 << LF << LF->getAccess() << RF << RF->getAccess()
8754 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +00008755 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008756 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008757
8758 // The comparison here must be unsigned, and performed with the same
8759 // width as the pointer.
8760 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8761 uint64_t CompareLHS = LHSOffset.getQuantity();
8762 uint64_t CompareRHS = RHSOffset.getQuantity();
8763 assert(PtrSize <= 64 && "Unexpected pointer width");
8764 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8765 CompareLHS &= Mask;
8766 CompareRHS &= Mask;
8767
8768 // If there is a base and this is a relational operator, we can only
8769 // compare pointers within the object in question; otherwise, the result
8770 // depends on where the object is located in memory.
8771 if (!LHSValue.Base.isNull() && IsRelational) {
8772 QualType BaseTy = getType(LHSValue.Base);
8773 if (BaseTy->isIncompleteType())
8774 return Error(E);
8775 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8776 uint64_t OffsetLimit = Size.getQuantity();
8777 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8778 return Error(E);
8779 }
8780
8781 if (CompareLHS < CompareRHS)
8782 return Success(CCR::Less, E);
8783 if (CompareLHS > CompareRHS)
8784 return Success(CCR::Greater, E);
8785 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008786 }
Richard Smith7bb00672012-02-01 01:42:44 +00008787
8788 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008789 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +00008790 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8791
8792 MemberPtr LHSValue, RHSValue;
8793
8794 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008795 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008796 return false;
8797
8798 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8799 return false;
8800
8801 // C++11 [expr.eq]p2:
8802 // If both operands are null, they compare equal. Otherwise if only one is
8803 // null, they compare unequal.
8804 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8805 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008806 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00008807 }
8808
8809 // Otherwise if either is a pointer to a virtual member function, the
8810 // result is unspecified.
8811 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8812 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008813 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00008814 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8815 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008816 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00008817
8818 // Otherwise they compare equal if and only if they would refer to the
8819 // same member of the same most derived object or the same subobject if
8820 // they were dereferenced with a hypothetical object of the associated
8821 // class type.
8822 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008823 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00008824 }
8825
Richard Smithab44d9b2012-02-14 22:35:28 +00008826 if (LHSTy->isNullPtrType()) {
8827 assert(E->isComparisonOp() && "unexpected nullptr operation");
8828 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8829 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8830 // are compared, the result is true of the operator is <=, >= or ==, and
8831 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008832 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +00008833 }
8834
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008835 return DoAfter();
8836}
8837
8838bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
8839 if (!CheckLiteralType(Info, E))
8840 return false;
8841
8842 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
8843 const BinaryOperator *E) {
8844 // Evaluation succeeded. Lookup the information for the comparison category
8845 // type and fetch the VarDecl for the result.
8846 const ComparisonCategoryInfo &CmpInfo =
8847 Info.Ctx.CompCategories.getInfoForType(E->getType());
8848 const VarDecl *VD =
8849 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
8850 // Check and evaluate the result as a constant expression.
8851 LValue LV;
8852 LV.set(VD);
8853 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
8854 return false;
8855 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
8856 };
8857 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
8858 return ExprEvaluatorBaseTy::VisitBinCmp(E);
8859 });
8860}
8861
8862bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8863 // We don't call noteFailure immediately because the assignment happens after
8864 // we evaluate LHS and RHS.
8865 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
8866 return Error(E);
8867
8868 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
8869 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8870 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
8871
8872 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
8873 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008874 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008875
8876 if (E->isComparisonOp()) {
8877 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
8878 // comparisons and then translating the result.
8879 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
8880 const BinaryOperator *E) {
8881 using CCR = ComparisonCategoryResult;
8882 bool IsEqual = ResKind == CCR::Equal,
8883 IsLess = ResKind == CCR::Less,
8884 IsGreater = ResKind == CCR::Greater;
8885 auto Op = E->getOpcode();
8886 switch (Op) {
8887 default:
8888 llvm_unreachable("unsupported binary operator");
8889 case BO_EQ:
8890 case BO_NE:
8891 return Success(IsEqual == (Op == BO_EQ), E);
8892 case BO_LT: return Success(IsLess, E);
8893 case BO_GT: return Success(IsGreater, E);
8894 case BO_LE: return Success(IsEqual || IsLess, E);
8895 case BO_GE: return Success(IsEqual || IsGreater, E);
8896 }
8897 };
8898 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
8899 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8900 });
8901 }
8902
8903 QualType LHSTy = E->getLHS()->getType();
8904 QualType RHSTy = E->getRHS()->getType();
8905
8906 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
8907 E->getOpcode() == BO_Sub) {
8908 LValue LHSValue, RHSValue;
8909
8910 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8911 if (!LHSOK && !Info.noteFailure())
8912 return false;
8913
8914 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8915 return false;
8916
8917 // Reject differing bases from the normal codepath; we special-case
8918 // comparisons to null.
8919 if (!HasSameBase(LHSValue, RHSValue)) {
8920 // Handle &&A - &&B.
8921 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
8922 return Error(E);
8923 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
8924 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
8925 if (!LHSExpr || !RHSExpr)
8926 return Error(E);
8927 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8928 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8929 if (!LHSAddrExpr || !RHSAddrExpr)
8930 return Error(E);
8931 // Make sure both labels come from the same function.
8932 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8933 RHSAddrExpr->getLabel()->getDeclContext())
8934 return Error(E);
8935 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
8936 }
8937 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8938 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8939
8940 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8941 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8942
8943 // C++11 [expr.add]p6:
8944 // Unless both pointers point to elements of the same array object, or
8945 // one past the last element of the array object, the behavior is
8946 // undefined.
8947 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8948 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
8949 RHSDesignator))
8950 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8951
8952 QualType Type = E->getLHS()->getType();
8953 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
8954
8955 CharUnits ElementSize;
8956 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
8957 return false;
8958
8959 // As an extension, a type may have zero size (empty struct or union in
8960 // C, array of zero length). Pointer subtraction in such cases has
8961 // undefined behavior, so is not constant.
8962 if (ElementSize.isZero()) {
8963 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
8964 << ElementType;
8965 return false;
8966 }
8967
8968 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8969 // and produce incorrect results when it overflows. Such behavior
8970 // appears to be non-conforming, but is common, so perhaps we should
8971 // assume the standard intended for such cases to be undefined behavior
8972 // and check for them.
8973
8974 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8975 // overflow in the final conversion to ptrdiff_t.
8976 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8977 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8978 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
8979 false);
8980 APSInt TrueResult = (LHS - RHS) / ElemSize;
8981 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8982
8983 if (Result.extend(65) != TrueResult &&
8984 !HandleOverflow(Info, E, TrueResult, E->getType()))
8985 return false;
8986 return Success(Result, E);
8987 }
8988
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008989 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008990}
8991
Peter Collingbournee190dee2011-03-11 19:24:49 +00008992/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8993/// a result as the expression's type.
8994bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8995 const UnaryExprOrTypeTraitExpr *E) {
8996 switch(E->getKind()) {
8997 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008998 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008999 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009000 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00009001 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009002 }
Eli Friedman64004332009-03-23 04:38:34 +00009003
Peter Collingbournee190dee2011-03-11 19:24:49 +00009004 case UETT_VecStep: {
9005 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00009006
Peter Collingbournee190dee2011-03-11 19:24:49 +00009007 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00009008 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00009009
Peter Collingbournee190dee2011-03-11 19:24:49 +00009010 // The vec_step built-in functions that take a 3-component
9011 // vector return 4. (OpenCL 1.1 spec 6.11.12)
9012 if (n == 3)
9013 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00009014
Peter Collingbournee190dee2011-03-11 19:24:49 +00009015 return Success(n, E);
9016 } else
9017 return Success(1, E);
9018 }
9019
9020 case UETT_SizeOf: {
9021 QualType SrcTy = E->getTypeOfArgument();
9022 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9023 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00009024 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9025 SrcTy = Ref->getPointeeType();
9026
Richard Smithd62306a2011-11-10 06:34:14 +00009027 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00009028 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00009029 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00009030 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009031 }
Alexey Bataev00396512015-07-02 03:40:19 +00009032 case UETT_OpenMPRequiredSimdAlign:
9033 assert(E->isArgumentType());
9034 return Success(
9035 Info.Ctx.toCharUnitsFromBits(
9036 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9037 .getQuantity(),
9038 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009039 }
9040
9041 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00009042}
9043
Peter Collingbournee9200682011-05-13 03:29:01 +00009044bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009045 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00009046 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00009047 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009048 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00009049 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00009050 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00009051 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00009052 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00009053 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00009054 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00009055 APSInt IdxResult;
9056 if (!EvaluateInteger(Idx, IdxResult, Info))
9057 return false;
9058 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9059 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009060 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009061 CurrentType = AT->getElementType();
9062 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9063 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00009064 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00009065 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009066
James Y Knight7281c352015-12-29 22:31:18 +00009067 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00009068 FieldDecl *MemberDecl = ON.getField();
9069 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009070 if (!RT)
9071 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009072 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009073 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00009074 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00009075 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00009076 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00009077 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00009078 CurrentType = MemberDecl->getType().getNonReferenceType();
9079 break;
9080 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009081
James Y Knight7281c352015-12-29 22:31:18 +00009082 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00009083 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00009084
James Y Knight7281c352015-12-29 22:31:18 +00009085 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00009086 CXXBaseSpecifier *BaseSpec = ON.getBase();
9087 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00009088 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009089
9090 // Find the layout of the class whose base we are looking into.
9091 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009092 if (!RT)
9093 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009094 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009095 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00009096 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9097
9098 // Find the base class itself.
9099 CurrentType = BaseSpec->getType();
9100 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9101 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009102 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00009103
Douglas Gregord1702062010-04-29 00:18:15 +00009104 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00009105 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00009106 break;
9107 }
Douglas Gregor882211c2010-04-28 22:16:22 +00009108 }
9109 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009110 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009111}
9112
Chris Lattnere13042c2008-07-11 19:10:17 +00009113bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009114 switch (E->getOpcode()) {
9115 default:
9116 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9117 // See C99 6.6p3.
9118 return Error(E);
9119 case UO_Extension:
9120 // FIXME: Should extension allow i-c-e extension expressions in its scope?
9121 // If so, we could clear the diagnostic ID.
9122 return Visit(E->getSubExpr());
9123 case UO_Plus:
9124 // The result is just the value.
9125 return Visit(E->getSubExpr());
9126 case UO_Minus: {
9127 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00009128 return false;
9129 if (!Result.isInt()) return Error(E);
9130 const APSInt &Value = Result.getInt();
9131 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9132 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9133 E->getType()))
9134 return false;
Richard Smithfe800032012-01-31 04:08:20 +00009135 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009136 }
9137 case UO_Not: {
9138 if (!Visit(E->getSubExpr()))
9139 return false;
9140 if (!Result.isInt()) return Error(E);
9141 return Success(~Result.getInt(), E);
9142 }
9143 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00009144 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00009145 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00009146 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009147 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00009148 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009149 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009150}
Mike Stump11289f42009-09-09 15:08:12 +00009151
Chris Lattner477c4be2008-07-12 01:15:53 +00009152/// HandleCast - This is used to evaluate implicit or explicit casts where the
9153/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00009154bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9155 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009156 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00009157 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009158
Eli Friedmanc757de22011-03-25 00:43:55 +00009159 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00009160 case CK_BaseToDerived:
9161 case CK_DerivedToBase:
9162 case CK_UncheckedDerivedToBase:
9163 case CK_Dynamic:
9164 case CK_ToUnion:
9165 case CK_ArrayToPointerDecay:
9166 case CK_FunctionToPointerDecay:
9167 case CK_NullToPointer:
9168 case CK_NullToMemberPointer:
9169 case CK_BaseToDerivedMemberPointer:
9170 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00009171 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00009172 case CK_ConstructorConversion:
9173 case CK_IntegralToPointer:
9174 case CK_ToVoid:
9175 case CK_VectorSplat:
9176 case CK_IntegralToFloating:
9177 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009178 case CK_CPointerToObjCPointerCast:
9179 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009180 case CK_AnyPointerToBlockPointerCast:
9181 case CK_ObjCObjectLValueCast:
9182 case CK_FloatingRealToComplex:
9183 case CK_FloatingComplexToReal:
9184 case CK_FloatingComplexCast:
9185 case CK_FloatingComplexToIntegralComplex:
9186 case CK_IntegralRealToComplex:
9187 case CK_IntegralComplexCast:
9188 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00009189 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009190 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009191 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009192 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009193 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009194 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00009195 llvm_unreachable("invalid cast kind for integral value");
9196
Eli Friedman9faf2f92011-03-25 19:07:11 +00009197 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009198 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009199 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00009200 case CK_ARCProduceObject:
9201 case CK_ARCConsumeObject:
9202 case CK_ARCReclaimReturnedObject:
9203 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009204 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009205 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009206
Richard Smith4ef685b2012-01-17 21:17:26 +00009207 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009208 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009209 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009210 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009211 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009212
9213 case CK_MemberPointerToBoolean:
9214 case CK_PointerToBoolean:
9215 case CK_IntegralToBoolean:
9216 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009217 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009218 case CK_FloatingComplexToBoolean:
9219 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009220 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009221 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009222 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009223 uint64_t IntResult = BoolResult;
9224 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9225 IntResult = (uint64_t)-1;
9226 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009227 }
9228
Eli Friedmanc757de22011-03-25 00:43:55 +00009229 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009230 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009231 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009232
Eli Friedman742421e2009-02-20 01:15:07 +00009233 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009234 // Allow casts of address-of-label differences if they are no-ops
9235 // or narrowing. (The narrowing case isn't actually guaranteed to
9236 // be constant-evaluatable except in some narrow cases which are hard
9237 // to detect here. We let it through on the assumption the user knows
9238 // what they are doing.)
9239 if (Result.isAddrLabelDiff())
9240 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009241 // Only allow casts of lvalues if they are lossless.
9242 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9243 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009244
Richard Smith911e1422012-01-30 22:27:01 +00009245 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9246 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009247 }
Mike Stump11289f42009-09-09 15:08:12 +00009248
Eli Friedmanc757de22011-03-25 00:43:55 +00009249 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009250 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9251
John McCall45d55e42010-05-07 21:00:08 +00009252 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009253 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009254 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009255
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009256 if (LV.getLValueBase()) {
9257 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009258 // FIXME: Allow a larger integer size than the pointer size, and allow
9259 // narrowing back down to pointer width in subsequent integral casts.
9260 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009261 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009262 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009263
Richard Smithcf74da72011-11-16 07:18:12 +00009264 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009265 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009266 return true;
9267 }
9268
Yaxun Liu402804b2016-12-15 08:09:08 +00009269 uint64_t V;
9270 if (LV.isNullPointer())
9271 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9272 else
9273 V = LV.getLValueOffset().getQuantity();
9274
9275 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009276 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009277 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009278
Eli Friedmanc757de22011-03-25 00:43:55 +00009279 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009280 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009281 if (!EvaluateComplex(SubExpr, C, Info))
9282 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009283 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009284 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009285
Eli Friedmanc757de22011-03-25 00:43:55 +00009286 case CK_FloatingToIntegral: {
9287 APFloat F(0.0);
9288 if (!EvaluateFloat(SubExpr, F, Info))
9289 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009290
Richard Smith357362d2011-12-13 06:39:58 +00009291 APSInt Value;
9292 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9293 return false;
9294 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009295 }
9296 }
Mike Stump11289f42009-09-09 15:08:12 +00009297
Eli Friedmanc757de22011-03-25 00:43:55 +00009298 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009299}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009300
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009301bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9302 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009303 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009304 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9305 return false;
9306 if (!LV.isComplexInt())
9307 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009308 return Success(LV.getComplexIntReal(), E);
9309 }
9310
9311 return Visit(E->getSubExpr());
9312}
9313
Eli Friedman4e7a2412009-02-27 04:45:43 +00009314bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009315 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009316 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009317 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9318 return false;
9319 if (!LV.isComplexInt())
9320 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009321 return Success(LV.getComplexIntImag(), E);
9322 }
9323
Richard Smith4a678122011-10-24 18:44:57 +00009324 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009325 return Success(0, E);
9326}
9327
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009328bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9329 return Success(E->getPackLength(), E);
9330}
9331
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009332bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9333 return Success(E->getValue(), E);
9334}
9335
Chris Lattner05706e882008-07-11 18:11:29 +00009336//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009337// Float Evaluation
9338//===----------------------------------------------------------------------===//
9339
9340namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009341class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009342 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009343 APFloat &Result;
9344public:
9345 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009346 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009347
Richard Smith2e312c82012-03-03 22:46:17 +00009348 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009349 Result = V.getFloat();
9350 return true;
9351 }
Eli Friedman24c01542008-08-22 00:06:13 +00009352
Richard Smithfddd3842011-12-30 21:15:51 +00009353 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009354 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9355 return true;
9356 }
9357
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009358 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009359
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009360 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009361 bool VisitBinaryOperator(const BinaryOperator *E);
9362 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009363 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009364
John McCallb1fb0d32010-05-07 22:08:54 +00009365 bool VisitUnaryReal(const UnaryOperator *E);
9366 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009367
Richard Smithfddd3842011-12-30 21:15:51 +00009368 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009369};
9370} // end anonymous namespace
9371
9372static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009373 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009374 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009375}
9376
Jay Foad39c79802011-01-12 09:06:06 +00009377static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009378 QualType ResultTy,
9379 const Expr *Arg,
9380 bool SNaN,
9381 llvm::APFloat &Result) {
9382 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9383 if (!S) return false;
9384
9385 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9386
9387 llvm::APInt fill;
9388
9389 // Treat empty strings as if they were zero.
9390 if (S->getString().empty())
9391 fill = llvm::APInt(32, 0);
9392 else if (S->getString().getAsInteger(0, fill))
9393 return false;
9394
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009395 if (Context.getTargetInfo().isNan2008()) {
9396 if (SNaN)
9397 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9398 else
9399 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9400 } else {
9401 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9402 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9403 // a different encoding to what became a standard in 2008, and for pre-
9404 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9405 // sNaN. This is now known as "legacy NaN" encoding.
9406 if (SNaN)
9407 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9408 else
9409 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9410 }
9411
John McCall16291492010-02-28 13:00:19 +00009412 return true;
9413}
9414
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009415bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009416 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009417 default:
9418 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9419
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009420 case Builtin::BI__builtin_huge_val:
9421 case Builtin::BI__builtin_huge_valf:
9422 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009423 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009424 case Builtin::BI__builtin_inf:
9425 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009426 case Builtin::BI__builtin_infl:
9427 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009428 const llvm::fltSemantics &Sem =
9429 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009430 Result = llvm::APFloat::getInf(Sem);
9431 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009432 }
Mike Stump11289f42009-09-09 15:08:12 +00009433
John McCall16291492010-02-28 13:00:19 +00009434 case Builtin::BI__builtin_nans:
9435 case Builtin::BI__builtin_nansf:
9436 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009437 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009438 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9439 true, Result))
9440 return Error(E);
9441 return true;
John McCall16291492010-02-28 13:00:19 +00009442
Chris Lattner0b7282e2008-10-06 06:31:58 +00009443 case Builtin::BI__builtin_nan:
9444 case Builtin::BI__builtin_nanf:
9445 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009446 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +00009447 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009448 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009449 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9450 false, Result))
9451 return Error(E);
9452 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009453
9454 case Builtin::BI__builtin_fabs:
9455 case Builtin::BI__builtin_fabsf:
9456 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009457 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009458 if (!EvaluateFloat(E->getArg(0), Result, Info))
9459 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009460
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009461 if (Result.isNegative())
9462 Result.changeSign();
9463 return true;
9464
Richard Smith8889a3d2013-06-13 06:26:32 +00009465 // FIXME: Builtin::BI__builtin_powi
9466 // FIXME: Builtin::BI__builtin_powif
9467 // FIXME: Builtin::BI__builtin_powil
9468
Mike Stump11289f42009-09-09 15:08:12 +00009469 case Builtin::BI__builtin_copysign:
9470 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009471 case Builtin::BI__builtin_copysignl:
9472 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009473 APFloat RHS(0.);
9474 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9475 !EvaluateFloat(E->getArg(1), RHS, Info))
9476 return false;
9477 Result.copySign(RHS);
9478 return true;
9479 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009480 }
9481}
9482
John McCallb1fb0d32010-05-07 22:08:54 +00009483bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009484 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9485 ComplexValue CV;
9486 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9487 return false;
9488 Result = CV.FloatReal;
9489 return true;
9490 }
9491
9492 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009493}
9494
9495bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009496 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9497 ComplexValue CV;
9498 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9499 return false;
9500 Result = CV.FloatImag;
9501 return true;
9502 }
9503
Richard Smith4a678122011-10-24 18:44:57 +00009504 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009505 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9506 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009507 return true;
9508}
9509
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009510bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009511 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009512 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009513 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009514 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009515 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009516 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9517 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009518 Result.changeSign();
9519 return true;
9520 }
9521}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009522
Eli Friedman24c01542008-08-22 00:06:13 +00009523bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009524 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9525 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009526
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009527 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009528 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009529 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009530 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009531 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9532 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009533}
9534
9535bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9536 Result = E->getValue();
9537 return true;
9538}
9539
Peter Collingbournee9200682011-05-13 03:29:01 +00009540bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9541 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009542
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009543 switch (E->getCastKind()) {
9544 default:
Richard Smith11562c52011-10-28 17:51:58 +00009545 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009546
9547 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009548 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009549 return EvaluateInteger(SubExpr, IntResult, Info) &&
9550 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9551 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009552 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009553
9554 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009555 if (!Visit(SubExpr))
9556 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009557 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9558 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009559 }
John McCalld7646252010-11-14 08:17:51 +00009560
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009561 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009562 ComplexValue V;
9563 if (!EvaluateComplex(SubExpr, V, Info))
9564 return false;
9565 Result = V.getComplexFloatReal();
9566 return true;
9567 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009568 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009569}
9570
Eli Friedman24c01542008-08-22 00:06:13 +00009571//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009572// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009573//===----------------------------------------------------------------------===//
9574
9575namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009576class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009577 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009578 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009579
Anders Carlsson537969c2008-11-16 20:27:53 +00009580public:
John McCall93d91dc2010-05-07 17:22:02 +00009581 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009582 : ExprEvaluatorBaseTy(info), Result(Result) {}
9583
Richard Smith2e312c82012-03-03 22:46:17 +00009584 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009585 Result.setFrom(V);
9586 return true;
9587 }
Mike Stump11289f42009-09-09 15:08:12 +00009588
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009589 bool ZeroInitialization(const Expr *E);
9590
Anders Carlsson537969c2008-11-16 20:27:53 +00009591 //===--------------------------------------------------------------------===//
9592 // Visitor Methods
9593 //===--------------------------------------------------------------------===//
9594
Peter Collingbournee9200682011-05-13 03:29:01 +00009595 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009596 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009597 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009598 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009599 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009600};
9601} // end anonymous namespace
9602
John McCall93d91dc2010-05-07 17:22:02 +00009603static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9604 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009605 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009606 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009607}
9608
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009609bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009610 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009611 if (ElemTy->isRealFloatingType()) {
9612 Result.makeComplexFloat();
9613 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9614 Result.FloatReal = Zero;
9615 Result.FloatImag = Zero;
9616 } else {
9617 Result.makeComplexInt();
9618 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9619 Result.IntReal = Zero;
9620 Result.IntImag = Zero;
9621 }
9622 return true;
9623}
9624
Peter Collingbournee9200682011-05-13 03:29:01 +00009625bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9626 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009627
9628 if (SubExpr->getType()->isRealFloatingType()) {
9629 Result.makeComplexFloat();
9630 APFloat &Imag = Result.FloatImag;
9631 if (!EvaluateFloat(SubExpr, Imag, Info))
9632 return false;
9633
9634 Result.FloatReal = APFloat(Imag.getSemantics());
9635 return true;
9636 } else {
9637 assert(SubExpr->getType()->isIntegerType() &&
9638 "Unexpected imaginary literal.");
9639
9640 Result.makeComplexInt();
9641 APSInt &Imag = Result.IntImag;
9642 if (!EvaluateInteger(SubExpr, Imag, Info))
9643 return false;
9644
9645 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9646 return true;
9647 }
9648}
9649
Peter Collingbournee9200682011-05-13 03:29:01 +00009650bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009651
John McCallfcef3cf2010-12-14 17:51:41 +00009652 switch (E->getCastKind()) {
9653 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009654 case CK_BaseToDerived:
9655 case CK_DerivedToBase:
9656 case CK_UncheckedDerivedToBase:
9657 case CK_Dynamic:
9658 case CK_ToUnion:
9659 case CK_ArrayToPointerDecay:
9660 case CK_FunctionToPointerDecay:
9661 case CK_NullToPointer:
9662 case CK_NullToMemberPointer:
9663 case CK_BaseToDerivedMemberPointer:
9664 case CK_DerivedToBaseMemberPointer:
9665 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009666 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009667 case CK_ConstructorConversion:
9668 case CK_IntegralToPointer:
9669 case CK_PointerToIntegral:
9670 case CK_PointerToBoolean:
9671 case CK_ToVoid:
9672 case CK_VectorSplat:
9673 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009674 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009675 case CK_IntegralToBoolean:
9676 case CK_IntegralToFloating:
9677 case CK_FloatingToIntegral:
9678 case CK_FloatingToBoolean:
9679 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009680 case CK_CPointerToObjCPointerCast:
9681 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009682 case CK_AnyPointerToBlockPointerCast:
9683 case CK_ObjCObjectLValueCast:
9684 case CK_FloatingComplexToReal:
9685 case CK_FloatingComplexToBoolean:
9686 case CK_IntegralComplexToReal:
9687 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009688 case CK_ARCProduceObject:
9689 case CK_ARCConsumeObject:
9690 case CK_ARCReclaimReturnedObject:
9691 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009692 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009693 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009694 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009695 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009696 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009697 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009698 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009699 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009700
John McCallfcef3cf2010-12-14 17:51:41 +00009701 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009702 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009703 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009704 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009705
9706 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009707 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009708 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009709 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009710
9711 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009712 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009713 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009714 return false;
9715
John McCallfcef3cf2010-12-14 17:51:41 +00009716 Result.makeComplexFloat();
9717 Result.FloatImag = APFloat(Real.getSemantics());
9718 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009719 }
9720
John McCallfcef3cf2010-12-14 17:51:41 +00009721 case CK_FloatingComplexCast: {
9722 if (!Visit(E->getSubExpr()))
9723 return false;
9724
9725 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9726 QualType From
9727 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9728
Richard Smith357362d2011-12-13 06:39:58 +00009729 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9730 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009731 }
9732
9733 case CK_FloatingComplexToIntegralComplex: {
9734 if (!Visit(E->getSubExpr()))
9735 return false;
9736
9737 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9738 QualType From
9739 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9740 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009741 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9742 To, Result.IntReal) &&
9743 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9744 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009745 }
9746
9747 case CK_IntegralRealToComplex: {
9748 APSInt &Real = Result.IntReal;
9749 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9750 return false;
9751
9752 Result.makeComplexInt();
9753 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9754 return true;
9755 }
9756
9757 case CK_IntegralComplexCast: {
9758 if (!Visit(E->getSubExpr()))
9759 return false;
9760
9761 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9762 QualType From
9763 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9764
Richard Smith911e1422012-01-30 22:27:01 +00009765 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9766 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009767 return true;
9768 }
9769
9770 case CK_IntegralComplexToFloatingComplex: {
9771 if (!Visit(E->getSubExpr()))
9772 return false;
9773
Ted Kremenek28831752012-08-23 20:46:57 +00009774 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009775 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009776 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009777 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009778 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9779 To, Result.FloatReal) &&
9780 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9781 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009782 }
9783 }
9784
9785 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009786}
9787
John McCall93d91dc2010-05-07 17:22:02 +00009788bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009789 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009790 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9791
Chandler Carrutha216cad2014-10-11 00:57:18 +00009792 // Track whether the LHS or RHS is real at the type system level. When this is
9793 // the case we can simplify our evaluation strategy.
9794 bool LHSReal = false, RHSReal = false;
9795
9796 bool LHSOK;
9797 if (E->getLHS()->getType()->isRealFloatingType()) {
9798 LHSReal = true;
9799 APFloat &Real = Result.FloatReal;
9800 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9801 if (LHSOK) {
9802 Result.makeComplexFloat();
9803 Result.FloatImag = APFloat(Real.getSemantics());
9804 }
9805 } else {
9806 LHSOK = Visit(E->getLHS());
9807 }
George Burgess IVa145e252016-05-25 22:38:36 +00009808 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009809 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009810
John McCall93d91dc2010-05-07 17:22:02 +00009811 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009812 if (E->getRHS()->getType()->isRealFloatingType()) {
9813 RHSReal = true;
9814 APFloat &Real = RHS.FloatReal;
9815 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9816 return false;
9817 RHS.makeComplexFloat();
9818 RHS.FloatImag = APFloat(Real.getSemantics());
9819 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009820 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009821
Chandler Carrutha216cad2014-10-11 00:57:18 +00009822 assert(!(LHSReal && RHSReal) &&
9823 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009824 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009825 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009826 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009827 if (Result.isComplexFloat()) {
9828 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9829 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009830 if (LHSReal)
9831 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9832 else if (!RHSReal)
9833 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9834 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009835 } else {
9836 Result.getComplexIntReal() += RHS.getComplexIntReal();
9837 Result.getComplexIntImag() += RHS.getComplexIntImag();
9838 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009839 break;
John McCalle3027922010-08-25 11:45:40 +00009840 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009841 if (Result.isComplexFloat()) {
9842 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9843 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009844 if (LHSReal) {
9845 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9846 Result.getComplexFloatImag().changeSign();
9847 } else if (!RHSReal) {
9848 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9849 APFloat::rmNearestTiesToEven);
9850 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009851 } else {
9852 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9853 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9854 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009855 break;
John McCalle3027922010-08-25 11:45:40 +00009856 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009857 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009858 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009859 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009860 // following naming scheme:
9861 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009862 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009863 APFloat &A = LHS.getComplexFloatReal();
9864 APFloat &B = LHS.getComplexFloatImag();
9865 APFloat &C = RHS.getComplexFloatReal();
9866 APFloat &D = RHS.getComplexFloatImag();
9867 APFloat &ResR = Result.getComplexFloatReal();
9868 APFloat &ResI = Result.getComplexFloatImag();
9869 if (LHSReal) {
9870 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9871 ResR = A * C;
9872 ResI = A * D;
9873 } else if (RHSReal) {
9874 ResR = C * A;
9875 ResI = C * B;
9876 } else {
9877 // In the fully general case, we need to handle NaNs and infinities
9878 // robustly.
9879 APFloat AC = A * C;
9880 APFloat BD = B * D;
9881 APFloat AD = A * D;
9882 APFloat BC = B * C;
9883 ResR = AC - BD;
9884 ResI = AD + BC;
9885 if (ResR.isNaN() && ResI.isNaN()) {
9886 bool Recalc = false;
9887 if (A.isInfinity() || B.isInfinity()) {
9888 A = APFloat::copySign(
9889 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9890 B = APFloat::copySign(
9891 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9892 if (C.isNaN())
9893 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9894 if (D.isNaN())
9895 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9896 Recalc = true;
9897 }
9898 if (C.isInfinity() || D.isInfinity()) {
9899 C = APFloat::copySign(
9900 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9901 D = APFloat::copySign(
9902 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9903 if (A.isNaN())
9904 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9905 if (B.isNaN())
9906 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9907 Recalc = true;
9908 }
9909 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9910 AD.isInfinity() || BC.isInfinity())) {
9911 if (A.isNaN())
9912 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9913 if (B.isNaN())
9914 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9915 if (C.isNaN())
9916 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9917 if (D.isNaN())
9918 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9919 Recalc = true;
9920 }
9921 if (Recalc) {
9922 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9923 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9924 }
9925 }
9926 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009927 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009928 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009929 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009930 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9931 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009932 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009933 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9934 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9935 }
9936 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009937 case BO_Div:
9938 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009939 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009940 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009941 // following naming scheme:
9942 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009943 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009944 APFloat &A = LHS.getComplexFloatReal();
9945 APFloat &B = LHS.getComplexFloatImag();
9946 APFloat &C = RHS.getComplexFloatReal();
9947 APFloat &D = RHS.getComplexFloatImag();
9948 APFloat &ResR = Result.getComplexFloatReal();
9949 APFloat &ResI = Result.getComplexFloatImag();
9950 if (RHSReal) {
9951 ResR = A / C;
9952 ResI = B / C;
9953 } else {
9954 if (LHSReal) {
9955 // No real optimizations we can do here, stub out with zero.
9956 B = APFloat::getZero(A.getSemantics());
9957 }
9958 int DenomLogB = 0;
9959 APFloat MaxCD = maxnum(abs(C), abs(D));
9960 if (MaxCD.isFinite()) {
9961 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009962 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9963 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009964 }
9965 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009966 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9967 APFloat::rmNearestTiesToEven);
9968 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9969 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009970 if (ResR.isNaN() && ResI.isNaN()) {
9971 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9972 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9973 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9974 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9975 D.isFinite()) {
9976 A = APFloat::copySign(
9977 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9978 B = APFloat::copySign(
9979 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9980 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9981 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9982 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9983 C = APFloat::copySign(
9984 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9985 D = APFloat::copySign(
9986 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9987 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9988 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9989 }
9990 }
9991 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009992 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009993 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9994 return Error(E, diag::note_expr_divide_by_zero);
9995
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009996 ComplexValue LHS = Result;
9997 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9998 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9999 Result.getComplexIntReal() =
10000 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10001 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10002 Result.getComplexIntImag() =
10003 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10004 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10005 }
10006 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010007 }
10008
John McCall93d91dc2010-05-07 17:22:02 +000010009 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010010}
10011
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010012bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10013 // Get the operand value into 'Result'.
10014 if (!Visit(E->getSubExpr()))
10015 return false;
10016
10017 switch (E->getOpcode()) {
10018 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010019 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010020 case UO_Extension:
10021 return true;
10022 case UO_Plus:
10023 // The result is always just the subexpr.
10024 return true;
10025 case UO_Minus:
10026 if (Result.isComplexFloat()) {
10027 Result.getComplexFloatReal().changeSign();
10028 Result.getComplexFloatImag().changeSign();
10029 }
10030 else {
10031 Result.getComplexIntReal() = -Result.getComplexIntReal();
10032 Result.getComplexIntImag() = -Result.getComplexIntImag();
10033 }
10034 return true;
10035 case UO_Not:
10036 if (Result.isComplexFloat())
10037 Result.getComplexFloatImag().changeSign();
10038 else
10039 Result.getComplexIntImag() = -Result.getComplexIntImag();
10040 return true;
10041 }
10042}
10043
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010044bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10045 if (E->getNumInits() == 2) {
10046 if (E->getType()->isComplexType()) {
10047 Result.makeComplexFloat();
10048 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10049 return false;
10050 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10051 return false;
10052 } else {
10053 Result.makeComplexInt();
10054 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10055 return false;
10056 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10057 return false;
10058 }
10059 return true;
10060 }
10061 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10062}
10063
Anders Carlsson537969c2008-11-16 20:27:53 +000010064//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000010065// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10066// implicit conversion.
10067//===----------------------------------------------------------------------===//
10068
10069namespace {
10070class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000010071 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010072 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000010073 APValue &Result;
10074public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010075 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10076 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000010077
10078 bool Success(const APValue &V, const Expr *E) {
10079 Result = V;
10080 return true;
10081 }
10082
10083 bool ZeroInitialization(const Expr *E) {
10084 ImplicitValueInitExpr VIE(
10085 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010086 // For atomic-qualified class (and array) types in C++, initialize the
10087 // _Atomic-wrapped subobject directly, in-place.
10088 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10089 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000010090 }
10091
10092 bool VisitCastExpr(const CastExpr *E) {
10093 switch (E->getCastKind()) {
10094 default:
10095 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10096 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010097 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10098 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000010099 }
10100 }
10101};
10102} // end anonymous namespace
10103
Richard Smith64cb9ca2017-02-22 22:09:50 +000010104static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10105 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000010106 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010107 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000010108}
10109
10110//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000010111// Void expression evaluation, primarily for a cast to void on the LHS of a
10112// comma operator
10113//===----------------------------------------------------------------------===//
10114
10115namespace {
10116class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010117 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000010118public:
10119 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10120
Richard Smith2e312c82012-03-03 22:46:17 +000010121 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000010122
Richard Smith7cd577b2017-08-17 19:35:50 +000010123 bool ZeroInitialization(const Expr *E) { return true; }
10124
Richard Smith42d3af92011-12-07 00:43:50 +000010125 bool VisitCastExpr(const CastExpr *E) {
10126 switch (E->getCastKind()) {
10127 default:
10128 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10129 case CK_ToVoid:
10130 VisitIgnoredValue(E->getSubExpr());
10131 return true;
10132 }
10133 }
Hal Finkela8443c32014-07-17 14:49:58 +000010134
10135 bool VisitCallExpr(const CallExpr *E) {
10136 switch (E->getBuiltinCallee()) {
10137 default:
10138 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10139 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000010140 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000010141 // The argument is not evaluated!
10142 return true;
10143 }
10144 }
Richard Smith42d3af92011-12-07 00:43:50 +000010145};
10146} // end anonymous namespace
10147
10148static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10149 assert(E->isRValue() && E->getType()->isVoidType());
10150 return VoidExprEvaluator(Info).Visit(E);
10151}
10152
10153//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000010154// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000010155//===----------------------------------------------------------------------===//
10156
Richard Smith2e312c82012-03-03 22:46:17 +000010157static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000010158 // In C, function designators are not lvalues, but we evaluate them as if they
10159 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000010160 QualType T = E->getType();
10161 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000010162 LValue LV;
10163 if (!EvaluateLValue(E, LV, Info))
10164 return false;
10165 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010166 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010167 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000010168 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010169 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010170 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010171 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010172 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000010173 LValue LV;
10174 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010175 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010176 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010177 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000010178 llvm::APFloat F(0.0);
10179 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010180 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000010181 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000010182 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000010183 ComplexValue C;
10184 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010185 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010186 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010187 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000010188 MemberPtr P;
10189 if (!EvaluateMemberPointer(E, P, Info))
10190 return false;
10191 P.moveInto(Result);
10192 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000010193 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010194 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010195 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010196 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000010197 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010198 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010199 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010200 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010201 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010202 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000010203 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010204 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010205 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010206 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010207 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010208 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010209 if (!EvaluateVoid(E, Info))
10210 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010211 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010212 QualType Unqual = T.getAtomicUnqualifiedType();
10213 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10214 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010215 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010216 if (!EvaluateAtomic(E, &LV, Value, Info))
10217 return false;
10218 } else {
10219 if (!EvaluateAtomic(E, nullptr, Result, Info))
10220 return false;
10221 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010222 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010223 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010224 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010225 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010226 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010227 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010228 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010229
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010230 return true;
10231}
10232
Richard Smithb228a862012-02-15 02:18:13 +000010233/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10234/// cases, the in-place evaluation is essential, since later initializers for
10235/// an object can indirectly refer to subobjects which were initialized earlier.
10236static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010237 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010238 assert(!E->isValueDependent());
10239
Richard Smith7525ff62013-05-09 07:14:00 +000010240 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010241 return false;
10242
10243 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010244 // Evaluate arrays and record types in-place, so that later initializers can
10245 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010246 QualType T = E->getType();
10247 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010248 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010249 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010250 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010251 else if (T->isAtomicType()) {
10252 QualType Unqual = T.getAtomicUnqualifiedType();
10253 if (Unqual->isArrayType() || Unqual->isRecordType())
10254 return EvaluateAtomic(E, &This, Result, Info);
10255 }
Richard Smithed5165f2011-11-04 05:33:44 +000010256 }
10257
10258 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010259 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010260}
10261
Richard Smithf57d8cb2011-12-09 22:58:01 +000010262/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10263/// lvalue-to-rvalue cast if it is an lvalue.
10264static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010265 if (E->getType().isNull())
10266 return false;
10267
Nick Lewyckyc190f962017-05-02 01:06:16 +000010268 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010269 return false;
10270
Richard Smith2e312c82012-03-03 22:46:17 +000010271 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010272 return false;
10273
10274 if (E->isGLValue()) {
10275 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010276 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010277 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010278 return false;
10279 }
10280
Richard Smith2e312c82012-03-03 22:46:17 +000010281 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010282 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010283}
Richard Smith11562c52011-10-28 17:51:58 +000010284
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010285static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010286 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010287 // Fast-path evaluations of integer literals, since we sometimes see files
10288 // containing vast quantities of these.
10289 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10290 Result.Val = APValue(APSInt(L->getValue(),
10291 L->getType()->isUnsignedIntegerType()));
10292 IsConst = true;
10293 return true;
10294 }
James Dennett0492ef02014-03-14 17:44:10 +000010295
10296 // This case should be rare, but we need to check it before we check on
10297 // the type below.
10298 if (Exp->getType().isNull()) {
10299 IsConst = false;
10300 return true;
10301 }
Daniel Jasperffdee092017-05-02 19:21:42 +000010302
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010303 // FIXME: Evaluating values of large array and record types can cause
10304 // performance problems. Only do so in C++11 for now.
10305 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10306 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010307 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010308 IsConst = false;
10309 return true;
10310 }
10311 return false;
10312}
10313
10314
Richard Smith7b553f12011-10-29 00:50:52 +000010315/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010316/// any crazy technique (that has nothing to do with language standards) that
10317/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010318/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10319/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010320bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010321 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010322 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010323 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010324
Richard Smith6d4c6582013-11-05 22:18:15 +000010325 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010326 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010327}
10328
Jay Foad39c79802011-01-12 09:06:06 +000010329bool Expr::EvaluateAsBooleanCondition(bool &Result,
10330 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010331 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010332 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010333 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010334}
10335
Richard Smith3f1d6de2018-05-21 20:36:58 +000010336static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10337 Expr::SideEffectsKind SEK) {
10338 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10339 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10340}
10341
Richard Smith5fab0c92011-12-28 19:48:30 +000010342bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10343 SideEffectsKind AllowSideEffects) const {
10344 if (!getType()->isIntegralOrEnumerationType())
10345 return false;
10346
Richard Smith11562c52011-10-28 17:51:58 +000010347 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010348 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000010349 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010350 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010351
Richard Smith11562c52011-10-28 17:51:58 +000010352 Result = ExprResult.Val.getInt();
10353 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010354}
10355
Richard Trieube234c32016-04-21 21:04:55 +000010356bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10357 SideEffectsKind AllowSideEffects) const {
10358 if (!getType()->isRealFloatingType())
10359 return false;
10360
10361 EvalResult ExprResult;
10362 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000010363 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000010364 return false;
10365
10366 Result = ExprResult.Val.getFloat();
10367 return true;
10368}
10369
Jay Foad39c79802011-01-12 09:06:06 +000010370bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010371 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010372
John McCall45d55e42010-05-07 21:00:08 +000010373 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010374 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10375 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000010376 Ctx.getLValueReferenceType(getType()), LV,
10377 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000010378 return false;
10379
Richard Smith2e312c82012-03-03 22:46:17 +000010380 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010381 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010382}
10383
Reid Kleckner1a840d22018-05-10 18:57:35 +000010384bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
10385 const ASTContext &Ctx) const {
10386 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
10387 EvalInfo Info(Ctx, Result, EM);
10388 if (!::Evaluate(Result.Val, Info, this))
10389 return false;
10390
10391 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
10392 Usage);
10393}
10394
Richard Smithd0b4dd62011-12-19 06:19:21 +000010395bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10396 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010397 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010398 // FIXME: Evaluating initializers for large array and record types can cause
10399 // performance problems. Only do so in C++11 for now.
10400 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010401 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010402 return false;
10403
Richard Smithd0b4dd62011-12-19 06:19:21 +000010404 Expr::EvalStatus EStatus;
10405 EStatus.Diag = &Notes;
10406
Richard Smith0c6124b2015-12-03 01:36:22 +000010407 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10408 ? EvalInfo::EM_ConstantExpression
10409 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010410 InitInfo.setEvaluatingDecl(VD, Value);
10411
10412 LValue LVal;
10413 LVal.set(VD);
10414
Richard Smithfddd3842011-12-30 21:15:51 +000010415 // C++11 [basic.start.init]p2:
10416 // Variables with static storage duration or thread storage duration shall be
10417 // zero-initialized before any other initialization takes place.
10418 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010419 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010420 !VD->getType()->isReferenceType()) {
10421 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010422 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010423 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010424 return false;
10425 }
10426
Richard Smith7525ff62013-05-09 07:14:00 +000010427 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10428 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010429 EStatus.HasSideEffects)
10430 return false;
10431
10432 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10433 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010434}
10435
Richard Smith7b553f12011-10-29 00:50:52 +000010436/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10437/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010438bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010439 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010440 return EvaluateAsRValue(Result, Ctx) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000010441 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010442}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010443
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010444APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010445 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010446 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010447 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010448 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010449 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010450 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010451 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010452
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010453 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010454}
John McCall864e3962010-05-07 05:32:02 +000010455
Richard Smithe9ff7702013-11-05 22:23:30 +000010456void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010457 bool IsConst;
10458 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010459 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010460 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010461 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10462 }
10463}
10464
Richard Smithe6c01442013-06-05 00:46:14 +000010465bool Expr::EvalResult::isGlobalLValue() const {
10466 assert(Val.isLValue());
10467 return IsGlobalLValue(Val.getLValueBase());
10468}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010469
10470
John McCall864e3962010-05-07 05:32:02 +000010471/// isIntegerConstantExpr - this recursive routine will test if an expression is
10472/// an integer constant expression.
10473
10474/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10475/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010476
10477// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010478// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10479// and a (possibly null) SourceLocation indicating the location of the problem.
10480//
John McCall864e3962010-05-07 05:32:02 +000010481// Note that to reduce code duplication, this helper does no evaluation
10482// itself; the caller checks whether the expression is evaluatable, and
10483// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010484// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010485
Dan Gohman28ade552010-07-26 21:25:24 +000010486namespace {
10487
Richard Smith9e575da2012-12-28 13:25:52 +000010488enum ICEKind {
10489 /// This expression is an ICE.
10490 IK_ICE,
10491 /// This expression is not an ICE, but if it isn't evaluated, it's
10492 /// a legal subexpression for an ICE. This return value is used to handle
10493 /// the comma operator in C99 mode, and non-constant subexpressions.
10494 IK_ICEIfUnevaluated,
10495 /// This expression is not an ICE, and is not a legal subexpression for one.
10496 IK_NotICE
10497};
10498
John McCall864e3962010-05-07 05:32:02 +000010499struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010500 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010501 SourceLocation Loc;
10502
Richard Smith9e575da2012-12-28 13:25:52 +000010503 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010504};
10505
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010506}
Dan Gohman28ade552010-07-26 21:25:24 +000010507
Richard Smith9e575da2012-12-28 13:25:52 +000010508static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10509
10510static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010511
Craig Toppera31a8822013-08-22 07:09:37 +000010512static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010513 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010514 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010515 !EVResult.Val.isInt())
10516 return ICEDiag(IK_NotICE, E->getLocStart());
10517
John McCall864e3962010-05-07 05:32:02 +000010518 return NoDiag();
10519}
10520
Craig Toppera31a8822013-08-22 07:09:37 +000010521static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010522 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010523 if (!E->getType()->isIntegralOrEnumerationType())
10524 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010525
10526 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010527#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010528#define STMT(Node, Base) case Expr::Node##Class:
10529#define EXPR(Node, Base)
10530#include "clang/AST/StmtNodes.inc"
10531 case Expr::PredefinedExprClass:
10532 case Expr::FloatingLiteralClass:
10533 case Expr::ImaginaryLiteralClass:
10534 case Expr::StringLiteralClass:
10535 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010536 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010537 case Expr::MemberExprClass:
10538 case Expr::CompoundAssignOperatorClass:
10539 case Expr::CompoundLiteralExprClass:
10540 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010541 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010542 case Expr::ArrayInitLoopExprClass:
10543 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010544 case Expr::NoInitExprClass:
10545 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010546 case Expr::ImplicitValueInitExprClass:
10547 case Expr::ParenListExprClass:
10548 case Expr::VAArgExprClass:
10549 case Expr::AddrLabelExprClass:
10550 case Expr::StmtExprClass:
10551 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010552 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010553 case Expr::CXXDynamicCastExprClass:
10554 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010555 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010556 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010557 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010558 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010559 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010560 case Expr::CXXThisExprClass:
10561 case Expr::CXXThrowExprClass:
10562 case Expr::CXXNewExprClass:
10563 case Expr::CXXDeleteExprClass:
10564 case Expr::CXXPseudoDestructorExprClass:
10565 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010566 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010567 case Expr::DependentScopeDeclRefExprClass:
10568 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010569 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010570 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010571 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010572 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010573 case Expr::CXXTemporaryObjectExprClass:
10574 case Expr::CXXUnresolvedConstructExprClass:
10575 case Expr::CXXDependentScopeMemberExprClass:
10576 case Expr::UnresolvedMemberExprClass:
10577 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010578 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010579 case Expr::ObjCArrayLiteralClass:
10580 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010581 case Expr::ObjCEncodeExprClass:
10582 case Expr::ObjCMessageExprClass:
10583 case Expr::ObjCSelectorExprClass:
10584 case Expr::ObjCProtocolExprClass:
10585 case Expr::ObjCIvarRefExprClass:
10586 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010587 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010588 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010589 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010590 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010591 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010592 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010593 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010594 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010595 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010596 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010597 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010598 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010599 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010600 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010601 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010602 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010603 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010604 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010605 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010606 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010607 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010608 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010609
Richard Smithf137f932014-01-25 20:50:08 +000010610 case Expr::InitListExprClass: {
10611 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10612 // form "T x = { a };" is equivalent to "T x = a;".
10613 // Unless we're initializing a reference, T is a scalar as it is known to be
10614 // of integral or enumeration type.
10615 if (E->isRValue())
10616 if (cast<InitListExpr>(E)->getNumInits() == 1)
10617 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10618 return ICEDiag(IK_NotICE, E->getLocStart());
10619 }
10620
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010621 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010622 case Expr::GNUNullExprClass:
10623 // GCC considers the GNU __null value to be an integral constant expression.
10624 return NoDiag();
10625
John McCall7c454bb2011-07-15 05:09:51 +000010626 case Expr::SubstNonTypeTemplateParmExprClass:
10627 return
10628 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10629
John McCall864e3962010-05-07 05:32:02 +000010630 case Expr::ParenExprClass:
10631 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010632 case Expr::GenericSelectionExprClass:
10633 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010634 case Expr::IntegerLiteralClass:
10635 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010636 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010637 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010638 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010639 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010640 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010641 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010642 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010643 return NoDiag();
10644 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010645 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010646 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10647 // constant expressions, but they can never be ICEs because an ICE cannot
10648 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010649 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010650 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010651 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010652 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010653 }
Richard Smith6365c912012-02-24 22:12:32 +000010654 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010655 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10656 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000010657 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010658 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010659 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010660 // Parameter variables are never constants. Without this check,
10661 // getAnyInitializer() can find a default argument, which leads
10662 // to chaos.
10663 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010664 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010665
10666 // C++ 7.1.5.1p2
10667 // A variable of non-volatile const-qualified integral or enumeration
10668 // type initialized by an ICE can be used in ICEs.
10669 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010670 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010671 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010672
Richard Smithd0b4dd62011-12-19 06:19:21 +000010673 const VarDecl *VD;
10674 // Look for a declaration of this variable that has an initializer, and
10675 // check whether it is an ICE.
10676 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10677 return NoDiag();
10678 else
Richard Smith9e575da2012-12-28 13:25:52 +000010679 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010680 }
10681 }
Richard Smith9e575da2012-12-28 13:25:52 +000010682 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010683 }
John McCall864e3962010-05-07 05:32:02 +000010684 case Expr::UnaryOperatorClass: {
10685 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10686 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010687 case UO_PostInc:
10688 case UO_PostDec:
10689 case UO_PreInc:
10690 case UO_PreDec:
10691 case UO_AddrOf:
10692 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010693 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010694 // C99 6.6/3 allows increment and decrement within unevaluated
10695 // subexpressions of constant expressions, but they can never be ICEs
10696 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010697 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010698 case UO_Extension:
10699 case UO_LNot:
10700 case UO_Plus:
10701 case UO_Minus:
10702 case UO_Not:
10703 case UO_Real:
10704 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010705 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010706 }
Richard Smith9e575da2012-12-28 13:25:52 +000010707
John McCall864e3962010-05-07 05:32:02 +000010708 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010709 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010710 }
10711 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010712 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10713 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10714 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10715 // compliance: we should warn earlier for offsetof expressions with
10716 // array subscripts that aren't ICEs, and if the array subscripts
10717 // are ICEs, the value of the offsetof must be an integer constant.
10718 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010719 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010720 case Expr::UnaryExprOrTypeTraitExprClass: {
10721 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10722 if ((Exp->getKind() == UETT_SizeOf) &&
10723 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010724 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010725 return NoDiag();
10726 }
10727 case Expr::BinaryOperatorClass: {
10728 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10729 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010730 case BO_PtrMemD:
10731 case BO_PtrMemI:
10732 case BO_Assign:
10733 case BO_MulAssign:
10734 case BO_DivAssign:
10735 case BO_RemAssign:
10736 case BO_AddAssign:
10737 case BO_SubAssign:
10738 case BO_ShlAssign:
10739 case BO_ShrAssign:
10740 case BO_AndAssign:
10741 case BO_XorAssign:
10742 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000010743 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10744 // constant expressions, but they can never be ICEs because an ICE cannot
10745 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010746 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010747
John McCalle3027922010-08-25 11:45:40 +000010748 case BO_Mul:
10749 case BO_Div:
10750 case BO_Rem:
10751 case BO_Add:
10752 case BO_Sub:
10753 case BO_Shl:
10754 case BO_Shr:
10755 case BO_LT:
10756 case BO_GT:
10757 case BO_LE:
10758 case BO_GE:
10759 case BO_EQ:
10760 case BO_NE:
10761 case BO_And:
10762 case BO_Xor:
10763 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010764 case BO_Comma:
10765 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000010766 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10767 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010768 if (Exp->getOpcode() == BO_Div ||
10769 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010770 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010771 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010772 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010773 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010774 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010775 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010776 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010777 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010778 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010779 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010780 }
10781 }
10782 }
John McCalle3027922010-08-25 11:45:40 +000010783 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010784 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010785 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10786 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010787 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10788 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010789 } else {
10790 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010791 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010792 }
10793 }
Richard Smith9e575da2012-12-28 13:25:52 +000010794 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010795 }
John McCalle3027922010-08-25 11:45:40 +000010796 case BO_LAnd:
10797 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010798 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10799 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010800 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010801 // Rare case where the RHS has a comma "side-effect"; we need
10802 // to actually check the condition to see whether the side
10803 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010804 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010805 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010806 return RHSResult;
10807 return NoDiag();
10808 }
10809
Richard Smith9e575da2012-12-28 13:25:52 +000010810 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010811 }
10812 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010813 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010814 }
10815 case Expr::ImplicitCastExprClass:
10816 case Expr::CStyleCastExprClass:
10817 case Expr::CXXFunctionalCastExprClass:
10818 case Expr::CXXStaticCastExprClass:
10819 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010820 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010821 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010822 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010823 if (isa<ExplicitCastExpr>(E)) {
10824 if (const FloatingLiteral *FL
10825 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10826 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10827 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10828 APSInt IgnoredVal(DestWidth, !DestSigned);
10829 bool Ignored;
10830 // If the value does not fit in the destination type, the behavior is
10831 // undefined, so we are not required to treat it as a constant
10832 // expression.
10833 if (FL->getValue().convertToInteger(IgnoredVal,
10834 llvm::APFloat::rmTowardZero,
10835 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010836 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010837 return NoDiag();
10838 }
10839 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010840 switch (cast<CastExpr>(E)->getCastKind()) {
10841 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010842 case CK_AtomicToNonAtomic:
10843 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010844 case CK_NoOp:
10845 case CK_IntegralToBoolean:
10846 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010847 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010848 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010849 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010850 }
John McCall864e3962010-05-07 05:32:02 +000010851 }
John McCallc07a0c72011-02-17 10:25:35 +000010852 case Expr::BinaryConditionalOperatorClass: {
10853 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10854 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010855 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010856 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010857 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10858 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10859 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010860 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010861 return FalseResult;
10862 }
John McCall864e3962010-05-07 05:32:02 +000010863 case Expr::ConditionalOperatorClass: {
10864 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10865 // If the condition (ignoring parens) is a __builtin_constant_p call,
10866 // then only the true side is actually considered in an integer constant
10867 // expression, and it is fully evaluated. This is an important GNU
10868 // extension. See GCC PR38377 for discussion.
10869 if (const CallExpr *CallCE
10870 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010871 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010872 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010873 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010874 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010875 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010876
Richard Smithf57d8cb2011-12-09 22:58:01 +000010877 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10878 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010879
Richard Smith9e575da2012-12-28 13:25:52 +000010880 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010881 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010882 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010883 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010884 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010885 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010886 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010887 return NoDiag();
10888 // Rare case where the diagnostics depend on which side is evaluated
10889 // Note that if we get here, CondResult is 0, and at least one of
10890 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010891 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010892 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010893 return TrueResult;
10894 }
10895 case Expr::CXXDefaultArgExprClass:
10896 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010897 case Expr::CXXDefaultInitExprClass:
10898 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010899 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010900 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010901 }
10902 }
10903
David Blaikiee4d798f2012-01-20 21:50:17 +000010904 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010905}
10906
Richard Smithf57d8cb2011-12-09 22:58:01 +000010907/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010908static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010909 const Expr *E,
10910 llvm::APSInt *Value,
10911 SourceLocation *Loc) {
10912 if (!E->getType()->isIntegralOrEnumerationType()) {
10913 if (Loc) *Loc = E->getExprLoc();
10914 return false;
10915 }
10916
Richard Smith66e05fe2012-01-18 05:21:49 +000010917 APValue Result;
10918 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010919 return false;
10920
Richard Smith98710fc2014-11-13 23:03:19 +000010921 if (!Result.isInt()) {
10922 if (Loc) *Loc = E->getExprLoc();
10923 return false;
10924 }
10925
Richard Smith66e05fe2012-01-18 05:21:49 +000010926 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010927 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010928}
10929
Craig Toppera31a8822013-08-22 07:09:37 +000010930bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10931 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010932 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010933 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010934
Richard Smith9e575da2012-12-28 13:25:52 +000010935 ICEDiag D = CheckICE(this, Ctx);
10936 if (D.Kind != IK_ICE) {
10937 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010938 return false;
10939 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010940 return true;
10941}
10942
Craig Toppera31a8822013-08-22 07:09:37 +000010943bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010944 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010945 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010946 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10947
10948 if (!isIntegerConstantExpr(Ctx, Loc))
10949 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010950 // The only possible side-effects here are due to UB discovered in the
10951 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10952 // required to treat the expression as an ICE, so we produce the folded
10953 // value.
10954 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010955 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010956 return true;
10957}
Richard Smith66e05fe2012-01-18 05:21:49 +000010958
Craig Toppera31a8822013-08-22 07:09:37 +000010959bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010960 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010961}
10962
Craig Toppera31a8822013-08-22 07:09:37 +000010963bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010964 SourceLocation *Loc) const {
10965 // We support this checking in C++98 mode in order to diagnose compatibility
10966 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010967 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010968
Richard Smith98a0a492012-02-14 21:38:30 +000010969 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010970 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010971 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010972 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010973 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010974
10975 APValue Scratch;
10976 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10977
10978 if (!Diags.empty()) {
10979 IsConstExpr = false;
10980 if (Loc) *Loc = Diags[0].first;
10981 } else if (!IsConstExpr) {
10982 // FIXME: This shouldn't happen.
10983 if (Loc) *Loc = getExprLoc();
10984 }
10985
10986 return IsConstExpr;
10987}
Richard Smith253c2a32012-01-27 01:14:48 +000010988
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010989bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10990 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010991 ArrayRef<const Expr*> Args,
10992 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010993 Expr::EvalStatus Status;
10994 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10995
George Burgess IV177399e2017-01-09 04:12:14 +000010996 LValue ThisVal;
10997 const LValue *ThisPtr = nullptr;
10998 if (This) {
10999#ifndef NDEBUG
11000 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11001 assert(MD && "Don't provide `this` for non-methods.");
11002 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11003#endif
11004 if (EvaluateObjectArgument(Info, This, ThisVal))
11005 ThisPtr = &ThisVal;
11006 if (Info.EvalStatus.HasSideEffects)
11007 return false;
11008 }
11009
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011010 ArgVector ArgValues(Args.size());
11011 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11012 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000011013 if ((*I)->isValueDependent() ||
11014 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011015 // If evaluation fails, throw away the argument entirely.
11016 ArgValues[I - Args.begin()] = APValue();
11017 if (Info.EvalStatus.HasSideEffects)
11018 return false;
11019 }
11020
11021 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000011022 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011023 ArgValues.data());
11024 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11025}
11026
Richard Smith253c2a32012-01-27 01:14:48 +000011027bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011028 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000011029 PartialDiagnosticAt> &Diags) {
11030 // FIXME: It would be useful to check constexpr function templates, but at the
11031 // moment the constant expression evaluator cannot cope with the non-rigorous
11032 // ASTs which we build for dependent expressions.
11033 if (FD->isDependentContext())
11034 return true;
11035
11036 Expr::EvalStatus Status;
11037 Status.Diag = &Diags;
11038
Richard Smith6d4c6582013-11-05 22:18:15 +000011039 EvalInfo Info(FD->getASTContext(), Status,
11040 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000011041
11042 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000011043 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000011044
Richard Smith7525ff62013-05-09 07:14:00 +000011045 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000011046 // is a temporary being used as the 'this' pointer.
11047 LValue This;
11048 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011049 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000011050
Richard Smith253c2a32012-01-27 01:14:48 +000011051 ArrayRef<const Expr*> Args;
11052
Richard Smith2e312c82012-03-03 22:46:17 +000011053 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000011054 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11055 // Evaluate the call as a constant initializer, to allow the construction
11056 // of objects of non-literal types.
11057 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000011058 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11059 } else {
11060 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000011061 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000011062 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000011063 }
Richard Smith253c2a32012-01-27 01:14:48 +000011064
11065 return Diags.empty();
11066}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011067
11068bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11069 const FunctionDecl *FD,
11070 SmallVectorImpl<
11071 PartialDiagnosticAt> &Diags) {
11072 Expr::EvalStatus Status;
11073 Status.Diag = &Diags;
11074
11075 EvalInfo Info(FD->getASTContext(), Status,
11076 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
11077
11078 // Fabricate a call stack frame to give the arguments a plausible cover story.
11079 ArrayRef<const Expr*> Args;
11080 ArgVector ArgValues(0);
11081 bool Success = EvaluateArgs(Args, ArgValues, Info);
11082 (void)Success;
11083 assert(Success &&
11084 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000011085 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011086
11087 APValue ResultScratch;
11088 Evaluate(ResultScratch, Info, E);
11089 return Diags.empty();
11090}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011091
11092bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11093 unsigned Type) const {
11094 if (!getType()->isPointerType())
11095 return false;
11096
11097 Expr::EvalStatus Status;
11098 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000011099 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011100}